This repository has been archived by the owner on Jul 31, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 66
/
proxy.py
1328 lines (1083 loc) · 41.6 KB
/
proxy.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
# GUI object/properties browser.
# Copyright (C) 2011 Matiychuk D.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either version 2.1
# of the License, or (at your option) any later version.
#
# This library 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc.,
# 59 Temple Place,
# Suite 330,
# Boston, MA 02111-1307 USA
import exceptions
import platform
import os
import sys
import string
import time
import thread
import warnings
import pywinauto
from code_manager import CodeGenerator, check_valid_identifier
from const import *
'''
proxy module for pywinauto
'''
pywinauto.timings.Timings.window_find_timeout = 1
def resource_path(filename):
if hasattr(sys, '_MEIPASS'):
# PyInstaller >= 1.6
###os.chdir(sys._MEIPASS)
filename = os.path.join(sys._MEIPASS, filename)
elif '_MEIPASS2' in os.environ:
# PyInstaller < 1.6 (tested on 1.5 only)
###os.chdir(os.environ['_MEIPASS2'])
filename = os.path.join(os.environ['_MEIPASS2'], filename)
else:
###os.chdir(sys.path.dirname(sys.argv[0]))
filename = os.path.join(os.path.dirname(sys.argv[0]), filename)
return filename
class PwaWrapper(object):
"""
Base proxy class for pywinauto objects.
"""
def __init__(self, pwa_obj, parent=None):
'''
Constructor
'''
#original pywinauto object
self.pwa_obj = pwa_obj
self.parent = parent
default_sort_key = lambda name: name[0].lower()
self.subitems_sort_key = default_sort_key
def GetProperties(self):
'''
Return dict of original + additional properties
Can be overridden for non pywinauto objects
'''
properties = {}
properties.update(self._get_properties())
properties.update(self._get_additional_properties())
return properties
def Get_subitems(self):
'''
Return list of children - [(control_text, swapy_obj),...]
Can be overridden for non pywinauto objects
'''
subitems = []
subitems += self._get_children()
subitems += self._get_additional_children()
subitems.sort(key=self.subitems_sort_key)
#encode names
subitems_encoded = []
for (name, obj) in subitems:
#name = name.encode('cp1251', 'replace')
subitems_encoded.append((name, obj))
return subitems_encoded
def Exec_action(self, action):
'''
Execute action on the control
'''
#print('self.pwa_obj.'+action+'()')
exec('self.pwa_obj.'+action+'()')
return 0
def Get_actions(self):
"""
return allowed actions for this object. [(id,action_name),...]
"""
allowed_actions = []
try:
obj_actions = dir(self.pwa_obj.WrapperObject())
except:
obj_actions = dir(self.pwa_obj)
for _id, action in ACTIONS.items():
if action in obj_actions:
allowed_actions.append((_id, action))
allowed_actions.sort(key=lambda name: name[1].lower())
return allowed_actions
def Get_extended_actions(self):
"""
Extended actions
"""
return []
def Highlight_control(self):
if self._check_visibility():
thread.start_new_thread(self._highlight_control,(3,))
return 0
def _get_properties(self):
'''
Get original pywinauto's object properties
'''
#print type(self.pwa_obj)
try:
properties = self.pwa_obj.GetProperties()
except exceptions.RuntimeError:
properties = {} #workaround
return properties
def _get_additional_properties(self):
"""
Get additional useful properties, like a handle, process ID, etc.
Can be overridden by derived class
"""
additional_properties = {}
#-----Access names
access_names = [name for name, obj in self.__get_uniq_names(target_control=self.pwa_obj)]
if access_names:
additional_properties.update({'Access names' : access_names})
#-----
#-----pwa_type
additional_properties.update({'pwa_type' : str(type(self.pwa_obj))})
#---
#-----handle
try:
additional_properties.update({'handle' : str(self.pwa_obj.handle)})
except:
pass
#---
return additional_properties
def _get_children(self):
"""
Return original pywinauto's object children & names
[(control_text, swapy_obj),...]
"""
if self.pwa_obj.Parent() and isinstance(self.parent, Pwa_window):
# Hide children of the non top level window control.
# Expect all the children are accessible from the top level window.
return []
u_names = None
children = []
children_controls = self.pwa_obj.Children()
for child_control in children_controls:
try:
texts = child_control.Texts()
except exceptions.WindowsError:
# texts = ['Unknown control name2!'] #workaround for
# WindowsError: [Error 0] ...
texts = None
except exceptions.RuntimeError:
# texts = ['Unknown control name3!'] #workaround for
# RuntimeError: GetButtonInfo failed for button
# with command id 256
texts = None
if texts:
texts = filter(bool, texts) # filter out '' and None items
if texts: # check again after the filtering
title = ', '.join(texts)
else:
# .Texts() does not have a useful title, trying get it
# from the uniqnames
if u_names is None:
# init unames list
u_names = self.__get_uniq_names()
child_uniq_name = [u_name for u_name, obj in u_names
if obj.WrapperObject() == child_control]
if child_uniq_name:
title = child_uniq_name[-1]
else:
# uniqnames has no useful title
title = 'Unknown control name1!'
children.append((title, self._get_swapy_object(child_control)))
return children
def _get_additional_children(self):
'''
Get additional children, like for a menu, submenu, subtab, etc.
Should be overridden in derived classes of non standard pywinauto object
'''
return []
def _get_pywinobj_type(self, obj):
'''
Check self pywinauto object type
'''
if type(obj) == pywinauto.application.WindowSpecification:
return 'window'
elif type(obj) == pywinauto.controls.menuwrapper.Menu:
return 'menu'
elif type(obj) == pywinauto.controls.menuwrapper.MenuItem:
return 'menu_item'
elif type(obj) == pywinauto.controls.win32_controls.ComboBoxWrapper:
return 'combobox'
elif type(obj) == pywinauto.controls.win32_controls.ListBoxWrapper:
return 'listbox'
elif type(obj) == pywinauto.controls.common_controls.ListViewWrapper:
return 'listview'
elif type(obj) == pywinauto.controls.common_controls.TabControlWrapper:
return 'tab'
elif type(obj) == pywinauto.controls.common_controls.ToolbarWrapper:
return 'toolbar'
elif type(obj) == pywinauto.controls.common_controls._toolbar_button:
return 'toolbar_button'
elif type(obj) == pywinauto.controls.common_controls.TreeViewWrapper:
return 'tree_view'
elif type(obj) == pywinauto.controls.common_controls._treeview_element:
return 'tree_item'
else:
return 'unknown'
def _get_swapy_object(self, pwa_obj):
pwa_type = self._get_pywinobj_type(pwa_obj)
#print pwa_type
if pwa_type == 'window':
process = Process(self, pwa_obj.ProcessID())
return Pwa_window(pwa_obj, process)
if pwa_type == 'menu':
return Pwa_menu(pwa_obj, self)
if pwa_type == 'menu_item':
return Pwa_menu_item(pwa_obj, self)
if pwa_type == 'combobox':
return Pwa_combobox(pwa_obj, self)
if pwa_type == 'listbox':
return Pwa_listbox(pwa_obj, self)
if pwa_type == 'listview':
return Pwa_listview(pwa_obj, self)
if pwa_type == 'tab':
return Pwa_tab(pwa_obj, self)
if pwa_type == 'toolbar':
return Pwa_toolbar(pwa_obj, self)
if pwa_type == 'toolbar_button':
return Pwa_toolbar_button(pwa_obj, self)
if pwa_type == 'tree_view':
return Pwa_tree(pwa_obj, self)
if pwa_type == 'tree_item':
return Pwa_tree_item(pwa_obj, self)
else:
return SWAPYObject(pwa_obj, self)
def _highlight_control(self, repeat = 1):
while repeat > 0:
repeat -= 1
self.pwa_obj.DrawOutline('red', thickness=1)
time.sleep(0.3)
self.pwa_obj.DrawOutline(colour=0xffffff, thickness=1)
time.sleep(0.2)
return 0
def _check_visibility(self):
'''
Check control/window visibility.
Return pwa.IsVisible() or False if fails
'''
is_visible = False
try:
is_visible = self.pwa_obj.IsVisible()
except:
pass
return is_visible
def _check_actionable(self):
'''
Check control/window Actionable.
Return True or False if fails
'''
try:
self.pwa_obj.VerifyActionable()
except:
is_actionable = False
else:
is_actionable = True
return is_actionable
def _check_existence(self):
'''
Check control/window Exists.
Return True or False if fails
'''
try:
handle_ = self.pwa_obj.handle
obj = pywinauto.application.WindowSpecification({'handle': handle_})
except:
is_exist = False
else:
is_exist = obj.Exists()
return is_exist
def __get_uniq_names(self, target_control=None):
"""
Return uniq_names of the control
[(uniq_name, obj), ]
If target_control specified, apply additional filtering for obj == target_control
"""
# TODO: cache this method
pwa_app = pywinauto.application.Application() # TODO: do not call .Application() everywhere.
try:
parent_obj = self.pwa_obj.TopLevelParent()
except pywinauto.controls.HwndWrapper.InvalidWindowHandle:
#For non visible windows
#...
#InvalidWindowHandle: Handle 0x262710 is not a valid window handle
parent_obj = self.pwa_obj
except AttributeError:
return []
visible_controls = [pwa_app.window_(handle=ch) for ch in
pywinauto.findwindows.find_windows(parent=parent_obj.handle, top_level_only=False)]
uniq_names_obj = [(uniq_name, obj) for uniq_name, obj
in pywinauto.findbestmatch.build_unique_dict(visible_controls).items()
if uniq_name != '' and (not target_control or obj.WrapperObject() == target_control)]
return sorted(uniq_names_obj, key=lambda name_obj: len(name_obj[0])) # sort by name
class SWAPYObject(PwaWrapper, CodeGenerator):
"""
Mix the pywinauto wrapper and the code generator
"""
code_self_pattern_attr = "{var} = {parent_var}.{access_name}"
code_self_pattern_item = "{var} = {parent_var}[{access_name}]"
code_action_pattern = "{var}.{action}()"
main_parent_type = None
short_name = 'control'
__code_var_pattern = None # cached value, to access even if the pwa
# object was closed
def __init__(self, *args, **kwargs):
super(SWAPYObject, self).__init__(*args, **kwargs)
self.code_parents = self.get_code_parents()
def get_code_parents(self):
"""
Collect a list of all parents needed to access the control.
Some parents may be excluded regarding to the `self.main_parent_type` parameter.
"""
grab_all = True if not self.main_parent_type else False
code_parents = []
parent = self.parent
while parent:
if not grab_all and isinstance(parent, self.main_parent_type):
grab_all = True
if grab_all:
code_parents.append(parent)
parent = parent.parent
return code_parents
@property
def _code_self(self):
"""
Default _code_self.
"""
#print self._get_additional_properties()
access_name = self.GetProperties()['Access names'][0]
if check_valid_identifier(access_name):
# A valid identifier
code = self.code_self_pattern_attr.format(
access_name=access_name, parent_var="{parent_var}",
var="{var}")
else:
#Not valid, encode and use as app's item.
if isinstance(access_name, unicode):
access_name = "u'%s'" % access_name.encode('unicode-escape')
elif isinstance(access_name, str):
access_name = "'%s'" % access_name
code = self.code_self_pattern_item.format(
access_name=access_name, parent_var="{parent_var}",
var="{var}")
return code
@property
def _code_action(self):
"""
Default _code_action.
"""
code = self.code_action_pattern
return code
@property
def _code_close(self):
"""
Default _code_close.
"""
return ""
@property
def code_var_pattern(self):
"""
Compose variable prefix, based on the control Class or
short name of the SWAPY wrapper class.
"""
if self.__code_var_pattern is None:
var_prefix = self.short_name
if 'Class' in self.GetProperties():
crtl_class = filter(lambda c: c in string.ascii_letters,
self.GetProperties()['Class']).lower()
if crtl_class:
var_prefix = crtl_class
self.__code_var_pattern = "{var_prefix}{id}".format(
var_prefix=var_prefix, id="{id}")
return self.__code_var_pattern
def SetCodestyle(self, extended_action_id):
"""
Switch a control code style regarding extended_action_id
"""
pass
class VirtualSWAPYObject(SWAPYObject):
def __init__(self, parent, index):
self.parent = parent
self.index = index
self.pwa_obj = self
self._check_visibility = self.parent._check_visibility
self._check_actionable = self.parent._check_actionable
self._check_existence = self.parent._check_existence
self.code_parents = self.get_code_parents()
code_action_pattern = "{parent_var}.{action}({index})"
@property
def _code_self(self):
"""
Rewrite default behavior.
"""
return ""
@property
def _code_action(self):
index = self.index
if isinstance(index, unicode):
index = "u'%s'" % index.encode('unicode-escape')
elif isinstance(index, str):
index = "'%s'" % index
code = self.code_action_pattern.format(index=index,
action="{action}",
var="{var}",
parent_var="{parent_var}")
return code
@property
def code_var_pattern(self):
raise Exception('Must not be used "code_var_pattern" prop for a VirtualSWAPYObject')
def Select(self):
self.parent.pwa_obj.Select(self.index)
def _get_properties(self):
return {}
def Get_subitems(self):
return []
def Highlight_control(self):
pass
return 0
class PC_system(SWAPYObject):
handle = 0
short_name = 'pc' # hope it never be used in the code generator
single_object = None
inited = False
def __new__(cls, *args, **kwargs):
if cls.single_object is None:
new = super(PC_system, cls).__new__(cls, *args, **kwargs)
cls.single_object = new
return new
else:
return cls.single_object
def __init__(self, *args, **kwargs):
if not self.inited:
super(PC_system, self).__init__(*args, **kwargs)
self.inited = True
@property
def _code_self(self):
# code = self.code_self_pattern.format(var="{var}")
# return code
return "from pywinauto.application import Application"
#
# @property
# def code_var_pattern(self):
# return "app{id}".format(id="{id}")
def Get_subitems(self):
'''
returns [(window_text, swapy_obj),...]
'''
#windows--------------------
windows = []
try_count = 3
app = pywinauto.application.Application()
for i in range(try_count):
try:
handles = pywinauto.findwindows.find_windows()
except exceptions.OverflowError: # workaround for OverflowError: array too large
time.sleep(1)
except exceptions.MemoryError:# workaround for MemoryError
time.sleep(1)
else:
break
else:
#TODO: add swapy exception: Could not get windows list
handles = []
#we have to find taskbar in windows list
warnings.filterwarnings("ignore", category=FutureWarning) #ignore future warning in taskbar module
from pywinauto import taskbar
taskbar_handle = taskbar.TaskBarHandle()
for w_handle in handles:
wind = app.window_(handle=w_handle)
if w_handle == taskbar_handle:
title = 'TaskBar'
else:
texts = wind.Texts()
texts = filter(bool, texts) # filter out '' and None items
if not texts:
title = 'Window#%s' % w_handle
else:
title = ', '.join(texts)
windows.append((title, self._get_swapy_object(wind)))
windows.sort(key=lambda name: name[0].lower())
#-----------------------
#smt new----------------
#------------------------
return windows
def _get_properties(self):
info = {'Platform': platform.platform(),
'Processor': platform.processor(),
'PC name': platform.node()}
return info
def Get_actions(self):
'''
No actions for PC_system
'''
return []
def Highlight_control(self):
pass
return 0
def _check_visibility(self):
return True
def _check_actionable(self):
return True
def _check_existence(self):
return True
class Process(CodeGenerator):
"""
Virtual parent for window objects.
It will never be shown in the object browser. Used to hold 'app' counter
independent of 'window' counters.
"""
processes = {}
inited = False
main_window = None
def __new__(cls, parent, pid):
if pid in cls.processes:
return cls.processes[pid]
else:
new_process = super(Process, cls).__new__(cls, parent, pid)
cls.processes[pid] = new_process
return new_process
def __init__(self, parent, pid):
if not self.inited:
self.parent = parent
self._var_name = None
self.inited = True
@property
def _code_self(self):
return ""
@property
def _code_action(self):
return ""
@property
def _code_close(self):
return ""
@property
def code_var_pattern(self):
return "{var_prefix}{id}".format(var_prefix='app', id="{id}")
@property
def code_var_name(self):
if self._var_name is None:
self._var_name = self.code_var_pattern.format(
id=self.get_code_id(self.code_var_pattern))
return self._var_name
class Pwa_window(SWAPYObject):
code_self_close = "{parent_var}.Kill_()"
short_name = 'window'
handles = {}
inited = False
def __new__(cls, pwa_obj, parent=None):
if pwa_obj.handle in cls.handles:
return cls.handles[pwa_obj.handle]
else:
new_window = super(Pwa_window, cls).__new__(cls, pwa_obj,
parent=None)
cls.handles[pwa_obj.handle] = new_window
return new_window
def __init__(self, *args, **kwargs):
if not self.inited:
# Set default style
self.code_self_style = self.__code_self_start
self.code_close_style = self.__code_close_start
super(Pwa_window, self).__init__(*args, **kwargs)
self.inited = True
def __code_self_connect(self):
title = self.pwa_obj.WindowText().encode('unicode-escape')
cls_name = self.pwa_obj.Class()
code = "\n{parent_var} = Application().Connect(title=u'{title}', " \
"class_name='{cls_name}')\n".format(title=title,
cls_name=cls_name,
parent_var="{parent_var}")
return code
def __code_self_start(self):
target_pid = self.pwa_obj.ProcessID()
cmd_line = None
process_modules = pywinauto.application._process_get_modules_wmi()
for pid, name, process_cmdline in process_modules:
if pid == target_pid:
cmd_line = os.path.normpath(process_cmdline)
cmd_line = cmd_line.encode('unicode-escape')
break
code = "\n{parent_var} = Application().Start(cmd_line=u'{cmd_line}')\n"\
.format(cmd_line=cmd_line, parent_var="{parent_var}")
return code
def __code_close_connect(self):
return ""
def __code_close_start(self):
return self.code_self_close.format(parent_var="{parent_var}")
@property
def _code_self(self):
code = ""
if not self._get_additional_properties()['Access names']:
raise NotImplementedError
else:
is_main_window = bool(self.parent.main_window is None or
self.parent.main_window == self or
self.parent.main_window.code_var_name is None)
if is_main_window:
code += self.code_self_style()
self.parent.main_window = self
code += super(Pwa_window, self)._code_self
if is_main_window and \
self.code_self_style == self.__code_self_start:
code += "\n{var}.Wait('ready')"
self.parent.main_window = self
return code
@property
def _code_close(self):
"""
Rewrite default behavior.
"""
code = ""
is_main_window = bool(self.parent.main_window is None or
self.parent.main_window == self or
self.parent.main_window.code_var_name is None)
if is_main_window:
code = self.code_close_style()
return code
def _get_additional_children(self):
'''
Add menu object as children
'''
additional_children = []
menu = self.pwa_obj.Menu()
if menu:
menu_child = [('!Menu', self._get_swapy_object(menu))]
additional_children += menu_child
return additional_children
def _get_additional_properties(self):
'''
Get additional useful properties, like a handle, process ID, etc.
Can be overridden by derived class
'''
additional_properties = {}
pwa_app = pywinauto.application.Application()
#-----Access names
access_names = [name for name in pywinauto.findbestmatch.build_unique_dict([self.pwa_obj]).keys() if name != '']
access_names.sort(key=len)
additional_properties.update({'Access names': access_names})
#-----
#-----pwa_type
additional_properties.update({'pwa_type': str(type(self.pwa_obj))})
#---
#-----handle
try:
additional_properties.update({'handle': str(self.pwa_obj.handle)})
except:
pass
#---
return additional_properties
def Get_extended_actions(self):
"""
Extended actions
"""
return [(_id, action) for _id, action in EXTENDED_ACTIONS.items()]
def SetCodestyle(self, extended_action_id):
"""
Switch to `Start` or `Connect` code
"""
if 'Application.Start' == EXTENDED_ACTIONS[extended_action_id]:
self.code_self_style = self.__code_self_start
self.code_close_style = self.__code_close_start
elif 'Application.Connect' == EXTENDED_ACTIONS[extended_action_id]:
self.code_self_style = self.__code_self_connect
self.code_close_style = self.__code_close_connect
else:
raise RuntimeError("Unknown menu id - %s" % extended_action_id)
# if self.code_snippet is not None:
# # Refresh self code after the changing of the code style
# own_code_self = self.get_code_self()
# own_close_code = self.get_code_close()
# self.code_snippet.update(init_code=own_code_self,
# close_code=own_close_code)
self.update_code_style()
def release_variable(self):
super(Pwa_window, self).release_variable()
if self.parent._var_name:
self.parent._var_name = None
self.parent.decrement_code_id(self.parent.code_var_pattern)
class Pwa_menu(SWAPYObject):
short_name = 'menu'
def _check_visibility(self):
is_visible = False
try:
is_visible = self.pwa_obj.ctrl.IsVisible()
except AttributeError:
pass
return is_visible
def _check_actionable(self):
if self.pwa_obj.accessible:
return True
else:
return False
def _check_existence(self):
try:
self.pwa_obj.ctrl.handle
except:
return False
else:
return True
def _get_additional_children(self):
'''
Add submenu object as children
'''
#print(dir(self.pwa_obj))
#print(self.pwa_obj.is_main_menu)
#print(self.pwa_obj.owner_item)
self.subitems_sort_key = lambda obj: obj[1].pwa_obj.Index() #sorts items by indexes
if not self.pwa_obj.accessible:
return []
additional_children = []
menu_items = self.pwa_obj.Items()
for menu_item in menu_items:
item_text = menu_item.Text()
if not item_text:
if menu_item.Type() == 2048:
item_text = '-----Separator-----'
else:
item_text = 'Index: %d' % menu_item.Index()
menu_item_child = [(item_text, self._get_swapy_object(menu_item))]
additional_children += menu_item_child
return additional_children
def _get_children(self):
'''
Return original pywinauto's object children
'''
return []
def Highlight_control(self):
pass
return 0
class Pwa_menu_item(Pwa_menu):
short_name = 'menu_item'
main_parent_type = Pwa_window
code_self_pattern = "{var} = {main_parent_var}.MenuItem(u'{menu_path}')"
@property
def _code_self(self):
menu_path = self.get_menuitems_path().encode('unicode-escape')
code = self.code_self_pattern.format(
menu_path=menu_path, main_parent_var="{main_parent_var}",
var="{var}")
return code
def _check_actionable(self):
if self.pwa_obj.State() == 3: #grayed
is_actionable = False
else:
is_actionable = True
return is_actionable
def _get_additional_children(self):
'''
Add submenu object as children
'''
#print(dir(self.pwa_obj))
#print(self.pwa_obj.menu)
#print self.get_menuitems_path()
additional_children = []
submenu = self.pwa_obj.SubMenu()
if submenu:
submenu_child = [(self.pwa_obj.Text()+' submenu', self._get_swapy_object(submenu))]
additional_children += submenu_child
return additional_children
def get_menuitems_path(self):
'''
Compose menuitems_path for GetMenuPath. Example "#0 -> Save As", "Tools -> #0 -> Configure"
'''
path = []
owner_item = self.pwa_obj
while owner_item:
text = owner_item.Text()
if not text:
text = '#%d' % owner_item.Index()
path.append(text)
menu = owner_item.menu
owner_item = menu.owner_item
return '->'.join(path[::-1])
class Pwa_combobox(SWAPYObject):
short_name = 'combobox'
def _get_additional_children(self):
'''
Add ComboBox items as children
'''
additional_children = []
for i, text in enumerate(self.pwa_obj.ItemTexts()):
if not text:
text = "option #%s" % i
additional_children.append((text,
virtual_combobox_item(self, i)))
else:
additional_children.append((text,
virtual_combobox_item(self, text)))
return additional_children
class virtual_combobox_item(VirtualSWAPYObject):
def _get_properties(self):
index = None
text = self.index
for i, name in enumerate(self.parent.pwa_obj.ItemTexts()):
if name == text:
index = i
break
return {'Index': index, 'Text': text}
class Pwa_listbox(SWAPYObject):