-
Notifications
You must be signed in to change notification settings - Fork 7
/
PreferencesController.py
1298 lines (1102 loc) · 60 KB
/
PreferencesController.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.
#
import re
import os
import platform
import json
from AppKit import (NSAccessibilityTitleAttribute,
NSAlertDefaultReturn,
NSApp,
NSEventTrackingRunLoopMode,
NSDragOperationGeneric,
NSNoTabsBezelBorder,
NSNoTabsNoBorder,
NSOnState,
NSOffState,
NSRunAlertPanel,
NSTableViewDropAbove,
NSTableViewDropOn,
NSTopTabsBezelBorder,
NSViewHeightSizable,
NSViewWidthSizable)
from Foundation import (NSArray,
NSBezierPath,
NSBundle,
NSColor,
NSImage,
NSIndexSet,
NSMakeRect,
NSMakeSize,
NSNotificationCenter,
NSScrollView,
NSString,
NSLocalizedString,
NSTabViewItem,
NSTabView,
NSURL,
NSUserDefaults,
NSWindowController,
NSRunLoop,
NSRunLoopCommonModes,
NSTimer,
NSWorkspace)
import objc
from application.notification import NotificationCenter, IObserver
from application.python import Null
from application.system import unlink
from gnutls.errors import GNUTLSError
from gnutls.crypto import X509Certificate, X509PrivateKey
from sipsimple.account import AccountManager, Account, BonjourAccount
from sipsimple.configuration import Setting, SettingsGroupMeta
from sipsimple.configuration.settings import SIPSimpleSettings
from sipsimple.threading import run_in_thread
from zope.interface import implementer
from BlinkLogger import BlinkLogger, FileLogger
from EnrollmentController import EnrollmentController
from PreferenceOptions import AccountSectionOrder, AccountSettingsOrder, AecSliderOption, AdvancedGeneralSectionOrder, BonjourAccountSectionOrder, DisabledAccountPreferenceSections, DisabledPreferenceSections, GeneralSettingsOrder, HiddenOption, PreferenceOptionTypes, SampleRateOption, SettingDescription, StaticPreferenceSections, SectionNames, ToolTips, Placeholders, formatName
from SIPManager import SIPManager
from VerticalBoxView import VerticalBoxView
from resources import ApplicationData
from util import run_in_gui_thread, AccountInfo, osx_version, trusted_cas
@implementer(IObserver)
class PreferencesController(NSWindowController, object):
toolbar = objc.IBOutlet()
mainTabView = objc.IBOutlet()
sectionDescription = objc.IBOutlet()
accountTable = objc.IBOutlet()
displayNameText = objc.IBOutlet()
addressText = objc.IBOutlet()
passwordText = objc.IBOutlet()
registration_status = objc.IBOutlet()
registration_tls_icon = objc.IBOutlet()
sync_with_icloud_checkbox = objc.IBOutlet()
selected_proxy_radio_button = objc.IBOutlet()
sectionHelpPlaceholder = objc.IBOutlet()
purgeLogsButton = objc.IBOutlet()
openLogsFolderButton = objc.IBOutlet()
addButton = objc.IBOutlet()
removeButton = objc.IBOutlet()
# account elements
advancedToggle = objc.IBOutlet()
advancedPop = objc.IBOutlet()
advancedTabView = objc.IBOutlet()
# general settings
generalTabView = objc.IBOutlet()
settingViews = {}
accounts = []
updating = False
saving = False
logsize_timer = None
def init(self):
self = objc.super(PreferencesController, self).init()
if self:
notification_center = NotificationCenter()
notification_center.add_observer(self, name="BlinkShouldTerminate")
notification_center.add_observer(self, name="BlinkTransportFailed")
notification_center.add_observer(self, name="BonjourAccountWillRegister")
notification_center.add_observer(self, name="BonjourAccountRegistrationDidSucceed")
notification_center.add_observer(self, name="BonjourAccountRegistrationDidFail")
notification_center.add_observer(self, name="BonjourAccountRegistrationDidEnd")
notification_center.add_observer(self, name="SIPAccountDidDeactivate")
notification_center.add_observer(self, name="SIPAccountRegistrationDidSucceed")
notification_center.add_observer(self, name="SIPAccountRegistrationDidFail")
notification_center.add_observer(self, name="SIPAccountRegistrationDidEnd")
notification_center.add_observer(self, name="SIPAccountRegistrationGotAnswer")
notification_center.add_observer(self, name="SIPAccountWillRegister")
notification_center.add_observer(self, name="SIPAccountChangedByICloud")
notification_center.add_observer(self, sender=AccountManager())
return self
@objc.python_method
def _NH_BlinkShouldTerminate(self, notification):
if self.window():
self.window().orderOut_(self)
def showWindow_(self, sender):
if not self.window():
NSBundle.loadNibNamed_owner_("PreferencesWindow", self)
self.addButton.setEnabled_(SIPManager().validateAddAccountAction())
self.buttonClicked_(self.advancedToggle)
self.window().setTitle_(NSLocalizedString("Accounts", "Window Title"))
self.accountTable.reloadData()
default_account = AccountManager().default_account
if default_account:
try:
row = self.accounts.index(default_account)
self.accountTable.selectRowIndexes_byExtendingSelection_(NSIndexSet.indexSetWithIndex_(row), False)
except ValueError:
pass
for view in list(self.settingViews.values()):
view.restore()
self.validateAddAccountButton()
NSApp.activateIgnoringOtherApps_(True)
NSWindowController.showWindow_(self, sender)
@objc.python_method
def validateAddAccountButton(self):
if self.addButton:
self.addButton.setEnabled_(SIPManager().validateAddAccountAction())
def close_(self, sender):
self.window().close()
def awakeFromNib(self):
if not self.accountTable:
return
NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, "userDefaultsDidChange:", "NSUserDefaultsDidChangeNotification", NSUserDefaults.standardUserDefaults())
dotPath = NSBezierPath.bezierPathWithOvalInRect_(NSMakeRect(2, 2, 8, 8))
self.dots = {}
for i, color in [("red", NSColor.redColor()), ("yellow", NSColor.yellowColor()), ("green", NSColor.greenColor())]:
dot = NSImage.alloc().initWithSize_(NSMakeSize(12,12))
dot.lockFocus()
color.set()
dotPath.fill()
dot.unlockFocus()
self.dots[i] = dot
if self.advancedTabView is not None:
self.tableViewSelectionDidChange_(None)
if self.accountTable:
self.accountTable.setDraggingSourceOperationMask_forLocal_(NSDragOperationGeneric, True)
self.accountTable.registerForDraggedTypes_(NSArray.arrayWithObject_("dragged-account"))
notification_center = NotificationCenter()
notification_center.add_observer(self, name="CFGSettingsObjectDidChange")
notification_center.add_observer(self, name="AudioDevicesDidChange")
notification_center.add_observer(self, name="VideoDevicesDidChange")
applicationName = NSApp.delegate().applicationNamePrint
self.window().setTitle_(NSLocalizedString("%s Preferences", "Window title") % applicationName)
self.toolbar.setSelectedItemIdentifier_('accounts')
if not NSApp.delegate().icloud_enabled:
self.sync_with_icloud_checkbox.setHidden_(True)
else:
major, minor = platform.mac_ver()[0].split('.')[0:2]
self.sync_with_icloud_checkbox.setHidden_(False if ((int(major) == 10 and int(minor) >= 7) or int(major) > 10) else True)
if not NSApp.delegate().recording_enabled:
PreferenceOptionTypes['audio.directory'] = HiddenOption
PreferenceOptionTypes['audio.auto_recording'] = HiddenOption
if not NSApp.delegate().file_logging_enabled:
PreferenceOptionTypes['logs.directory'] = HiddenOption
if not NSApp.delegate().history_enabled:
PreferenceOptionTypes['contacts.enable_incoming_calls_group'] = HiddenOption
PreferenceOptionTypes['contacts.enable_outgoing_calls_group'] = HiddenOption
PreferenceOptionTypes['contacts.enable_missed_calls_group'] = HiddenOption
if not NSApp.delegate().contactsWindowController.sessionControllersManager.isMediaTypeSupported('video'):
try:
item = next((item for item in self.toolbar.visibleItems() if item.itemIdentifier() == 'video'))
self.toolbar.removeItemAtIndex_(self.toolbar.visibleItems().index(item))
except StopIteration:
pass
if not NSApp.delegate().advanced_options_enabled:
for identifier in ('answering_machine', 'advanced'):
try:
item = next((item for item in self.toolbar.visibleItems() if item.itemIdentifier() == identifier))
self.toolbar.removeItemAtIndex_(self.toolbar.visibleItems().index(item))
except StopIteration:
pass
if not NSApp.delegate().answering_machine_enabled:
for identifier in ('answering_machine'):
try:
item = next((item for item in self.toolbar.visibleItems() if item.itemIdentifier() == identifier))
self.toolbar.removeItemAtIndex_(self.toolbar.visibleItems().index(item))
except StopIteration:
pass
self.userDefaultsDidChange_(None)
def userDefaultsDidChange_(self, notification):
icloud_sync_enabled = NSUserDefaults.standardUserDefaults().stringForKey_("iCloudSyncEnabled")
self.sync_with_icloud_checkbox.setState_(NSOnState if icloud_sync_enabled == 'Enabled' else NSOffState)
@objc.IBAction
def userClickedSelectedProxyRadioButton_(self, sender):
account_info = self.selectedAccount()
if account_info:
account = account_info.account
if sender.selectedCell().tag() == 0:
account.sip.outbound_proxy = account.sip.primary_proxy
account.sip.selected_proxy = 0
account.save()
elif sender.selectedCell().tag() == 1:
account.sip.outbound_proxy = account.sip.alternative_proxy
account.sip.selected_proxy = 1
account.save()
@objc.IBAction
@run_in_thread('file-io')
def userClickedPurgeLogsButton_(self, sender):
log_manager = FileLogger()
log_manager.stop()
for path, dirs, files in os.walk(os.path.join(ApplicationData.directory, 'logs'), topdown=False):
for name in files:
try:
os.remove(os.path.join(path, name))
except (OSError, IOError):
pass
for name in dirs:
try:
os.rmdir(os.path.join(path, name))
except (OSError, IOError):
pass
log_manager.start()
self._update_logs_size_label()
@objc.IBAction
def userClickedToolbarButton_(self, sender):
section_name = sender.itemIdentifier()
if section_name == 'advanced':
self.generalTabView.setTabViewType_(NSTopTabsBezelBorder)
self.createGeneralOptionsUI('advanced')
self.sectionHelpPlaceholder.setHidden_(False)
elif section_name != 'help':
self.createGeneralOptionsUI('basic')
self.generalTabView.setTabViewType_(NSNoTabsBezelBorder)
if section_name == 'accounts':
self.mainTabView.selectTabViewItemWithIdentifier_("accounts")
self.window().setTitle_(NSLocalizedString("Accounts", "Window title"))
self.sectionHelpPlaceholder.setHidden_(True)
elif section_name == 'audio':
self.mainTabView.selectTabViewItemWithIdentifier_("settings")
self.generalTabView.selectTabViewItemWithIdentifier_("audio")
self.sectionDescription.setStringValue_(NSLocalizedString("Audio Settings", "Label"))
self.sectionHelpPlaceholder.setHidden_(False)
settings = SIPSimpleSettings()
settings.audio.echo_canceller.enabled = settings.audio.enable_aec
settings.audio.sample_rate = 32000 if settings.audio.echo_canceller.enabled and settings.audio.sample_rate not in ('16000', '32000') else 48000
spectrum = settings.audio.sample_rate/1000/2 if settings.audio.sample_rate/1000/2 < 20 else 20
rate = settings.audio.sample_rate/1000
help_line = NSLocalizedString("Audio sample rate is set to %dkHz", "Preferences text label") % rate + NSLocalizedString(" covering 0-%dkHz spectrum", "Preferences text label") % spectrum
if spectrum >=20:
help_line += NSLocalizedString(".\nFor studio quality, disable the option 'Use ambient noise reduction' in System Preferences > Sound > Input section. ", "Preferences text label")
self.sectionHelpPlaceholder.setStringValue_(help_line)
self.window().setTitle_(NSLocalizedString("Audio", "Window title"))
elif section_name == 'video':
self.generalTabView.setTabViewType_(NSNoTabsNoBorder)
self.mainTabView.selectTabViewItemWithIdentifier_("settings")
self.generalTabView.selectTabViewItemWithIdentifier_("video")
self.sectionDescription.setStringValue_(NSLocalizedString("Video Settings", "Label"))
self.sectionHelpPlaceholder.setHidden_(False)
self.window().setTitle_(NSLocalizedString("Video", "Window title"))
elif section_name == 'answering_machine':
self.mainTabView.selectTabViewItemWithIdentifier_("settings")
self.generalTabView.selectTabViewItemWithIdentifier_("answering_machine")
self.sectionDescription.setStringValue_(NSLocalizedString("Answering Machine Settings", "Label"))
self.window().setTitle_(NSLocalizedString("Answering Machine", "Window title"))
self.sectionHelpPlaceholder.setStringValue_(NSLocalizedString("When enabled, Answering Machine will auto answer the call after the predefined delay", "Preferences placeholder text"))
elif section_name == 'chat':
self.mainTabView.selectTabViewItemWithIdentifier_("settings")
self.generalTabView.selectTabViewItemWithIdentifier_("chat")
self.sectionDescription.setStringValue_(NSLocalizedString("Chat Settings", "Label"))
self.window().setTitle_(NSLocalizedString("Chat", "Window title"))
self.sectionHelpPlaceholder.setStringValue_('')
elif section_name == 'file-transfer':
self.mainTabView.selectTabViewItemWithIdentifier_("settings")
self.generalTabView.selectTabViewItemWithIdentifier_("file_transfer")
self.sectionDescription.setStringValue_(NSLocalizedString("File Transfer Settings", "Label"))
self.window().setTitle_(NSLocalizedString("File Transfer", "Window title"))
self.sectionHelpPlaceholder.setStringValue_('')
elif section_name == 'screen-sharing':
self.mainTabView.selectTabViewItemWithIdentifier_("settings")
self.generalTabView.selectTabViewItemWithIdentifier_("screen_sharing_server")
self.sectionDescription.setStringValue_(NSLocalizedString("Screen Sharing Settings", "Label"))
self.window().setTitle_(NSLocalizedString("Screen Sharing", "Window title"))
self.sectionHelpPlaceholder.setHidden_(False)
self.sectionHelpPlaceholder.setStringValue_(NSLocalizedString("Enable Screen Sharing in System Preferences > Sharing section.\nClick on the 'Computer Settings...' button and check the option 'Anyone may request permission to control screen'", "Preferences help label"))
elif section_name == 'alerts':
self.mainTabView.selectTabViewItemWithIdentifier_("settings")
self.generalTabView.selectTabViewItemWithIdentifier_("sounds")
self.sectionDescription.setStringValue_(NSLocalizedString("Sound Alerts", "Label"))
self.window().setTitle_(NSLocalizedString("Alerts", "Window title"))
self.sectionHelpPlaceholder.setStringValue_('')
elif section_name == 'contacts':
self.mainTabView.selectTabViewItemWithIdentifier_("settings")
self.generalTabView.selectTabViewItemWithIdentifier_("contacts")
self.sectionDescription.setStringValue_(NSLocalizedString("Contacts Settings", "Label"))
self.window().setTitle_(NSLocalizedString("Contacts", "Window title"))
self.sectionHelpPlaceholder.setStringValue_('')
elif section_name == 'advanced':
self.sectionDescription.setStringValue_(NSLocalizedString("Advanced Settings", "Label"))
self.mainTabView.selectTabViewItemWithIdentifier_("settings")
self.window().setTitle_(NSLocalizedString("Advanced", "Window title"))
elif section_name == 'help':
self.window().setTitle_(NSLocalizedString("Help", "Window title"))
NSApp.delegate().contactsWindowController.showHelp('#preferences')
@objc.python_method
def createGeneralOptionsUI(self, type='basic'):
for i in range(self.generalTabView.numberOfTabViewItems()):
self.generalTabView.removeTabViewItem_(self.generalTabView.tabViewItemAtIndex_(0))
settings = SIPSimpleSettings()
sections = [section_name for section_name in dir(SIPSimpleSettings) if isinstance(getattr(SIPSimpleSettings, section_name, None), SettingsGroupMeta)]
frame = self.generalTabView.frame()
frame.origin.x = 0
frame.origin.y = 0
if type == 'advanced':
for section_name in AdvancedGeneralSectionOrder:
view = self.createViewForSection(settings, frame, section_name, getattr(SIPSimpleSettings, section_name))
tabItem = NSTabViewItem.alloc().initWithIdentifier_(section_name)
try:
label = SectionNames[section_name]
except KeyError:
label = formatName(section_name)
tabItem.setLabel_(label)
tabItem.setIdentifier_(section_name)
tabItem.setView_(view)
if section_name not in StaticPreferenceSections:
self.generalTabView.addTabViewItem_(tabItem)
elif type == 'basic':
for section in (section for section in sections if section not in DisabledPreferenceSections):
section_object = getattr(settings, section, None)
section_names = [section_name for section_name in dir(section_object.__class__) if isinstance(getattr(section_object.__class__, section_name, None), SettingsGroupMeta) and section_name not in DisabledPreferenceSections]
view = self.createViewForSection(settings, frame, section, getattr(SIPSimpleSettings, section))
tabItem = NSTabViewItem.alloc().initWithIdentifier_(section)
if section_names:
subsectionsTabView = NSTabView.alloc().init()
subsectionsTabView.setDelegate_(self)
tabItem.setView_(subsectionsTabView)
self.generalTabView.addTabViewItem_(tabItem)
tabItem = NSTabViewItem.alloc().initWithIdentifier_('General')
tabItem.setLabel_(NSLocalizedString("General", "Label"))
tabItem.setView_(view)
subsectionsTabView.addTabViewItem_(tabItem)
for section_name in section_names:
view = self.createViewForSection(settings, frame, section_name, getattr(section_object.__class__, section_name), section_object=getattr(section_object, section_name))
tabItem = NSTabViewItem.alloc().initWithIdentifier_(section_name)
try:
label = SectionNames[section_name]
except KeyError:
label = formatName(section_name)
tabItem.setLabel_(label)
tabItem.setView_(view)
subsectionsTabView.addTabViewItem_(tabItem)
elif section in StaticPreferenceSections:
try:
label = SectionNames[section]
except KeyError:
label = formatName(section)
tabItem.setLabel_(label)
tabItem.setView_(view)
self.generalTabView.addTabViewItem_(tabItem)
@objc.python_method
def createAccountOptionsUI(self, account):
self.advancedPop.removeAllItems()
for i in range(self.advancedTabView.numberOfTabViewItems()):
self.advancedTabView.removeTabViewItem_(self.advancedTabView.tabViewItemAtIndex_(0))
#sections = [section_name for section_name in dir(account.__class__) if isinstance(getattr(account.__class__, section_name, None), SettingsGroupMeta)]
sections = BonjourAccountSectionOrder if account is BonjourAccount() else AccountSectionOrder
frame = self.advancedTabView.frame()
for section_name in (section_name for section_name in sections if section_name not in DisabledAccountPreferenceSections):
if section_name in NSApp.delegate().hidden_account_preferences_sections:
continue
if NSApp.delegate().chat_replication_password_hidden:
PreferenceOptionTypes['chat.replication_password'] = HiddenOption
if not NSApp.delegate().icloud_enabled:
PreferenceOptionTypes['gui.sync_with_icloud'] = HiddenOption
try:
view = self.createViewForSection(account, frame, section_name, getattr(account.__class__, section_name))
except Exception:
import traceback
traceback.print_exc()
tabItem = NSTabViewItem.alloc().initWithIdentifier_(section_name)
try:
label = SectionNames[section_name]
except KeyError:
label = formatName(section_name)
self.advancedPop.addItemWithTitle_(label)
self.advancedPop.lastItem().setRepresentedObject_(section_name)
tabItem.setLabel_(label)
tabItem.setView_(view)
self.advancedTabView.addTabViewItem_(tabItem)
@objc.python_method
def createViewForSection(self, storage_object, frame, section_name, section_class, section_object=None):
if section_object is None:
section_object = getattr(storage_object, section_name)
forAccount = isinstance(storage_object, (Account, BonjourAccount))
section_view = NSScrollView.alloc().initWithFrame_(frame)
section_view.setDrawsBackground_(False)
section_view.setAutohidesScrollers_(True)
# we will need a scrollbar if the number of settings cause the box to become to high
e = True if section_name in ('rtp') else False
section_view.setHasVerticalScroller_(e)
section_view.setAutoresizingMask_(NSViewWidthSizable|NSViewHeightSizable)
settings_box_view = VerticalBoxView.alloc().initWithFrame_(frame)
settings_box_view.setAutoresizingMask_(NSViewWidthSizable|NSViewHeightSizable)
settings_box_view.setSpacing_(8)
settings_box_view.setBorderWidth_(8)
section_view.setDocumentView_(settings_box_view)
unordered_options = [opt for opt in dir(section_class) if isinstance(getattr(section_class, opt, None), Setting)]
#assert not [opt for opt in dir(section_class) if isinstance(getattr(section_class, opt, None), SettingsGroupMeta)]
try:
options = AccountSettingsOrder[section_name] if forAccount else GeneralSettingsOrder[section_name]
remaining_options = [opt for opt in unordered_options if opt not in options]
options.extend(remaining_options)
except KeyError:
options = unordered_options
if not NSApp.delegate().external_alert_enabled:
PreferenceOptionTypes['web_alert.alert_url'] = HiddenOption
if not NSApp.delegate().debug:
PreferenceOptionTypes['audio.sound_card_delay'] = HiddenOption
PreferenceOptionTypes['audio.sample_rate'] = HiddenOption
else:
PreferenceOptionTypes['audio.sound_card_delay'] = AecSliderOption
PreferenceOptionTypes['audio.sample_rate'] = SampleRateOption
for option_name in options:
if section_name == 'auth' and option_name == 'password':
continue
if option_name == 'video_codec_list' and not NSApp.delegate().contactsWindowController.sessionControllersManager.isMediaTypeSupported('video'):
continue
option = getattr(section_class, option_name, None)
if option is None:
continue
controlFactory = PreferenceOptionTypes.get(section_name + "." + option_name, None)
if not controlFactory:
controlFactory = None
if forAccount:
try:
controlFactory = PreferenceOptionTypes.get(option.type.__name__+":account", None)
except AttributeError:
pass
if not controlFactory:
try:
controlFactory = PreferenceOptionTypes.get(option.type.__name__, None)
except AttributeError:
pass
if not controlFactory:
print("Error: Option %s is not supported (while reading %s)" % (option, option_name))
controlFactory = PreferenceOptionTypes[str.__name__]
if controlFactory is HiddenOption:
continue
description_key = '%s.%s' % (section_name, option_name)
try:
description = SettingDescription[description_key]
except KeyError:
description = None
control = controlFactory(section_object, option_name, option, description)
try:
tooltip = ToolTips[description_key]
control.setTooltip(tooltip)
except KeyError:
pass
try:
placeholder = Placeholders[description_key]
control.setPlaceHolder(placeholder)
except KeyError:
pass
self.settingViews[section_name+"."+option_name] = control
settings_box_view.addSubview_(control)
control.delegate = self
control.owner = storage_object
control.restore()
return section_view
@objc.python_method
def optionDidChange(self, option):
self.saving = True
option.owner.save()
self.saving = False
@objc.python_method
def showOptionsForAccount(self, account):
self.updating = True
if account.display_name:
self.displayNameText.setStringValue_(account.display_name)
else:
self.displayNameText.setStringValue_("")
if account is not BonjourAccount():
self.addressText.setStringValue_(str(account.id))
self.passwordText.setStringValue_(account.auth.password)
userdef = NSUserDefaults.standardUserDefaults()
section = userdef.integerForKey_("SelectedAdvancedSection")
else:
userdef = NSUserDefaults.standardUserDefaults()
section = userdef.integerForKey_("SelectedAdvancedBonjourSection")
self.createAccountOptionsUI(account)
if section is not None and section >=0 and section < self.advancedPop.numberOfItems():
self.advancedPop.selectItemAtIndex_(section)
self.advancedTabView.selectTabViewItemAtIndex_(section)
self.updating = False
@objc.python_method
def addAccount(self):
enroll = EnrollmentController.alloc().init()
enroll.setupForAdditionalAccounts()
enroll.runModal()
@objc.python_method
def removeSelectedAccount(self):
account_info = self.selectedAccount()
if account_info:
account = account_info.account
text = NSLocalizedString("Permanently remove account %s?", "Label") % account_info.name
text = re.sub("%", "%%", text)
# http://stackoverflow.com/questions/4498709/problem-in-displaying-in-nsrunalertpanel
if NSRunAlertPanel(NSLocalizedString("Remove Account", "Button title"), text, NSLocalizedString("Remove", "Button title"), NSLocalizedString("Cancel", "Button title"), None) != NSAlertDefaultReturn:
return
account_manager = AccountManager()
if account_manager.default_account is account:
try:
account_manager.default_account = next((acc for acc in account_manager.iter_accounts() if acc is not account and acc.enabled))
except StopIteration:
account_manager.default_account = None
account.delete()
def controlTextDidEndEditing_(self, notification):
account_info = self.selectedAccount()
if account_info:
account = account_info.account
if notification.object() == self.displayNameText:
account.display_name = str(self.displayNameText.stringValue())
account.save()
elif notification.object() == self.passwordText:
account.auth.password = self.passwordText.stringValue()
account.save()
@objc.python_method
def selectedAccount(self):
if not self.accountTable:
return None
selected = self.accountTable.selectedRow()
if selected < 0:
return None
return self.getAccountForRow(selected)
@objc.python_method
def getAccountForRow(self, row):
return self.accounts[row]
@objc.python_method
def refresh_account_table(self):
if self.accountTable:
self.accountTable.reloadData()
@objc.python_method
def updateRegistrationStatus(self):
if self.registration_status:
selected_account = self.selectedAccount()
frame = self.registration_status.frame()
frame.origin.x = 330
self.registration_status.setFrame_(frame)
self.registration_status.setHidden_(True)
self.registration_tls_icon.setHidden_(True)
if selected_account:
if selected_account.register_failure_code and selected_account.register_failure_reason:
self.registration_status.setStringValue_(NSLocalizedString("Registration failed:", "Label") + " %s (%s)" % (selected_account.register_failure_reason, selected_account.register_failure_code))
self.registration_status.setHidden_(False)
elif selected_account.register_failure_reason:
self.registration_status.setStringValue_(NSLocalizedString("Registration failed:", "Label") + " " + selected_account.register_failure_reason)
self.registration_status.setHidden_(False)
else:
if selected_account.register_state and selected_account.register_state != NSLocalizedString("ended", "Label"):
if selected_account.registrar and selected_account.register_state == NSLocalizedString("succeeded", "Label"):
label = NSLocalizedString("Registration succeeded", "Label") + NSLocalizedString(" at %s", "Network address follows") % selected_account.registrar
self.registration_status.setStringValue_(label)
self.registration_tls_icon.setHidden_(False if selected_account.registrar.startswith('tls:') else True)
if selected_account.registrar.startswith('tls:'):
frame.origin.x = 312
self.registration_status.setFrame_(frame)
else:
self.registration_status.setStringValue_(NSLocalizedString("Registration %s", "Label") % selected_account.register_state)
self.registration_status.setHidden_(False)
@objc.python_method
@run_in_gui_thread
def handle_notification(self, notification):
handler = getattr(self, '_NH_%s' % notification.name, Null)
handler(notification)
@objc.python_method
def _NH_SIPAccountChangedByICloud(self, notification):
self.refresh_account_table()
if self.accountTable:
self.tableViewSelectionDidChange_(None)
self.validateAddAccountButton()
self.updateRegistrationStatus()
@objc.python_method
def _NH_SIPAccountManagerDidAddAccount(self, notification):
account = notification.data.account
self.accounts.insert(account.order, AccountInfo(account))
self.refresh_account_table()
if self.accountTable:
self.tableViewSelectionDidChange_(None)
self.validateAddAccountButton()
self.updateRegistrationStatus()
@objc.python_method
def _NH_SIPAccountManagerDidRemoveAccount(self, notification):
position = self.accounts.index(notification.data.account)
del self.accounts[position]
self.refresh_account_table()
if self.accountTable:
self.tableViewSelectionDidChange_(None)
self.validateAddAccountButton()
self.updateRegistrationStatus()
@objc.python_method
def _NH_SIPAccountDidDeactivate(self, notification):
try:
position = self.accounts.index(notification.sender)
except ValueError:
return
self.accounts[position].register_state = ''
self.accounts[position].register_failure_code = None
self.accounts[position].register_failure_reason = None
self.updateRegistrationStatus()
@objc.python_method
def _NH_SIPAccountWillRegister(self, notification):
try:
position = self.accounts.index(notification.sender)
except ValueError:
return
self.accounts[position].register_state = NSLocalizedString("started", "Label")
self.refresh_account_table()
self.updateRegistrationStatus()
@objc.python_method
def _NH_SIPAccountRegistrationDidSucceed(self, notification):
try:
position = self.accounts.index(notification.sender)
except ValueError:
return
self.accounts[position].register_state = NSLocalizedString("succeeded", "Label")
self.accounts[position].register_failure_code = None
self.accounts[position].register_failure_reason = None
self.refresh_account_table()
self.updateRegistrationStatus()
@objc.python_method
def _NH_SIPAccountRegistrationGotAnswer(self, notification):
try:
position = self.accounts.index(notification.sender)
except ValueError:
return
if notification.data.code > 200:
self.accounts[position].register_failure_code = notification.data.code
self.accounts[position].register_failure_reason = NSLocalizedString("Connection failed", "Error label") if notification.data.reason == 'Unknown error 61' else notification.data.reason.decode() if isinstance(notification.data.reason, bytes) else notification.data.reason
else:
self.accounts[position].register_failure_code = None
self.accounts[position].register_failure_reason = None
self.accounts[position].registrar = '%s:%s:%d' % (notification.data.registrar.transport, notification.data.registrar.address, notification.data.registrar.port)
self.updateRegistrationStatus()
@objc.python_method
def _NH_SIPAccountRegistrationDidFail(self, notification):
try:
position = self.accounts.index(notification.sender)
except ValueError:
return
self.accounts[position].register_state = NSLocalizedString("failed", "Label")
self.accounts[position].registrar = None
if self.accounts[position].register_failure_reason is None and hasattr(notification.data, 'error'):
self.accounts[position].register_failure_reason = NSLocalizedString("Connection failed", "Error label") if notification.data.error == 'Unknown error 61' else notification.data.error.decode() if isinstance(notification.data.error, bytes) else notification.data.error
self.refresh_account_table()
self.updateRegistrationStatus()
@objc.python_method
def _NH_SIPAccountRegistrationDidEnd(self, notification):
try:
position = self.accounts.index(notification.sender)
except ValueError:
return
self.accounts[position].register_state = NSLocalizedString("ended", "Label")
self.refresh_account_table()
self.updateRegistrationStatus()
_NH_BonjourAccountWillRegister = _NH_SIPAccountWillRegister
_NH_BonjourAccountRegistrationDidSucceed = _NH_SIPAccountRegistrationDidSucceed
_NH_BonjourAccountRegistrationDidFail = _NH_SIPAccountRegistrationDidFail
_NH_BonjourAccountRegistrationDidEnd = _NH_SIPAccountRegistrationDidEnd
@objc.python_method
def _NH_CFGSettingsObjectDidChange(self, notification):
sender = notification.sender
settings = SIPSimpleSettings()
if sender is settings:
if 'video.resolution' in notification.data.modified:
if settings.video.resolution == (640, 480):
settings.video.h264.level = "3.0"
elif settings.video.resolution == (1280, 720):
settings.video.h264.level = "3.1"
settings.save()
if not self.saving and sender in (settings, self.selectedAccount()):
for option in (o for o in notification.data.modified if o in self.settingViews):
self.settingViews[option].restore()
if 'display_name' in notification.data.modified:
self.displayNameText.setStringValue_(sender.display_name or '')
if 'logs.trace_pjsip_to_file' in notification.data.modified:
if settings.logs.trace_pjsip_to_file:
if not settings.logs.trace_pjsip:
settings.logs.trace_pjsip = True
settings.save()
else:
if settings.logs.trace_pjsip != settings.logs.trace_pjsip_in_gui:
settings.logs.trace_pjsip = settings.logs.trace_pjsip_in_gui
settings.save()
if 'audio.silent' in notification.data.modified:
try:
self.settingViews['audio.silent'].restore()
except KeyError:
pass
if 'ldap.transport' in notification.data.modified:
sender.ldap.port = 389 if sender.ldap.transport == 'tcp' else 636
sender.save()
if 'sip.primary_proxy' in notification.data.modified:
if not sender.sip.selected_proxy:
sender.sip.outbound_proxy = sender.sip.primary_proxy
sender.save()
if 'sip.register' in notification.data.modified and sender.sip.register is False:
try:
position = self.accounts.index(sender)
except ValueError:
pass
else:
self.accounts[position].register_state = ''
self.accounts[position].register_failure_code = None
self.accounts[position].register_failure_reason = None
if 'sip.alternative_proxy' in notification.data.modified:
account_info = self.selectedAccount()
if account_info:
account = account_info.account
if account == sender:
self.selected_proxy_radio_button.setEnabled_(True if account.sip.always_use_my_proxy and account.sip.alternative_proxy is not None else False)
if sender.sip.selected_proxy:
sender.sip.outbound_proxy = sender.sip.alternative_proxy
sender.save()
if 'ldap.port' in notification.data.modified:
if sender.ldap.port == 389 and sender.ldap.transport != 'tcp':
sender.ldap.transport = 'tcp'
sender.save()
elif sender.ldap.port == 636 and sender.ldap.transport != 'tls':
sender.ldap.transport = 'tls'
sender.save()
if 'rtp.encryption_type' in notification.data.modified:
if sender.rtp.encryption_type == '':
sender.rtp.encryption.enabled = False
elif sender.rtp.encryption_type == 'opportunistic':
sender.rtp.encryption.enabled = True
sender.rtp.encryption.key_negotiation = 'opportunistic'
elif sender.rtp.encryption_type == 'sdes_optional':
sender.rtp.encryption.enabled = True
sender.rtp.encryption.key_negotiation = 'sdes_optional'
elif sender.rtp.encryption_type == 'sdes_mandatory':
sender.rtp.encryption.enabled = True
sender.rtp.encryption.key_negotiation = 'sdes_mandatory'
elif sender.rtp.encryption_type == 'zrtp':
sender.rtp.encryption.enabled = True
sender.rtp.encryption.key_negotiation = 'zrtp'
sender.save()
if 'sip.always_use_my_proxy' in notification.data.modified:
account_info = self.selectedAccount()
if account_info:
account = account_info.account
if account == sender:
self.selected_proxy_radio_button.setEnabled_(True if account.sip.always_use_my_proxy and account.sip.alternative_proxy is not None else False)
if 'sip.selected_proxy' in notification.data.modified:
account_info = self.selectedAccount()
if account_info:
account = account_info.account
if account == sender:
self.selected_proxy_radio_button.selectCellWithTag_(sender.sip.selected_proxy)
if 'audio.sound_card_delay' in notification.data.modified:
settings = SIPSimpleSettings()
settings.audio.echo_canceller.tail_length = settings.audio.sound_card_delay
settings.save()
if 'audio.sample_rate' in notification.data.modified:
settings = SIPSimpleSettings()
spectrum = settings.audio.sample_rate/1000/2 if int(settings.audio.sample_rate)/1000/2 < 20 else 20
rate = settings.audio.sample_rate/1000
help_line = NSLocalizedString("Audio sample rate is set to %dkHz", "Preferences text label") % rate + NSLocalizedString(" covering 0-%dkHz spectrum", "Preferences text label") % spectrum
if spectrum >=20:
help_line += ".\n" + NSLocalizedString("For studio quality, disable the option 'Use ambient noise reduction' in System Preferences > Sound > Input section. ", "Label")
self.sectionHelpPlaceholder.setStringValue_(help_line)
if "audio.input_device" in notification.data.modified:
self.update_per_device_aec()
if "audio.output_device" in notification.data.modified:
self.update_per_device_aec()
if 'audio.enable_aec' in notification.data.modified:
settings = SIPSimpleSettings()
settings.audio.echo_canceller.enabled = settings.audio.enable_aec
new_sample_rate = 32000 if settings.audio.echo_canceller.enabled and settings.audio.sample_rate not in ('16000', '32000') else 48000
if not NSApp.delegate().contactsWindowController.has_audio:
settings.audio.sample_rate = new_sample_rate
settings.save()
else:
NSApp.delegate().contactsWindowController.new_audio_sample_rate = new_sample_rate
combined_audio_device = (settings.audio.input_device or "") + " " + (settings.audio.output_device or "")
data = {}
if settings.audio.per_device_aec is not None:
try:
data = json.loads(settings.audio.per_device_aec)
except (TypeError, json.decoder.JSONDecodeError) as e:
pass
data[combined_audio_device] = settings.audio.enable_aec
try:
encoded_data = json.dumps(data)
except (TypeError, ValueError) as e:
pass
else:
settings.audio.per_device_aec = encoded_data
settings.save()
if isinstance(sender, Account):
self.refresh_account_table()
self.updateRegistrationStatus()
@objc.python_method
def update_per_device_aec(self):
settings = SIPSimpleSettings()
combined_audio_device = (settings.audio.input_device or "") + " " + (settings.audio.output_device or "")
data = {}
if settings.audio.per_device_aec is not None:
try:
data = json.loads(settings.audio.per_device_aec)
except (TypeError, ValueError) as e:
pass
try:
per_device_aec = data[combined_audio_device]
except KeyError:
data[combined_audio_device] = settings.audio.enable_aec
try:
encoded_data = json.dumps(data)
except (TypeError, ValueError) as e:
pass
else:
settings.audio.per_device_aec = encoded_data
settings.save()
else:
if per_device_aec != settings.audio.enable_aec:
print("Changing AEC to %s" % per_device_aec)
settings.audio.enable_aec = per_device_aec
settings.save()
@objc.python_method
def _NH_BlinkTransportFailed(self, notification):
self.refresh_account_table()
self.updateRegistrationStatus()
@objc.python_method
def _NH_AudioDevicesDidChange(self, notification):
self.updateAudioDevices_(None)
@objc.python_method
def _NH_VideoDevicesDidChange(self, notification):