-
Notifications
You must be signed in to change notification settings - Fork 7
/
ChatWindowController.py
2224 lines (1905 loc) · 106 KB
/
ChatWindowController.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) 2009-2011 AG Projects. See LICENSE for details.
#
from AppKit import (NSAlertDefaultReturn,
NSApp,
NSCommandKeyMask,
NSDragOperationAll,
NSDragOperationNone,
NSEventTrackingRunLoopMode,
NSFilenamesPboardType,
NSFitPagination,
NSLeftMouseUp,
NSModalPanelRunLoopMode,
NSOffState,
NSOnState,
NSPortraitOrientation,
NSRunAlertPanel,
NSTableViewDropAbove,
NSTableViewSelectionDidChangeNotification,
NSSplitViewDidResizeSubviewsNotification,
NSStringPboardType,
NSWindowDocumentIconButton)
from Foundation import (CFURLCreateStringByAddingPercentEscapes,
kCFStringEncodingUTF8,
NSArray,
NSBundle,
NSColor,
NSDate,
NSDefaultRunLoopMode,
NSEvent,
NSImage,
NSIndexSet,
NSLocalizedString,
NSMakeSize,
NSMenu,
NSMenuItem,
NSNotFound,
NSNotificationCenter,
NSObject,
NSPasteboard,
NSPrintInfo,
NSRunLoop,
NSRunLoopCommonModes,
NSString,
NSTimer,
NSTabViewItem,
NSURL,
NSWindowController,
NSWorkspace,
NSZeroPoint)
from Quartz import (CGWindowListCopyWindowInfo,
kCGNullWindowID,
kCGWindowBounds,
kCGWindowIsOnscreen,
kCGWindowListOptionOnScreenOnly,
kCGWindowListExcludeDesktopElements,
kCGWindowName,
kCGWindowNumber,
kCGWindowOwnerName)
import objc
import os
import time
from application.notification import NotificationCenter, IObserver
from application.python import Null
from itertools import chain
from operator import attrgetter
from sipsimple.account import BonjourAccount
from sipsimple.core import SIPURI, SIPCoreError
from sipsimple.util import ISOTimestamp
from sipsimple.streams.msrp.chat import ChatIdentity
from sipsimple.configuration.settings import SIPSimpleSettings
from urllib.parse import unquote
from zope.interface import implementer
import FancyTabSwitcher
import ParticipantsTableView
from BlinkLogger import BlinkLogger
from ChatPrivateMessageController import ChatPrivateMessageController
from MediaStream import STREAM_PROPOSING, STREAM_RINGING, STREAM_CONNECTED, STREAM_WAITING_DNS_LOOKUP
from MediaStream import STATE_CONNECTING, STATE_CONNECTED, STATE_DNS_LOOKUP, STATE_IDLE
from ConferenceScreenSharing import ConferenceScreenSharing
from ConferenceFileCell import ConferenceFileCell
from ContactListModel import BlinkConferenceContact, BlinkPresenceContact, BlinkMyselfConferenceContact
from FileTransferSession import OutgoingPullFileTransferHandler
from FileTransferWindowController import openFileTransferSelectionDialog
from NicknameController import NicknameController
from SIPManager import SIPManager
from SmileyManager import SmileyManager
from SubjectController import SubjectController
from util import format_identity_to_string, format_size_rounded, sip_prefix_pattern, beautify_audio_codec, run_in_gui_thread
CONFERENCE_ROOM_MENU_ADD_CONFERENCE_CONTACT = 314
CONFERENCE_ROOM_MENU_ADD_CONTACT = 301
CONFERENCE_ROOM_MENU_REMOVE_FROM_CONFERENCE = 310
CONFERENCE_ROOM_MENU_SEND_PRIVATE_MESSAGE = 311
CONFERENCE_ROOM_MENU_MUTE = 315
CONFERENCE_ROOM_MENU_NICKNAME = 316
CONFERENCE_ROOM_MENU_SUBJECT = 317
CONFERENCE_ROOM_MENU_COPY_ROOM_TO_CLIPBOARD = 318
CONFERENCE_ROOM_MENU_COPY_PARTICIPANT_TO_CLIPBOARD = 319
CONFERENCE_ROOM_MENU_SEND_EMAIL = 325
CONFERENCE_ROOM_MENU_NOTIFY_CHANGE_PARTICIPANTS = 326
CONFERENCE_ROOM_MENU_INVITE_TO_CONFERENCE = 312
CONFERENCE_ROOM_MENU_GOTO_CONFERENCE_WEBSITE = 313
CONFERENCE_ROOM_MENU_START_AUDIO_SESSION = 320
CONFERENCE_ROOM_MENU_START_CHAT_SESSION = 321
CONFERENCE_ROOM_MENU_START_VIDEO_SESSION = 322
CONFERENCE_ROOM_MENU_DETACH_VIDEO_SESSION = 327
CONFERENCE_ROOM_MENU_SILENCE_NOTIFICATIONS = 328
CONFERENCE_ROOM_MENU_SEND_FILES = 323
CONFERENCE_ROOM_MENU_VIEW_SCREEN = 324
CONFERENCE_ROOM_MENU_SHOW_SESSION_INFO = 400
CONFERENCE_ROOM_MENU_FONT_SIZE = 500
CONFERENCE_ROOM_MENU_INCREASE_FONT_SIZE = 501
CONFERENCE_ROOM_MENU_DECREASE_FONT_SIZE = 502
TOOLBAR_SCREENSHARING_MENU_REQUEST_REMOTE = 201
TOOLBAR_SCREENSHARING_MENU_OFFER_LOCAL = 202
TOOLBAR_SCREENSHARING_MENU_CANCEL = 203
TOOLBAR_SCREENSHOT_MENU_QUALITY_MENU_HIGH = 401
TOOLBAR_SCREENSHOT_MENU_QUALITY_MENU_MEDIUM = 403
TOOLBAR_SCREENSHOT_MENU_QUALITY_MENU_LOW = 402
SKIP_SCREENSHARING_FOR_APPS= ('SystemUIServer', 'Dock', 'Window Server')
@implementer(IObserver)
class ChatWindowController(NSWindowController):
tabView = objc.IBOutlet()
toolbar = objc.IBOutlet()
tabSwitcher = objc.IBOutlet()
screenShareMenu = objc.IBOutlet()
conferenceScreenSharingMenu = objc.IBOutlet()
participantMenu = objc.IBOutlet()
encryptionMenu = objc.IBOutlet()
sharedFileMenu = objc.IBOutlet()
drawer = objc.IBOutlet()
participantsTableView = objc.IBOutlet()
conferenceFilesTableView = objc.IBOutlet()
drawerScrollView = objc.IBOutlet()
drawerSplitView = objc.IBOutlet()
screenSharingPopUpButton = objc.IBOutlet()
actionsButton = objc.IBOutlet()
editorButton = objc.IBOutlet()
videoButton = objc.IBOutlet()
muteButton = objc.IBOutlet()
recordButton = objc.IBOutlet()
audioStatus = objc.IBOutlet()
encryptionIconMenuItem = objc.IBOutlet()
videoView = objc.IBOutlet()
conferenceFilesView = objc.IBOutlet()
participantsView = objc.IBOutlet()
refresh_drawer_counter = 1
full_screen_in_progress = False
contact_timer = None
def init(self):
self = objc.super(ChatWindowController, self).init()
if self:
BlinkLogger().log_debug('Starting Chat Window Controller')
smileys = SmileyManager()
self.closing = False
self.participants = []
self.conference_shared_files = []
self.remote_screens_closed_by_user = set()
self.sessions = {}
self.stream_controllers = {}
self.unreadMessageCounts = {}
self.remoteScreens = {}
# keep a reference to the controller object because it may be used later by cocoa
NSBundle.loadNibNamed_owner_("ChatWindow", self)
self.notification_center = NotificationCenter()
self.notification_center.add_observer(self, name="AudioStreamDidStartRecording")
self.notification_center.add_observer(self, name="AudioStreamDidStopRecording")
self.notification_center.add_observer(self, name="BonjourAccountPresenceStateDidChange")
self.notification_center.add_observer(self, name="BlinkAudioStreamChangedHoldState")
self.notification_center.add_observer(self, name="BlinkShouldTerminate")
self.notification_center.add_observer(self, name="BlinkCollaborationEditorContentHasChanged")
self.notification_center.add_observer(self, name="BlinkConferenceGotUpdate")
self.notification_center.add_observer(self, name="BlinkContactsHaveChanged")
self.notification_center.add_observer(self, name="BlinkGotProposal")
self.notification_center.add_observer(self, name="BlinkSentAddProposal")
self.notification_center.add_observer(self, name="BlinkSentRemoveProposal")
self.notification_center.add_observer(self, name="BlinkProposalGotRejected")
self.notification_center.add_observer(self, name="BlinkMuteChangedState")
self.notification_center.add_observer(self, name="BlinkSessionChangedState")
self.notification_center.add_observer(self, name="BlinkStreamHandlerChangedState")
self.notification_center.add_observer(self, name="BlinkStreamHandlersChanged")
self.notification_center.add_observer(self, name="BlinkDidRenegotiateStreams")
self.notification_center.add_observer(self, name="BlinkVideoEnteredFullScreen")
self.notification_center.add_observer(self, name="BlinkVideoExitedFullScreen")
self.notification_center.add_observer(self, name="BlinkConferenceContactPresenceHasChanged")
self.notification_center.add_observer(self, name="SIPAccountGotSelfPresenceState")
self.notification_center.add_observer(self, name="SIPAccountDidDeactivate")
self.notification_center.add_observer(self, name="SIPApplicationWillEnd")
ns_nc = NSNotificationCenter.defaultCenter()
ns_nc.addObserver_selector_name_object_(self, "participantSelectionChanged:", NSTableViewSelectionDidChangeNotification, self.participantsTableView)
ns_nc.addObserver_selector_name_object_(self, "sharedFileSelectionChanged:", NSTableViewSelectionDidChangeNotification, self.conferenceFilesTableView)
ns_nc.addObserver_selector_name_object_(self, "drawerSplitViewDidResize:", NSSplitViewDidResizeSubviewsNotification, self.drawerSplitView)
self.refresh_drawer_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(0.3, self, "refreshDrawerTimer:", None, True)
NSRunLoop.currentRunLoop().addTimer_forMode_(self.refresh_drawer_timer, NSModalPanelRunLoopMode)
NSRunLoop.currentRunLoop().addTimer_forMode_(self.refresh_drawer_timer, NSDefaultRunLoopMode)
self.backend = SIPManager()
if self.backend.is_muted():
self.muteButton.setImage_(NSImage.imageNamed_("muted"))
self.muteButton.setState_(NSOnState)
else:
self.muteButton.setImage_(NSImage.imageNamed_("mute"))
self.muteButton.setState_(NSOffState)
self.setOwnIcon()
if not self.sessionControllersManager.isMediaTypeSupported('video'):
for identifier in ('video', 'maximize'):
for idx, item in enumerate(self.toolbar.visibleItems()):
if item.itemIdentifier() == identifier:
self.toolbar.removeItemAtIndex_(idx)
break
return self
@property
def sessionControllersManager(self):
return NSApp.delegate().contactsWindowController.sessionControllersManager
@objc.python_method
def addTimer(self):
if not self.contact_timer:
self.contact_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(1.0, self, "updateContactTimer:", None, True)
NSRunLoop.currentRunLoop().addTimer_forMode_(self.contact_timer, NSRunLoopCommonModes)
NSRunLoop.currentRunLoop().addTimer_forMode_(self.contact_timer, NSEventTrackingRunLoopMode)
@objc.python_method
def removeContactTimer(self):
if self.contact_timer:
self.contact_timer.invalidate()
def setOwnIcon(self):
self.own_icon = None
path = NSApp.delegate().contactsWindowController.iconPathForSelf()
if path:
self.own_icon = NSImage.alloc().initWithContentsOfFile_(path)
@objc.python_method
def setScreenSharingToolbarIconSize(self):
frame = self.screenSharingPopUpButton.frame()
frame.size.height = 38
frame.size.width = 54
frame.origin.y = 14
self.screenSharingPopUpButton.setFrame_(frame)
def updateContactTimer_(self, timer):
# remove tile after few seconds to have time to see the reason in the drawer
session = self.selectedSessionController()
if session:
change = False
for uri in list(session.failed_to_join_participants.keys()):
for contact in session.invited_participants:
try:
uri_time = session.failed_to_join_participants[uri]
if uri == contact.uri and (time.time() - uri_time > 5):
session.log_info('Removing %s from list of invited partipants' % uri)
session.invited_participants.remove(contact)
contact.destroy()
del session.failed_to_join_participants[uri]
change = True
except KeyError:
pass
if change:
self.refreshDrawer()
def awakeFromNib(self):
self.participantsTableView.registerForDraggedTypes_(NSArray.arrayWithObject_("x-blink-sip-uri"))
self.participantsTableView.registerForDraggedTypes_(NSArray.arrayWithObject_(NSFilenamesPboardType))
self.conferenceFilesTableView.registerForDraggedTypes_(NSArray.arrayWithObject_(NSFilenamesPboardType))
self.participantsTableView.setTarget_(self)
self.participantsTableView.setDoubleAction_("doubleClickReceived:")
self.conferenceFilesTableView.setTarget_(self)
self.conferenceFilesTableView.setDoubleAction_("doubleClickReceived:")
self.setScreenSharingToolbarIconSize()
def splitView_shouldHideDividerAtIndex_(self, view, index):
if self.conference_shared_files:
return False
return True
def shouldPopUpDocumentPathMenu_(self, menu):
return False
@objc.python_method
def _findInactiveSessionCompatibleWith_(self, session):
for k, s in self.sessions.items():
is_active = s.isActive()
if s == session or s.identifier == session.identifier:
return s
if not is_active:
if s.device_id and s.device_id == session.device_id:
#s.contact = session.contact
#s.remoteAOR = session.remoteAOR
return s
if s.remoteAOR == session.remoteAOR:
return s
if s.contact and s.contact == session.contact:
return s
return None
def replaceInactiveWithCompatibleSession_(self, newSession):
oldSession = self._findInactiveSessionCompatibleWith_(newSession)
ok = False
if oldSession:
for item in self.tabView.tabViewItems():
if item.identifier() == oldSession.identifier:
del self.sessions[oldSession.identifier]
self.sessions[newSession.identifier] = newSession
item.setView_(newSession.streamHandlerOfType("chat").getContentView())
item.setLabel_(newSession.titleShort)
self.tabView.selectTabViewItem_(item)
item.setIdentifier_(newSession.identifier)
ok = True
break
return ok and oldSession or None
def addSession_withView_(self, session, view):
self.sessions[session.identifier] = session
tabItem = NSTabViewItem.alloc().initWithIdentifier_(session.identifier)
self.stream_controllers[tabItem] = session.streamHandlerOfType("chat")
tabItem.setView_(view)
tabItem.setLabel_(session.titleShort)
self.tabSwitcher.addTabViewItem_(tabItem)
self.tabSwitcher.selectLastTabViewItem_(None)
chat_stream = session.streamHandlerOfType("chat")
self.tabSwitcher.setTabViewItem_busy_(tabItem, chat_stream.isConnecting if chat_stream else False)
if chat_stream and chat_stream.isConnecting:
chat_stream.chatViewController.loadingTextIndicator.setStringValue_(NSLocalizedString("Connecting...", "Label"))
chat_stream.chatViewController.loadingProgressIndicator.startAnimation_(None)
else:
chat_stream.chatViewController.loadingTextIndicator.setStringValue_("")
chat_stream.chatViewController.loadingProgressIndicator.stopAnimation_(None)
self.updateTitle()
if session.remote_focus:
self.drawer.open()
else:
self.closeDrawer()
if session.mustCloseAudioDrawer:
NSApp.delegate().contactsWindowController.drawer.close()
self.participantsTableView.deselectAll_(self)
@objc.python_method
def closeDrawer(self):
self.drawer.close()
def removeSession_(self, session):
index = self.tabView.indexOfTabViewItemWithIdentifier_(session.identifier)
if index == NSNotFound:
return None
tabItem = self.tabView.tabViewItemAtIndex_(index)
view = tabItem.view()
view.removeFromSuperview()
tabItem.setView_(None)
self.tabSwitcher.removeTabViewItem_(tabItem)
try:
del self.stream_controllers[tabItem]
except KeyError:
pass
try:
del self.sessions[session.identifier]
except KeyError:
pass
def selectSession_(self, session):
index = self.tabView.indexOfTabViewItemWithIdentifier_(session.identifier)
if index == NSNotFound:
raise Exception("Attempt to select invalid tab")
self.tabView.selectTabViewItemWithIdentifier_(session.identifier)
def hasSession_(self, session):
return session.identifier in self.sessions
@objc.python_method
def selectedSessionController(self):
activeTab = self.tabView.selectedTabViewItem()
if activeTab and activeTab.identifier() in self.sessions:
return self.sessions[activeTab.identifier()]
return None
@objc.python_method
def updateTitle(self):
title = self.getConferenceTitle()
icon = None
if title:
self.window().setTitle_(NSLocalizedString("Chat with %s", "Window title") % title)
self.window().setRepresentedURL_(NSURL.fileURLWithPath_(title))
session = self.selectedSessionController()
if session:
try:
if session.session.transport == "tls":
icon = NSImage.imageNamed_("locked-green")
icon.setSize_(NSMakeSize(12, 12))
except AttributeError:
pass
self.window().standardWindowButton_(NSWindowDocumentIconButton).setImage_(icon)
def window_shouldDragDocumentWithEvent_from_withPasteboard_(self, window, event, point, pasteboard):
return False
@objc.python_method
def getConferenceTitle(self):
title = None
session = self.selectedSessionController()
if session:
if session.conference_info is not None:
if session.subject is not None:
title = "%s" % session.subject
else:
conf_desc = session.conference_info.conference_description
title = "%s <%s>" % (conf_desc.display_text, format_identity_to_string(session.remoteIdentity)) if conf_desc.display_text else "%s" % session.titleLong
else:
title = "%s" % session.titleShort if isinstance(session.account, BonjourAccount) else "%s" % session.titleLong
return title
def noteSession_isComposing_(self, session, flag):
index = self.tabView.indexOfTabViewItemWithIdentifier_(session.identifier)
if index == NSNotFound:
return
tabItem = self.tabView.tabViewItemAtIndex_(index)
item = self.tabSwitcher.itemForTabViewItem_(tabItem)
if item:
item.setComposing_(flag)
def noteSession_isScreenSharing_(self, session, flag):
index = self.tabView.indexOfTabViewItemWithIdentifier_(session.identifier)
if index == NSNotFound:
return
tabItem = self.tabView.tabViewItemAtIndex_(index)
item = self.tabSwitcher.itemForTabViewItem_(tabItem)
if item:
item.setScreenSharing_(flag)
def noteNewMessageForSession_(self, session):
index = self.tabView.indexOfTabViewItemWithIdentifier_(session.identifier)
if index == NSNotFound:
return
tabItem = self.tabView.tabViewItemAtIndex_(index)
if self.tabView.selectedTabViewItem() == tabItem:
return
item = self.tabSwitcher.itemForTabViewItem_(tabItem)
if item:
count = self.unreadMessageCounts[session.identifier] = self.unreadMessageCounts.get(session.identifier, 0) + 1
item.setBadgeLabel_(str(count))
def windowDidBecomeKey_(self, notification):
session = self.selectedSessionController()
if session and session.streamHandlerOfType("chat"):
self.window().makeFirstResponder_(session.streamHandlerOfType("chat").chatViewController.inputText)
@objc.python_method
def init_aspect_ratio(self, width, height):
self.refresh_drawer_counter += 1
@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)
@objc.python_method
def _NH_BlinkShouldTerminate(self, sender, data):
if self.window():
self.window().orderOut_(self)
@objc.python_method
def _NH_SIPApplicationWillEnd(self, sender, data):
if self.refresh_drawer_timer:
self.refresh_drawer_timer.invalidate()
if self.contact_timer:
self.contact_timer.invalidate()
@objc.python_method
def _NH_BonjourAccountPresenceStateDidChange(self, sender, data):
selectedSession = self.selectedSessionController()
if selectedSession:
if selectedSession.account == sender:
self.refreshDrawer()
@objc.python_method
def _NH_SIPAccountGotSelfPresenceState(self, sender, data):
selectedSession = self.selectedSessionController()
if selectedSession:
if selectedSession.account == sender:
self.refreshDrawer()
@objc.python_method
def _NH_SIPAccountDidDeactivate(self, sender, data):
selectedSession = self.selectedSessionController()
if selectedSession:
if selectedSession.account == sender:
self.refreshDrawer()
@objc.python_method
def _NH_BlinkStreamHandlerChangedState(self, sender, data):
session = sender.sessionController
if session:
chat_stream = session.streamHandlerOfType("chat")
if chat_stream:
index = self.tabView.indexOfTabViewItemWithIdentifier_(session.identifier)
if index != NSNotFound:
tabItem = self.tabView.tabViewItemAtIndex_(index)
self.tabSwitcher.setTabViewItem_busy_(tabItem, chat_stream.isConnecting)
if chat_stream.isConnecting:
chat_stream.chatViewController.loadingTextIndicator.setStringValue_(NSLocalizedString("Connecting...", "Label"))
chat_stream.chatViewController.loadingProgressIndicator.startAnimation_(None)
else:
video_stream = session.streamHandlerOfType("video")
audio_stream = session.streamHandlerOfType("audio")
if data.state == STATE_IDLE:
chat_stream.chatViewController.loadingTextIndicator.setStringValue_("")
chat_stream.chatViewController.loadingProgressIndicator.stopAnimation_(None)
elif data.state == STREAM_WAITING_DNS_LOOKUP:
chat_stream.chatViewController.loadingTextIndicator.setStringValue_(NSLocalizedString("Finding Destination...", "Audio status label"))
chat_stream.chatViewController.loadingProgressIndicator.stopAnimation_(None)
elif video_stream:
if video_stream.isConnecting:
chat_stream.chatViewController.loadingTextIndicator.setStringValue_(NSLocalizedString("Adding Video...", "Label"))
chat_stream.chatViewController.loadingProgressIndicator.startAnimation_(None)
else:
chat_stream.chatViewController.loadingTextIndicator.setStringValue_("")
chat_stream.chatViewController.loadingProgressIndicator.stopAnimation_(None)
elif audio_stream:
if audio_stream.isConnecting:
chat_stream.chatViewController.loadingTextIndicator.setStringValue_(NSLocalizedString("Adding Audio...", "Label"))
chat_stream.chatViewController.loadingProgressIndicator.startAnimation_(None)
else:
chat_stream.chatViewController.loadingTextIndicator.setStringValue_("")
chat_stream.chatViewController.loadingProgressIndicator.stopAnimation_(None)
else:
chat_stream.chatViewController.loadingTextIndicator.setStringValue_("")
chat_stream.chatViewController.loadingProgressIndicator.stopAnimation_(None)
self.revalidateToolbar()
self.refreshDrawer()
@objc.python_method
def _NH_BlinkSessionChangedState(self, sender, data):
session = sender
if session:
chat_stream = session.streamHandlerOfType("chat")
if chat_stream:
index = self.tabView.indexOfTabViewItemWithIdentifier_(session.identifier)
if index != NSNotFound:
tabItem = self.tabView.tabViewItemAtIndex_(index)
self.tabSwitcher.setTabViewItem_busy_(tabItem, chat_stream.isConnecting)
if chat_stream.isConnecting:
chat_stream.chatViewController.loadingTextIndicator.setStringValue_(NSLocalizedString("Connecting...", "Label"))
chat_stream.chatViewController.loadingProgressIndicator.startAnimation_(None)
else:
audio_stream = session.streamHandlerOfType("audio")
if audio_stream and audio_stream.isConnecting:
chat_stream.chatViewController.loadingTextIndicator.setStringValue_(NSLocalizedString("Adding Audio...", "Label"))
chat_stream.chatViewController.loadingProgressIndicator.startAnimation_(None)
else:
chat_stream.chatViewController.loadingTextIndicator.setStringValue_("")
chat_stream.chatViewController.loadingProgressIndicator.stopAnimation_(None)
self.revalidateToolbar()
self.refreshDrawer()
@objc.python_method
def _NH_BlinkAudioStreamChangedHoldState(self, sender, data):
self.revalidateToolbar()
self.refreshDrawer()
@objc.python_method
def _NH_BlinkStreamHandlersChanged(self, sender, data):
self.revalidateToolbar()
self.refreshDrawer()
@objc.python_method
def _NH_BlinkDidRenegotiateStreams(self, sender, data):
self.revalidateToolbar()
self.refreshDrawer()
@objc.python_method
def _NH_BlinkVideoEnteredFullScreen(self, sender, data):
self.toolbar.setVisible_(False)
@objc.python_method
def _NH_BlinkVideoExitedFullScreen(self, sender, data):
self.toolbar.setVisible_(True)
@objc.python_method
def _NH_AudioStreamDidStartRecording(self, sender, data):
self.revalidateToolbar()
@objc.python_method
def _NH_AudioStreamDidStopRecording(self, sender, data):
self.revalidateToolbar()
@objc.python_method
def _NH_BlinkGotProposal(self, sender, data):
self.revalidateToolbar()
self.refreshDrawer()
@objc.python_method
def _NH_BlinkProposalGotRejected(self, sender, data):
self.revalidateToolbar()
self.refreshDrawer()
@objc.python_method
def _NH_BlinkSentAddProposal(self, sender, data):
self.revalidateToolbar()
self.refreshDrawer()
@objc.python_method
def _NH_BlinkSentRemoveProposal(self, sender, data):
self.revalidateToolbar()
self.refreshDrawer()
@objc.python_method
def _NH_BlinkConferenceGotUpdate(self, sender, data):
self.refreshDrawer()
@objc.python_method
def _NH_BlinkContactsHaveChanged(self, sender, data):
self.setOwnIcon()
self.refreshDrawer()
@objc.python_method
def _NH_BlinkMuteChangedState(self, sender, data):
if self.backend.is_muted():
self.muteButton.setImage_(NSImage.imageNamed_("muted"))
self.muteButton.setState_(NSOnState)
else:
self.muteButton.setState_(NSOffState)
self.muteButton.setImage_(NSImage.imageNamed_("mute"))
@objc.python_method
def _NH_BlinkCollaborationEditorContentHasChanged(self, sender, data):
if not sender.editorVisible:
self.noteSession_isComposing_(sender.delegate.sessionController, True)
self.revalidateToolbar()
def validateToolbarItem_(self, item):
selectedSession = self.selectedSessionController()
if selectedSession:
chatStream = selectedSession.streamHandlerOfType("chat")
if chatStream:
return chatStream.validateToolbarButton(item)
else:
return False
@objc.python_method
def _NH_BlinkConferenceContactPresenceHasChanged(self, sender, data):
try:
idx = self.participants.index(sender)
self.participantsTableView.reloadDataForRowIndexes_columnIndexes_(NSIndexSet.indexSetWithIndex_(idx), NSIndexSet.indexSetWithIndex_(0))
except ValueError:
pass
@objc.IBAction
def stopConferenceScreenSharing_(self, sender):
selectedSession = self.selectedSessionController()
if selectedSession:
chat_stream = selectedSession.streamHandlerOfType("chat")
if chat_stream and chat_stream.screensharing_allowed:
if chat_stream.screensharing_handler and chat_stream.screensharing_handler.connected:
chat_stream.toggleScreensharingWithConferenceParticipants()
chat_stream.screensharing_handler.setWindowId(None)
i = 7
while i < self.conferenceScreenSharingMenu.numberOfItems() - 2:
item = self.conferenceScreenSharingMenu.itemAtIndex_(i)
item.setState_(NSOffState)
i += 1
@objc.IBAction
def selectConferenceScreenSharingWindow_(self, sender):
selectedSession = self.selectedSessionController()
if selectedSession:
chat_stream = selectedSession.streamHandlerOfType("chat")
if chat_stream and chat_stream.screensharing_allowed:
wob = sender.representedObject()
id = wob['id']
application = wob['application']
if chat_stream.screensharing_handler and chat_stream.screensharing_handler.connected:
if id != chat_stream.screensharing_handler.window_id:
selectedSession.log_info('Selecting %s for screen sharing' % application)
chat_stream.screensharing_handler.setWindowId(id)
elif sender.state() == NSOnState:
chat_stream.toggleScreensharingWithConferenceParticipants()
chat_stream.screensharing_handler.setWindowId(None)
else:
chat_stream.toggleScreensharingWithConferenceParticipants()
chat_stream.screensharing_handler.setWindowId(id)
i = 7
while i < self.conferenceScreenSharingMenu.numberOfItems() - 2:
item = self.conferenceScreenSharingMenu.itemAtIndex_(i)
item.setState_(NSOnState if item.representedObject()['id'] == id else NSOffState)
i += 1
def keyDown_(self, event):
if (event.modifierFlags() & NSCommandKeyMask):
keys = event.characters()
session = self.selectedSessionController()
if keys[0] == 'i' and session and session.info_panel is not None:
session.info_panel.toggle()
else:
objc.super(ChatWindowController, self).keyDown_(event)
def close_(self, sender):
chat_sessions = len([s for s in list(self.sessions.values()) if s.hasStreamOfType("chat")])
if chat_sessions > 1:
selectedSession = self.selectedSessionController()
if selectedSession:
chat_stream = selectedSession.streamHandlerOfType("chat")
if chat_stream:
chat_stream.closeTab()
else:
self.window().performClose_(None)
def windowWillClose_(self, sender):
self.removeContactTimer()
def windowShouldClose_(self, sender):
active = len([s for s in list(self.sessions.values()) if s.hasStreamOfType("chat") and s.state == STATE_CONNECTED])
if active > 1:
ret = NSRunAlertPanel(NSLocalizedString("Close Chat Window", "Window Title"),
NSLocalizedString("There are %i Chat sessions, click Close to terminate them all.", "Label") % active,
NSLocalizedString("Close", "Button title"),
NSLocalizedString("Cancel", "Button title"),
None)
if ret != NSAlertDefaultReturn:
return False
self.window().close()
self.closing = True
# close active sessions
for s in list(self.sessions.values()): # we need a copy of the dict contents as it will change as a side-effect of removeSession_()
chat_stream = s.streamHandlerOfType("chat")
if chat_stream:
chat_stream.closeTab()
# close idle sessions
for chat_stream in list(self.stream_controllers.values()):
if chat_stream:
chat_stream.closeTab()
self.closing = False
self.sessions = {}
self.stream_controllers = {}
self.notification_center.post_notification("BlinkChatWindowClosed", sender=self)
return True
@objc.python_method
def joinConferenceWindow(self, session, participants=[]):
media_type = []
if session.hasStreamOfType("chat"):
media_type.append("chat")
if session.hasStreamOfType("audio"):
media_type.append("audio")
if format_identity_to_string(session.remoteIdentity) not in participants:
participants.append(format_identity_to_string(session.remoteIdentity))
conference = NSApp.delegate().contactsWindowController.showJoinConferenceWindow(participants=participants, media_type=media_type, autostart=True)
if conference is not None:
NSApp.delegate().contactsWindowController.joinConference(conference.target, conference.media_type, conference.participants, conference.nickname)
@objc.python_method
def getSelectedParticipant(self):
row = self.participantsTableView.selectedRow()
if not self.participantsTableView.isRowSelected_(row):
return None
try:
return self.participants[row]
except IndexError:
return None
@objc.python_method
def isConferenceParticipant(self, uri):
session = self.selectedSessionController()
if session and hasattr(session.conference_info, "users"):
for user in session.conference_info.users:
participant = sip_prefix_pattern.sub("", user.entity)
if participant == uri:
return True
return False
@objc.python_method
def isInvitedParticipant(self, uri):
session = self.selectedSessionController()
try:
return uri in (contact.uri for contact in session.invited_participants)
except AttributeError:
return False
def participantSelectionChanged_(self, notification):
contact = self.getSelectedParticipant()
session = self.selectedSessionController()
if not session or contact is None:
self.participantMenu.itemWithTag_(CONFERENCE_ROOM_MENU_ADD_CONTACT).setEnabled_(False)
self.participantMenu.itemWithTag_(CONFERENCE_ROOM_MENU_REMOVE_FROM_CONFERENCE).setEnabled_(False)
self.participantMenu.itemWithTag_(CONFERENCE_ROOM_MENU_MUTE).setEnabled_(False)
self.participantMenu.itemWithTag_(CONFERENCE_ROOM_MENU_SEND_PRIVATE_MESSAGE).setEnabled_(False)
self.participantMenu.itemWithTag_(CONFERENCE_ROOM_MENU_NICKNAME).setEnabled_(False)
self.participantMenu.itemWithTag_(CONFERENCE_ROOM_MENU_SUBJECT).setEnabled_(False)
self.participantMenu.itemWithTag_(CONFERENCE_ROOM_MENU_COPY_ROOM_TO_CLIPBOARD).setEnabled_(False)
self.participantMenu.itemWithTag_(CONFERENCE_ROOM_MENU_SEND_EMAIL).setEnabled_(False)
self.participantMenu.itemWithTag_(CONFERENCE_ROOM_MENU_NOTIFY_CHANGE_PARTICIPANTS).setEnabled_(False)
self.participantMenu.itemWithTag_(CONFERENCE_ROOM_MENU_COPY_PARTICIPANT_TO_CLIPBOARD).setEnabled_(False)
self.participantMenu.itemWithTag_(CONFERENCE_ROOM_MENU_START_AUDIO_SESSION).setEnabled_(False)
self.participantMenu.itemWithTag_(CONFERENCE_ROOM_MENU_START_CHAT_SESSION).setEnabled_(False)
self.participantMenu.itemWithTag_(CONFERENCE_ROOM_MENU_START_VIDEO_SESSION).setEnabled_(False)
self.participantMenu.itemWithTag_(CONFERENCE_ROOM_MENU_SEND_FILES).setEnabled_(False)
self.participantMenu.itemWithTag_(CONFERENCE_ROOM_MENU_VIEW_SCREEN).setEnabled_(False)
else:
own_uri = '%s@%s' % (session.account.id.username, session.account.id.domain)
remote_uri = format_identity_to_string(session.remoteIdentity)
hasContactMatchingURI = NSApp.delegate().contactsWindowController.hasContactMatchingURI
self.participantMenu.itemWithTag_(CONFERENCE_ROOM_MENU_ADD_CONTACT).setEnabled_(False if (hasContactMatchingURI(contact.uri) or contact.uri == own_uri or isinstance(session.account, BonjourAccount)) else True)
self.participantMenu.itemWithTag_(CONFERENCE_ROOM_MENU_REMOVE_FROM_CONFERENCE).setEnabled_(True if self.canBeRemovedFromConference(contact.uri) else False)
if remote_uri != contact.uri and own_uri != contact.uri and session.hasStreamOfType("chat") and self.isConferenceParticipant(contact.uri):
chat_stream = session.streamHandlerOfType("chat")
stream_supports_screen_sharing = chat_stream.screensharing_allowed
self.participantMenu.itemWithTag_(CONFERENCE_ROOM_MENU_SEND_PRIVATE_MESSAGE).setEnabled_(True if chat_stream.stream.private_messages_allowed and 'message' in contact.active_media else False)
else:
stream_supports_screen_sharing = False
self.participantMenu.itemWithTag_(CONFERENCE_ROOM_MENU_SEND_PRIVATE_MESSAGE).setEnabled_(False)
self.participantMenu.itemWithTag_(CONFERENCE_ROOM_MENU_VIEW_SCREEN).setEnabled_(True if stream_supports_screen_sharing and contact.uri != own_uri and not isinstance(session.account, BonjourAccount) and (contact.screensharing_url is not None or self.participantMenu.itemWithTag_(CONFERENCE_ROOM_MENU_VIEW_SCREEN).state == NSOnState) else False)
self.participantMenu.itemWithTag_(CONFERENCE_ROOM_MENU_START_AUDIO_SESSION).setEnabled_(True if contact.uri != own_uri and not isinstance(session.account, BonjourAccount) else False)
self.participantMenu.itemWithTag_(CONFERENCE_ROOM_MENU_START_CHAT_SESSION).setEnabled_(True if contact.uri != own_uri and not isinstance(session.account, BonjourAccount) else False)
self.participantMenu.itemWithTag_(CONFERENCE_ROOM_MENU_START_VIDEO_SESSION).setEnabled_(not session.hasStreamOfType("video"))
self.participantMenu.itemWithTag_(CONFERENCE_ROOM_MENU_SEND_FILES).setEnabled_(True if contact.uri != own_uri and not isinstance(session.account, BonjourAccount) else False)
self.participantMenu.itemWithTag_(CONFERENCE_ROOM_MENU_COPY_PARTICIPANT_TO_CLIPBOARD).setEnabled_(True)
def sharedFileSelectionChanged_(self, notification):
session = self.selectedSessionController()
if not session:
self.sharedFileMenu.itemWithTag_(100).setEnabled_(False)
else:
row = self.conferenceFilesTableView.selectedRow()
if row == -1:
return
conference_file = self.conference_shared_files[row]
self.sharedFileMenu.itemWithTag_(100).setEnabled_(conference_file.file.status == 'OK')
def drawerSplitViewDidResize_(self, notification):
session = self.selectedSessionController()
if not session:
return
chat_stream = session.streamHandlerOfType("chat")
if not chat_stream:
return
parent_frame = self.drawerSplitView.frame()
top_frame = self.participantsView.frame()
bottom_frame = self.conferenceFilesView.frame()
must_resize = False
if top_frame.size.height < 200:
top_frame.size.height = 200
bottom_frame.size.height = parent_frame.size.height - top_frame.size.height
top_frame.origin.y = 0
bottom_frame.origin.y = top_frame.size.height
must_resize = True
if bottom_frame.size.height < 50 and bottom_frame.size.height > 0:
top_frame.size.height = parent_frame.size.height
bottom_frame.size.height = 0
top_frame.origin.y = 0
bottom_frame.origin.y = top_frame.size.height
must_resize = True
chat_stream.drawerSplitterPosition = {'parent_frame': parent_frame, 'top_frame': top_frame, 'bottom_frame': bottom_frame}
if must_resize:
self.resizeDrawerSplitter()
@objc.python_method
def resizeDrawerSplitter(self):
session = self.selectedSessionController()
if not session:
return
chat_stream = session.streamHandlerOfType("chat")
if not chat_stream:
return
if chat_stream.drawerSplitterPosition is None:
return
self.participantsView.setFrame_(chat_stream.drawerSplitterPosition['top_frame'])
self.conferenceFilesView.setFrame_(chat_stream.drawerSplitterPosition['bottom_frame'])
self.participantsTableView.reloadData()
self.conferenceFilesTableView.reloadData()
self.drawerSplitView.setNeedsDisplay_(True)
@objc.python_method
def sendPrivateMessage(self):
session = self.selectedSessionController()
if session:
row = self.participantsTableView.selectedRow()
try:
contact = self.participants[row]
except IndexError:
return
try:
recipient = ChatIdentity(SIPURI.parse('sip:%s' % str(contact.uri)), display_name=contact.name)
except SIPCoreError:
return
controller = ChatPrivateMessageController(contact)
message = controller.runModal()
controller.release()
if message:
chat_stream = session.streamHandlerOfType("chat")
chat_stream.outgoing_message_handler.send(message, recipient, True)
@objc.python_method
def setNickname(self):
session = self.selectedSessionController()
if session:
chat_handler = session.streamHandlerOfType("chat")
if chat_handler:
controller = NicknameController()
nickname = controller.runModal(session.nickname)
if nickname or (not nickname and session.nickname):
chat_handler.setNickname(nickname)
@objc.python_method
def setSubject(self):
session = self.selectedSessionController()
if session:
chat_handler = session.streamHandlerOfType("chat")
if chat_handler:
controller = SubjectController()
subject = controller.runModal(session.subject)
if chat_handler.stream:
body = 'SUBJECT %s' % subject if subject else 'SUBJECT'
chat_handler.stream.send_message(body, content_type='sylkserver/control', timestamp=ISOTimestamp.now())
if subject or (not subject and session.subject):
session.subject = subject if subject else None
@objc.python_method
def canGoToConferenceWebsite(self):
session = self.selectedSessionController()
if session.conference_info and session.conference_info.host_info and session.conference_info.host_info.web_page:
return True
return False
@objc.python_method
def canSetNickname(self):
session = self.selectedSessionController()
if session is not None and session.hasStreamOfType("chat"):
chat_handler = session.streamHandlerOfType("chat")
try:
return chat_handler.stream.nickname_allowed
except Exception:
pass
return False
@objc.python_method