forked from sanyaade-machine-learning/Transana
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathControlObjectClass.py
More file actions
2964 lines (2668 loc) · 165 KB
/
ControlObjectClass.py
File metadata and controls
2964 lines (2668 loc) · 165 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) 2003 - 2014 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.
#
"""This module implements the Control Object class for Transana,
which is responsible for managing communication between the
four main windows. Each object (Menu, Visualization, Video, Transcript,
and Data) should communicate only with the Control Object, not with
each other.
"""
__author__ = 'David Woods <dwoods@wcer.wisc.edu>, Rajas Sambhare'
DEBUG = False
if DEBUG:
print "ControlObjectClass DEBUG is ON!"
# Import wxPython
import wx
# import Transana's Constants
import TransanaConstants
# Import the Menu Constants
import MenuSetup
# Import Transana's Global Values
import TransanaGlobal
# import the Transana Series Object definition
import Series
# import the Transana Episode Object definition
import Episode
# import the Transana Transcript Object definition
import Transcript
# import the Transana Collection Object definition
import Collection
# import the Transana Clip Object definition
import Clip
# import the Transana Miscellaneous Routines
import Misc
# import Transana Database Interface
import DBInterface
# import Transana's Dialogs
import Dialogs
# import Transana's DragAndDrop Objects for Quick Clip creation
import DragAndDropObjects
# import Transana File Management System
import FileManagement
# import Play All Clips
import PlayAllClips
# import the Episode Transcript Change Propagation tool
import PropagateEpisodeChanges
# import the Snapshot Window
import SnapshotWindow
# import Transana's Exceptions
import TransanaExceptions
# Import Transana's Transcript User Interface for creating supplemental Transcript Windows
if TransanaConstants.USESRTC:
import TranscriptionUI_RTC as TranscriptionUI
else:
import TranscriptionUI
# import Python's os module
import os
# import Python's sys module
import sys
# Import Python's fast cPickle module
import cPickle
# import Python's pickle module
import pickle
class ControlObject(object):
""" The ControlObject operationalizes all inter-window and inter-object communication and control.
All objects should speak only to the ControlObject, not to each other directly. The purpose of
this is to allow greater modularity of code, so that modules can be swapped in and out in with
changes affecting only this object if the APIs change. """
def __init__(self):
""" Initialize the ControlObject """
# Define Objects that need controlling (initializing to None)
self.MenuWindow = None
self.VideoWindow = None
# There may be multiple Transcript Windows. We'll use a List to keep track of them.
self.TranscriptWindow = []
self.shuttingDown = False # We need to signal when we want to shut down to prevent problems
# with the Visualization Window's IDLE event trying to call the
# VideoWindow after it's been destroyed.
# We need to know what transcript is "Active" (most recently selected) at any given point. -1 signals none.
self.activeTranscript = -1
self.VisualizationWindow = None
self.DataWindow = None
# Keep track of all Snapshot Windows that are opened
self.SnapshotWindows = []
self.PlayAllClipsWindow = None
self.NotesBrowserWindow = None
self.ChatWindow = None
# Keep track of all Report, Map, and Graph Windows that are opened
self.ReportWindows = {}
# Initialize variables
self.VideoFilename = '' # Video File Name
self.VideoStartPoint = 0 # Starting Point for video playback in Milliseconds
self.VideoEndPoint = 0 # Ending Point for video playback in Milliseconds
self.WindowPositions = [] # Initial Screen Positions for all Windows, used for Presentation Mode
self.TranscriptNum = [] # Transcript record # LIST loaded
self.currentObj = None # Currently loaded Object (Episode or Clip)
self.reportNumber = 0 # Report Number, for tracking reports in the Window Menu
# Have the Export Directory default to the Video Root, but then remember its changed value for the session
self.defaultExportDir = TransanaGlobal.configData.videoPath
self.playInLoop = False # Should we loop playback?
self.LoopPresMode = None # What presentation mode are we ignoring while Looping?
self.shutdownPlayAllClips = False # Flag to signal the need to reformat the screen following Play All Clips
def Register(self, Menu='', Video='', Transcript='', Data='', Visualization='', PlayAllClips='', NotesBrowser='', Chat=''):
""" The ControlObject can extert control only over those objects it knows about. This method
provides a way to let the ControlObject know about other objects. This infrastructure allows
for objects to be swapped in and out. For example, if you need a different video window
that supports a format not available on the current one, you can hide the current one, show
a new one, and register that new one with the ControlObject. Once this is done, the new
player will handle all tasks for the program. """
# This function expects parameters passed by name and "registers" the components that
# need to be available to the ControlObject to be controlled. To remove an
# object registration, pass in "None"
if Menu != '':
self.MenuWindow = Menu # Define the Menu Window Object
if Video != '':
self.VideoWindow = Video # Define the Video Window Object
if Transcript != '':
# Add the Transcript Window reference to the list of Transcript Windows
self.TranscriptWindow.append(Transcript)
# Add the Transcript Number to the list of Transcript Numbers
self.TranscriptNum.append(0)
# Set the new Transcript to be the Active Transcript
self.activeTranscript = len(self.TranscriptWindow) - 1
if Data != '':
self.DataWindow = Data # Define the Data Window Object
if Visualization != '':
self.VisualizationWindow = Visualization # Define the Visualization Window Object
if PlayAllClips != '':
self.PlayAllClipsWindow = PlayAllClips # Define the Play All Clips Window Object
if NotesBrowser != '':
self.NotesBrowserWindow = NotesBrowser # Define the Notes Browser Window Object
if Chat != '':
self.ChatWindow = Chat # Define the Chat Window Object
def CloseAll(self):
""" This method closes all application windows and cleans up objects when the user
quits Transana. """
# Closing the MenuWindow will automatically close the Transcript, Data, and Visualization
# Windows in the current setup of Transana, as these windows are all defined as child dialogs
# of the MenuWindow.
self.MenuWindow.Close()
# VideoWindow needs to be closed explicitly.
self.VideoWindow.close()
def CloseAllImages(self):
""" Close all Snapshot Windows """
# For each Shapshot Window (from the end of the list to the start) ...
while len(self.SnapshotWindows) > 0:
# ... close it, thus releasing any records that might be locked there.
self.SnapshotWindows[len(self.SnapshotWindows) - 1].Close()
def CloseAllReports(self):
""" Close all Report Windows """
# For each Report Window (from the end of the list to the start) ...
while len(self.ReportWindows) > 0:
# ... close it, thus releasing any records that might be locked there.
self.ReportWindows[self.ReportWindows.keys()[len(self.ReportWindows) - 1]].Close()
def IconizeAll(self, iconize):
""" Have all windows minimize and restore together """
self.MenuWindow.Iconize(iconize)
self.VisualizationWindow.Iconize(iconize)
self.VideoWindow.Iconize(iconize)
# The TranscriptWindow sometimes MUST be called here, while other times it isn't needed.
for win in self.TranscriptWindow:
win.dlg.Iconize(iconize)
self.DataWindow.Iconize(iconize)
for win in self.SnapshotWindows:
win.Iconize(iconize)
if self.NotesBrowserWindow != None:
self.NotesBrowserWindow.Iconize(iconize)
# The File Management Window also does not need to be processed here.
# For each Report Window ...
for win in self.ReportWindows.keys():
# ... minimize/restore the Report
self.ReportWindows[win].Iconize(iconize)
def LoadTranscript(self, series, episode, transcript):
""" When a Transcript is identified to trigger systemic loading of all related information,
this method should be called so that all Transana Objects are set appropriately. """
# Before we do anything else, let's save the current transcript if it's been modified.
if self.TranscriptWindow[self.activeTranscript].TranscriptModified():
if TransanaConstants.partialTranscriptEdit:
self.SaveTranscript(1, cleardoc=1, continueEditing=False)
else:
self.SaveTranscript(1, cleardoc=1)
# activeTranscript 0 signals we should reset everything in the interface!
if self.activeTranscript == 0:
clearAll = True
else:
clearAll = False
# Clear all Windows
self.ClearAllWindows(resetMultipleTranscripts = clearAll)
# Because transcript names can be identical for different episodes in different series, all parameters are mandatory.
# They are:
# series - the Series associated with the desired Transcript
# episode - the Episode associated with the desired Transcript
# transcript - the Transcript to be displayed in the Transcript Window
seriesObj = Series.Series(series) # Load the Series which owns the Episode which owns the Transcript
episodeObj = Episode.Episode(series=seriesObj.id, episode=episode) # Load the Episode in the Series that owns the Transcript
# Set the current object to the loaded Episode
self.currentObj = episodeObj
transcriptObj = Transcript.Transcript(transcript, ep=episodeObj.number)
# Load the Transcript in the Episode in the Series
# reset the video start and end points
self.VideoStartPoint = 0 # Set the Video Start Point to the beginning of the video
self.VideoEndPoint = 0 # Set the Video End Point to 0, indicating that the video should not end prematurely
# Remove any tabs in the Data Window beyond the Database Tab
self.DataWindow.DeleteTabs()
if self.LoadVideo(self.currentObj): # Load the video identified in the Episode
# Delineate the appropriate start and end points for Video Control. (Required to prevent Waveform Visualization problems)
self.SetVideoSelection(0, 0)
# Force the Visualization to load here. This ensures that the Episode visualization is shown
# rather than the Clip visualization when Locating a Clip
self.VisualizationWindow.OnIdle(None)
# Identify the loaded Object
prompt = _('Transcript "%s" for Series "%s", Episode "%s"')
if self.activeTranscript > 0:
prompt = '** ' + prompt + ' **'
if 'unicode' in wx.PlatformInfo:
# Encode with UTF-8 rather than TransanaGlobal.encoding because this is a prompt, not DB Data.
prompt = unicode(prompt, 'utf8')
# Set the window's prompt
self.TranscriptWindow[self.activeTranscript].dlg.SetTitle(prompt % (transcriptObj.id, seriesObj.id, episodeObj.id))
# If we have only one video file ...
if len(self.currentObj.additional_media_files) == 0:
# Identify the loaded media file
if 'unicode' in wx.PlatformInfo:
# Encode with UTF-8 rather than TransanaGlobal.encoding because this is a prompt, not DB Data.
prompt = unicode(_('Video Media File: "%s"'), 'utf8')
else:
prompt = _('Video Media File: "%s"')
# Place the file name in the video window's Title bar
self.VideoWindow.SetTitle(prompt % episodeObj.media_filename)
# If there are multiple videos ...
else:
# Just label the video window generically. There's not room for file names.
self.VideoWindow.SetTitle(_("Video"))
# Open Transcript in Transcript Window
self.TranscriptWindow[self.activeTranscript].LoadTranscript(transcriptObj) #flies off to transcriptionui.py
# Add the Transcript Number to the list that tracks the numbers of the open transcripts
self.TranscriptNum[self.activeTranscript] = transcriptObj.number
# Add the Episode Clips Tab to the DataWindow
self.DataWindow.AddEpisodeClipsTab(seriesObj=seriesObj, episodeObj=episodeObj)
# Add the Selected Episode Clips Tab, initially set to the beginning of the video file
# TODO: When the Transcript Window updates the selected text, we need to update this tab in the Data Window!
self.DataWindow.AddSelectedEpisodeClipsTab(seriesObj=seriesObj, episodeObj=episodeObj, TimeCode=0)
# Add the Keyword Tab to the DataWindow
self.DataWindow.AddKeywordsTab(seriesObj=seriesObj, episodeObj=episodeObj)
# Enable the transcript menu item options
self.MenuWindow.SetTranscriptOptions(True)
if TransanaConstants.USESRTC:
# After two seconds, call the EditorPaint method of the Transcript Dialog (in the TranscriptionUI_RTC file)
# This causes improperly placed line numers to "correct" themselves!
wx.CallLater(2000, self.TranscriptWindow[self.activeTranscript].dlg.EditorPaint, None)
# Set focus to the new Transcript's Editor (so that CommonKeys work on the Mac)
self.TranscriptWindow[self.activeTranscript].dlg.editor.SetFocus()
# If the video won't load ...
else:
# Clear the interface!
self.ClearAllWindows()
# We only want to load the File Manager in the Single User version. It's not the appropriate action
# for the multi-user version!
if TransanaConstants.singleUserVersion:
# Open the File Management Window just as if the Menu Item was selected, which
# doesn't cause menu problems on OS X
self.MenuWindow.OnFileManagement(None)
## REPLACED - on Mac, when you exit the File Manager, you don't get the menus back!! Yikes!
## # Create a File Management Window
## fileManager = FileManagement.FileManagement(self.MenuWindow, -1, _("Transana File Management"))
## # Set up, display, and process the File Management Window
## fileManager.Setup(showModal=True)
## # Destroy the File Manager window
## fileManager.Destroy()
def LoadClipByNumber(self, clipNum):
""" When a Clip is identified to trigger systematic loading of all related information,
this method should be called so that all Transana Objects are set appropriately. """
# Before we do anything else, let's save the current transcript if it's been modified.
if self.TranscriptWindow[self.activeTranscript].TranscriptModified():
if TransanaConstants.partialTranscriptEdit:
self.SaveTranscript(1, cleardoc=1, continueEditing=False)
else:
self.SaveTranscript(1, cleardoc=1)
# Set Active Transcript to 0 to signal close of all existing secondary Transcript Windows
self.activeTranscript = 0
# Clear all Windows
self.ClearAllWindows()
# Load the Clip based on the ClipNumber
clipObj = Clip.Clip(clipNum)
# Set the current object to the loaded Episode
self.currentObj = clipObj
# Load the Collection that contains the loaded Clip
collectionObj = Collection.Collection(clipObj.collection_num)
# set the video start and end points to the start and stop points defined in the clip
self.VideoStartPoint = clipObj.clip_start # Set the Video Start Point to the Clip beginning
self.VideoEndPoint = clipObj.clip_stop # Set the Video End Point to the Clip end
# Load the video identified in the Clip
if self.LoadVideo(self.currentObj):
# If we have only one video file ...
if len(self.currentObj.additional_media_files) == 0:
# Identify the loaded media file
if 'unicode' in wx.PlatformInfo:
# Encode with UTF-8 rather than TransanaGlobal.encoding because this is a prompt, not DB Data.
prompt = unicode(_('Video Media File: "%s"'), 'utf8')
else:
prompt = _('Video Media File: "%s"')
# Place the file name in the video window's Title bar
self.VideoWindow.SetTitle(prompt % clipObj.media_filename)
# If there are multiple videos ...
else:
# Just label the video window generically. There's not room for file names.
self.VideoWindow.SetTitle(_("Video"))
# Delineate the appropriate start and end points for Video Control
self.SetVideoSelection(self.VideoStartPoint, self.VideoEndPoint)
# Identify the loaded Object
if 'unicode' in wx.PlatformInfo:
# Encode with UTF-8 rather than TransanaGlobal.encoding because this is a prompt, not DB Data.
str = unicode(_('Transcript for Collection "%s", Clip "%s"'), 'utf8') % (collectionObj.GetNodeString(), clipObj.id)
else:
str = _('Transcript for Collection "%s", Clip "%s"') % (collectionObj.GetNodeString(), clipObj.id)
# The Mac doesn't clean up around frame titles!
# (The Mac centers titles, while Windows left-justifies them and should not get the leading spaces!)
if 'wxMac' in wx.PlatformInfo:
str = " " + str + " "
self.TranscriptWindow[self.activeTranscript].dlg.SetTitle(str)
# Open the first Clip Transcript in Transcript Window (activeTranscript is ALWAYS 0 here!)
self.TranscriptWindow[self.activeTranscript].LoadTranscript(clipObj.transcripts[0])
# If we allow multiple transcripts ...
if TransanaConstants.proVersion:
# Open the remaining clip transcripts in additional transcript windows.
for tr in clipObj.transcripts[1:]:
self.OpenAdditionalTranscript(tr.number, isEpisodeTranscript=False)
self.TranscriptWindow[len(self.TranscriptWindow) - 1].dlg.SetTitle(str)
# Remove any tabs in the Data Window beyond the Database Tab. (This was moved down to late in the
# process due to problems on the Mac documented in the DataWindow object.)
self.DataWindow.DeleteTabs()
# Add the Keyword Tab to the DataWindow
self.DataWindow.AddKeywordsTab(collectionObj=collectionObj, clipObj=clipObj)
# Get the current selection(s) from the Database Tree
selItems = self.DataWindow.DBTab.tree.GetSelections()
# If there are one or more items selected ...
if len(selItems) >= 1:
# ... get the item data from the first selection
selData = self.DataWindow.DBTab.tree.GetPyData(selItems[0])
# If NO items are selected ...
else:
# ... then there's no item data to get
selData = None
# If no items are selected or the item selected is NOT a Search Collection or Search Clip ...
if (selData == None) or not (selData.nodetype in ['SearchCollectionNode', 'SearchClipNode']):
# Let's make sure this clip is displayed in the Database Tree
nodeList = (_('Collections'),) + self.currentObj.GetNodeData()
# Now point the DBTree (the notebook's parent window's DBTab's tree) to the loaded Clip
self.DataWindow.DBTab.tree.select_Node(nodeList, 'ClipNode')
# Enable the transcript menu item options
self.MenuWindow.SetTranscriptOptions(True)
return True
else:
# Remove any tabs in the Data Window beyond the Database Tab
self.DataWindow.DeleteTabs()
# We only want to load the File Manager in the Single User version. It's not the appropriate action
# for the multi-user version!
if TransanaConstants.singleUserVersion:
# Create a File Management Window
fileManager = FileManagement.FileManagement(self.MenuWindow, -1, _("Transana File Management"))
# Set up, display, and process the File Management Window
fileManager.Setup(showModal=True)
# Destroy the File Manager window
fileManager.Destroy()
return False
def LoadSnapshot(self, snapshot):
""" Load the SnapshotWindow for the Snapshot object passed in """
# Assume no Snapshot Window exists for this snapshot
windowOpen = False
# If we have a known Snapshot Number ...
if snapshot.number != 0:
# ... iterate through all Snapshot Windows ...
for snapshotWindow in self.SnapshotWindows:
# ... see if there is already a Snapshot Window open for the specified Snapshot
if snapshotWindow.obj.number == snapshot.number:
# If so, show the windows ...
snapshotWindow.Show()
# ... raise it to the top of the stack ...
snapshotWindow.Raise()
# ... and if it's Iconized (minimized) ...
if snapshotWindow.IsIconized():
# ... then un-minimize it. (This is different from maximizing it, of course!)
snapshotWindow.Iconize(False)
# Note that an open windows was found
windowOpen = True
# We can stop looking once we've found an open windows
break
# If we did NOT find an open window ...
if not windowOpen:
# Start Exception Handling
try:
# ... create a new Snapshot Window ...
snapshotDlg = SnapshotWindow.SnapshotWindow(self.MenuWindow, -1, snapshot.id, snapshot)
# ... and add this to the list of open Snapshot Windows
self.SnapshotWindows.append(snapshotDlg)
# Iterate through the existing Snapshot Windows
for win in self.SnapshotWindows:
# For all windows except the newest one ...
if win != snapshotDlg:
# ... add the looping window's ID to the Window Menu
snapshotDlg.AddWindowMenuItem(win.obj.id, win.obj.number)
# Add the new window's ID to the looping window's Window menu
win.AddWindowMenuItem(snapshot.id, snapshot.number)
# Add this to the Menu Window's Window's menu
self.MenuWindow.AddWindowMenuItem(snapshot.id, snapshot.number)
# If an ImageLoadError occurs ...
except TransanaExceptions.ImageLoadError, exception:
# ... report the error to the user
dlg = Dialogs.ErrorDialog(self.MenuWindow, exception.explanation)
dlg.ShowModal()
dlg.Destroy()
def SelectSnapshotWindow(self, itemName, itemNumber, selectInDataWindow=False):
""" Select the indicated Snapshot Window """
# Assume the window will NOT be found
winFound = False
# Iterate through the Snapshot Windows
for win in self.SnapshotWindows:
# If we have the correct window ...
if (itemName == win.obj.id) and (itemNumber == win.obj.number):
# ... if we're supposed to select the Snapshot in the Data Window ...
if selectInDataWindow:
# ... bet the Snapshot's Node Data ...
nodeList = (_('Collections'),) + win.obj.GetNodeData()
# ... and point the DBTree to the loaded Snapshot
self.DataWindow.DBTab.tree.select_Node(nodeList, 'SnapshotNode')
# ... bring it to the top of the window stack ...
win.Raise()
# ... make sure it's not minimized ...
win.Iconize(False)
# ... give it focus ...
win.SetFocus()
# Note that the window has been found
winFound = True
# ... and stop looking
break
# Return an indicator of whether the window was found
return winFound
def RemoveSnapshotWindow(self, itemName, itemNumber):
""" Remove a Snapshot Window and all references from Transana's Interface """
# Iterate through the Snapshot Windows.
for snapshotWindow in self.SnapshotWindows:
# When we find the Snapshot Window reference for this Snapshot ...
if itemNumber == snapshotWindow.obj.number:
# ... remove it from the List of Snapshot Windows
self.SnapshotWindows.remove(snapshotWindow)
# Iterate through the Snapshot Windows again. (remove() above changed the number of items, so skips one!)
for snapshotWindow in self.SnapshotWindows:
# Remove this item from the Snapshot Windows' Window menu
snapshotWindow.DeleteWindowMenuItem(itemName, itemNumber)
# Remove this from the Menu Window's Window's menu
self.MenuWindow.DeleteWindowMenuItem(itemName, itemNumber)
def GetOpenSnapshotWindows(self, editableOnly=False):
""" Return a list of all Snapshot Windows that are open """
# Initialize values to be returned
values = []
# Iterate through the Snapshot Windows
for win in self.SnapshotWindows:
# If we want all windows, or if the current window is editable ...
if (not editableOnly) or win.editTool.IsToggled():
# ... then add the window to the return values
values.append(win)
# Return the Return values
return values
def UpdateWindowMenu(self, oldSnapshotName, oldSnapshotNumber, newSnapshotName, newSnapshotNumber):
""" Update all Window Menus when a Snapshot Window changes Snapshots through Prev / Next buttons """
# See if the NEW window is already open somewhere
if self.SelectSnapshotWindow(newSnapshotName, newSnapshotNumber):
# If so, iterate through the open Snapshot Windows ...
for win in self.SnapshotWindows:
# If this Snapshot Window matches the one we're trying to open ...
if (win.obj.id == newSnapshotName) and (win.obj.number == newSnapshotNumber):
# ... then close it! (This will save unsaved edits!
win.Close()
# Iterate through the open Snapshot Windows ...
for win in self.SnapshotWindows:
# ... and trigger an update to their MenuWindows
win.UpdateWindowMenuItem(oldSnapshotName, oldSnapshotNumber, newSnapshotName, newSnapshotNumber)
# Update the MenuWindow's Windows Menu
self.MenuWindow.UpdateWindowMenuItem(oldSnapshotName, oldSnapshotNumber, newSnapshotName, newSnapshotNumber)
def ShowNotesBrowser(self):
""" Bring the Notes Browser to the front """
# Raise the Notes Browser Window to the top
self.NotesBrowserWindow.Raise()
# If the Notes Browser is minimized ...
if self.NotesBrowserWindow.IsIconized():
# ... restore it to full size
self.NotesBrowserWindow.Iconize(False)
# Push the Visualization Window behind it
self.VisualizationWindow.Lower()
# Push the Video Window behind it
self.VideoWindow.Lower()
# For each Transcript Window ...
for win in self.TranscriptWindow:
# ... push the transcript behind the Notes Browser
win.dlg.Lower()
# Push the Data Window behind it
self.DataWindow.Lower()
# For each Snapshot Window ...
for win in self.SnapshotWindows:
# ... push the Snapshot behind the Notes Browser
win.Lower()
# For each Report Window ...
for win in self.ReportWindows.keys():
# ... push the Report behind the Notes Browser
self.ReportWindows[win].Lower()
def AddReportWindow(self, reportWindow):
""" Add a Report Window to Transana's Interface """
# Increment the unique Report Number
self.reportNumber += 1
# Remember the report in the ReportWindows dictionary
self.ReportWindows[self.reportNumber] = reportWindow
# Add the unique Report Number to the report
reportWindow.reportNumber = self.reportNumber
# Add the Report to the Window Menu
self.MenuWindow.AddWindowMenuItem(reportWindow.title, self.reportNumber)
def SelectReportWindow(self, reportName, reportNumber):
""" Select the indicated Report Window """
# If the desired report number is in the ReportWindows keys ...
if reportNumber in self.ReportWindows.keys():
# ... select the correct window
win = self.ReportWindows[reportNumber]
# ... bring it to the top of the window stack ...
win.Raise()
# ... make sure it's not minimized ...
win.Iconize(False)
# ... give it focus ...
win.SetFocus()
def RemoveReportWindow(self, reportName, reportNumber):
""" Remove a Report Window from Transana's Interface """
# If the report window still exists ... (sometimes a close event will get double-called and the report will already be gone!)
if self.ReportWindows.has_key(reportNumber):
# Delete the Report Window from the ReportWindows dictionary
del(self.ReportWindows[reportNumber])
# Remove this from the Menu Window's Window's menu
self.MenuWindow.DeleteWindowMenuItem(reportName, reportNumber)
def OpenAdditionalTranscript(self, transcriptNum, seriesID='', episodeID='', isEpisodeTranscript=True):
""" Open an additional Transcript without replacing the current one """
# Create a new Transcript Window
newTranscriptWindow = TranscriptionUI.TranscriptionUI(TransanaGlobal.menuWindow, includeClose=True)
# Register this new Transcript Window with the Control Object (self)
self.Register(Transcript=newTranscriptWindow)
# Register the Control Object (self) with the new Transcript Window
newTranscriptWindow.Register(self)
# Get out Transcript object from the database
transcriptObj = Transcript.Transcript(transcriptNum)
# If we have an Episode Transcript, it needs a Window title. (Clip titles are handled in the calling routine.)
if isEpisodeTranscript:
# If we haven't been sent an Episode ID ...
if episodeID == '':
# ... get the Episode data based on the Transcript Object ...
episodeObj = Episode.Episode(transcriptObj.episode_num)
# ... and note the Episode ID
episodeID = episodeObj.id
# If we haven't been sent the Series ID ...
if seriesID == '':
# ... get the Series data based on the Episode object ...
seriesObj = Series.Series(episodeObj.series_num)
# ... and note the Series ID
seriesID = seriesObj.id
# Identify the loaded Object
prompt = _('Transcript "%s" for Series "%s", Episode "%s"')
if self.activeTranscript > 0:
prompt = '** ' + prompt + ' **'
if 'unicode' in wx.PlatformInfo:
# Encode with UTF-8 rather than TransanaGlobal.encoding because this is a prompt, not DB Data.
prompt = unicode(prompt, 'utf8')
# Set the window's prompt
newTranscriptWindow.dlg.SetTitle(prompt % (transcriptObj.id, seriesID, episodeID))
# Load the transcript text into the new transcript window
newTranscriptWindow.LoadTranscript(transcriptObj)
# Add the new transcript's number to the list that tracks the numbers of the open transcripts.
self.TranscriptNum[len(self.TranscriptNum) - 1] = transcriptObj.number
# Now we need to arrange the various Transcript windows.
# if Auto Arrange is enabled ...
if TransanaGlobal.configData.autoArrange:
self.AutoArrangeTranscriptWindows()
# If Auto Arrange is OFF
else:
# Determine the position and size of the LAST Transcript Window
(left, top) = self.TranscriptWindow[self.activeTranscript - 1].dlg.GetPositionTuple()
(width, height) = self.TranscriptWindow[self.activeTranscript - 1].dlg.GetSizeTuple()
# Make the new Transcript offset from the last transcript and just a little smaller
self.TranscriptWindow[self.activeTranscript].dlg.SetDimensions(left + 16, top + 16, width - 16, height - 16)
# Display the new Transcript window
newTranscriptWindow.Show()
newTranscriptWindow.UpdatePosition(self.VideoWindow.GetCurrentVideoPosition())
# Enable the Multiple Transcript buttons
for x in range(len(self.TranscriptWindow)):
self.TranscriptWindow[x].dlg.toolbar.UpdateMultiTranscriptButtons(True)
# Set focus to the new Transcript's Editor (so that CommonKeys work on the Mac)
self.TranscriptWindow[self.activeTranscript].dlg.editor.SetFocus()
if DEBUG:
print "ControlObjectClass.OpenAdditionalTranscript(%d) %d" % (transcriptNum, self.activeTranscript)
for x in range(len(self.TranscriptWindow)):
print x, self.TranscriptWindow[x].transcriptWindowNumber, self.TranscriptNum[x]
print
def CloseAdditionalTranscript(self, transcriptNum):
""" Close a secondary transcript """
# If we're closeing a transcript other than the active transcript ...
if self.activeTranscript != transcriptNum and not self.shuttingDown:
# ... remember which transcript WAS active ...
prevActiveTranscript = self.activeTranscript
# ... and make the one we're supposed to close active.
self.activeTranscript = transcriptNum
# If we're closing the active transcript ...
else:
# ... then focus should switch to the top transcript, # 0
prevActiveTranscript = 0
# If the prevActiveTranscript is about to be closed, we need to reduce it by one to avoid
# problems on the Mac.
if prevActiveTranscript == len(self.TranscriptWindow) - 1:
prevActiveTranscript = self.activeTranscript - 1
# Before we do anything else, let's save the current transcript if it's been modified.
if self.TranscriptWindow[transcriptNum].TranscriptModified():
if TransanaConstants.partialTranscriptEdit:
self.SaveTranscript(1, cleardoc=1, continueEditing=False)
else:
self.SaveTranscript(1, cleardoc=1)
if transcriptNum == 0:
(left, top) = self.TranscriptWindow[0].dlg.GetPositionTuple()
self.TranscriptWindow[1].dlg.SetPosition(wx.Point(left, top))
# ... remove it from the Transcript Window list
del(self.TranscriptWindow[transcriptNum])
# ... and remove it from the Transcript Numbers list
del(self.TranscriptNum[transcriptNum])
# When all the Transcript Windows are closed, rearrrange the screen
self.AutoArrangeTranscriptWindows()
# We need to update the window numbers of the transcript windows.
for x in range(len(self.TranscriptWindow)):
# Update the TranscriptUI object
self.TranscriptWindow[x].transcriptWindowNumber = x
# Also update the TranscriptUI's Dialog object. (This is crucial)
self.TranscriptWindow[x].dlg.transcriptWindowNumber = x
# Set the frame focus to the Previous active transcript (I'm not convinced this does anything!)
self.TranscriptWindow[prevActiveTranscript].dlg.SetFocus()
# Update the Active Transcript number
self.activeTranscript = prevActiveTranscript
# If there's only one transcript left ...
if len(self.TranscriptWindow) == 1:
# ... Disable the Multiple Transcript buttons
self.TranscriptWindow[0].dlg.toolbar.UpdateMultiTranscriptButtons(False)
def SaveAllTranscriptCursors(self):
""" Save the current cursor position or selection for all open Transcript windows """
# For each Transcript Window ...
for trWin in self.TranscriptWindow:
# ... save the cursorPosition
trWin.dlg.editor.SaveCursor()
def RestoreAllTranscriptCursors(self):
""" Restore the previously saved cursor position or selection for all open Transcript windows """
# For each Transcript Window ...
for trWin in self.TranscriptWindow:
# ... if it HAS a saved cursorPosition ...
if trWin.dlg.editor.cursorPosition != 0:
# ... restore the cursor position or selection
trWin.dlg.editor.RestoreCursor()
def AutoArrangeTranscriptWindows(self):
# If we have more than one window ...
if len(self.TranscriptWindow) > 1:
# ... define a style that includes the Close Box. (System_Menu is required for Close to show on Windows in wxPython.)
style = wx.CAPTION | wx.RESIZE_BORDER | wx.WANTS_CHARS | wx.SYSTEM_MENU | wx.CLOSE_BOX
# If there's only one window...
else:
# ... then we don't want the close box
style = wx.CAPTION | wx.RESIZE_BORDER | wx.WANTS_CHARS
# Reset the style for the top window
self.TranscriptWindow[0].dlg.SetWindowStyleFlag(style)
# Some style changes require a refresh
self.TranscriptWindow[0].dlg.Refresh()
# We need to arrange the transcripts if we're leaving Play All Clips mode or if we're in All Windows presentation mode
if (self.PlayAllClipsWindow == None) or \
(self.MenuWindow.menuBar.optionsmenu.IsChecked(MenuSetup.MENU_OPTIONS_PRESENT_ALL)):
# Determine the position and size of the first Transcript
(left, top) = self.TranscriptWindow[0].dlg.GetPositionTuple()
(width, height) = self.TranscriptWindow[0].dlg.GetSizeTuple()
# Get the size of the full screen
(x, y, w, h) = wx.Display(TransanaGlobal.configData.primaryScreen).GetClientArea() # self.MenuWindow.GetClientRect()
# We don't want the height of the first Transcript window, but the size of the space for all Transcript windows.
# We assume that it extends from the top of the first Transcript window to the bottom of the whole screen.
height = y + h - top
# If there's only ONE Media Player AND AutoArrange is turned ON ...
if (len(self.VideoWindow.mediaPlayers) == 1) and TransanaGlobal.configData.autoArrange:
# ... the width from the Transcript may very well be incorrect. Let's grab the width from the Visualization Window
(width, vh) = self.VisualizationWindow.GetSizeTuple()
# Initialize a Window Counter
cnt = 0
# Remember if we're resizing All
tmpResizingAll = TransanaGlobal.resizingAll
# For the moment, we want to signal we are resizing all regardless
TransanaGlobal.resizingAll = True
# Iterate through all the Transcript Windows
for win in self.TranscriptWindow:
# Increment the counter
cnt += 1
# Set the position of each window so they evenly fill up the Transcript space
win.dlg.SetDimensions(left, top + int((cnt-1) * (height / len(self.TranscriptWindow))), width, int(height / len(self.TranscriptWindow)))
# Restore the original value of resizingAll
TransanaGlobal.resizingAll = tmpResizingAll
def ClearAllWindows(self, resetMultipleTranscripts = True):
""" Clears all windows and resets all objects """
# Let's stop the media from playing
self.VideoWindow.Stop()
# Prompt for save if transcript modifications exist
if TransanaConstants.partialTranscriptEdit:
self.SaveTranscript(1, continueEditing=False)
else:
self.SaveTranscript(1)
if resetMultipleTranscripts:
self.activeTranscript = 0
# Reset the ControlObject's TranscriptNum
self.TranscriptNum[self.activeTranscript] = 0
# Clear Transcript Window
self.TranscriptWindow[self.activeTranscript].ClearDoc()
# Identify the loaded Object
str = _('Transcript')
self.TranscriptWindow[self.activeTranscript].dlg.SetTitle(str)
# Force the screen updates.
# If this is left out, we get an exception when deleting an OPEN multi-transcript clip on OS X.
# there can be an issue with recursive calls to wxYield, so trap the exception ...
try:
wx.Yield()
# ... and ignore it!
except:
pass
# Clear the Menu Window (Reset menus to initial state)
self.MenuWindow.ClearMenus()
# Clear Visualization Window
self.VisualizationWindow.ClearVisualization()
# Clear the Video Window
self.VideoWindow.ClearVideo()
# Clear the Video Filename as well!
self.VideoFilename = ''
# Identify the loaded media file
str = _('Video')
self.VideoWindow.SetTitle(str)
# If we are resetting multiple transcripts ...
if resetMultipleTranscripts:
# While there are additional Transcript windows open ...
while len(self.TranscriptWindow) > 1:
# Save the transcript
if TransanaConstants.partialTranscriptEdit:
self.SaveTranscript(1, transcriptToSave=len(self.TranscriptWindow) - 1, continueEditing=False)
else:
self.SaveTranscript(1, transcriptToSave=len(self.TranscriptWindow) - 1)
# Clear Transcript Window
self.TranscriptWindow[len(self.TranscriptWindow) - 1].ClearDoc()
self.TranscriptWindow[len(self.TranscriptWindow) - 1].dlg.Close()
# When all the Transcritp Windows are closed, rearrrange the screen
self.AutoArrangeTranscriptWindows()
# Clear the Data Window
self.DataWindow.ClearData()
## # Close all Snapshot Windows
## self.CloseAllImages()
## # Close all Reports
## # BREAKS RIGHT-CLICK for Keyword Map and Series Keyword Sequence Map !!
## self.CloseAllReports()
# Clear the currently loaded object, as there is none
self.currentObj = None
# Force the screen updates
# there can be an issue with recursive calls to wxYield, so trap the exception ...
try:
wx.Yield()
# ... and ignore it!
except:
pass
def GetNewDatabase(self):
""" Close the old database and open a new one. """
# set the active transcript to 0 so multiple transcript will be cleared
self.activeTranscript = 0
# Clear all existing Data
self.ClearAllWindows()
# Close all Snapshot Windows
self.CloseAllImages()
# Close all Reports
self.CloseAllReports()
# If we're in multi-user ...
if not TransanaConstants.singleUserVersion:
# ... stop the Connection Timer so it won't fire while the Database is closed
TransanaGlobal.connectionTimer.Stop()
# Close the existing database connection
DBInterface.close_db()
# Reset the global encoding to UTF-8 if the Database supports it
if (TransanaGlobal.DBVersion >= u'4.1') or \
(not TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']):
TransanaGlobal.encoding = 'utf8'
# Otherwise, if we're in Russian, change the encoding to KOI8r
elif TransanaGlobal.configData.language == 'ru':
TransanaGlobal.encoding = 'koi8_r'
# If we're in Chinese, change the encoding to the appropriate Chinese encoding
elif TransanaGlobal.configData.language == 'zh':
TransanaGlobal.encoding = TransanaConstants.chineseEncoding
# If we're in East Europe Encoding, change the encoding to 'iso8859_2'
elif TransanaGlobal.configData.language == 'easteurope':
TransanaGlobal.encoding = 'iso8859_2'
# If we're in Greek, change the encoding to 'iso8859_7'
elif TransanaGlobal.configData.language == 'el':
TransanaGlobal.encoding = 'iso8859_7'
# If we're in Japanese, change the encoding to cp932
elif TransanaGlobal.configData.language == 'ja':
TransanaGlobal.encoding = 'cp932'
# If we're in Korean, change the encoding to cp949
elif TransanaGlobal.configData.language == 'ko':
TransanaGlobal.encoding = 'cp949'
# Otherwise, fall back to Latin-1
else:
TransanaGlobal.encoding = 'latin1'
# If a new database login fails three times, we need to close the program.
# Initialize a counter to track that.
logonCount = 1
# Flag if Logon succeeds
loggedOn = False
# Keep trying for three tries or until successful
while (logonCount <= 3) and (not loggedOn):
# Increment logon counter
logonCount += 1
# Call up the Username and Password Dialog to get new connection information
if DBInterface.establish_db_exists():
# Now update the Data Window
self.DataWindow.DBTab.tree.refresh_tree()
# Indicate successful logon
loggedOn = True
# If logon fails, inform user and offer to try again twice.
elif logonCount <= 3:
# Create a Dialog Box
dlg = Dialogs.QuestionDialog(self.MenuWindow, _('Transana was unable to connect to the database.\nWould you like to try again?'),
_('Transana Database Connection'))
# If the user does not want to try again, set the counter to 4, which will cause the program to exit
if dlg.LocalShowModal() == wx.ID_NO:
logonCount = 4
# Clean up the Dialog Box
dlg.Destroy()
# If we're in multi-user and we successfully logged in ...
if not TransanaConstants.singleUserVersion and loggedOn:
# ... start the Connection Timer. This attempts to prevent the "Connection to Database Lost" error by
# running a very small query every 10 minutes. See Transana.py.
TransanaGlobal.connectionTimer.Start(600000)
# If the Database Connection fails ...
if not loggedOn:
# ... Close Transana
self.MenuWindow.OnFileExit(None)
def ShowDataTab(self, tabValue):
""" Changes the visible tab in the notebook in the Data Window """
if self.MenuWindow.menuBar.optionsmenu.IsChecked(MenuSetup.MENU_OPTIONS_PRESENT_ALL):
# Display the Keywords Tab
self.DataWindow.nb.SetSelection(tabValue)
# Refresh the display for OS X
self.DataWindow.Refresh()
def ProcessCommonKeyCommands(self, event):
""" Process keyboard commands common to several of Transana's main windows """
# Assume the key WILL be processed here in this this method
keyProcessed = True
# Extract the key code from the event passed in
c = event.GetKeyCode()
# Determine if there are modifiers
hasMods = event.AltDown() or event.ControlDown() or event.CmdDown() or event.ShiftDown()
# Note whether there is something loaded in the main interface
loaded = (self.currentObj != None)
# F1 = Focus on Menu Window
if (c == wx.WXK_F1) and not hasMods:
# Set the focus on the Menu Window
self.MenuWindow.tmpCtrl.SetFocus()
# F2 = Focus on Visualization Window
elif (c == wx.WXK_F2) and not hasMods:
# Set the focus to the Visualization Window
self.VisualizationWindow.SetFocus()
# F3 = Focus on Video Window
elif (c == wx.WXK_F3) and not hasMods:
# Set the focus to the Video Window
self.VideoWindow.SetFocus()
# F4 = Focus on Transcript Window
elif (c == wx.WXK_F4) and not hasMods:
# Determine where the focus currently is (I don't exactly understand why this works. It's something about
# this being a "static function")
tmpFocVal = self.TranscriptWindow[self.activeTranscript].dlg.editor.FindFocus()
# Now set the focus to the currently active transcript window
self.TranscriptWindow[self.activeTranscript].dlg.editor.SetFocus()
# If the focus didn't change ...
if tmpFocVal == self.TranscriptWindow[self.activeTranscript].dlg.editor.FindFocus():
# ... then the Transcript Window already HAD focus. So see if there is more than one Transcript Window ...
if len(self.TranscriptWindow) > 1:
# ... if so, see if the active window is NOT the highest numbered transcript window.
if self.activeTranscript < len(self.TranscriptWindow) - 1:
# If NOT, increment the Transcript Window by one
self.activeTranscript += 1
# If we're on the highest-numbered transcript window ...
else:
# ... then increment back to the start, window zero
self.activeTranscript = 0
# Now set the focus to the NEW Transcript Window
self.TranscriptWindow[self.activeTranscript].dlg.editor.SetFocus()
# F5 = Focus on Data Window
elif (c == wx.WXK_F5) and not hasMods:
# If the Data Window is currently showing the Database tab ...
if self.DataWindow.nb.GetPageText(self.DataWindow.nb.GetSelection()) == unicode(_("Database"), 'utf8'):
# ... set the focus to the Database Tree on that tab
self.DataWindow.DBTab.tree.SetFocus()
# Otherwise ...
else:
# ... just focus on the Data Window Notebook control.
self.DataWindow.nb.SetFocus()
# F6 = Toggle Edit / Read Only Mode
elif (c == wx.WXK_F6) and not hasMods and loaded:
# Set the focus to the Transcript
self.TranscriptWindow[self.activeTranscript].dlg.editor.SetFocus()
# Toggle the Read Only Button on the Transcript Toolbar
self.TranscriptWindow[self.activeTranscript].dlg.toolbar.ToggleTool(
self.TranscriptWindow[self.activeTranscript].dlg.toolbar.CMD_READONLY_ID,
self.TranscriptWindow[self.activeTranscript].dlg.editor.get_read_only())
# Emulate the Press of the Read Only Button by calling its event directly
self.TranscriptWindow[self.activeTranscript].dlg.toolbar.OnReadOnlySelect(event)
# F12 and Ctrl-F12 (for Mac) are Quick Save
elif (c == wx.WXK_F12) and not (event.AltDown() or event.CmdDown() or event.ShiftDown()) and loaded:
# if the transcript is in EDIT mode ...
if not self.TranscriptWindow[self.activeTranscript].dlg.editor.get_read_only():
# ... save it