Repository navigation
Expand file tree
/
Copy pathDebugWindow.py
More file actions
1857 lines (1640 loc) · 91.7 KB
/
Copy pathDebugWindow.py
File metadata and controls
1857 lines (1640 loc) · 91.7 KB
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-2026 AG Projects. See LICENSE for details.
#
from AppKit import (NSFontAttributeName,
NSForegroundColorAttributeName,
NSOnState,
NSOffState)
from Foundation import (NSAttributedString,
NSTimer,
NSBundle,
NSColor,
NSDictionary,
NSFont,
NSMakeRange,
NSMutableAttributedString,
NSNotFound,
NSNotificationCenter,
NSObject,
NSString
)
import objc
from datetime import datetime
import threading
from application.notification import NotificationCenter, IObserver
from application.python import Null
from zope.interface import implementer
from BlinkLogger import BlinkLogger
from sipsimple.configuration.settings import SIPSimpleSettings
from util import log_gui_exception, run_in_gui_thread, format_size
from SessionInfoController import ice_candidates
# User choices for debug: Disabled, Simplified, Full
#
class Disabled(int):
def __new__(cls):
return int.__new__(cls, 1)
def __eq__(self, value):
return value==0 or value==1
def __ne__(self, value):
return value!=0 and value!=1
def __repr__(self):
return self.__class__.__name__
class Simplified(int):
def __new__(cls):
return int.__new__(cls, 2)
def __repr__(self):
return self.__class__.__name__
class Full(int):
def __new__(cls):
return int.__new__(cls, 3)
def __repr__(self):
return self.__class__.__name__
Disabled = Disabled()
Simplified = Simplified()
Full = Full()
@implementer(IObserver)
class DebugWindow(NSObject):
window = objc.IBOutlet()
tabView = objc.IBOutlet()
activityTextView = objc.IBOutlet()
sipTextView = objc.IBOutlet()
rtpTextView = objc.IBOutlet()
msrpTextView = objc.IBOutlet()
xcapTextView = objc.IBOutlet()
notificationsTextView = objc.IBOutlet()
pjsipTextView = objc.IBOutlet()
activityInfoLabel = objc.IBOutlet()
sipInfoLabel = objc.IBOutlet()
msrpInfoLabel = objc.IBOutlet()
rtpInfoLabel = objc.IBOutlet()
xcapInfoLabel = objc.IBOutlet()
notificationsInfoLabel = objc.IBOutlet()
pjsipInfoLabel = objc.IBOutlet()
filterSipApplication = objc.IBOutlet()
autoScrollCheckbox = objc.IBOutlet()
sipInCount = 0
sipOutCount = 0
sipBytes = 0
msrpInCount = 0
msrpOutCount = 0
msrpBytes = 0
pjsipCount = 0
pjsipBytes = 0
notificationsBytes = 0
filterNotificationsSearchBox = objc.IBOutlet()
sipRadio = objc.IBOutlet()
msrpRadio = objc.IBOutlet()
xcapRadio = objc.IBOutlet()
notificationsCheckBox = objc.IBOutlet()
pjsipCheckBox = objc.IBOutlet()
notifications = []
notifications_unfiltered = []
lastSIPMessageWasDNS = False
_siptrace_start_time = None
_siptrace_packet_count = 0
filter_sip_application = None
filter_sip_methods = {
'PUBLISH': ['subscriptions'],
'NOTIFY': ['subscriptions'],
'SUBSCRIBE': ['subscriptions'],
'REGISTER': ['sessions', 'register'],
'INVITE': ['sessions'],
'BYE': ['sessions'],
'CANCEL': ['sessions'],
'ACK': ['sessions'],
'PRACK': ['sessions'],
'REFER': ['sessions'],
'MESSAGE': ['messages'],
'UPDATE': ['sessions']
}
normalText = NSDictionary.dictionaryWithObject_forKey_(NSColor.controlTextColor(), NSForegroundColorAttributeName)
boldTextAttribs = NSDictionary.dictionaryWithObjectsAndKeys_(NSFont.boldSystemFontOfSize_(NSFont.systemFontSize()), NSFontAttributeName, NSColor.controlTextColor(), NSForegroundColorAttributeName)
boldRedTextAttribs = NSDictionary.dictionaryWithObjectsAndKeys_(NSFont.boldSystemFontOfSize_(NSFont.systemFontSize()), NSFontAttributeName, NSColor.redColor(), NSForegroundColorAttributeName)
newline = NSAttributedString.alloc().initWithString_("\n")
receivedText = NSAttributedString.alloc().initWithString_attributes_("RECEIVED:", NSDictionary.dictionaryWithObject_forKey_(NSColor.blueColor(), NSForegroundColorAttributeName))
sendingText = NSAttributedString.alloc().initWithString_attributes_("SENDING:", NSDictionary.dictionaryWithObject_forKey_(NSColor.orangeColor(), NSForegroundColorAttributeName))
def init(self):
self = objc.super(DebugWindow, self).init()
NSBundle.loadNibNamed_owner_("DebugWindow", self)
for textView in [self.activityTextView, self.sipTextView, self.rtpTextView, self.msrpTextView, self.xcapTextView, self.pjsipTextView]:
textView.setString_("")
# Touching layoutManager() drops the view to TextKit 1, where
# non-contiguous layout lets us scroll to the end of a large
# log without laying out everything before it.
textView.layoutManager().setAllowsNonContiguousLayout_(True)
for label in [self.activityInfoLabel, self.sipInfoLabel, self.rtpInfoLabel, self.msrpInfoLabel, self.xcapInfoLabel, self.notificationsInfoLabel, self.pjsipInfoLabel]:
label.setStringValue_('')
# Become the window's delegate so we get windowWillClose_ and can
# detach BlinkLogger.gui_logger when the panel goes off-screen.
# Without this, every log_info would still post a run_in_gui_thread
# block to append to the (invisible) NSTextView — exactly the
# over-scheduling that turns a journal-sync burst into a beachball.
self.window.setDelegate_(self)
# Don't attach to BlinkLogger yet. The DebugWindow object is
# created eagerly at app launch (BlinkAppDelegate.init), but the
# user typically never opens the Activity panel during a normal
# session. Stay detached — log lines accumulate cheaply in the
# backlog buffer — and only attach when the panel is shown.
BlinkLogger().detach_gui_logger()
settings = SIPSimpleSettings()
# Lightweight session-related observers stay attached for the
# life of the app — they fire rarely and feed RTP / quality
# tracking state. The high-frequency *trace* observers
# (SIPEngineSIPTrace, SIPEngineLog, MSRPLibraryLog,
# MSRPTransportTrace) are deliberately NOT registered here.
# Each SIP/MSRP packet triggers _NH_SIPEngineSIPTrace etc. which
# appends to a (possibly hidden) NSTextView on the GUI thread —
# 7%+ of total CPU during startup per a py-spy profile. We
# attach those only while the panel is visible (show() /
# windowWillClose_) so a closed Activity / Trace tab pays no
# main-thread cost. The on-disk sip_trace.txt / pjsip_trace.txt
# files keep capturing every packet regardless via FileLogger.
notification_center = NotificationCenter()
notification_center.add_observer(self, name="CFGSettingsObjectDidChange")
notification_center.add_observer(self, name="SIPSessionDidStart")
notification_center.add_observer(self, name="SIPSessionDidRenegotiateStreams")
notification_center.add_observer(self, name="AudioSessionHasQualityIssues")
notification_center.add_observer(self, name="AudioSessionQualityRestored")
# Software echo canceller statistics, posted by AudioController every
# 10 s while a call is connected and once at the end of the call.
notification_center.add_observer(self, name="BlinkAudioEchoCancellerStatistics")
notification_center.add_observer(self, name="RTPStreamICENegotiationDidSucceed")
notification_center.add_observer(self, name="RTPStreamICENegotiationDidFail")
notification_center.add_observer(self, name="RTPStreamICENegotiationStateDidChange")
# ZRTP negotiation traces — logged into the RTP tab alongside ICE.
notification_center.add_observer(self, name="RTPStreamDidEnableEncryption")
notification_center.add_observer(self, name="RTPStreamDidNotEnableEncryption")
notification_center.add_observer(self, name="RTPStreamZRTPReceivedSAS")
notification_center.add_observer(self, name="RTPStreamZRTPVerifiedStateChanged")
notification_center.add_observer(self, name="RTPStreamZRTPLog")
notification_center.add_observer(self, name="RTPStreamZRTPPeerNameChanged")
# Sylk-ZRTP-over-MESSAGE (X25519+HKDF on top of SRTP/SDES) state
# transitions. The SDK posts these on the sipsimple Session for
# every (probing → key-agreed → key-active) edge so the RTP debug
# window can tell the user the layered E2E encryption is up,
# alongside the regular SRTP/ZRTP lines that come from the
# underlying transport.
notification_center.add_observer(self, name="SIPSessionSylkZRTPStateChanged")
# Tracks whether the high-frequency trace observers are
# currently attached. show() flips this on, windowWillClose_
# flips it off; both are idempotent thanks to add_observer /
# discard_observer being idempotent themselves.
self._trace_observers_attached = False
if settings.logs.trace_notifications_in_gui:
notification_center.add_observer(self)
self.sipRadio.selectCellWithTag_(settings.logs.trace_sip_in_gui or Disabled)
self.msrpRadio.selectCellWithTag_(settings.logs.trace_msrp_in_gui or Disabled)
self.xcapRadio.selectCellWithTag_(settings.logs.trace_xcap_in_gui or Disabled)
self.pjsipCheckBox.setState_(NSOnState if settings.logs.trace_pjsip_in_gui else NSOffState)
self.notificationsCheckBox.setState_(NSOnState if settings.logs.trace_notifications_in_gui else NSOffState)
return self
@objc.python_method
def _attach_trace_observers(self):
"""Subscribe to the per-packet trace notifications so the
SIP / MSRP / pjsip tabs render live data while visible.
DNSLookupTrace is also re-added when the SIP-trace radio is
Simplified / Full — the radio handler (syncSIPtrace) is what
normally flips it on, but we have to honour the persisted
radio state when the panel re-opens after being hidden.
"""
if self._trace_observers_attached:
return
nc = NotificationCenter()
nc.add_observer(self, name="SIPEngineSIPTrace")
nc.add_observer(self, name="SIPEngineLog")
nc.add_observer(self, name="MSRPLibraryLog")
nc.add_observer(self, name="MSRPTransportTrace")
if SIPSimpleSettings().logs.trace_sip_in_gui != Disabled:
nc.add_observer(self, name="DNSLookupTrace")
self._trace_observers_attached = True
@objc.python_method
def _detach_trace_observers(self):
"""Unsubscribe from per-packet trace notifications when the
panel goes off-screen so the GUI thread isn't doing live
rendering work no one can see."""
if not self._trace_observers_attached:
return
nc = NotificationCenter()
nc.discard_observer(self, name="SIPEngineSIPTrace")
nc.discard_observer(self, name="SIPEngineLog")
nc.discard_observer(self, name="MSRPLibraryLog")
nc.discard_observer(self, name="MSRPTransportTrace")
nc.discard_observer(self, name="DNSLookupTrace")
self._trace_observers_attached = False
def show(self):
# Re-attach to BlinkLogger so live activity flows back into the
# NSTextView. set_gui_logger flushes any backlog accumulated
# while the panel was hidden.
BlinkLogger().set_gui_logger(self.renderActivity)
# Re-arm the per-packet trace observers so the SIP / MSRP /
# pjsip tabs update in real time again.
self._attach_trace_observers()
self.window.makeKeyAndOrderFront_(self)
# Catch up on scrolls skipped while the window was hidden.
self._flushPendingScrolls()
def close_(self, sender):
self.window.close()
def windowWillClose_(self, notification):
# Detach so we stop scheduling run_in_gui_thread NSTextView
# appends for log lines no one can see. activity.txt continues
# to capture every line regardless.
BlinkLogger().detach_gui_logger()
# And stop processing per-packet SIP/MSRP/pjsip traces — those
# ran unconditionally before, contributing ~7% of CPU during
# startup according to py-spy. The on-disk sip_trace.txt /
# pjsip_trace.txt files are still being written by FileLogger.
self._detach_trace_observers()
def tabView_didSelectTabViewItem_(self, tabView, item):
pass
def numberOfRowsInTableView_(self, table):
try:
return len(self.notifications)
except Exception:
log_gui_exception('the notifications row count')
return 0
def tableView_objectValueForTableColumn_row_(self, table, column, row):
try:
return self.notifications[row][int(column.identifier())]
except Exception:
log_gui_exception('the notifications data source (row %s)' % row)
return None
@objc.IBAction
def notificationsCheckboxClicked_(self, sender):
settings = SIPSimpleSettings()
settings.logs.trace_notifications_in_gui = bool(sender.state())
settings.logs.trace_notifications = settings.logs.trace_notifications_in_gui or settings.logs.trace_notifications_to_file
settings.save()
notification_center = NotificationCenter()
if settings.logs.trace_notifications_in_gui:
notification_center.add_observer(self)
else:
notification_center.discard_observer(self)
@objc.IBAction
def engineCheckboxClicked_(self, sender):
settings = SIPSimpleSettings()
settings.logs.trace_pjsip_in_gui = bool(sender.state())
settings.logs.trace_pjsip = settings.logs.trace_pjsip_in_gui or settings.logs.trace_pjsip_to_file
settings.save()
@objc.IBAction
def sipRadioClicked_(self, sender):
self.syncSIPtrace(sender.selectedCell().tag())
@objc.python_method
def syncSIPtrace(self, trace):
settings = SIPSimpleSettings()
notification_center = NotificationCenter()
settings.logs.trace_sip_in_gui = trace
self.sipRadio.selectCellWithTag_(settings.logs.trace_sip_in_gui)
if trace == Disabled:
notification_center.discard_observer(self, name="DNSLookupTrace")
settings.logs.trace_sip = settings.logs.trace_sip_to_file
elif trace == Simplified:
notification_center.add_observer(self, name="DNSLookupTrace")
settings.logs.trace_sip = True
elif trace == Full:
notification_center.add_observer(self, name="DNSLookupTrace")
settings.logs.trace_sip = True
settings.save()
@objc.IBAction
def msrpRadioClicked_(self, sender):
trace = sender.selectedCell().tag()
settings = SIPSimpleSettings()
settings.logs.trace_msrp_in_gui = trace
if trace == Disabled:
settings.logs.trace_msrp = settings.logs.trace_msrp_to_file
elif trace == Simplified:
settings.logs.trace_msrp = True
elif trace == Full:
settings.logs.trace_msrp = True
settings.save()
@objc.IBAction
def xcapRadioClicked_(self, sender):
notification_center = NotificationCenter()
trace = sender.selectedCell().tag()
settings = SIPSimpleSettings()
settings.logs.trace_xcap_in_gui = trace
if trace == Disabled:
notification_center.discard_observer(self, name="XCAPManagerDidDiscoverServerCapabilities")
notification_center.discard_observer(self, name="XCAPManagerDidChangeState")
notification_center.discard_observer(self, name="XCAPManagerDidStart")
notification_center.discard_observer(self, name="XCAPManagerDidDiscoverServerCapabilities")
notification_center.discard_observer(self, name="XCAPManagerDidReloadData")
notification_center.discard_observer(self, name="XCAPManagerDidInitialize")
notification_center.discard_observer(self, name="XCAPManagerDidAddContact")
notification_center.discard_observer(self, name="XCAPManagerDidUpdateContact")
notification_center.discard_observer(self, name="XCAPManagerDidDeleteContact")
notification_center.discard_observer(self, name="XCAPManagerDidAddGroup")
notification_center.discard_observer(self, name="XCAPManagerDidUpdateGroup")
notification_center.discard_observer(self, name="XCAPManagerDidRemoveGroup")
notification_center.discard_observer(self, name="XCAPManagerDidAddGroup")
notification_center.discard_observer(self, name="XCAPManageDidAddGroupMember")
notification_center.discard_observer(self, name="XCAPManageDidRemoveGroupMember")
notification_center.discard_observer(self, name="XCAPManagerClientWillInitialize")
notification_center.discard_observer(self, name="XCAPManagerClientDidInitialize")
notification_center.discard_observer(self, name="XCAPManagerClientDidNotInitialize")
notification_center.discard_observer(self, name="XCAPManagerClientError")
notification_center.discard_observer(self, name="XCAPDocumentsDidChange")
notification_center.discard_observer(self, name="XCAPTrace")
settings.logs.trace_xcap = settings.logs.trace_xcap_to_file
elif trace == Simplified:
notification_center.add_observer(self, name="XCAPManagerDidDiscoverServerCapabilities")
notification_center.add_observer(self, name="XCAPManagerDidChangeState")
notification_center.add_observer(self, name="XCAPManagerClientWillInitialize")
notification_center.add_observer(self, name="XCAPManagerClientDidInitialize")
notification_center.add_observer(self, name="XCAPManagerClientDidNotInitialize")
notification_center.add_observer(self, name="XCAPManagerDidStart")
notification_center.add_observer(self, name="XCAPManagerClientError")
notification_center.add_observer(self, name="XCAPDocumentsDidChange")
notification_center.discard_observer(self, name="XCAPManagerDidAddContact")
notification_center.discard_observer(self, name="XCAPManagerDidUpdateContact")
notification_center.discard_observer(self, name="XCAPManagerDidDeleteContact")
notification_center.discard_observer(self, name="XCAPManagerDidAddGroup")
notification_center.discard_observer(self, name="XCAPManagerDidUpdateGroup")
notification_center.discard_observer(self, name="XCAPManagerDidRemoveGroup")
notification_center.discard_observer(self, name="XCAPManagerDidAddGroup")
notification_center.discard_observer(self, name="XCAPManageDidAddGroupMember")
notification_center.discard_observer(self, name="XCAPManageDidRemoveGroupMember")
notification_center.discard_observer(self, name="XCAPTrace")
settings.logs.trace_xcap = True
elif trace == Full:
notification_center.add_observer(self, name="XCAPManagerDidDiscoverServerCapabilities")
notification_center.add_observer(self, name="XCAPManagerDidChangeState")
notification_center.add_observer(self, name="XCAPManagerDidStart")
notification_center.add_observer(self, name="XCAPManagerDidReloadData")
notification_center.add_observer(self, name="XCAPManagerDidInitialize")
notification_center.add_observer(self, name="XCAPManagerClientWillInitialize")
notification_center.add_observer(self, name="XCAPManagerClientDidInitialize")
notification_center.add_observer(self, name="XCAPManagerClientDidNotInitialize")
notification_center.add_observer(self, name="XCAPManagerClientError")
notification_center.add_observer(self, name="XCAPDocumentsDidChange")
notification_center.add_observer(self, name="XCAPManagerDidAddContact")
notification_center.add_observer(self, name="XCAPManagerDidUpdateContact")
notification_center.add_observer(self, name="XCAPManagerDidDeleteContact")
notification_center.add_observer(self, name="XCAPManagerDidAddGroup")
notification_center.add_observer(self, name="XCAPManagerDidUpdateGroup")
notification_center.add_observer(self, name="XCAPManagerDidRemoveGroup")
notification_center.add_observer(self, name="XCAPManagerDidAddGroup")
notification_center.add_observer(self, name="XCAPManageDidAddGroupMember")
notification_center.add_observer(self, name="XCAPManageDidRemoveGroupMember")
notification_center.add_observer(self, name="XCAPTrace")
settings.logs.trace_xcap = True
settings.save()
@objc.IBAction
def filterSipApplicationClicked_(self, sender):
tag = sender.selectedItem().tag()
self.filter_sip_application = None
if tag == 1:
self.filter_sip_application = 'sessions'
elif tag == 2:
self.filter_sip_application = 'subscriptions'
elif tag == 3:
self.filter_sip_application = 'register'
elif tag == 4:
self.filter_sip_application = 'messages'
@objc.IBAction
def clearClicked_(self, sender):
if sender.tag() == 100:
self.activityTextView.textStorage().deleteCharactersInRange_(NSMakeRange(0, self.activityTextView.textStorage().length()))
elif sender.tag() == 101:
self.sipTextView.textStorage().deleteCharactersInRange_(NSMakeRange(0, self.sipTextView.textStorage().length()))
self.sipInCount = 0
self.sipOutCount = 0
self.sipBytes = 0
self.sipInfoLabel.setStringValue_('')
elif sender.tag() == 102:
self.rtpTextView.textStorage().deleteCharactersInRange_(NSMakeRange(0, self.rtpTextView.textStorage().length()))
elif sender.tag() == 104:
self.msrpInCount = 0
self.msrpOutCount = 0
self.msrpBytes = 0
self.msrpInfoLabel.setStringValue_('')
self.msrpTextView.textStorage().deleteCharactersInRange_(NSMakeRange(0, self.msrpTextView.textStorage().length()))
elif sender.tag() == 105:
self.xcapTextView.textStorage().deleteCharactersInRange_(NSMakeRange(0, self.xcapTextView.textStorage().length()))
elif sender.tag() == 103:
self.notifications = []
self.notifications_unfiltered = []
self.notificationsBytes = 0
self.notificationsTextView.reloadData()
self.notificationsInfoLabel.setStringValue_('')
elif sender.tag() == 107:
self.pjsipCount = 0
self.pjsipBytes = 0
self.pjsipInfoLabel.setStringValue_('')
self.pjsipTextView.textStorage().deleteCharactersInRange_(NSMakeRange(0, self.pjsipTextView.textStorage().length()))
@objc.IBAction
def searchNotifications_(self, sender):
self.renderNotifications()
def renderNotifications(self):
text = str(self.filterNotificationsSearchBox.stringValue().strip().lower())
self.notifications = [notification for notification in self.notifications_unfiltered if text in notification[0].lower()] if text else self.notifications_unfiltered
self.notificationsTextView.noteNumberOfRowsChanged()
self.notificationsTextView.scrollRowToVisible_(len(self.notifications)-1)
self.notificationsInfoLabel.setStringValue_('%d notifications, %sytes' % (len(self.notifications), format_size(self.notificationsBytes)) if not text else '%d notifications matched' % len(self.notifications))
def dealloc(self):
# Observers added in init
NSNotificationCenter.defaultCenter().removeObserver_(self)
notification_center = NotificationCenter()
notification_center.discard_observer(self, name="SIPSessionDidStart")
notification_center.discard_observer(self, name="SIPSessionDidRenegotiateStreams")
notification_center.discard_observer(self, name="AudioSessionHasQualityIssues")
notification_center.discard_observer(self, name="AudioSessionQualityRestored")
notification_center.discard_observer(self, name="RTPStreamICENegotiationDidSucceed")
notification_center.discard_observer(self, name="RTPStreamICENegotiationDidFail")
notification_center.discard_observer(self, name="RTPStreamICENegotiationStateDidChange")
notification_center.discard_observer(self, name="RTPStreamDidEnableEncryption")
notification_center.discard_observer(self, name="RTPStreamDidNotEnableEncryption")
notification_center.discard_observer(self, name="RTPStreamZRTPReceivedSAS")
notification_center.discard_observer(self, name="RTPStreamZRTPVerifiedStateChanged")
notification_center.discard_observer(self, name="RTPStreamZRTPLog")
notification_center.discard_observer(self, name="RTPStreamZRTPPeerNameChanged")
# Observers added when settings change
notification_center.discard_observer(self, name="SIPEngineSIPTrace")
notification_center.discard_observer(self, name="DNSLookupTrace")
notification_center.discard_observer(self, name="MSRPLibraryLog")
notification_center.discard_observer(self, name="MSRPTransportTrace")
notification_center.discard_observer(self, name="XCAPManagerDidDiscoverServerCapabilities")
notification_center.discard_observer(self, name="XCAPManagerDidChangeState")
notification_center.discard_observer(self, name="SIPEngineLog")
notification_center.discard_observer(self)
objc.super(DebugWindow, self).dealloc()
# Bound on how much text each log view keeps. The panel stays alive for
# the whole app lifetime and some tabs (RTP/ZRTP) are fed even while it
# is hidden, so without a cap a long-running Blink ends up with a text
# storage of hundreds of MB.
LOG_VIEW_MAX_CHARS = 2000000
SCROLL_COALESCE_INTERVAL = 0.2
@objc.python_method
def _trimLogView(self, textView):
storage = textView.textStorage()
length = storage.length()
if length <= self.LOG_VIEW_MAX_CHARS:
return
cut = length - int(self.LOG_VIEW_MAX_CHARS * 0.8)
# Cut on a line boundary so the first visible line is whole.
text = storage.string()
text = text.nsstring() if hasattr(text, 'nsstring') else text
nl = text.rangeOfString_options_range_("\n", 0, NSMakeRange(cut, min(4096, length - cut)))
if nl.location != NSNotFound:
cut = nl.location + 1
storage.deleteCharactersInRange_(NSMakeRange(0, cut))
@objc.python_method
def _scrollToEnd(self, textView):
"""Trim and schedule a coalesced scroll-to-end for textView.
scrollRangeToVisible_ on a TextKit 2 NSTextView forces layout to be
ensured from the document start (O(text size)); calling it once per
appended line from handle_notification made the main thread spend
~95% of its time in -[NSTextLayoutManager ensureLayoutForRange:]
once the logs grew large. Now: at most one scroll per view per
SCROLL_COALESCE_INTERVAL, and none at all while the window is
hidden (show() scrolls once on re-open).
"""
self._trimLogView(textView)
if self.autoScrollCheckbox.state() != NSOnState:
return
try:
pending = self._pending_scrolls
except AttributeError:
pending = self._pending_scrolls = set()
pending.add(textView)
if not self.window.isVisible():
return
if getattr(self, '_scroll_flush_scheduled', False):
return
self._scroll_flush_scheduled = True
NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
self.SCROLL_COALESCE_INTERVAL, self, "scrollFlushTimer:", None, False)
def scrollFlushTimer_(self, timer):
self._scroll_flush_scheduled = False
self._flushPendingScrolls()
@objc.python_method
def _flushPendingScrolls(self):
try:
pending = self._pending_scrolls
except AttributeError:
return
self._pending_scrolls = set()
if self.autoScrollCheckbox.state() != NSOnState:
return
for textView in pending:
length = textView.textStorage().length()
if length:
textView.scrollRangeToVisible_(NSMakeRange(length - 1, 1))
@objc.python_method
def append_line(self, textView, line):
if isinstance(line, NSAttributedString):
textView.textStorage().appendAttributedString_(line)
else:
textView.textStorage().appendAttributedString_(NSAttributedString.alloc().initWithString_attributes_(line+"\n", self.normalText))
self._scrollToEnd(textView)
@objc.python_method
def append_error_line(self, textView, line):
red = NSDictionary.dictionaryWithObject_forKey_(NSColor.redColor(), NSForegroundColorAttributeName)
textView.textStorage().appendAttributedString_(NSAttributedString.alloc().initWithString_attributes_(line+"\n", red))
self._scrollToEnd(textView)
# Patterns matched against the un-timestamped activity message to
# decide whether the line ALSO belongs in the RTP tab. Anything
# matching is appended to both activityTextView (general log) and
# rtpTextView (RTP tab) so a user looking at the RTP panel sees the
# full negotiation round-trip (offered codecs, encryption setting,
# stream-established lines with selected codec, ICE / encryption
# status, remote video size and aspect changes) without having to
# cross-reference the activity log. The matcher runs once per
# message; literal substrings are cheap and there's no per-call
# priority order to maintain.
_RTP_LOG_SUBSTRINGS = (
# Proposal / configuration (one per outgoing session)
"Proposed media:",
"Proposed audio codecs:",
"Proposed video codecs:",
"Proposed video options:",
"Account RTP encryption:",
# Stream-start lifecycle
"MediaStreamDidStart",
"MediaStreamDidEnd",
"Audio stream established",
"Audio stream ended",
"Video stream established",
"Video stream ended",
"Video channel received data",
# Codec details
"Video codec negotiated:",
"Video codec fmtp:",
# Encryption outcomes
"RTP encryption:", # our new verbose form
"SRTP/SDES audio encryption active",
"SRTP/SDES video encryption active",
"ZRTP audio encryption active",
"ZRTP video encryption active",
# ICE outcomes
"ICE negotiation",
# Remote-side stream descriptors
"Remote video stream at",
"Remote aspect ratio is",
)
# Activity lines are buffered and flushed in batches. This used to be
# @run_in_gui_thread, i.e. one main-thread dispatch AND one NSTextView
# edit (plus a scrollRangeToVisible) per log line. A journal sync emits
# thousands of lines in a burst -- "Remove message ..." alone can be
# hundreds -- and that is enough to beachball the app all by itself.
# Buffering turns N dispatches into one flush per FLUSH_INTERVAL.
ACTIVITY_FLUSH_INTERVAL = 0.15
ACTIVITY_BUFFER_LIMIT = 4000
@objc.python_method
def _activityBuffer(self):
try:
return self._activity_lines
except AttributeError:
self._activity_lines = []
self._activity_buffer_lock = threading.Lock()
self._activity_flush_scheduled = False
self._activity_dropped = 0
return self._activity_lines
@objc.python_method
def renderActivity(self, text):
try:
iserror = text.lower().startswith("error")
except (TypeError, AttributeError) as e:
return
# Decide whether this line ALSO belongs in the RTP tab BEFORE
# prepending the timestamp - the substring check is cheaper
# against the raw message and avoids accidentally matching a
# message that happens to share characters with the timestamp.
rtp_mirror = False
try:
for needle in self._RTP_LOG_SUBSTRINGS:
if needle in text:
rtp_mirror = True
break
except (TypeError, AttributeError):
rtp_mirror = False
text = "%s %s"%(datetime.now().replace(microsecond=0), text)
self._activityBuffer()
with self._activity_buffer_lock:
if len(self._activity_lines) >= self.ACTIVITY_BUFFER_LIMIT:
# Never grow without bound: a burst that outruns the flush
# would otherwise turn a slow panel into a memory problem.
self._activity_dropped += 1
return
self._activity_lines.append((text, iserror, rtp_mirror))
already_scheduled = self._activity_flush_scheduled
self._activity_flush_scheduled = True
if not already_scheduled:
self.scheduleActivityFlush()
return
@objc.python_method
@run_in_gui_thread
def scheduleActivityFlush(self):
NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
self.ACTIVITY_FLUSH_INTERVAL, self, "activityFlushTimer:", None, False)
def activityFlushTimer_(self, timer):
self._activityBuffer()
with self._activity_buffer_lock:
lines = self._activity_lines
dropped = self._activity_dropped
self._activity_lines = []
self._activity_dropped = 0
self._activity_flush_scheduled = False
if not lines:
return
# Collapse consecutive lines of the same kind into one attributed
# string so the text view is mutated a handful of times, not once
# per line.
self._appendBatch(self.activityTextView, lines, key=lambda row: row[1])
rtp_lines = [row for row in lines if row[2]]
if rtp_lines:
self._appendBatch(self.rtpTextView, rtp_lines, key=lambda row: row[1])
if dropped:
self.append_error_line(self.activityTextView,
"%s [%d activity lines dropped: logging faster than the panel can render]"
% (datetime.now().replace(microsecond=0), dropped))
@objc.python_method
def _appendBatch(self, textView, lines, key):
storage = textView.textStorage()
storage.beginEditing()
try:
run = []
run_kind = None
for row in lines:
kind = key(row)
if run and kind != run_kind:
self._appendRun(storage, run, run_kind)
run = []
run_kind = kind
run.append(row[0])
if run:
self._appendRun(storage, run, run_kind)
finally:
storage.endEditing()
self._scrollToEnd(textView)
@objc.python_method
def _appendRun(self, storage, lines, iserror):
if iserror:
attrs = NSDictionary.dictionaryWithObject_forKey_(NSColor.redColor(), NSForegroundColorAttributeName)
else:
attrs = self.normalText
blob = "\n".join(lines) + "\n"
storage.appendAttributedString_(NSAttributedString.alloc().initWithString_attributes_(blob, attrs))
@objc.python_method
def _renderActivityUnbatched(self, text, iserror, rtp_mirror):
if iserror:
self.append_error_line(self.activityTextView, text)
else:
self.append_line(self.activityTextView, text)
if rtp_mirror:
# Reuse the same red-for-error / normal-for-info colouring
# as the activity log so eye-tracking between the two
# panels is straightforward.
if iserror:
self.append_error_line(self.rtpTextView, text)
else:
self.append_line(self.rtpTextView, text)
@objc.python_method
def _sylk_zrtp_capability_info(self, session):
"""Return a tuple (account_advertises, peer_advertises) where each
element is None if unknown, a string descriptor otherwise. Used
by renderAudio/renderVideo to log the Sylk-ZRTP capability
exchange alongside the SRTP/ZRTP configuration."""
account_str = None
peer_str = None
try:
account = getattr(session, 'account', None)
if account is not None:
rtp_enc = getattr(account.rtp, 'encryption', None)
if rtp_enc is not None and getattr(rtp_enc, 'enabled', False):
if rtp_enc.key_negotiation in ('opportunistic', 'zrtp'):
account_str = 'v=1; suites=AES-128-GCM'
except Exception:
pass
# Peer's capability is in the remote request (incoming) or remote
# response (outgoing) headers. The SDK stashes both.
for attr in ('remote_request_headers', 'remote_response_headers'):
hdrs = getattr(session, attr, None)
if not hdrs:
continue
try:
hdr = hdrs.get('X-Sylk-ZRTP') or hdrs.get('x-sylk-zrtp')
except Exception:
hdr = None
if hdr is None:
continue
value = hdr.body if hasattr(hdr, 'body') else str(hdr)
if isinstance(value, bytes):
try:
value = value.decode('ascii')
except Exception:
value = repr(value)
peer_str = value
break
return account_str, peer_str
@objc.python_method
def _video_negotiated_fmtp_summary(self, session):
"""Pull the rtpmap + fmtp for the selected video PT out of
session.local_sdp and return a "Video codec negotiated: ...
/ fmtp: ..." string for the RTP tab. Returns None if any
expected field is missing - the caller's try/except logs that
case verbatim. Tries a couple of attribute names since
sipsimple's SDPSession exposes 'local_sdp' on outgoing-side
sessions; falls back to the stream's own cached SDP when the
Session hasn't published its post-negotiation copy yet."""
sdp = None
sdp_source = None
# Path 1: the canonical post-negotiation SDP - session._invitation.sdp.active_local.
# The sipsimple Session does NOT expose a top-level local_sdp
# attribute; an earlier version of this helper looked for
# session.local_sdp and always missed, returning None mid-call.
invitation = getattr(session, '_invitation', None)
invitation_sdp = getattr(invitation, 'sdp', None) if invitation is not None else None
if invitation_sdp is not None:
for attr_name in ('active_local', 'proposed_local'):
candidate = getattr(invitation_sdp, attr_name, None)
if candidate is not None and getattr(candidate, 'media', None):
sdp = candidate
sdp_source = 'invitation.sdp.' + attr_name
break
# Path 2: defensive fall-back if a future sipsimple Session
# subclass / change does expose local_sdp directly.
if sdp is None:
for attr_name in ('local_sdp', '_local_sdp'):
candidate = getattr(session, attr_name, None)
if candidate is not None and getattr(candidate, 'media', None):
sdp = candidate
sdp_source = 'session.' + attr_name
break
# Path 3: the stream's own cached SDP - reachable on early-media paths.
if sdp is None:
video_stream = None
try:
video_stream = next((s for s in session.streams or [] if s.type == 'video'))
except StopIteration:
video_stream = None
if video_stream is not None:
for attr_name in ('_local_sdp', 'local_sdp'):
candidate = getattr(video_stream, attr_name, None)
if candidate is not None and getattr(candidate, 'media', None):
sdp = candidate
sdp_source = 'stream.' + attr_name
break
if sdp is None:
return None
# Locate the m=video media line.
video_media = None
for media in sdp.media:
media_type = media.media
if isinstance(media_type, bytes):
media_type = media_type.decode()
if media_type == 'video':
video_media = media
break
if video_media is None:
return None
formats = getattr(video_media, 'formats', None) or []
if not formats:
return None
selected_pt = formats[0]
if isinstance(selected_pt, bytes):
selected_pt = selected_pt.decode()
selected_pt = str(selected_pt)
rtpmap_value = None
fmtp_value = None
for attr in video_media.attributes:
name = attr.name.decode() if isinstance(attr.name, bytes) else attr.name
value = attr.value.decode() if isinstance(attr.value, bytes) else (attr.value or '')
if name == 'rtpmap' and value.startswith(selected_pt + ' '):
rtpmap_value = value.partition(' ')[2]
elif name == 'fmtp' and value.startswith(selected_pt + ' '):
fmtp_value = value.partition(' ')[2]
if rtpmap_value:
head = 'Video codec negotiated: %s (PT %s, from %s)' % (rtpmap_value, selected_pt, sdp_source)
else:
head = 'Video codec negotiated: PT %s (no rtpmap, from %s)' % (selected_pt, sdp_source)
tail = 'fmtp: %s' % (fmtp_value if fmtp_value else '(none)')
return head + ' / ' + tail
@objc.python_method
def renderRTP(self, session):
self.renderAudio(session)
self.renderVideo(session)
@objc.python_method
def renderAudio(self, session):
try:
audio_stream = next((s for s in session.streams or [] if s.type=='audio'))
except StopIteration:
return
text = '\n%s New Audio call %s\n' % (session.start_time, session.remote_identity)
if audio_stream.local_rtp_address and audio_stream.local_rtp_port and audio_stream.remote_rtp_address and audio_stream.remote_rtp_port:
if audio_stream.ice_active and audio_stream.local_rtp_candidate and audio_stream.remote_rtp_candidate:
text += '%s Audio RTP endpoints %s:%d (ICE type %s) <-> %s:%d (ICE type %s)\n' % (session.start_time,
audio_stream.local_rtp_address,
audio_stream.local_rtp_port,
ice_candidates[audio_stream.local_rtp_candidate.type.lower()],
audio_stream.remote_rtp_address,
audio_stream.remote_rtp_port,
ice_candidates[audio_stream.remote_rtp_candidate.type.lower()])
else:
text += '%s Audio RTP endpoints %s:%d <-> %s:%d\n' % (session.start_time,
audio_stream.local_rtp_address,
audio_stream.local_rtp_port,
audio_stream.remote_rtp_address,
audio_stream.remote_rtp_port)
if audio_stream.codec and audio_stream.sample_rate:
text += '%s Audio call established using %s codec at %sHz\n' % (session.start_time, audio_stream.codec, audio_stream.sample_rate)
if audio_stream.encryption.active:
text += '%s RTP audio stream is encrypted with %s (%s)\n' % (session.start_time, audio_stream.encryption.type, audio_stream.encryption.cipher.decode() if isinstance(audio_stream.encryption.cipher, bytes) else audio_stream.encryption.cipher)
# Log the account's RTP encryption fields VERBATIM (both enabled
# and key_negotiation), not the collapsed "disabled" / policy
# string the previous version produced. The Blink Preferences
# "Encryption" dropdown's "Disabled" label maps to key_negotiation
# rather than to encryption.enabled=False in some Blink versions,
# so the previous collapsed line could read "disabled" while
# the actual stored policy was "sdes_optional" - exactly the
# discrepancy that made Sylk -> Blink call diagnosis hard.
# Show both so the policy that's actually applied is visible
# in the RTP tab without cross-referencing settings.cfg.
try:
account = getattr(session, 'account', None)
if account is not None:
rtp_enc = getattr(account.rtp, 'encryption', None)
if rtp_enc is None:
text += '%s Audio RTP encryption setting: account has no rtp.encryption (BonjourAccount?)\n' % session.start_time
else:
enabled = getattr(rtp_enc, 'enabled', False)
key_neg = getattr(rtp_enc, 'key_negotiation', None) or '(unset)'
text += '%s Audio RTP encryption setting: enabled=%s, key_negotiation=%s\n' % (session.start_time, enabled, key_neg)
except Exception:
pass
# Also surface the audio codec preference list from settings, so
# the RTP trace shows what we OFFERED vs. what got negotiated
# (the negotiated codec is the "Audio call established using"
# line above; comparing them tells you whether the peer honoured
# your priority order or imposed their own).
try:
from sipsimple.configuration.settings import SIPSimpleSettings
audio_list = list(SIPSimpleSettings().rtp.audio_codec_list or [])
if audio_list:
text += '%s Proposed audio codecs: %s\n' % (session.start_time, ', '.join(audio_list))
except Exception:
pass
account_str, peer_str = self._sylk_zrtp_capability_info(session)
if account_str is not None:
text += '%s Local X-Sylk-ZRTP capability advertised: %s\n' % (session.start_time, account_str)
if peer_str is not None:
text += '%s Remote X-Sylk-ZRTP capability detected: %s\n' % (session.start_time, peer_str)
if session.remote_user_agent is not None:
text += '%s Remote SIP User Agent is "%s"\n' % (session.start_time, session.remote_user_agent)
astring = NSAttributedString.alloc().initWithString_attributes_(text, self.normalText)
self.rtpTextView.textStorage().appendAttributedString_(astring)
self._scrollToEnd(self.rtpTextView)
@objc.python_method
def renderVideo(self, session):
try:
video_stream = next((s for s in session.streams or [] if s.type=='video'))
except StopIteration:
return
text = '\n%s New Video call %s\n' % (session.start_time, session.remote_identity)
if video_stream.local_rtp_address and video_stream.local_rtp_port and video_stream.remote_rtp_address and video_stream.remote_rtp_port:
if video_stream.ice_active and video_stream.local_rtp_candidate and video_stream.remote_rtp_candidate:
text += '%s Video RTP endpoints %s:%d (ICE type %s) <-> %s:%d (ICE type %s)\n' % (session.start_time,