-
Notifications
You must be signed in to change notification settings - Fork 0
/
live.py
364 lines (293 loc) · 11.1 KB
/
live.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
"""
Module for Live Reloading
"""
import threading
from time import sleep
import os
import re
from random import randrange
from platform import system
from glob import glob
from PyQt6.QtCore import QObject, pyqtSignal, pyqtSlot, QFile, QResource, QIODevice, pyqtProperty
from misc import Split
QResource.registerResource("_qmlview_resource_.rcc")
class Live(QObject):
"""
"""
def __init__(self, watch_file):
QObject.__init__(self)
self.os_name = system().lower()
self.watch_file = os.path.realpath(watch_file)
self.folder = os.path.split(watch_file)[0]
self.u_qmltypes = ()
self.u_qmltypes_map = {}
# add permission
if self.os_name != 'windows':
# add permissions
os.system(f'chmod +rw {self.folder}')
self.filename = os.path.join(self.folder, '00001000.qml')
self.show_props = False
self.old_code = ''
self.old_props = ''
self.old_qmltypes_codes = {}
self.new_qmltypes_files = {}
self.not_closed = True
self._initialiase()
updated = pyqtSignal(str, arguments=['updater'])
propsUpdated = pyqtSignal(list, str, arguments=['props_updater'])
def props_updater(self, props, filename):
try:
filename = 'file:///' + filename
self.propsUpdated.emit(props, filename)
except RuntimeError:
# possibly user exited out
pass
def updater(self, filename):
try:
filename = 'file:///' + filename
self.updated.emit(filename)
except RuntimeError:
# possibly user exited out
pass
@pyqtProperty(list)
def oldProps(self):
return self.old_props
@oldProps.setter
def oldProps(self, props):
self.old_props = props
@pyqtSlot(bool)
def show_props(self, show):
self.show_props = show
def _initialiase(self):
# Initialise everything
with open(self.watch_file, 'r') as fh:
code = fh.read()
with open(self.filename, 'w') as fw:
fw.write(code)
# pick initial qmltypes
self._find_qmltypes(self.folder)
# replace all qmltypes in there
# replace it in all of our qmltypes and the filename
patt = os.path.join(self.folder, 'Live*_*.qml')
items = glob(patt)
items.append(self.filename)
for item in items:
self._init_replace_conts(item)
self.monitor_qmltypes()
self._call_auto_reload()
def _call_auto_reload(self):
"""
The method creates the thread for the _auto_reload method
"""
a_thread = threading.Thread(target=self._auto_reload)
a_thread.daemon = True
a_thread.start()
def _auto_reload(self):
"""
This is the method that monitors
and updates the watch file
"""
while self.not_closed:
if not self.show_props:
code = self._read_file(self.watch_file)
if code != self.old_code:
self._save_to_file(code)
# send filename to the UI
self.updater(self.filename)
self.old_code = code
else:
props, code = self._read_all_file(self.watch_file)
if props != self.old_props:
self._save_to_file(code)
self.props_updater(props, self.filename)
self.old_props = props
elif code == self.old_code:
self.old_code = code
self.updater(code)
sleep(0.1)
def _find_qmltypes(self, folder):
"""
Initially find all qmltypes
"""
u_qmltypes = list(self.u_qmltypes)
patt = os.path.join(folder, '*.qml')
items = glob(patt)
for x in items:
name = os.path.split(x)[1]
if name[0].istitle():
with open(x, 'r') as fh:
code = fh.read()
type_name = name.rsplit('.')[0]
new_t_name = f'Live{randrange(1,250)}_{type_name}'
self.u_qmltypes_map[type_name] = new_t_name
new_file = os.path.join(folder, new_t_name+'.qml')
self.new_qmltypes_files[x] = new_file
self.old_qmltypes_codes[x] = code
# save to a new qmltype file
with open(new_file, 'w') as fh:
fh.write(code)
u_qmltypes.append(x)
self.u_qmltypes = tuple(u_qmltypes)
def _find_qmltypes_in_file(self, filename):
# useless delete
with open(filename, 'r') as fh:
data = fh.read()
all_types = re.findall(r'\s*[A-Z][A-Za-z0-9]+\s*{', data)
def _is_in_file(self, needle, filename):
# check if a qml file contains type
with open(filename, 'r') as fh:
data = fh.read()
entry = re.findall(needle, data)
if entry:
return True
def _init_replace_conts(self, filename):
# replace all occurences of a type with
# the new one with a common space between the curly bracket
with open(filename, 'r') as fh:
data = fh.read()
u_qml_map = self.u_qmltypes_map.copy()
for x in u_qml_map:
patt = x + r'\s*{'
# no of types found in file
founds = re.findall(r''+patt, data)
y = self.u_qmltypes_map[x]
yx = '\n' + y + ' {'
#self.u_qmltypes_map[y] = ''
for y in founds:
data = data.replace(y, yx)
# save to that file
with open(filename, 'w') as fh:
fh.write(data)
def monitor_qmltypes(self):
m_thread = threading.Thread(target=self._monitor_qmltype)
m_thread.daemon = True
m_thread.start()
def _monitor_qmltype(self):
# Monitor qmltypes
while self.not_closed:
for file in self.u_qmltypes:
code = self._read_qmltype_file(file)
if code != self.old_qmltypes_codes[file]:
# re-arrange the code to the code we all know
# and deal with inside qml
new_code = self._load_with_qmltypes(code)
self._save_qmltype_file(new_code, file)
self._rename_all()
# updater
with open(self.filename, 'r') as fh:
data = fh.read()
new_data = self._load_with_qmltypes(data)
self._save_to_file(new_data)
self.updater(self.filename)
self.old_qmltypes_codes[file] = code
sleep(0.1)
def _load_with_qmltypes(self, code):
for x in self.u_qmltypes_map:
xs = r'\s' + x + ' {'
ys = '\n' +self.u_qmltypes_map[x] + ' {'
code = re.sub(xs, ys, code)
return code
def _read_file(self, filename):
code = ""
splitter = Split(filename, pick_comp=True)
imps = splitter.orig_imp_stats
bottom_code = splitter.orig_bottom_lines
imps_text = ''.join(imps)
btm_code_text = ''.join(bottom_code)
# Append Rectangle to bottom code
cont = '\nRectangle {\n anchors.fill: parent\n'
cont += 'color: "transparent"\n' + btm_code_text + '\n}'
code = imps_text + cont
return code
def _read_qmltype_file(self, filename):
with open(filename, 'r') as fh:
data = fh.read()
return data
def _read_all_file(self, filename):
splitter = Split(filename, pick_comp=True)
imps = splitter.orig_imp_stats
bottom_code = splitter.orig_bottom_lines
props = splitter.wind_user_props
prop = [props['width'].split(':')[-1].strip(), props['height'].split(':')[-1].strip()]
imps_text = ''.join(imps)
btm_code_text = ''.join(bottom_code)
# Append Rectangle to bottom code
cont = '\nRectangle {\n anchors.fill: parent\n'
cont += 'color: "transparent"\n' + btm_code_text + '\n}'
code = imps_text + cont
return prop, code
def _rename_all(self):
# reconstruct all
# generate new names for a qml type
# rename that file
# rename all files containing that name
all_types = self.new_qmltypes_files.copy()
for x in all_types:
old_file = all_types[x]
folder, base_name = tuple(os.path.split(old_file))
old_t_name = base_name.rsplit('.')[0]
main_name = old_t_name.split('_', 1)[-1]
# new name
new_name = f'Live{randrange(1,250)}_{main_name}'
# rename
new_file = os.path.join(folder, f'{new_name}.qml')
os.rename(old_file, new_file)
self.new_qmltypes_files[x] = new_file
self.u_qmltypes_map[old_t_name] = new_name
# delete the old keys
for k,v in self.u_qmltypes_map.copy().items():
if v == old_t_name:
del self.u_qmltypes_map[k]
break
# rename all files with that name
for y in self.new_qmltypes_files:
qml_file = self.new_qmltypes_files[y]
old_obj = r'\s' + old_t_name + ' {'
new_obj = '\n' + new_name + ' {'
if self._is_in_file(old_obj, qml_file):
with open(qml_file, 'r') as fh:
data = fh.read()
data = re.sub(old_obj, new_obj, data)
with open(qml_file, 'w') as fw:
fw.write(data)
def _save_to_file(self, code):
# remove old file
if os.path.exists(self.filename):
os.unlink(self.filename)
# Make file hidden to user
if self.os_name == 'windows':
name = str(randrange(1, 100000))
else:
name = '.' + str(randrange(1, 100000))
self.filename = os.path.join(self.folder, name + '.qml')
# TODO
# whole replace function should be removed
# replace
for x in self.u_qmltypes_map:
rx = r'\s' + x +' {'
yx = '\n' + self.u_qmltypes_map[x] +' {'
code = re.sub(rx, yx, code)
# save file
with open(self.filename, 'w') as fh:
fh.write(code)
# Make file hidden on win
if self.os_name == 'windows':
dos = 'attrib +s +h ' + self.filename
#os.system(dos)
return True
def _save_qmltype_file(self, code, filename):
"""
saves the code of a qmltype
to a new filename specified by self.new_qmltypes_files
"""
# delete the current filename used for the qmltype
_, name = os.path.split(filename)
if name.startswith('Live'):
os.unlink(filename)
new_file = self.new_qmltypes_files[filename]
with open(new_file, 'w') as fh:
fh.write(code)
# Make file hidden on win (Currently causes problems)
# if self.os_name == 'windows':
# dos = 'attrib +s +h ' + new_file
# os.system(dos)