-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathioutils.py
More file actions
282 lines (258 loc) · 10.8 KB
/
ioutils.py
File metadata and controls
282 lines (258 loc) · 10.8 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
#
# macro utilities for creating macro-behaviours
#
import logging
from sqlite3 import OperationalError, connect
from win32gui import ShowWindow, IsWindowVisible, GetWindowText, EnumWindows, BringWindowToTop, SetForegroundWindow
#import os
logging.basicConfig(level=logging.INFO)
### DECORATORS ###
def sanitise_movement(func):
def checker(*args,**kwargs):
print args
print kwargs
ret = func(*args,**kwargs)
return ret
return checker
### CLASSES ###
class MacroObj():
def __init__(self,string='',flags=0):
self.string=string
self.flags=flags
UPDATES_USAGE = "#keyboard macro (name, string, flag) tuples\n" \
"#flag '0xff' prevents macro preprocessing e.g. vim/screen\n"
class FileStore():
""" manage the storage of configurations to file """
#logger=logging.getLogger('')
def __init__(self,defaults_filename='defaults.conf',
updates_filename='updates.conf',
working_directory='c:/Natlink/Natlink/MacroSystem/',
preDict={},delim="|",
db_filename='natlink.db',
schema=None):
#print os.getcwd()
# self.updates_filename=updates_filename
self.postDict=preDict
self.delimchar=delim
self.wd=working_directory
count=0
if schema:
logging.info("schema present")
count = self.readdb(schema)
if not count:
count = self.readfile(defaults_filename)
if count:
logging.info("%d macros"% count)
count = self.readfile(updates_filename)
print count
if count:
logging.info("%d updated macros"% count)
count = self.writefile()
logging.info("%d macros to file"% (count))
if schema:
count = self.writedb(schema)
logging.info("%d macros to db, cleaning updates file"
% (count))
with open(self.wd + updates_filename,'w') as myfile:
myfile.write(UPDATES_USAGE)
else:
logging.error('could not open : %s' %
defaults_filename)
def readfile(self, filename):
logging.info("opening %s" % self.wd+filename)
count=0
try:
with open(self.wd + filename,'r') as myfile:
for line in myfile:
# logging.debug("reading %s" % line)
if not line.startswith('#'):
try:
# logging.debug(str(line.split('|',3)))
gram, macro, flags = line.split('|')
#logging.debug("%s %s %s" % (str(gram), str(macro), str(flags).strip(r'r\n')))
self.postDict[gram] = MacroObj(macro, int(flags.strip(r'r\n ')))
count+=1
except:
logging.info("%s line not a macro entry" % line)
except:
logging.error('could not open : %s' % filename)
finally:
return count
def writefile(self, output_filename='output.conf'):
logging.info("writing to file...")
outfile_fd=open(self.wd + output_filename,'w')
#eogging.debug('keys: %s' % self.postDict.keys())
outfile_fd.write('keyboard macro (name, string, flag) tuples')
count=0
for gram, macroobj in self.postDict.iteritems():
try:
outfile_fd.write('\n' + str(self.delimchar).join([gram,
macroobj.string,
str(macroobj.flags)]))
count+=1
except:
pass
return count
def readdb(self, schema, db_filename='natlink.db', table_name='kb_macros'):
logging.info("reading from database...")
count=0
try:
conn = connect(self.wd + db_filename)
c = conn.cursor()
col_names= schema.replace(' text','')
c.execute("SELECT %s FROM %s" % (col_names, table_name))
for row in c.fetchall():
gram, macro_raw, flags = row
macro=self.customdecodechars(macro_raw)
self.postDict[gram] = MacroObj(macro, int(flags)) # .strip(r'r\n ')))
# col_index=0
# for col_name in col_names.split(','):
# #logging.info("col: %s=%s," % (col_name,row_decoded[col_index]))
# col_index+=1
# print row
count+=1
conn.close()
except:
logging.info("error reading from database...")
finally:
return count
# except sqlite3.OperationalError, err:
# logging.exception( "OperationalError: %s" % err)
# return 1
def writedb(self, schema, db_filename='natlink.db', table_name='kb_macros'):
logging.info("writing to database...")
count = 0
try:
conn = connect(self.wd + db_filename)
c = conn.cursor()
# Create table
c.execute("DROP TABLE %s" % (table_name))
c.execute("CREATE TABLE %s (%s)" % (table_name, schema))
for gram, macroobj in self.postDict.iteritems():
# Insert a row of data
macro_string=self.customencodechar(macroobj.string)
print gram, macroobj.string, macro_string
c.execute("INSERT INTO %s (%s) VALUES ('%s', '%s', '%s')" %
(table_name, schema.replace(' text', ''),
gram, macro_string, str(macroobj.flags)))
conn.commit()
count+=1
#except Exception, err:
conn.close()
except OperationalError, err:
logging.exception( "OperationalError: %s" % err)
finally:
return count
def customencodechar(self, string):
return string.replace("'","SNGL_QUOTE")
def customdecodechars(self, string):
if "SNGL_QUOTE" in string:
new_string= str(string).replace("SNGL_QUOTE", "'")
#logging.info("old %s, new %s" % (string, new_string))
return string
class AppWindow:
def __init__(self, names, rect=None, hwin=None):
self.winNames = names
self.winRect = rect
self.winHandle = hwin
self.vert_offset = 0
self.TOGGLE_VOFFSET = 9
buttons = ['home', 'menu', 'back', 'search', 'call', 'end']
self.mimicCmds = {}.fromkeys(buttons)
class Windows:
def __init__(self, appDict={}, nullTitles=[]):
self.appDict=appDict
self.nullTitles=nullTitles
self.skipTitle=None
def _callBack_popWin(self, hwin, args):
""" this callback function is called with handle of each top-level
window. Window handles are used to check the of window in question is
visible and if so it's title strings checked to see if it is a standard
application (e.g. not the start button or natlink voice command itself).
Populate dictionary of window title keys to window handle values. """
#print '.' #self.nullTitles
#nullTitles = self.nullTitles.append(self.skipTitle)
#print nullTitles
if IsWindowVisible(hwin):
winText = GetWindowText(hwin).strip()
nt = self.nullTitles + [self.skipTitle,]
if winText and winText not in nt: # and\
# enable duplicates #winText not in args.values():
if winText.count('WinSCP') and winText != 'WinSCP Login':
if winText in args.values():
return
args.update({hwin: winText})
#else:
# logging.error('cannot retrieve window title %s' % winText)
# and filter(lambda x: x in args[0], winText.split()):
def winDiscovery(self, appName=None, winTitle=None, beginTitle=None,
skipTitle=None):
""" support finding and focusing on application window or simple window
title. Find the index and focuses on the first match of any of these.
Applications within the application dictionary could have a number
window_titles associated. """
wins = {}
hwin = None
index = None
self.skipTitle = skipTitle
# numerate windows into dictionary "wins" through callback function
EnumWindows(self._callBack_popWin, wins)
# clear the skip title that was passed into this function
self.skipTitle = None
total_windows = len(wins)
# creating match lists for window titles
namelist=[]
partlist=[]
if winTitle:
namelist.append(winTitle)
elif beginTitle:
for v in wins.values():
if v.startswith(beginTitle):
namelist.append(v)
if appName:
# trying to find window title of selected application within window
# dictionary( local application context). Checking that the window
# exists and it has supporting local application context (appDict)
app = self.appDict[str(appName)]
# app is an AppWindow object
# checking if the window names is a list, handle string occurrence
try:
if app.winHandle:
ShowWindow(int(hwin), 1) #SW_RESTORE)
SetForegroundWindow(int(hwin))
#SetActiveWindow(int(hwin))
return (str(hwin), wins)
except:
pass
# check if winNames is a list and add name to append to namelist
if getattr(app.winNames, 'append', None):
namelist = namelist + app.winNames
else:
namelist.append(app.winNames)
# iterate through populated list of potential window titles
for name in namelist:
try:
for title in wins.values():
if name in title:
index = wins.values().index(title)
break
except:
pass
if index is not None:
# logging.debug("index of application window: %s = %d" %
# (wins[index],index))
hwin = (wins.keys())[index]
logging.debug(
"Name: {0}, Handle: {1}".format(wins[hwin], str(hwin)))
try:
app.winHandle = hwin
except:
pass
# ShowWindow and SetForegroundWindow are the recommended functions
ShowWindow(int(hwin), 1) #SW_RESTORE)
SetForegroundWindow(int(hwin))
#SetActiveWindow(int(hwin))
#app.winRect = wg.GetWindowRect(hwin)
return (str(hwin), wins)
else:
return (None, wins)