-
Notifications
You must be signed in to change notification settings - Fork 17
/
ChatWindow.py
1917 lines (1721 loc) · 114 KB
/
ChatWindow.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) 2003 - 2015 The Board of Regents of the University of Wisconsin System
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of version 2 of the GNU General Public License as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
""" A Message Client that processes inter-instance chat communication between Transana-MU
clients. This client utility requires connection to a Transana Message Server. """
__author__ = 'David Woods <[email protected]>'
DEBUG = False
if DEBUG:
print "ChatWindow DEBUG is ON!"
VERSION = 300
# import wxPython
import wx
if __name__ == '__main__':
__builtins__._ = wx.GetTranslation
# import Python ssl module
import ssl
# import Python socket module
import socket
import datetime
# import Python os module
import os
# import Python sys module
import sys
# import Python time module
import time
# import Python threading module
import threading
# import Transana's Global module
import TransanaGlobal
# import Transana Exceptions
import TransanaExceptions
# import Transana's Images
import TransanaImages
# import Transana's Database Interface
import DBInterface
# import Transana Dialogs
import Dialogs
# import Transana's Document Object
import Document
# import Transana's Library object
import Library
# import Transana's Episode object
import Episode
# import Transana's Transcript object
import Transcript
# import Transana's Collection object
import Collection
# import Transana's Quote object
import Quote
# import Transana's Clip object
import Clip
# import Transana's Snapshot object
import Snapshot
# import Transana's Note object
import Note
# We create a thread to listen for messages from the Message Server. However,
# only the Main program thread can interact with a wxPython GUI. Therefore,
# we need to create a custom event to receive the event from the Message Server
# (via the socket connection) and transfer that data to the Main program thread
# where it will be displayed.
#
# We need a second event to signal that the socket connection has died and that
# the Chat Window needs to be closed.
# Get an ID for a custom Event for posting messages received in a thread
EVT_POST_MESSAGE_ID = wx.NewId()
# Get an ID for a custom Event for signalling that the Chat Window needs to be closed
EVT_CLOSE_MESSAGE_ID = wx.NewId()
# Get an ID for a custom Event for if the Message Server is lost
EVT_MESSAGESERVER_LOST_ID = wx.NewId()
# Define a custom "Post Message" event
def EVT_POST_MESSAGE(win, func):
""" Defines the EVT_POST_MESSAGE event type """
win.Connect(-1, -1, EVT_POST_MESSAGE_ID, func)
# Define a custom "Close Message" event
def EVT_CLOSE_MESSAGE(win, func):
""" Defines the EVT_CLOSE_MESSAGE event type """
win.Connect(-1, -1, EVT_CLOSE_MESSAGE_ID, func)
# Define a custom "Message Server Lost" event
def EVT_MESSAGESERVER_LOST(win, func):
""" Defines the EVT_CLOSE_MESSAGE event type """
win.Connect(-1, -1, EVT_MESSAGESERVER_LOST_ID, func)
# Create the actual Custom Post Message Event object
class PostMessageEvent(wx.PyEvent):
""" This event is used to trigger posting a message in the GUI. It carries the data. """
def __init__(self, data):
# Initialize a wxPyEvent
wx.PyEvent.__init__(self)
# Link the event to the Event ID
self.SetEventType(EVT_POST_MESSAGE_ID)
# Store the message data in the Custom Event object
self.data = data
if DEBUG:
print "PostMessageEvent created with data =", self.data.encode('latin1'), "ChatWindow.EventIDS:", EVT_POST_MESSAGE_ID, EVT_CLOSE_MESSAGE_ID, EVT_MESSAGESERVER_LOST_ID
# Create the actual Custom Close Message Event object
class CloseMessageEvent(wx.PyEvent):
""" This event is used to trigger closing the GUI. """
def __init__(self):
# Initialize a wxPyEvent
wx.PyEvent.__init__(self)
# Link the event to the Event ID
self.SetEventType(EVT_CLOSE_MESSAGE_ID)
# Create the actual Custom Message Server Lost Event object
class MessageServerLostEvent(wx.PyEvent):
""" This event is used to indicate that the Message Server has been lost to the GUI. """
def __init__(self):
# Initialize a wxPyEvent
wx.PyEvent.__init__(self)
# Link the event to the Event ID
self.SetEventType(EVT_MESSAGESERVER_LOST_ID)
if DEBUG:
print "MessageServerLost Event created"
# Create a Thread Lock object so that we can use thread locking as needed
threadLock = threading.Lock()
# Create a custom Thread object for listening for messages from the Message Server
class ListenerThread(threading.Thread):
""" custom Thread object for listening for Messages from the Message Server """
def __init__(self, notificationWindow, socketObj):
# parameters are:
# notificationWindow -- the GUI window that must be notified that a message has been received
# socketObj -- the socket object to listen to for messages.
# Initialize the Thread object
threading.Thread.__init__(self)
# Remember the window that needs to be notified
self.window = notificationWindow
# Remember the socket object
self.socketObj = socketObj
# Signal that we don't yet want to abort the thread
self._want_abort = False
# prevent the application from hanging on Close
self.setDaemon(1)
# Start the thread
self.start()
def run(self):
# We need to track overflow (incomplete messages) from the socket from when the socket buffer
# gets full.
dataOverflow = ''
# As long as the thread is running ...
while not self._want_abort:
try:
# listen to the socket for a message from the Message Server
newData = self.socketObj.recv(2048)
# if we're using Unicode, we need to decode the socket message.
# Either way, we need to add the socket message to whatever overflow is unprocessed.
if 'unicode' in wx.PlatformInfo:
data = dataOverflow + newData.decode('utf8')
else:
data = dataOverflow + newData
except socket.error:
if DEBUG:
print 'ChatWindow.ListenerThread.run() socket error'
# NOTE: No GUI from inside the thread. We use a MessageServerLost Event instead.
wx.PostEvent(self.window, MessageServerLostEvent())
# Signal that the thread should close itself.
self._want_abort = True
# Post a Close Message
wx.PostEvent(self.window, CloseMessageEvent())
if DEBUG:
print "ChatWindow.ListenerThread.run() about to break"
# Break out of the while loop
break
except:
if DEBUG:
print "ChatWindow.ListenerThread.run() other error"
if DEBUG:
print '"%s"' % data.encode('latin1')
# As long as data should be processed, and the data is not blank ...
if not self._want_abort and (data != ''):
# Lock the thread
threadLock.acquire()
# A single data element from the Message Server can contain multiple Transana messages, separated
# by the ' ||| ' message separator. Break a Message Server message into its component messages.
messages = data.split(' ||| ')
# The last segment is USUALLY '', but when we get to > 80 connections, that's not always
# true. It might be an incomplete message segment. Therefore, we'll remember it and
# stick it on the front of the NEXT message. If it's blank, like it's supposed to be,
# then it will make no difference, but if it's NOT blank, it would otherwise get lost.
dataOverflow = messages[-1]
# Process all the messages. (The last message is always blank or overflow, so skip it!)
for message in messages[:-1]:
if DEBUG:
print "ChatWindow.ListenerThread.run() posting a PostMessageEvent of '%s'" % message
tmpEvent = PostMessageEvent(message)
# Post the Message Event with the message as data
wx.PostEvent(self.window, tmpEvent)
# Unlock the thread when we're done processing all the messages.
threadLock.release()
else:
if DEBUG:
print "Blank message received. This may mean that the socket connection was lost!!\nOr it may not."
# NOTE: No GUI from inside the thread. We use a MessageServerLost Event instead.
if self.window.reportSocketLoss:
try:
wx.PostEvent(self.window, MessageServerLostEvent())
except wx._core.PyDeadObjectError:
pass
return
else:
# If we want to abort the thread, post the message event with None as the data
# NOTE: This probably never gets called, as the code waits at the socket.recv()
# line until it gets a message of the connection is broken.
# wx.PostEvent(self.window, PostMessageEvent(None))
return
def abort(self):
# Signal that you want to abort the thread. (Probably not effective, as the thread is
# waiting on a socket.recv() call)
self._want_abort = True
class ChatWindow(wx.Frame):
""" This window displays the Chat form. """
def __init__(self, parent, id, title, socketObj):
# Remember the parent window
self.parent = parent
# Remember the window title
self.title = title
# remember the Socket object
self.socketObj = socketObj
# Get the username from the TransanaGlobal module
self.userName = TransanaGlobal.userName
# Define the main Frame for the Chat Window
wx.Frame.__init__(self, parent, -1, title, size = (710,450), style=wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE)
# Set the background to White
self.SetBackgroundColour(wx.WHITE)
# To look right, the Mac needs the Small Window Variant.
if "__WXMAC__" in wx.PlatformInfo:
self.SetWindowVariant(wx.WINDOW_VARIANT_SMALL)
# Set the Chat Window Icon
transanaIcon = wx.Icon(TransanaGlobal.programDir + os.sep + "images/Transana.ico", wx.BITMAP_TYPE_ICO)
self.SetIcon(transanaIcon)
# Create a Sizer for the form
box = wx.BoxSizer(wx.VERTICAL)
# Create a Sizer for data the form receives
boxRecv = wx.BoxSizer(wx.HORIZONTAL)
# Create a Sizer for the Memo section
boxMemo = wx.BoxSizer(wx.VERTICAL)
# Create a label for the Memo section
self.txtMemo = wx.StaticText(self, -1, _("Messages"))
# Put the label in the Memo Sizer, with a little padding below
boxMemo.Add(self.txtMemo, 0, wx.BOTTOM, 3)
# Add a TextCtrl for the chat text. This is read only, as it is filled programmatically.
self.memo = wx.TextCtrl(self, -1, style = wx.TE_MULTILINE | wx.TE_WORDWRAP | wx.TE_READONLY)
# Put the Memo control in the Memo Sizer
boxMemo.Add(self.memo, 1, wx.EXPAND)
# Add the Memo display to the Receiver Sizer
boxRecv.Add(boxMemo, 8, wx.EXPAND)
# Create a Sizer for the User section
boxUser = wx.BoxSizer(wx.VERTICAL)
# Create a label for the User section
self.txtUser = wx.StaticText(self, -1, _("Current Users"))
# Put the label in the User Sizer with a little padding below
boxUser.Add(self.txtUser, 0, wx.BOTTOM, 3)
# Add a ListBox to hold the names of active users. Allow multiple selection for Private Chat specification.
self.userList = wx.ListBox(self, -1, choices=[self.userName], style=wx.LB_MULTIPLE)
boxUser.Add(self.userList, 1, wx.BOTTOM | wx.EXPAND, 3)
# Create a dictionary that knows the SSL status of each connected user
self.sslStatus = {}
# Add the SSL image
# Create a Row Sizer
infoSizer = wx.BoxSizer(wx.HORIZONTAL)
# If Chat has an SSL connection ...
if TransanaGlobal.chatIsSSL:
# ... load the "locked" image
image = TransanaImages.locked.GetBitmap()
# If Chat has an un-encrypted connection ...
else:
# ... load the "unlocked" image
image = TransanaImages.unlocked.GetBitmap()
# Create a BitMap to display on screen
self.sslImage = wx.StaticBitmap(self, -1, image, (16, 16))
# Add the image to the Row sizer
infoSizer.Add(self.sslImage, 0, wx.RIGHT, 4)
# Make the image clickable
self.sslImage.Bind(wx.EVT_LEFT_DOWN, self.OnSSLClick)
# Add a checkbox to enable/disable audio feedback
self.useSound = wx.CheckBox(self, -1, _("Sound Enabled"))
# Check the box to start
self.useSound.SetValue(True)
# Add the checkbox to the Row sizer
infoSizer.Add(self.useSound, 0)
# Add the Row Sizer to the User column Sizer
boxUser.Add(infoSizer, 0)
# Add the User List display to the Receiver Sizer
boxRecv.Add(boxUser, 2, wx.EXPAND | wx.LEFT, 6)
# Put the TextCtrl in the form sizer
box.Add(boxRecv, 13, wx.EXPAND | wx.ALL, 4)
# Create a sizer for the text entry and send portion of the form
boxSend = wx.BoxSizer(wx.HORIZONTAL)
# Add a TextCtrl where the user can enter messages. It needs to process the Enter key.
self.txtEntry = wx.TextCtrl(self, -1, style = wx.TE_PROCESS_ENTER)
# Add the Text Entry control to the Text entry sizer
boxSend.Add(self.txtEntry, 5, wx.EXPAND)
# bind the OnSend event with the Text Entry control's enter key event
self.txtEntry.Bind(wx.EVT_TEXT_ENTER, self.OnSend)
# Bind the OnKeyUp event with the Text Entry control's wxEVT_KEY_UP event
self.txtEntry.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
# Add a "Send" button
self.btnSend = wx.Button(self, -1, _("Send"))
# Add the Send button to the Text Entry sizer
boxSend.Add(self.btnSend, 0, wx.LEFT, 6)
# Bind the OnSend event to the send button's press event
self.btnSend.Bind(wx.EVT_BUTTON, self.OnSend)
# Add a "Clear" button
self.btnClear = wx.Button(self, -1, _("Clear"))
# Add the Clear button to the Text Entry sizer
boxSend.Add(self.btnClear, 0, wx.LEFT, 6)
# Bind the OnClear event to the Clear button's press event
self.btnClear.Bind(wx.EVT_BUTTON, self.OnClear)
# Add the send Sizer to the Form Sizer
box.Add(boxSend, 1, wx.EXPAND | wx.ALL, 4)
# Define the Chat Sound
flName = TransanaGlobal.programDir + os.sep + 'images' + os.sep + 'chatmessage.wav'
# Create the player for the Chat Sound
self.soundplayer = wx.media.MediaCtrl(self, -1, fileName = flName)
# Hide the player for the Chat Sound. It doesn't need to be visible.
self.soundplayer.Show(False)
# Define the form's OnClose handler
self.Bind(wx.EVT_CLOSE, self.OnClose)
# Attach the Form's Main Sizer to the form
self.SetSizer(box)
# Set AutoLayout on
self.SetAutoLayout(True)
# Lay out the form
self.Layout()
# Set the minimum size for the form.
self.SetSizeHints(minW = 600, minH = 440)
# Center the form on the screen
if __name__ == '__main__':
self.CentreOnScreen()
else:
TransanaGlobal.CenterOnPrimary(self)
# Set the initial focus to the Text Entry control
self.txtEntry.SetFocus()
# We need to know if loss of socket connection is expected or should be reported
self.reportSocketLoss = True
# Start the Listener Thread to listen for messages from the Message Server
self.listener = ListenerThread(self, self.socketObj)
# Define the custom Post Message Event's handler
EVT_POST_MESSAGE(self, self.OnPostMessage)
# Define the custom Post Message Event's handler
EVT_MESSAGESERVER_LOST(self, self.OnMessageServerLost)
if DEBUG and False:
print
print "Threads:"
for thr in threading.enumerate():
if type(thr).__name__ == 'ListenerThread':
print thr, type(thr).__name__, thr.socketObj
else:
print thr, type(thr).__name__
print
# Define the custom Close Message Event's handler
EVT_CLOSE_MESSAGE(self, self.OnCloseMessage)
# Register with the Control Object
if (TransanaGlobal.menuWindow != None) and (TransanaGlobal.menuWindow.ControlObject != None):
TransanaGlobal.menuWindow.ControlObject.Register(Chat=self)
self.ControlObject = TransanaGlobal.menuWindow.ControlObject
else:
self.ControlObject = None
# Inform the message server of user's identity and database connection
if 'unicode' in wx.PlatformInfo:
if __name__ == '__main__':
userName = 'Test_' + sys.platform
host = '192.168.1.19'
db = 'ChatTestDB'
ssl = False
else:
userName = self.userName.encode('utf8')
host = TransanaGlobal.configData.host.encode('utf8')
db = TransanaGlobal.configData.database.encode('utf8')
ssl = TransanaGlobal.chatIsSSL
if DEBUG:
print 'C %s %s %s %s %s ||| ' % (userName, host, db, ssl, VERSION)
if ('wxGTK' in wx.PlatformInfo) and (host.lower() == 'localhost'):
host = 'walnut-v.ad.education.wisc.edu'
print
print '***************************************************************************'
print '* GTK Message Server Faked! *'
print '***************************************************************************'
# If we are running the Transana Client on the same computer as the MySQL server, we MUST refer to it as localhost.
# In this circumstance, this copy of the Transana Client will not be recognized by the Transana Message Server
# as being connected to the same database as other computers connecting to it. To get around this, we need to
# get the correct Server name from the user.
# Detect the use of "localhost"
if host.lower() == 'localhost':
# Create a Text Entry Dialog to get the proper server name from the user.
dlg = wx.TextEntryDialog(self, _('What is the Host / Server name other computers use to connect to this MySQL Server?'),
_('Transana Message Server connection'), 'localhost')
# Show the Text Entry. See if the user selects "OK".
if dlg.ShowModal() == wx.ID_OK:
# If so, update the host name to pass to the Transana Message Server
host = dlg.GetValue()
# Destroy the Text Entry Dialog.
dlg.Destroy()
self.socketObj.send('C %s %s %s %s %s ||| ' % (userName, host, db, ssl, VERSION))
# Add this user to the SSL Status Dictionary
if ssl:
self.sslStatus[userName] = 'TRUE'
else:
self.sslStatus[userName] = 'FALSE'
else:
self.socketObj.send('C %s %s %s %s %s ||| ' % (self.userName, TransanaGlobal.configData.host, TransanaGlobal.configData.database, TransanaGlobal.chatIsSSL, VERSION))
# Add this user to the SSL Status Dictionary
if TransanaGlobal.chatIsSSL:
self.sslStatus[self.userName] = 'TRUE'
else:
self.sslStatus[self.userName] = 'FALSE'
# Okay, this is really annoying. Here's the scoop.
# July 21, 2015. If I use OS X 10.10.3 (Yosemite), the current OS X release,
# the Chat and MU Messaging infrastructure doesn't work on the Mac.
# That's because EVT_POST_MESSAGE works to Post a Message, but for reasons that elude me,
# it doesn't trigger ChatWindow.OnPostMessage() like it's supposed to. So the message
# coming in from the Message Server gets received and written to the Event Queue okay,
# but it doesn't get "read" and posted in the Chat Window because the ChatWindow's
# EVT_POST_MESSAGE handler doesn't get called in response to the message being queued
# correctly.
#
# So what I've done is set up a time that's called every half second. All it does is
# call wx.YieldIfNeeded(). That seems to be enough!
#
# I know I shouldn't HAVE to do this, but at least for now, I do.
#
## if 'wxMac' in wx.PlatformInfo:
## if DEBUG:
## self.processMessageQueueTime = datetime.datetime.now()
## self.processMessageQueueTimer = wx.Timer()
## self.processMessageQueueTimer.Bind(wx.EVT_TIMER, self.OnProcessMessageQueue)
## self.processMessageQueueTimer.Start(500)
# Create a Timer to check for Message Server validation.
# Initialize to unvalidated state
self.serverValidation = False
# Create a Timer
self.validationTimer = wx.Timer()
# Assign the Timer's event
self.validationTimer.Bind(wx.EVT_TIMER, self.OnValidationTimer)
# 10 seconds should be sufficient for the connection to the message server to be established and confirmed
self.validationTimer.Start(10000)
## def OnProcessMessageQueue(self, event):
##
## if DEBUG:
## print "ChatWIndow.ProcessMessageQueue():", datetime.datetime.now() - self.processMessageQueueTime
##
## wx.YieldIfNeeded()
def SendMessage(self, message):
""" Send a message through the chatWindow's socket """
try:
# Process Windows Messages, if needed. (Completes SAVES, in theory!)
wx.YieldIfNeeded()
msg = '%s ||| ' % message
# If we're using Unicode, we need to encode the messages passed to the socket.
if 'unicode' in wx.PlatformInfo:
self.socketObj.send(msg.encode('utf8'))
else:
self.socketObj.send(msg)
# This *should* allow messages to be sent totally independently.
time.sleep(0.05)
except socket.error:
if DEBUG:
print "ChatWindow.SendMessage() socket error."
# NOTE: No GUI from inside the thread. We use a MessageServerLost Event instead.
wx.PostEvent(self.window, MessageServerLostEvent())
# Close the Chat Window if the connection's been broken.
self.Close()
except:
print sys.exc_info()[0]
print sys.exc_info()[1]
import traceback
traceback.print_exc(file=sys.stdout)
def OnSend(self, event):
""" Send Message handler """
# Get the message from the text entry box
message = self.txtEntry.GetValue()
# if a User Report is requested ...
if message.upper() == _('REPORT'):
# ... get the user list
userList = self.userList.GetItems()
# Print the Report Header
self.memo.AppendText(_('User Report:') + u'\n')
# For each user ...
for x in userList:
# ... determine the user's SSL Status
if self.sslStatus[x] == 'TRUE':
status = _('Secure')
else:
status = _('NOT secure')
# Add a line to the Report indicating the user name and SSL status
self.memo.AppendText(unicode('%s\t\t%s\n', 'utf8') % (x, status))
# Add a blank line to the Report
self.memo.AppendText('\n')
# Make sure there IS a message!
elif message.strip() != "":
# If there are user selections, we want PRIVATE MESSAGING. If all or none are selected,
# everyone gets to see the message. If only the current user is selected, there are NO
# RECIPIENTS, so don't sent the message!
if (len(self.userList.GetSelections()) > 0) and \
(self.userList.GetSelections() != (0, )):
# (len(self.userList.GetSelections()) < self.userList.GetCount()) and \
# Make sure THIS user is NOT selected
if self.userList.IsSelected(0):
self.userList.Deselect(0)
# If (and only if) not everyone in the list is selected ...
if len(self.userList.GetSelections()) < self.userList.GetCount() - 1:
# Indicate a Private Message by adding on the intended recipients
message += ' >|<'
# Add the recipients list to the message
for index in self.userList.GetSelections():
message += ' ' + self.userList.GetString(index)
# if more than just the current user is selected ...
if (self.userList.GetSelections() != (0, )):
# ... send the message. Indicate that this is a Text Message by prefacing the text with "M".
self.SendMessage('M %s' % message)
# Clear the Text Entry control
self.txtEntry.SetValue('')
# Set the focus to the Text Entry Control
self.txtEntry.SetFocus()
def OnKeyUp(self, event):
""" Text Entry Control's wxEVT_KEY_UP method """
# if the message length exceeds 800 characters, and the user presses SPACE ...
if (len(self.txtEntry.GetValue()) > 800) and (event.GetKeyCode() == wx.WXK_SPACE):
# ... just send the damn message
self.OnSend(event)
def OnClear(self, event):
""" Clear button handler """
# Clear the previous chat text
self.memo.Clear()
# Set the focus to the Text Entry control
self.txtEntry.SetFocus()
def UpdateSSLStatus(self):
""" Check and Update the SSL Connection Status of the Chat Window """
# See if there are unsecured connections ...
if "FALSE" in self.sslStatus.values():
# ... load the "unlocked" image
image = TransanaImages.unlocked.GetBitmap()
# If Chat has only encrypted connections ...
else:
# ... load the "locked" image
image = TransanaImages.locked.GetBitmap()
# Update the BitMap on screen
self.sslImage.SetBitmap(image)
# Notify the Control Object to update other SSL indicator(s)
if self.ControlObject != None:
self.ControlObject.UpdateSSLStatus(not ("FALSE" in self.sslStatus.values()))
def OnSSLClick(self, event):
""" Handle click on the SSL indicator image """
# Determine whether SSL is in use with the Database connection
dbIsSSL = TransanaGlobal.configData.ssl
# Determine whether SSL is FULLY in use with the Message Server connection
chatIsSSL = not ("FALSE" in self.sslStatus.values())
# Start building user feedback based on SSL usage
if dbIsSSL:
prompt = _("You have a secure connection to the Database. ")
else:
prompt = _("You do not have a secure connection to the Database. ")
if chatIsSSL:
prompt += '\n' + _("You have a secure connection to the Message Server. ")
else:
prompt += '\n' + _("You do not have a secure connection to the Message Server. ")
prompt += "\n\n"
# Complete user feedback with a summary based on SSL usage
if dbIsSSL:
if chatIsSSL:
prompt += _("Therefore, your Transana connection is as secure as we can make it.")
else:
prompt += _('To maintain data security, you should avoid using identifying\ninformation in object names, keywords, and chat messages.')
else:
prompt += _("Therefore, your data could be observed during transmission.\nYou may want to look into making your Transana connections more secure.")
# Create and display a dialog to provide the user security feedback.
tmpDlg = Dialogs.InfoDialog(self, prompt)
tmpDlg.ShowModal()
tmpDlg.Destroy()
def OnPostMessage(self, event):
""" Post Message handler """
def ConvertMessageToNodeList(message):
""" Take a message from the Transana Message Server and convert it to a NodeList for use with the DB Tree
add_Node method """
nodelist = ()
for m in message.split(' >|< '):
nodelist += (m,)
return nodelist
if DEBUG:
print "ChatWindow.OnPostMessage():", event.data
# If there is data in the message event ...
if event.data != None:
if DEBUG:
print 'event.data = "%s"' % event.data.encode('latin1')
message = event.data
messageHeader = message[:message.find(' ')]
message = message[message.find(' ') + 1:].strip()
messageSender = message[:message.find(' ') - 1] # drop the ":"
message = message[message.find(' ') + 1:].strip()
if DEBUG:
print 'messageHeader = "%s"' % messageHeader
print 'messageSender = "%s"' % messageSender
print 'message = "%s"' % message.encode('latin1')
print
# Determine what type of message it is by looking at the first character.
# Text Message ?
if messageHeader == 'M':
# If it's not visible ...
if not self.IsShown():
# ... show the ChatWindow and ...
self.Show(True)
# ... display the message (minus the Message Prefix) on the screen
self.memo.AppendText("%s\n" % event.data[2:])
# If sound is enabled...
if self.useSound.IsChecked():
# ... play the message sound.
self.soundplayer.Play()
# Connection Message
elif messageHeader == 'C':
# This signals that a UserName should be added to the list of current users.
# Drop the Message Prefix.
st = event.data[2:]
# Break the message into its components
tmpData = st.split(' ')
# See how many components were included. If five (when OTHER users connect using 2.61 or later) ...
if len(tmpData) == 5:
# ... then SSL is the 4th (index 3) of them.
tmpSSL = tmpData[3].upper()
# If there are only 2 elements (OTHER users when WE first connect)
elif len(tmpData) == 2:
tmpSSL = tmpData[1].upper()
# If not five or 2 (OTHER users using 2.60 or earlier have 4, for example) ...
else:
# ... then SSL is missing, so is FALSE!!
tmpSSL = 'FALSE'
# Only add a user name if it's not redundant. (The message server should prevent this
# from occurring.)
if (tmpData[0] != self.userName) and not (tmpData[0] in self.userList.GetItems()):
# Add the user to the User List
self.userList.Append(tmpData[0])
# Add the user's SSL Status to the dictionary
self.sslStatus[tmpData[0]] = tmpSSL
# Update the SSL indicators
self.UpdateSSLStatus()
# Rename Message ?
elif messageHeader == 'R':
# If a user name is duplicated, the Message Server renames it to prevent confusion.
# This code indicates that THIS USER's account has been renamed by the Message Server.
# Remove the "old" user name
self.userList.Delete(0)
# Start Exception Handling
try:
# Try to remove the user from the SSL Status dictionary
del(self.sslStatus[self.userName])
# If a KeyError is generated ...
except KeyError:
# ... we can ignore it.
pass
# Drop the Message Prefix
st = event.data[2:]
# Break the message into its parts
tmpData = st.split(' ')
# The first part will be the user name
self.userName = tmpData[0]
# The second part will be the user's SSL status
SSL = tmpData[1]
# Add the user to the User List
self.userList.Append(self.userName)
# Add this user's SSL Status to the dictionary
self.sslStatus[tmpData[0]] = tmpData[1]
# Update SSL Status indicators
self.UpdateSSLStatus()
# Import Message
elif messageHeader == 'I':
# Another user has imported a database. We need to refresh the whole Database Tree!
# See if a Control Object has been defined.
if self.ControlObject != None:
# See if there's a Notes Browser open
if self.ControlObject.NotesBrowserWindow != None:
# If so, close it.
self.ControlObject.NotesBrowserWindow.Close()
# Update the Data Window via the Control Object
self.ControlObject.UpdateDataWindow()
# Server Validation
elif messageHeader == 'V':
# Indicate that the server has been validated. The Validation Timer processes this later.
self.serverValidation = True
# Disconnect Message ?
elif messageHeader == 'D':
# Remove the Message Prefix.
st = event.data[2:]
try:
# The remainder of the message is the username to be removed. Delete it from the User List.
self.userList.Delete(self.userList.FindString(st))
# Remove the user from the SSL Status dictionary
del(self.sslStatus[st])
# Update the SSL Status indicators
self.UpdateSSLStatus()
except:
pass
else:
# The remaining messages should not be processed if this user was the message sender
if self.userName != messageSender:
# We can't have the tree selection changing because of the activity of other users. That creates all kinds of
# problems if we're in the middle of editing something. So let's note the current selection
currentSelection = self.ControlObject.DataWindow.DBTab.tree.GetSelections()
# The Control Object MUST be defined (and always will be)
if self.ControlObject != None:
# Add Library Message
if messageHeader == 'AS':
tempLibrary = Library.Library(message)
self.ControlObject.DataWindow.DBTab.tree.add_Node('LibraryNode', (_('Libraries'), message), tempLibrary.number, None, expandNode=False, avoidRecursiveYields = True)
# Add Episode Message
elif messageHeader == 'AE':
# Convert the Message to a Node List
nodelist = ConvertMessageToNodeList(message)
tempEpisode = Episode.Episode(series=nodelist[0], episode=nodelist[1])
self.ControlObject.DataWindow.DBTab.tree.add_Node('EpisodeNode', (_('Libraries'),) + nodelist, tempEpisode.number, tempEpisode.series_num, expandNode=False, avoidRecursiveYields = True)
# Add Transcript Message
elif messageHeader == 'AT':
# Convert the Message to a Node List
nodelist = ConvertMessageToNodeList(message)
tempEpisode = Episode.Episode(series=nodelist[0], episode=nodelist[1])
# To save time here, we can skip loading the actual transcript text, which can take time once we start dealing with images!
tempTranscript = Transcript.Transcript(nodelist[-1], ep=tempEpisode.number, skipText=True)
self.ControlObject.DataWindow.DBTab.tree.add_Node('TranscriptNode', (_('Libraries'),) + nodelist, tempTranscript.number, tempEpisode.number, expandNode=False, avoidRecursiveYields = True)
# Add Document Message
elif messageHeader == 'AD':
# Convert the Message to a Node List
nodelist = ConvertMessageToNodeList(message)
tempDocument = Document.Document(libraryID=nodelist[0], documentID=nodelist[1])
self.ControlObject.DataWindow.DBTab.tree.add_Node('DocumentNode', (_('Libraries'),) + nodelist, tempDocument.number, tempDocument.library_num, expandNode=False, avoidRecursiveYields = True)
# Add Collection Message
elif messageHeader == 'AC':
# Convert the Message to a Node List
nodelist = ConvertMessageToNodeList(message)
parentNum = 0
for coll in nodelist:
tempCollection = Collection.Collection(coll, parentNum)
parentNum = tempCollection.number
# avoidRecursiveYields added to try to prevent a problem on the Mac when converting Searches
self.ControlObject.DataWindow.DBTab.tree.add_Node('CollectionNode', (_('Collections'),) + nodelist, tempCollection.number, tempCollection.parent, expandNode=False, avoidRecursiveYields=True)
# Add Quote Message
elif messageHeader == 'AQ':
# Convert the Message to a Node List
nodelist = ConvertMessageToNodeList(message)
parentNum = 0
for coll in nodelist[:-1]:
tempCollection = Collection.Collection(coll, parentNum)
parentNum = tempCollection.number
# Get a temporary copy of the Quote. We don't need the quote's text, which speeds this up.
tempQuote = Quote.Quote(quoteID=nodelist[-1], collectionID=tempCollection.id, collectionParent=tempCollection.parent, skipText=True)
# avoidRecursiveYields added to try to prevent a problem on the Mac when converting Searches
self.ControlObject.DataWindow.DBTab.tree.add_Node('QuoteNode', (_('Collections'),) + nodelist, tempQuote.number, tempCollection.number, sortOrder=tempQuote.sort_order, expandNode=False, avoidRecursiveYields=True)
# If the Quote's Document is open, it needs to be updated with the Quote information!
self.ControlObject.AddQuoteToOpenDocument(tempQuote)
# If we are moving a Quote, the quote's Notes need to travel with the Quote. The first step is to
# get a list of those Notes.
noteList = DBInterface.list_of_notes(Quote=tempQuote.number)
# If there are Quote Notes, we need to make sure they travel with the Quote
if noteList != []:
insertNode = self.ControlObject.DataWindow.DBTab.tree.select_Node((_('Collections'),) + nodelist, 'QuoteNode', ensureVisible=False)
# We accomplish this using the TreeCtrl's "add_note_nodes" method
self.ControlObject.DataWindow.DBTab.tree.add_note_nodes(noteList, insertNode, Quote=tempQuote.number)
self.ControlObject.DataWindow.DBTab.tree.Refresh()
# Add Clip Message
elif messageHeader == 'ACl':
# Convert the Message to a Node List
nodelist = ConvertMessageToNodeList(message)
parentNum = 0
for coll in nodelist[:-1]:
tempCollection = Collection.Collection(coll, parentNum)
parentNum = tempCollection.number
# Get a temporary copy of the Clip. We don't need the clip's transcript, which speeds this up.
tempClip = Clip.Clip(nodelist[-1], tempCollection.id, tempCollection.parent, skipText=True)
# avoidRecursiveYields added to try to prevent a problem on the Mac when converting Searches
self.ControlObject.DataWindow.DBTab.tree.add_Node('ClipNode', (_('Collections'),) + nodelist, tempClip.number, tempCollection.number, sortOrder=tempClip.sort_order, expandNode=False, avoidRecursiveYields=True)
# If we are moving a Clip, the clip's Notes need to travel with the Clip. The first step is to
# get a list of those Notes.
noteList = DBInterface.list_of_notes(Clip=tempClip.number)
# If there are Clip Notes, we need to make sure they travel with the Clip
if noteList != []:
insertNode = self.ControlObject.DataWindow.DBTab.tree.select_Node((_('Collections'),) + nodelist, 'ClipNode', ensureVisible=False)
# We accomplish this using the TreeCtrl's "add_note_nodes" method
self.ControlObject.DataWindow.DBTab.tree.add_note_nodes(noteList, insertNode, Clip=tempClip.number)
self.ControlObject.DataWindow.DBTab.tree.Refresh()
# Add Clip in Sort Order Message
elif messageHeader == 'AClSO':
# Convert the Message to a Node List
nodelist = ConvertMessageToNodeList(message)
parentNum = 0
for coll in nodelist[:-2]:
tempCollection = Collection.Collection(coll, parentNum)
parentNum = tempCollection.number
# We need the NODE for the Clip we should place the new clip in front of. Let's get that here.
insertNode = self.ControlObject.DataWindow.DBTab.tree.select_Node((_('Collections'),) + nodelist[:-1], 'ClipNode', ensureVisible=False)
# Get a temporary copy of the Clip. We don't need the clip's transcript, which speeds this up.
tempClip = Clip.Clip(nodelist[-1], tempCollection.id, tempCollection.parent, skipText=True)
# Add new node, leaving the insertNode out of the nodeList.
# avoidRecursiveYields added to try to prevent a problem on the Mac when converting Searches
self.ControlObject.DataWindow.DBTab.tree.add_Node('ClipNode', (_('Collections'),) + nodelist[:-2] + (nodelist[-1],), tempClip.number, tempCollection.number, sortOrder=tempClip.sort_order, expandNode=False, insertPos=insertNode, avoidRecursiveYields=True)
# If we are moving a Clip, the clip's Notes need to travel with the Clip. The first step is to
# get a list of those Notes.
noteList = DBInterface.list_of_notes(Clip=tempClip.number)
# If there are Clip Notes, we need to make sure they travel with the Clip
if noteList != []:
insertNode = self.ControlObject.DataWindow.DBTab.tree.select_Node((_('Collections'),) + nodelist[:-2] + (nodelist[-1],), 'ClipNode', ensureVisible=False)
# We accomplish this using the TreeCtrl's "add_note_nodes" method
self.ControlObject.DataWindow.DBTab.tree.add_note_nodes(noteList, insertNode, Clip=tempClip.number)
self.ControlObject.DataWindow.DBTab.tree.Refresh()
# Order Collection Message
elif messageHeader == 'OC':
# Convert the message to a Node List
nodelist = ConvertMessageToNodeList(message)
# Get the Collection's Tree Node
node = self.ControlObject.DataWindow.DBTab.tree.select_Node((_('Collections'),) + nodelist[1:], 'CollectionNode')
# Update the Sort Information for that tree node
self.ControlObject.DataWindow.DBTab.tree.UpdateCollectionSortOrder(node, sendMessage=False)
# Add Snapshot Message
elif messageHeader == 'ASnap':
# Convert the Message to a Node List
nodelist = ConvertMessageToNodeList(message)
# Initialize the Parent Number variable
parentNum = 0
# Get the appropriate Collection by interating through the node list ...
for coll in nodelist[:-1]:
# ... get the Collection for each node ...
tempCollection = Collection.Collection(coll, parentNum)
# ... and the parent number
parentNum = tempCollection.number
# Get a temporary copy of the Snapshot.
tempSnapshot = Snapshot.Snapshot(nodelist[-1], parentNum)
# avoidRecursiveYields added to try to prevent a problem on the Mac when converting Searches
self.ControlObject.DataWindow.DBTab.tree.add_Node('SnapshotNode', (_('Collections'),) + nodelist, tempSnapshot.number, tempCollection.number, sortOrder=tempSnapshot.sort_order, expandNode=False, avoidRecursiveYields=True)
# If we are moving a Snapshot, the snapshot's Notes need to travel with the Snapshot. The first step is to
# get a list of those Notes.
noteList = DBInterface.list_of_notes(Snapshot=tempSnapshot.number)
# If there are Snapshot Notes, we need to make sure they travel with the Snapshot
if noteList != []:
insertNode = self.ControlObject.DataWindow.DBTab.tree.select_Node((_('Collections'),) + nodelist, 'SnapshotNode', ensureVisible=False)
# We accomplish this using the TreeCtrl's "add_note_nodes" method
self.ControlObject.DataWindow.DBTab.tree.add_note_nodes(noteList, insertNode, Snapshot=tempSnapshot.number)
self.ControlObject.DataWindow.DBTab.tree.Refresh()
# Add Note Message
elif messageHeader in ['ASN', 'ADN', 'AEN', 'ATN', 'ACN', 'AQN', 'AClN', 'ASnN']:
# Convert the Message to a Node List
nodelist = ConvertMessageToNodeList(message)
# Initialize variables
parentNum = 0
objectType = None
nodeType = None
tempObj = None
parentNum = 0
nodeCount = 0
# Iterate through the node list to figure out what kind of Note we're looking at
for node in nodelist[:-1]:
# Count how far into the list we are
nodeCount += 1
# If the first entry in the node list is the "Library" Root Node ...
if (objectType == None) and (node == 'Libraries'):
# ... then we're climbing up the Library branch, and are at a Library record.
objectType = 'Library'
# If we're already at a Library record and we have an Episode or Transcript Note ...
elif (objectType == 'Library') and (messageHeader in ['ASN', 'AEN', 'ATN']):
# ... then we're moving on to an Episode next
objectType = 'Episode'
# We might have a Library Note, at least if we stop here!
nodeType = 'LibraryNoteNode'
# Let's load the Library record ...
tempObj = Library.Library(node)
# .. and note that the parent of the NEXT object is this Library's number!
parentNum = tempObj.number
# If we're already at a Library record and we have a Document Note ...
elif (objectType == 'Library') and (messageHeader in ['ADN']):
# ... then we're moving on to an Document next
objectType = 'Document'
# We might have a Library Note, at least if we stop here!
nodeType = 'LibraryNoteNode'
# Let's load the Library record ...
tempObj = Library.Library(node)
# .. and note that the parent of the NEXT object is this Library's number!
parentNum = tempObj.number
# If we're already at a Document record ...
elif (objectType == 'Document'):