forked from gispos/AvsPmod
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwxp.py
2402 lines (2202 loc) · 107 KB
/
wxp.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
# wxp - general framework classes for wxPython
#
# Copyright 2007 Peter Jang <http://avisynth.nl/users/qwerpoi>
# 2010-2013 the AvsPmod authors <https://github.com/avspmod/avspmod>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# 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., 675 Mass Ave, Cambridge, MA 02139, USA, or visit
# http://www.gnu.org/copyleft/gpl.html .
# Dependencies:
# Python (tested on v2.6 and 2.7)
# wxPython (tested on v2.8 Unicode and 2.9)
# Scripts:
# icon.py (icons embedded in a Python script)
import wx
import wx.lib.buttons as wxButtons
import wx.lib.mixins.listctrl as listmix
import wx.lib.filebrowsebutton as filebrowse
import wx.lib.colourselect as colourselect
#import colourselect_dpi as colourselect
from wx.lib.agw.floatspin import FloatSpin
from wx.lib.agw.hyperlink import HyperLinkCtrl
import wx.lib.agw.ultimatelistctrl as ULC
from wx import stc
import string
import keyword
import os
import os.path
import sys
import copy
import time
import dpi
import wx.lib.newevent
import socket
try:
import thread
except:
pass
# or import threading??
try:
from StringIO import StringIO
except ImportError:
from io import StringIO # not 100% the same, ComvertError can occur
# Python 3: The StringIO and cStringIO modules are gone.
# Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.
try:
import cPickle # Python 2
except ImportError:
import pickle as cPickle # Python 3
from icons import checked_icon, unchecked_icon
OPT_ELEM_CHECK = 0
OPT_ELEM_INT = 1
OPT_ELEM_FLOAT = 1
OPT_ELEM_SPIN = 1
OPT_ELEM_STRING = 2
OPT_ELEM_FILE = 3
OPT_ELEM_FILE_OPEN = 3
OPT_ELEM_FILE_SAVE = 4
OPT_ELEM_FILE_URL = 5
OPT_ELEM_DIR = 6
OPT_ELEM_DIR_URL = 7
OPT_ELEM_RADIO = 8
OPT_ELEM_LIST = 9
OPT_ELEM_SLIDER = 10
OPT_ELEM_COLOR = 11
OPT_ELEM_FONT = 12
OPT_ELEM_BUTTON = 13
OPT_ELEM_SEP = 14
keyStringList = [
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12',
'Enter', 'Space', 'Escape', 'Tab', 'Insert', 'Backspace', 'Delete',
'Home', 'End', 'PgUp', 'PgDn', 'Up', 'Down', 'Left', 'Right', 'NumLock',
'Numpad 0', 'Numpad 1', 'Numpad 2', 'Numpad 3', 'Numpad 4', 'Numpad 5', 'Numpad 6', 'Numpad 7', 'Numpad 8', 'Numpad 9',
'Numpad +', 'Numpad -', 'Numpad *', 'Numpad /', 'Numpad .', 'Numpad Enter',
'`', '-', '=', '\\', '[', ']', ';', "'", ',', '.', '/',
'~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '|', '{', '}', ':', '"', '<', '>', '?',
]
numpadDict = {
'NumLock' : wx.WXK_NUMLOCK,
'Numpad 0': wx.WXK_NUMPAD0,
'Numpad 1': wx.WXK_NUMPAD1,
'Numpad 2': wx.WXK_NUMPAD2,
'Numpad 3': wx.WXK_NUMPAD3,
'Numpad 4': wx.WXK_NUMPAD4,
'Numpad 5': wx.WXK_NUMPAD5,
'Numpad 6': wx.WXK_NUMPAD6,
'Numpad 7': wx.WXK_NUMPAD7,
'Numpad 8': wx.WXK_NUMPAD8,
'Numpad 9': wx.WXK_NUMPAD9,
'Numpad +': wx.WXK_NUMPAD_ADD,
'Numpad -': wx.WXK_NUMPAD_SUBTRACT,
'Numpad *': wx.WXK_NUMPAD_MULTIPLY,
'Numpad /': wx.WXK_NUMPAD_DIVIDE,
'Numpad .': wx.WXK_NUMPAD_DECIMAL,
'Numpad Enter': wx.WXK_NUMPAD_ENTER,
}
(PostArgsEvent, EVT_POST_ARGS) = wx.lib.newevent.NewEvent()
try: _
except NameError:
def _(s): return s
def MakeWindowTransparent(window, amount, intangible=False):
import ctypes
user32 = ctypes.windll.user32
hwnd = window.GetHandle()
style = user32.GetWindowLongA(hwnd, 0xffffffec) # Python3: no L suffix after 0xffffffec
style |= 0x00080000
if intangible:
style |= 0x00000020 # Python3: no L suffix
window.SetWindowStyleFlag(window.GetWindowStyleFlag()|wx.STAY_ON_TOP)
user32.SetWindowLongA(hwnd, 0xffffffec, style) # Python3: no L suffix after 0xffffffec
user32.SetLayeredWindowAttributes(hwnd, 0, amount, 2)
def GetTranslatedShortcut(shortcut):
return shortcut.replace('Ctrl', _('Ctrl')).replace('Shift', _('Shift')).replace('Alt', _('Alt'))
class CharValidator(wx.PyValidator):
def __init__(self, flag):
wx.PyValidator.__init__(self)
self.flag = flag
self.Bind(wx.EVT_CHAR, self.OnChar)
def Clone(self):
return CharValidator(self.flag)
def Validate(self, win):
return True
def TransferToWindow(self):
return True
def TransferFromWindow(self):
return True
def OnChar(self, event):
key = event.GetKeyCode()
if key < wx.WXK_SPACE or key == wx.WXK_DELETE or key > 255:
event.Skip()
return
if self.flag == 'alpha' and chr(key) in string.letters:
event.Skip()
return
if self.flag == 'digit' and chr(key) in string.digits:
event.Skip()
return
return
class ListCtrl(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin):
def __init__(self, parent, ID, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0):
wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
listmix.ListCtrlAutoWidthMixin.__init__(self)
self.parent = parent
def SelectItem(self, item, setFocus=True):
self.SetItemState(item, wx.LIST_STATE_SELECTED|wx.LIST_STATE_FOCUSED, wx.LIST_STATE_SELECTED|wx.LIST_STATE_FOCUSED)
self.EnsureVisible(item)
if setFocus:
self.SetFocus()
def SelectLabel(self, label):
item = self.FindItem(-1, label)
self.SelectItem(item)
def GetSelectedItem(self):
return self.GetNextItem(-1, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED)
class UListCtrl(ULC.UltimateListCtrl, listmix.ListCtrlAutoWidthMixin):
def __init__(self, parent, ID, agwStyle=0):
ULC.UltimateListCtrl.__init__(self, parent, ID, agwStyle=agwStyle)
self.parent = parent
def SelectItem(self, item):
self.SetItemState(item, ULC.ULC_STATE_SELECTED|ULC.ULC_STATE_FOCUSED, ULC.ULC_STATE_SELECTED|ULC.ULC_STATE_FOCUSED)
self.EnsureVisible(item)
def GetSelectedItem(self):
return self.GetNextItem(-1, ULC.ULC_NEXT_ALL, ULC.ULC_STATE_SELECTED)
class MenuItemInfo(object):
def __init__(self, label=None, handler=None, status=None, submenu=None, id=wx.ID_ANY):
self.label = label
self.handler = handler
self.submenu = submenu
self.id = id
class StdoutStderrWindow:
"""
A class that can be used for redirecting Python's stdout and
stderr streams. It will do nothing until something is written to
the stream at which point it will create a Frame with a text area
and write the text there.
"""
def __init__(self, title=None):
if title is None:
title = _('Error Window')
self.frame = None
self.title = title
self.pos = wx.DefaultPosition
self.size = dpi.tuplePPI(550, 300)
self.parent = None
logname = 'error_log.txt'
if hasattr(sys,'frozen'):
self.logfilename = os.path.join(os.path.dirname(sys.executable), logname)
else:
self.logfilename = os.path.join(os.getcwdu(), logname)
self.firstTime = True
def SetParent(self, parent):
"""Set the window to be used as the popup Frame's parent."""
self.parent = parent
def CreateOutputWindow(self, st):
if self.frame is None:
self.frame = wx.Frame(self.parent, -1, self.title, self.pos, self.size,
style=wx.DEFAULT_FRAME_STYLE)
dpi.SetFontPPI(self.frame)
self.text = TextCtrl(self.frame, -1, "",
style=wx.TE_MULTILINE|wx.TE_READONLY)
wx.EVT_CLOSE(self.frame, self.OnCloseWindow)
if st:
self.text.AppendText(st)
self.frame.Show(True)
def OnCloseWindow(self, event=None):
if self.frame is not None:
self.frame.Destroy()
self.frame = None
self.text = None
# These methods provide the file-like output behaviour.
def write(self, text):
"""
Create the output window if needed and write the string to it.
If not called in the context of the gui thread then uses
CallAfter to do the work there.
"""
if self.frame is None:
if not wx.Thread_IsMain():
wx.CallAfter(self.CreateOutputWindow, text)
else:
self.CreateOutputWindow(text)
else:
if not wx.Thread_IsMain():
wx.CallAfter(self.text.AppendText, text)
else:
self.text.AppendText(text)
f = open(self.logfilename, 'a')
if self.firstTime:
f.write('\n[%s]\n' % time.asctime())
self.firstTime = False
f.write(text)
f.close()
def close(self):
if self.frame is not None:
wx.CallAfter(self.OnCloseWindow, None)
def flush(self):
pass
class App(wx.App):
outputWindowClass = StdoutStderrWindow
class SingleInstanceApp(wx.App):
outputWindowClass = StdoutStderrWindow
#~port = 50009
# GPo 2020, make sure the port in AvsPmode is the same
# make a difference between x64, x32
xSys = 'x64' if sys.maxsize > 2**32 else 'x32'
port = 50009 if xSys == 'x64' else 50008
name = 'SingleInstanceApp'
IsFirstInstance = True
boolSingleInstance = True
def __init__(self, *args, **kwargs):
# Get extra keyword arguments
if kwargs.has_key('name'):
#~self.name = kwargs.pop('name')
self.name = kwargs.pop('name') + xSys # GPo 2020, make sure the name in AvsPmode is the same
if kwargs.has_key('port'):
self.port = kwargs.pop('port')
# Determine if program is already running or not
self.instance = wx.SingleInstanceChecker(self.name+wx.GetUserId())
if self.instance.IsAnotherRunning():
self.IsFirstInstance = False
if self.boolSingleInstance:
# Send data to the main instance via socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', self.port))
pickledstring = StringIO()
cPickle.dump(sys.argv[1:],pickledstring)
sock.sendall(pickledstring.getvalue())
response = sock.recv(8192)
# Start the wx.App (typically check self.IsFirstInstance flag and return False)
wx.App.__init__(self, *args, **kwargs)
else:
self.IsFirstInstance = True
wx.App.__init__(self, *args, **kwargs)
# Start socket server (in a separate thread) to receive arguments from other instances
self.argsPosterThread = ArgsPosterThread(self)
self.argsPosterThread.Start()
def OnExit(self):
if self.IsFirstInstance:
wx.Yield()
self.argsPosterThread.Stop()
running = 1
while running:
running = 0
running = running + self.argsPosterThread.IsRunning()
time.sleep(0.1)
class ArgsPosterThread:
def __init__(self, app):
self.app = app
def Start(self):
self.keepGoing = self.running = True
thread.start_new_thread(self.Run, ())
def Stop(self):
self.keepGoing = False
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect(('localhost', self.app.port))
sock.close()
except:
pass
def IsRunning(self):
return self.running
def Run(self):
# Prevent open sockets from being inherited by child processes
# see http://bugs.python.org/issue3006
# code taken from CherryPy
#
# Copyright (c) 2004-2011, CherryPy Team ([email protected])
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the CherryPy Team nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
try:
import fcntl
except ImportError:
try:
from ctypes import windll, WinError
except ImportError:
def prevent_socket_inheritance(sock):
"""Dummy function, since neither fcntl nor ctypes are available."""
pass
else:
def prevent_socket_inheritance(sock):
"""Mark the given socket fd as non-inheritable (Windows)."""
if not windll.kernel32.SetHandleInformation(sock.fileno(), 1, 0):
raise WinError()
else:
def prevent_socket_inheritance(sock):
"""Mark the given socket fd as non-inheritable (POSIX)."""
fd = sock.fileno()
old_flags = fcntl.fcntl(fd, fcntl.F_GETFD)
fcntl.fcntl(fd, fcntl.F_SETFD, old_flags | fcntl.FD_CLOEXEC)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
prevent_socket_inheritance(sock)
sock.bind(('localhost',self.app.port))
sock.listen(5)
try:
while self.keepGoing:
newSocket, address = sock.accept()
prevent_socket_inheritance(newSocket)
while True:
receivedData = newSocket.recv(8192)
if not receivedData: break
# Post a wxPython event with the unpickled data
pickledstring = StringIO(receivedData)
unpickled = cPickle.load(pickledstring)
evt = PostArgsEvent(data=unpickled)
wx.PostEvent(self.app, evt)
newSocket.sendall(receivedData)
newSocket.close()
if self.app.IsIconized():
self.app.Iconize(False)
else:
self.app.Raise()
if self.app.separatevideowindow and self.app.videoDialog.IsShown():
if self.app.videoDialog.IsIconized():
self.app.videoDialog.Iconize(False)
else:
self.app.videoDialog.Raise()
finally:
sock.close()
self.running = False
class Frame(wx.Frame):
def createMenuBar(self, menuBarInfo, shortcutList, oldShortcuts, menuBackups=[], backupShowShortcuts=False):
'''
General utility function to create a menu bar of menus
Input is a list of label/menuInfo tuples
The function utilizes the createMenu function (defined below)
'''
buckups = menuBackups[:]
menuBackups[:] = []
index = 0
self._shortcutBindWindowDict = {}
menuBar = wx.MenuBar()
for eachMenuBarInfo in menuBarInfo:
menuLabel = eachMenuBarInfo[0]
menuInfo = eachMenuBarInfo[1:]
menu = self.createMenu(menuInfo, menuLabel, shortcutList, oldShortcuts)
menuBar.Append(menu, menuLabel)
if index in buckups:
menuBackups.append(self.createMenu(menuInfo, menuLabel, shortcutList, oldShortcuts, True, backupShowShortcuts))
index += 1
return menuBar
def createMenu(self, menuInfo, name='', shortcutList = None, oldShortcuts=None, backup=False, backupShowShortcuts=False):
menu = wx.Menu()
if shortcutList is None:
shortcutList = []
if oldShortcuts is None:
oldShortcutNames = []
oldShortcuts = []
else:
try:
oldShortcutNames, oldShortcutInfos = oldShortcuts
except ValueError:
oldShortcutNames = []
oldShortcuts = []
for eachMenuInfo in menuInfo:
# Get the info, fill in missing info with defaults
nItems = len(eachMenuInfo)
# Special case: separator
if eachMenuInfo == '' or nItems == 1:
menu.AppendSeparator()
menu.Remove(menu.Append(wx.ID_ANY, '0',).GetId()) # wxGTK fix
continue
if nItems > 7:
raise
defaults = ('', '', None, '', wx.ITEM_NORMAL, None, self)
label, shortcut, handler, status, attr, state, bindwindow = eachMenuInfo + defaults[nItems:]
if not bindwindow or bindwindow is None:
bindwindow = self
# Special case: submenu
if handler is None: #not isinstance(handler, FunctionType):
submenu = self.createMenu(shortcut, '%s -> %s'% (name, label), shortcutList, oldShortcuts, backup, backupShowShortcuts)
menu.AppendMenu(wx.ID_ANY, label, submenu, status)
continue
elif handler == -1:
submenu = shortcut #self.createMenu(shortcut, '%s -> %s'% (name, label), shortcutList, oldShortcuts, bindwindow)
menu.AppendMenu(wx.ID_ANY, label, submenu, status)
continue
# Get the id and type (normal, checkbox, radio)
if attr in (wx.ITEM_CHECK, wx.ITEM_RADIO):
kind = attr
id = wx.ID_ANY
elif attr == wx.ITEM_NORMAL:
kind = attr
id = wx.ID_ANY
elif type(attr) is tuple:
kind, state, id = attr
else:
kind = wx.ITEM_NORMAL
id = attr
# Get the shortcut string
itemName = '%s -> %s'% (name, label)
itemName = itemName.replace('&', '')
try:
index = oldShortcutNames.index(itemName)
shortcut = oldShortcutInfos[index][1]
except ValueError:
pass
# GPo, show the shortcuts in the context menus (videoWindow, script)
if backup:
shortcutString = ''
if backupShowShortcuts and shortcut != '':
for item in shortcutList:
if item[0] == itemName and item[1] == shortcut:
shortcutString = u'\t%s\u00a0' % GetTranslatedShortcut(shortcut)
break
else:
if shortcut != '' and shortcut not in [item[1] for item in shortcutList]:
shortcutString = u'\t%s\u00a0' % GetTranslatedShortcut(shortcut)
else:
shortcutString = ''
# Append the menu item
if os.name != 'nt' and wx.version() >= '2.9': # XXX
shortcutString = shortcutString[:-1]
menuItem = menu.Append(id, '%s%s' % (label, shortcutString), status, kind)
id = menuItem.GetId()
self.Bind(wx.EVT_MENU, handler, menuItem)
# Add the accelerator
if shortcut is not None:
if not backup and (shortcut == '' or not shortcut[-1].isspace()):
shortcutList.append([itemName, shortcut, id])
try:
bindShortcutIdList = self._shortcutBindWindowDict.setdefault(bindwindow, [])
bindShortcutIdList.append(id)
except AttributeError:
pass
# Extra properties (enable/disable, check)
if state is not None:
if kind == wx.ITEM_NORMAL:
menuItem.Enable(state)
else:
menuItem.Check(state)
return menu
def BindShortcutsToWindows(self, shortcutInfo, forcewindow=None):
idDict = dict([(id, shortcut) for itemName, shortcut, id in shortcutInfo])
forceAccelList = []
for window, idList in self._shortcutBindWindowDict.items():
accelList = []
#~ for label, data in value.items():
#~ accelString, id = data
#~ accel = wx.GetAccelFromString('\t'+accelString)
#~ accelList.append((accel.GetFlags(), accel.GetKeyCode(), id))
for id in idList:
try:
accelString = idDict[id]
except KeyError:
continue
#~ index = [z for x,y,z in shortcutInfo].index(id)
accel = wx.GetAccelFromString('\t'+accelString)
if accel is not None and accel.IsOk():
accelList.append((accel.GetFlags(), accel.GetKeyCode(), id))
else:
for key in numpadDict:
if accelString.endswith(key):
break
accelString = accelString.replace(key, 'Space')
accel = wx.GetAccelFromString('\t'+accelString)
accelList.append((accel.GetFlags(), numpadDict[key], id))
if forcewindow is None:
accelTable = wx.AcceleratorTable(accelList)
window.SetAcceleratorTable(accelTable)
else:
forceAccelList += accelList
if forcewindow is not None:
accelTable = wx.AcceleratorTable(forceAccelList)
forcewindow.SetAcceleratorTable(accelTable)
def accelListFromMenu(self, menu, accelList):
for menuItem in menu.GetMenuItems():
submenu = menuItem.GetSubMenu()
if submenu is not None:
self.accelListFromMenu(submenu, accelList)
else:
id = menuItem.GetId()
text = menuItem.GetText()
accel = wx.GetAccelFromString(text)
if accel is not None and accel.IsOk():
accelList.append((accel.GetFlags(), accel.GetKeyCode(), id))
def createButton(self, parent, label='', id=wx.ID_ANY, handler=None, pos=(0,0)):
button = wx.Button(parent, id, label, pos)
if handler:
button.Bind(wx.EVT_BUTTON, handler)
return button
def createToolbarButton(self, parent, label, handler, pos=(0, 0), size=wx.DefaultSize, style=wx.NO_BORDER, toolTipTxt=None, statusTxt=None, showStatusTxt=True):
# Return a static line if empty
if type(label) == type('') and label == '':
return wx.StaticLine(parent, style=wx.LI_VERTICAL)
# Create the button
try: # label is a bitmap
w,h = label.GetSize()
button = wxButtons.GenBitmapButton(parent, wx.ID_ANY, label, pos, size, style)
button.SetBestSize((w+7, h+7))
except AttributeError: # label is a string
button = wxButtons.GenButton(parent, wx.ID_ANY, label, pos, size, style)
# Bind the button to the given handler
button.Bind(wx.EVT_BUTTON, handler)
# Set the tool tip string if given
if toolTipTxt:
button.SetToolTipString(toolTipTxt)
# Define mouse event functions (change status bar text and button bevel width)
def OnMouseMove(event):
if statusTxt and self.options['showbuttontooltip']:
self.SetStatusText(statusTxt)
def OnMouseOver(event):
if statusTxt and self.options['showbuttontooltip']:
self.SetStatusText(statusTxt)
b = event.GetEventObject()
b.SetBezelWidth(b.GetBezelWidth()+1)
b.Refresh()
def OnMouseLeave(event):
if statusTxt and self.options['showbuttontooltip']:
try:
self.ResetStatusText()
except AttributeError:
self.SetStatusText('')
b = event.GetEventObject()
b.SetBezelWidth(b.GetBezelWidth()-1)
b.Refresh()
button.Bind(wx.EVT_ENTER_WINDOW, OnMouseOver)
button.Bind(wx.EVT_MOTION, OnMouseMove)
button.Bind(wx.EVT_LEAVE_WINDOW, OnMouseLeave)
return button
class Notebook(wx.Notebook):
"""wx.Notebook, changing selected tab on mouse scroll"""
def __init__(self, *args, **kwargs):
self.invert_mouse_wheel_rotation = kwargs.pop('invert_scroll', False)
wx.Notebook.__init__(self, *args, **kwargs)
self.mouse_wheel_rotation = 0
self.Bind(wx.EVT_MOUSEWHEEL, self.OnMouseWheelNotebook)
def OnMouseWheelNotebook(self, event):
"""Rotate between tabs"""
rotation = event.GetWheelRotation()
if self.mouse_wheel_rotation * rotation < 0:
self.mouse_wheel_rotation = rotation
else:
self.mouse_wheel_rotation += rotation
if abs(self.mouse_wheel_rotation) >= event.GetWheelDelta():
inc = -1 if self.mouse_wheel_rotation > 0 else 1
if self.invert_mouse_wheel_rotation: inc = -inc
self.SelectTab(inc=inc)
self.mouse_wheel_rotation = 0
def SelectTab(self, index=None, inc=0):
"""Change to another tab
index: go the specified tab
inc: increment, with wrap-around"""
nTabs = self.GetPageCount()
if nTabs == 1:
self.SetSelection(0)
return True
if index is None:
index = inc + self.GetSelection()
# Allow for wraparound with user-specified inc
if index < 0:
index = nTabs - abs(index) % nTabs
if index == nTabs:
index = 0
if index > nTabs - 1:
index = index % nTabs
# Limit index if specified directly by user
if index < 0:
return False
if index > nTabs - 1:
return False
self.SetSelection(index)
return True
class QuickFindDialog(wx.Dialog):
''' Simple find dialog for a wx.StyledTextCtrl, using FindReplaceDialog'''
def __init__(self, parent, text=''):
wx.Dialog.__init__(self, parent, wx.ID_ANY, _('Quick find'), style=0)
self.app = parent.app
dpi.SetFontPPI(self)
# Prepare a toolbar-like dialog
find_bitmap = wx.StaticBitmap(self, wx.ID_ANY, wx.ArtProvider.GetBitmap(wx.ART_FIND))
self.find_text_ctrl = wx.TextCtrl(self, wx.ID_ANY, size=(200, -1),
style=wx.TE_PROCESS_ENTER, value=text)
id = wx.ID_CLOSE if wx.version() >= '2.9' else wx.ID_OK
self.close = wx.BitmapButton(self, id, bitmap=wx.ArtProvider.GetBitmap(wx.ART_CROSS_MARK))
sizer = wx.BoxSizer(wx.HORIZONTAL)
sizer.Add(find_bitmap, 0, wx.ALIGN_CENTER|wx.ALL, 5)
sizer.Add(self.find_text_ctrl, 1, wx.EXPAND|wx.ALIGN_CENTER|wx.TOP|wx.BOTTOM, 5)
sizer.Add(self.close, 0, wx.ALIGN_CENTER|wx.ALL, 5)
sizer.Fit(self)
self.SetSizer(sizer)
sizer.SetSizeHints(self)
sizer.Layout()
self.Bind(wx.EVT_BUTTON, self.OnClose, self.close)
self.Bind(wx.EVT_TEXT, self.OnInstantFindNext, self.find_text_ctrl)
self.Bind(wx.EVT_TEXT_ENTER, self.OnFindNext, self.find_text_ctrl)
self.find_text_ctrl.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
self.find_text_ctrl.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
# Auto-hide timer
class QuickFindTimer(wx.Timer):
def __init__(self, parent):
wx.Timer.__init__(self)
self.parent = parent
def Notify(self):
self.parent.Hide()
self.timer = QuickFindTimer(self)
# Bind open find/replace dialog and up and down arrows
up_id = wx.NewId()
self.Bind(wx.EVT_MENU, self.OnFindPrevious, id=up_id)
down_id = wx.NewId()
self.Bind(wx.EVT_MENU, self.OnFindNext, id=down_id)
accel_list = []
accel_list.append(wx.AcceleratorEntry(wx.ACCEL_NORMAL, wx.WXK_UP, up_id))
accel_list.append(wx.AcceleratorEntry(wx.ACCEL_NORMAL, wx.WXK_DOWN, down_id))
find = replace = False
find_menu = u'{0} -> {1}'.format(_('&Edit'), _('Find...')).replace('&', '')
replace_menu = u'{0} -> {1}'.format(_('&Edit'), _('Replace...')).replace('&', '')
for menu_item, shortcut, id in self.app.options['shortcuts']:
if not find and menu_item.replace('&', '') == find_menu:
accel = wx.GetAccelFromString('\t' + shortcut)
if accel is not None and accel.IsOk():
accel_list.append(wx.AcceleratorEntry(accel.GetFlags(), accel.GetKeyCode(), id))
self.Bind(wx.EVT_MENU, lambda event:self.UpdateText(), id=id)
find = True
if not replace and menu_item.replace('&', '') == replace_menu:
accel = wx.GetAccelFromString('\t' + shortcut)
if accel is not None and accel.IsOk():
accel_list.append(wx.AcceleratorEntry(accel.GetFlags(), accel.GetKeyCode(), id))
self.Bind(wx.EVT_MENU, self.app.OnMenuEditReplace, id=id)
replace = True
if find and replace: break
self.SetAcceleratorTable(wx.AcceleratorTable(accel_list))
def SetFocus(self):
self.find_text_ctrl.SetFocus()
def OnSetFocus(self, event):
self.timer.Stop()
self.find_text_ctrl.SelectAll()
def OnKillFocus(self, event):
self.timer.Start(3000)
def GetFindText(self):
return self.find_text_ctrl.GetValue()
def SetFindText(self, text):
self.find_text_ctrl.ChangeValue(text)
self.find_text_ctrl.SetInsertionPointEnd()
def UpdateText(self, text=None):
if text is None:
text = self.app.currentScript.GetSelectedText()
self.SetFindText(text)
self.app.replaceDialog.SetFindText(text)
def OnInstantFindNext(self, event):
script = self.app.currentScript
range = (script.GetSelectionStart(),
script.GetLineEndPosition(script.GetLineCount() - 1))
self.app.replaceDialog.SetFindText(self.GetFindText())
self.app.replaceDialog.OnFindNext(range=range, update_list=False)
def OnFindNext(self, event):
self.app.replaceDialog.SetFindText(self.GetFindText())
self.app.replaceDialog.OnFindNext()
def OnFindPrevious(self, event):
self.app.replaceDialog.SetFindText(self.GetFindText())
self.app.replaceDialog.OnFindPrevious()
def OnClose(self, event):
self.Hide()
class FindReplaceDialog(wx.Dialog):
''' Find/replace dialog for a wx.StyledTextCtrl'''
def __init__(self, parent, text=''):
wx.Dialog.__init__(self, parent, wx.ID_ANY, _('Find/replace text'),
style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)
self.app = parent.app
dpi.SetFontPPI(self)
self.find_recent = self.app.options['find_recent']
self.replace_recent = self.app.options['replace_recent']
# Set controls
panel = wx.Panel(self)
find_text = wx.StaticText(self, wx.ID_ANY, _('Search &for'))
self.find_text_ctrl = wx.ComboBox(self, wx.ID_ANY, style=wx.CB_DROPDOWN,
size=(dpi.intPPI(200),-1), value=text, choices=self.find_recent)
replace_text = wx.StaticText(self, wx.ID_ANY, _('R&eplace with'))
self.replace_text_ctrl = wx.ComboBox(self, wx.ID_ANY, size=(dpi.intPPI(200),-1),
style=wx.CB_DROPDOWN|wx.TE_PROCESS_ENTER,
value='', choices=self.replace_recent)
self.find_next = wx.Button(self, wx.ID_ANY, label=_('Find &next'))
self.find_previous = wx.Button(self, wx.ID_ANY, label=_('Find &previous'))
self.replace_next = wx.Button(self, wx.ID_ANY, label=_('&Replace next'))
self.replace_all = wx.Button(self, wx.ID_ANY, label=_('Replace &all'))
id = wx.ID_CLOSE if wx.version() >= '2.9' else wx.ID_OK
self.close = wx.Button(self, id, label=_('Close'))
self.word_start = wx.CheckBox(self, wx.ID_ANY, label=_('Only on word s&tart'))
self.whole_word = wx.CheckBox(self, wx.ID_ANY, label=_('Only &whole words'))
self.only_selection = wx.CheckBox(self, wx.ID_ANY, label=_('Only in &selection'))
self.dont_wrap = wx.CheckBox(self, wx.ID_ANY, label=_("&Don't wrap-around"))
self.match_case = wx.CheckBox(self, wx.ID_ANY, label=_('&Case sensitive'))
self.find_regexp = wx.CheckBox(self, wx.ID_ANY, label=_('Use regular e&xpressions'))
re_url = HyperLinkCtrl(self, wx.ID_ANY, label='?',
URL=r'http://www.yellowbrain.com/stc/regexp.html')
self.escape_sequences = wx.CheckBox(self, wx.ID_ANY, label=_('&Interpret escape sequences'))
# Bind events
def OnChar(event):
key = event.GetKeyCode()
if key == wx.WXK_TAB: # wx.TE_PROCESS_ENTER causes wx.EVT_CHAR to also process TAB
panel.Navigate(flags = 0 if event.ShiftDown() else wx.NavigationKeyEvent.IsForward)
else:
event.Skip()
self.replace_text_ctrl.Bind(wx.EVT_CHAR, OnChar)
self.Bind(wx.EVT_TEXT_ENTER, self.OnReplace, self.replace_text_ctrl)
self.Bind(wx.EVT_BUTTON, self.OnFindNext, self.find_next)
self.Bind(wx.EVT_BUTTON, self.OnFindPrevious, self.find_previous)
self.Bind(wx.EVT_BUTTON, self.OnReplace, self.replace_next)
self.Bind(wx.EVT_BUTTON, self.OnReplaceAll, self.replace_all)
self.Bind(wx.EVT_BUTTON, self.OnClose, self.close)
# Organize controls
check1_sizer = wx.BoxSizer(wx.VERTICAL)
check1_sizer.Add(self.word_start, 0, wx.EXPAND|wx.RIGHT|wx.TOP|wx.BOTTOM, 4)
check1_sizer.Add(self.whole_word, 0, wx.EXPAND|wx.RIGHT|wx.TOP|wx.BOTTOM, 4)
check1_sizer.Add(self.only_selection, 0, wx.EXPAND|wx.RIGHT|wx.TOP|wx.BOTTOM, 4)
check1_sizer.Add(self.dont_wrap, 0, wx.EXPAND|wx.RIGHT|wx.TOP|wx.BOTTOM, 4)
check2_sizer = wx.BoxSizer(wx.VERTICAL)
check2_sizer.Add(self.match_case, 0, wx.EXPAND|wx.ALL, 4)
re_sizer = wx.BoxSizer(wx.HORIZONTAL)
re_sizer.Add(self.find_regexp, 0)
re_sizer.Add(re_url, wx.LEFT, 5)
check2_sizer.Add(re_sizer, 0, wx.EXPAND|wx.ALL, 4)
check2_sizer.Add(self.escape_sequences, 0, wx.EXPAND|wx.ALL, 4)
check_sizer = wx.BoxSizer(wx.HORIZONTAL)
check_sizer.Add(check1_sizer, 0)
check_sizer.Add(check2_sizer, 0)
ctrl_sizer = wx.BoxSizer(wx.VERTICAL)
ctrl_sizer.Add(find_text, 0, wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, 3)
ctrl_sizer.Add(self.find_text_ctrl, 0, wx.EXPAND|wx.ALL, 3)
ctrl_sizer.Add(replace_text, 0, wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, 3)
ctrl_sizer.Add(self.replace_text_ctrl, 0, wx.EXPAND|wx.ALL, 3)
ctrl_sizer.Add(check_sizer, 0, wx.EXPAND|wx.ALL, 3)
button_sizer = wx.BoxSizer(wx.VERTICAL)
button_sizer.Add(self.find_next, 0, wx.EXPAND|wx.ALL, 3)
button_sizer.Add(self.find_previous, 0, wx.EXPAND|wx.ALL, 3)
button_sizer.Add(self.replace_next, 0, wx.EXPAND|wx.ALL, 3)
button_sizer.Add(self.replace_all, 0, wx.EXPAND|wx.ALL, 3)
button_sizer.Add(self.close, 0, wx.EXPAND|wx.ALL, 3)
col_sizer = wx.BoxSizer(wx.HORIZONTAL)
col_sizer.Add(ctrl_sizer, 1, wx.EXPAND|wx.ALIGN_CENTER)
col_sizer.Add(button_sizer, 0, wx.EXPAND|wx.ALIGN_CENTER|wx.LEFT, 2)
# Size the elements
dlgSizer = wx.BoxSizer(wx.VERTICAL)
dlgSizer.Add(col_sizer, 0, wx.EXPAND|wx.ALL, 5)
dlgSizer.Fit(self)
self.SetSizer(dlgSizer)
dlgSizer.SetSizeHints(self)
dlgSizer.Layout()
self.find_next.SetDefault()
self.find_text_ctrl.SetFocus()
def GetFindText(self):
return self.find_text_ctrl.GetValue()
def GetReplaceText(self):
return self.replace_text_ctrl.GetValue()
def SetFindText(self, text):
self.find_text_ctrl.SetValue(text)
if self.IsShown():
self.find_text_ctrl.SetFocus()
self.find_text_ctrl.SetInsertionPointEnd()
def SetReplaceText(self, text):
self.replace_text_ctrl.SetValue(text)
if self.IsShown():
self.replace_text_ctrl.SetFocus()
self.replace_text_ctrl.SetInsertionPointEnd()
def UpdateText(self, text=None, ctrl='find'):
if text is None:
text = self.app.currentScript.GetSelectedText()
if ctrl == 'find':
self.SetFindText(text)
else:
self.SetReplaceText(text)
def OnFindNext(self, event=None, range=None, update_list=True):
text = self.GetFindText()
if not text: return
if update_list and text not in self.find_recent:
self.find_recent[11:] = []
self.find_recent.insert(0, text)
self.find_text_ctrl.Insert(text, 0)
if self.escape_sequences.IsChecked():
text = self.Unescape(text)
if self.Find(text, True, range):
script = self.app.currentScript
script.EnsureCaretVisible()
def OnFindPrevious(self, event=None):
text = self.GetFindText()
if not text: return
if text not in self.find_recent:
self.find_recent[11:] = []
self.find_recent.insert(0, text)
self.find_text_ctrl.Insert(text, 0)
if self.escape_sequences.IsChecked():
text = self.Unescape(text)
if self.Find(text, False):
script = self.app.currentScript
script.EnsureCaretVisible()
def Find(self, text, top2bottom=True, range=None, wrap=None):
script = self.app.currentScript
stcflags = 0
if self.match_case.IsChecked():
stcflags = stcflags | stc.STC_FIND_MATCHCASE
if self.word_start.IsChecked():
stcflags = stcflags | stc.STC_FIND_WORDSTART
if self.whole_word.IsChecked():
stcflags = stcflags | stc.STC_FIND_WHOLEWORD
if self.find_regexp.IsChecked():
stcflags = stcflags | stc.STC_FIND_REGEXP
if self.only_selection.IsChecked() and not range:
range = script.GetSelection()
if wrap is None:
wrap = not self.dont_wrap.IsChecked()
if not range:
if top2bottom:
minPos, maxPos = (script.GetSelectionEnd(),
script.GetLineEndPosition(script.GetLineCount() - 1))
else:
minPos, maxPos = script.GetSelectionStart(), 0
elif top2bottom:
minPos, maxPos = range
else:
minPos, maxPos = reversed(range)
findpos = script.FindText(minPos, maxPos, text, stcflags)
if findpos == -1 and wrap:
minPos = 0 if top2bottom else script.GetLineEndPosition(script.GetLineCount() - 1)
findpos = script.FindText(minPos, maxPos, text, stcflags)
if findpos == -1:
script.app.GetStatusBar().SetStatusText(_('Cannot find "%(text)s"') % locals())
else:
script.app.GetStatusBar().SetStatusText('')
script.SetAnchor(findpos)
script.SetCurrentPos(findpos + len(text.encode('utf-8')))
return findpos
def OnReplace(self, event=None):
find_text = self.GetFindText()
replace_text = self.GetReplaceText()
if not find_text or find_text == replace_text: return
if find_text not in self.find_recent:
self.find_recent[11:] = []
self.find_recent.insert(0, find_text)
self.find_text_ctrl.Insert(find_text, 0)
if replace_text not in self.replace_recent:
self.replace_recent[11:] = []