forked from nwutils/Web2Executable
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util_classes.py
290 lines (226 loc) · 9.67 KB
/
util_classes.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
import os
import re
import zipfile
import tarfile
import config
import utils
from PySide import QtGui, QtCore
class ExistingProjectDialog(QtGui.QDialog):
def __init__(self, recent_projects, directory_callback, parent=None):
super(ExistingProjectDialog, self).__init__(parent)
self.setWindowTitle('Open Project Folder')
self.setWindowIcon(QtGui.QIcon(config.get_file('files/images/icon.png')))
self.setMinimumWidth(500)
group_box = QtGui.QGroupBox('Existing Projects')
gbox_layout = QtGui.QVBoxLayout()
self.project_list = QtGui.QListWidget()
gbox_layout.addWidget(self.project_list)
group_box.setLayout(gbox_layout)
self.callback = directory_callback
self.projects = recent_projects
for project in recent_projects:
text = u'{} - {}'.format(os.path.basename(project), project)
self.project_list.addItem(text)
self.project_list.itemClicked.connect(self.project_clicked)
self.cancel = QtGui.QPushButton('Cancel')
self.open = QtGui.QPushButton('Open Selected')
self.browse = QtGui.QPushButton('Browse...')
self.open.setEnabled(False)
self.open.clicked.connect(self.open_clicked)
self.browse.clicked.connect(self.browse_clicked)
buttons = QtGui.QWidget()
button_layout = QtGui.QHBoxLayout()
button_layout.addWidget(self.cancel)
button_layout.addWidget(QtGui.QWidget())
button_layout.addWidget(self.browse)
button_layout.addWidget(self.open)
buttons.setLayout(button_layout)
layout = QtGui.QVBoxLayout()
layout.addWidget(group_box)
layout.addWidget(buttons)
self.setLayout(layout)
self.cancel.clicked.connect(self.cancelled)
def browse_clicked(self):
default = self.parent().project_dir() or self.parent().last_project_dir
directory = QtGui.QFileDialog.getExistingDirectory(self, 'Find Project Directory',
default)
if directory:
self.callback(directory)
self.close()
def open_clicked(self):
pos = self.project_list.currentRow()
self.callback(self.projects[pos])
self.close()
def project_clicked(self, _):
self.open.setEnabled(True)
def cancelled(self):
self.close()
class Validator(QtGui.QRegExpValidator):
def __init__(self, regex, action, parent=None):
self.exp = regex
self.action = str
if hasattr(str, action):
self.action = getattr(str, action)
reg = QtCore.QRegExp(regex)
super(Validator, self).__init__(reg, parent)
def validate(self, text, pos):
result = super(Validator, self).validate(text, pos)
return result
def fixup(self, text):
return ''.join(re.findall(self.exp, self.action(text)))
class BackgroundThread(QtCore.QThread):
def __init__(self, widget, method_name, parent=None):
QtCore.QThread.__init__(self, parent)
self.widget = widget
self.method_name = method_name
def run(self):
if hasattr(self.widget, self.method_name):
func = getattr(self.widget, self.method_name)
func()
class Setting(object):
"""Class that describes a setting from the setting.cfg file"""
def __init__(self, name='', display_name=None, value=None,
required=False, type=None, file_types=None, *args, **kwargs):
self.name = name
self.display_name = (display_name
if display_name
else name.replace('_', ' ').capitalize())
self.value = value
self.last_value = None
self.required = required
self.type = type
self.url = kwargs.pop('url', '')
self.copy = kwargs.pop('copy', True)
self.file_types = file_types
self.scope = kwargs.pop('scope', 'local')
self.default_value = kwargs.pop('default_value', None)
self.button = kwargs.pop('button', None)
self.button_callback = kwargs.pop('button_callback', None)
self.description = kwargs.pop('description', u'')
self.values = kwargs.pop('values', [])
self.filter = kwargs.pop('filter', '.*')
self.filter_action = kwargs.pop('filter_action', 'None')
self.check_action = kwargs.pop('check_action', 'None')
self.action = kwargs.pop('action', None)
self.set_extra_attributes_from_keyword_args(**kwargs)
if self.value is None:
self.value = self.default_value
self.save_path = kwargs.pop('save_path', u'')
self.get_file_information_from_url()
def filter_name(self, text):
"""Use the filter action to filter out invalid text"""
if hasattr(self.filter_action, text):
action = getattr(self.filter_action, text)
return action(text)
return text
def get_file_information_from_url(self):
"""Extract the file information from the setting url"""
if hasattr(self, 'url'):
self.file_name = self.url.split(u'/')[-1]
self.full_file_path = utils.path_join(self.save_path, self.file_name)
self.file_ext = os.path.splitext(self.file_name)[1]
if self.file_ext == '.zip':
self.extract_class = zipfile.ZipFile
self.extract_args = ()
elif self.file_ext == '.gz':
self.extract_class = tarfile.TarFile.open
self.extract_args = ('r:gz',)
def save_file_path(self, version, location=None, sdk_build=False):
"""Get the save file path based on the version"""
if location:
self.save_path = location
else:
self.save_path = self.save_path or config.DEFAULT_DOWNLOAD_PATH
self.get_file_information_from_url()
if self.full_file_path:
path = self.full_file_path.format(version)
if sdk_build:
path = utils.replace_right(path, 'nwjs', 'nwjs-sdk', 1)
return path
return ''
def set_extra_attributes_from_keyword_args(self, **kwargs):
for undefined_key, undefined_value in kwargs.items():
setattr(self, undefined_key, undefined_value)
def extract(self, ex_path, version, sdk_build=False):
if os.path.exists(ex_path):
utils.rmtree(ex_path, ignore_errors=True)
path = self.save_file_path(version, sdk_build=sdk_build)
file = self.extract_class(path,
*self.extract_args)
# currently, python's extracting mechanism for zipfile doesn't
# copy file permissions, resulting in a binary that
# that doesn't work. Copied from a patch here:
# http://bugs.python.org/file34873/issue15795_cleaned.patch
if path.endswith('.zip'):
members = file.namelist()
for zipinfo in members:
minfo = file.getinfo(zipinfo)
target = file.extract(zipinfo, ex_path)
mode = minfo.external_attr >> 16 & 0x1FF
os.chmod(target, mode)
else:
file.extractall(ex_path)
if path.endswith('.tar.gz'):
dir_name = utils.path_join(ex_path, os.path.basename(path).replace('.tar.gz', ''))
else:
dir_name = utils.path_join(ex_path, os.path.basename(path).replace('.zip', ''))
if os.path.exists(dir_name):
for p in os.listdir(dir_name):
abs_file = utils.path_join(dir_name, p)
utils.move(abs_file, ex_path)
utils.rmtree(dir_name, ignore_errors=True)
def __repr__(self):
url = ''
if hasattr(self, 'url'):
url = self.url
return (
u'Setting: (name={}, '
u'display_name={}, '
u'value={}, required={}, '
u'type={}, url={})'
).format(self.name,
self.display_name,
self.value,
self.required,
self.type,
url)
class CompleterLineEdit(QtGui.QLineEdit):
def __init__(self, tag_dict, *args):
QtGui.QLineEdit.__init__(self, *args)
self.pref = ''
self.tag_dict = tag_dict
def text_changed(self, text):
all_text = str(text)
text = all_text[:self.cursorPosition()]
prefix = re.split('[^%a-zA-Z)(_-]', text)[-1].strip()
self.pref = prefix
if prefix.strip() != prefix:
self.pref = ''
def complete_text(self, text):
cursor_pos = self.cursorPosition()
before_text = str(self.text())[:cursor_pos]
after_text = str(self.text())[cursor_pos:]
prefix_len = len(re.split('[^%a-zA-Z)(_-]', before_text)[-1].strip())
tag_text = self.tag_dict.get(text)
if tag_text is None:
tag_text = text
new_text = '{}{}{}'.format(before_text[:cursor_pos - prefix_len],
tag_text,
after_text)
self.setText(new_text)
self.setCursorPosition(len(new_text))
class TagsCompleter(QtGui.QCompleter):
def __init__(self, parent, all_tags):
self.keys = sorted(all_tags.keys())
self.vals = sorted([val for val in all_tags.values()])
self.tags = list(sorted(self.vals+self.keys))
QtGui.QCompleter.__init__(self, self.tags, parent)
self.editor = parent
def update(self, text):
obj = self.editor
completion_prefix = obj.pref
model = QtGui.QStringListModel(self.tags, self)
self.setModel(model)
self.setCompletionPrefix(completion_prefix)
if completion_prefix.strip() != '':
self.complete()