-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCustomFileWidget.py
336 lines (290 loc) · 11.8 KB
/
CustomFileWidget.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
# -*- coding: utf-8 -*-
import os
import re
from typing import List
from PyQt5.QtCore import Qt, QRegularExpression, QFileInfo, pyqtSignal, QDir, QSize
from PyQt5.QtGui import QDropEvent, QDragEnterEvent, QDragLeaveEvent
from PyQt5.QtWidgets import QFileDialog, QHBoxLayout, QWidget, QLineEdit, \
QToolButton
class QgsFileDropEdit(QLineEdit):
fileDropped = pyqtSignal(str)
def __init__(self, parent=None):
super(QgsFileDropEdit, self).__init__(parent)
self.parent = parent
self.setAcceptDrops(True)
self.acceptable_extensions = []
self.set_correct_placeholder_text()
@property
def dir_only(self) -> bool:
return self.dir_only
@dir_only.setter
def dir_only(self, value: bool) -> None:
self.dir_only = value
@property
def file_only(self) -> bool:
return self.file_only
@file_only.setter
def file_only(self, value: bool) -> None:
self.file_only = value
@property
def suffixFilter(self) -> str:
return self.suffixFilter
@suffixFilter.setter
def suffixFilter(self, value: str) -> None:
self.suffixFilter = value
def set_correct_placeholder_text(self) -> None:
if self.parent.mStorageMode == CustomFileWidget.GetMultipleFiles:
self.setPlaceholderText('Select files..')
elif self.parent.mStorageMode == CustomFileWidget.GetFile:
self.setPlaceholderText('Select file..')
elif self.parent.mStorageMode == CustomFileWidget.SaveFile:
self.setPlaceholderText('Save output file..')
else:
self.setPlaceholderText('Select directory..')
def set_filters(self, filters: str) -> None:
self.acceptable_extensions.clear()
if '*.*' in filters:
return
regex_match = QRegularExpression("\\*\\.(\\w+)").globalMatch(filters)
while regex_match.hasNext():
match = regex_match.next()
if match.hasMatch():
self.acceptable_extensions.append(match.captured(1).lower())
def filter_acceptable_paths(self, event: QDropEvent) -> List[str]:
raw_paths = []
paths = []
if event.mimeData().hasUrls():
urls = event.mimeData().urls()
for url in urls:
local = url.toLocalFile()
if local not in raw_paths:
raw_paths.append(local)
if not event.mimeData().text() and \
event.mimeData().text() not in raw_paths:
raw_paths.append(event.mimeData().text())
for path in raw_paths:
file = QFileInfo(path)
if self.parent.mStorageMode in [
CustomFileWidget.GetFile,
CustomFileWidget.GetMultipleFiles,
CustomFileWidget.SaveFile]:
if file.isFile() and (not self.acceptable_extensions or [
elem for elem in self.acceptable_extensions
if elem.lower() == file.suffix().lower()]):
paths.append(file.filePath())
elif self.parent.mStorageMode == CustomFileWidget.GetDirectory:
if file.isDir():
paths.append(file.filePath())
elif file.isFile():
paths.append(file.absolutePath())
return paths
def acceptable_path(self, event: QDropEvent) -> str:
paths = self.filter_acceptable_paths(event)
if len(paths) > 1:
return os.path.normpath(os.sep.join(re.split(r'\\|/', paths[0])))
elif len(paths) == 1:
return paths[0]
else:
return ''
def dragEnterEvent(self, event: QDragEnterEvent) -> None:
file_path = self.acceptable_path(event)
if file_path:
event.acceptProposedAction()
else:
event.ignore()
def dragLeaveEvent(self, event: QDragLeaveEvent) -> None:
super(QgsFileDropEdit, self).dragLeaveEvent(event)
event.accept()
def dropEvent(self, event: QDropEvent):
file_path = self.acceptable_path(event)
if file_path:
event.acceptProposedAction()
self.fileDropped.emit(file_path)
class CustomFileWidget(QWidget):
def __init__(self, parent=None, default_root=None, dialog_title=''):
super(CustomFileWidget, self).__init__(parent)
main_layout = QHBoxLayout()
main_layout.setContentsMargins(0, 0, 0, 0)
self._filePath = ''
self._defaultRoot = default_root
self._dialogTitle = dialog_title
self._filter = ''
self._options = QFileDialog.ShowDirsOnly
self._mStorageMode = CustomFileWidget.GetMultipleFiles
self.file_lineEdit = QgsFileDropEdit(self)
self.file_lineEdit.setDragEnabled(True)
self.file_lineEdit.setToolTip(
"Full path to the file(s), including name and extension")
self.file_lineEdit.textChanged.connect(self.textEdited)
self.file_lineEdit.fileDropped.connect(self.fileDropped)
main_layout.addWidget(self.file_lineEdit)
self.browse_btn = QToolButton()
self.browse_btn.setText('...')
self.browse_btn.setToolTip("Browse")
self.browse_btn.clicked.connect(self.openFileDialog)
main_layout.addWidget(self.browse_btn)
self.setLayout(main_layout)
@property
def filePath(self) -> str:
return self._filePath
@filePath.setter
def filePath(self, value: str) -> None:
self._filePath = value
def splitFilePaths(self, path: str) -> List[str]:
paths = []
pathParts = re.split("\"\\s+\"", path)
cleanRe = "(^\\s*\")|(\"\\s*)"
for path_part in pathParts:
paths.append(re.sub(cleanRe, '', path_part))
return paths
def setFilePath(self, path: str) -> None:
self.file_lineEdit.setText(path)
def setReadOnly(self, readOnly: bool) -> None:
if self.mReadOnly != readOnly:
self.mReadOnly = readOnly
self.updateLayout()
@property
def dialogTitle(self) -> str:
return self._dialogTitle
@dialogTitle.setter
def dialogTitle(self, value: str) -> None:
self._dialogTitle = value
@property
def filter(self) -> str:
return self._filter
@filter.setter
def filter(self, value: str) -> None:
self._filter = value
self.file_lineEdit.set_filters(value)
@property
def options(self) -> str:
return self._options
@options.setter
def options(self, value: str) -> None:
self._options = value
def isMultiFiles(self, path: str) -> bool:
return "\" \"" in path
def textEdited(self, path: str) -> None:
self._filePath = path
if self.isMultiFiles(path):
self.file_lineEdit.setToolTip(
f'Selected files:<br><ul><li>{"</li><li>".join(self.splitFilePaths(path))}</li></ul><br>')
else:
self.file_lineEdit.setToolTip('')
def fileDropped(self, filePath: str) -> None:
self.setSelectedFileNames([filePath])
self.file_lineEdit.selectAll()
self.file_lineEdit.setFocus(Qt.MouseFocusReason)
@property
def defaultRoot(self) -> str:
return self._defaultRoot
@defaultRoot.setter
def defaultRoot(self, value: str) -> None:
self._defaultRoot = value
@property
def mStorageMode(self) -> int:
return self._mStorageMode
@mStorageMode.setter
def mStorageMode(self, value: int) -> None:
self._mStorageMode = value
self.file_lineEdit.setStorageMode(value)
@property
def lineEdit(self) -> QLineEdit:
return self.file_lineEdit
def updateLayout(self) -> None:
self.browse_btn.setEnabled(not self.mReadOnly)
self.file_lineEdit.setEnabled(not self.mReadOnly)
def openFileDialog(self) -> None:
old_path = ''
if self._filePath and (os.path.exists(
self._filePath) or self._mStorageMode == CustomFileWidget.SaveFile):
old_path = self.relativePath(self._filePath, False)
elif self._defaultRoot:
old_path = QDir.cleanPath(self._defaultRoot)
file_name = ''
file_names = []
if self._mStorageMode == CustomFileWidget.GetFile:
title = self._dialogTitle if self._dialogTitle \
else 'Select a file'
file_name = QFileDialog.getOpenFileName(
parent=self, caption=title,
directory=QFileInfo(
old_path).absoluteFilePath(),
filter=self._filter,
options=self._options)
if file_name:
file_name = file_name[0]
elif self._mStorageMode == CustomFileWidget.GetMultipleFiles:
title = self._dialogTitle if self._dialogTitle \
else 'Select one or more files'
file_names = QFileDialog.getOpenFileNames(
parent=self,
caption=title,
directory=QFileInfo(
old_path).absoluteFilePath(),
filter=self._filter,
options=self._options)
if file_names:
file_names = file_names[0]
elif self._mStorageMode == CustomFileWidget.GetDirectory:
title = self._dialogTitle if self._dialogTitle \
else "Select a directory"
file_name = QFileDialog.getExistingDirectory(
parent=self,
caption=title,
directory=QFileInfo(
old_path).absoluteFilePath(),
options=self._options)
elif self._mStorageMode == CustomFileWidget.SaveFile:
title = self._dialogTitle if self._dialogTitle \
else "Create or select a file"
file_name = QFileDialog.getSaveFileName(
parent=self, caption=title,
directory=QFileInfo(
old_path).absoluteFilePath(),
filter=self._filter,
options=self._options)
if file_name:
file_name = file_name[0]
self.activateWindow()
if not file_name and not file_names:
return
if self._mStorageMode != CustomFileWidget.GetMultipleFiles:
file_names = [file_name]
for index in range(len(file_names)):
file_names[index] = QDir.toNativeSeparators(QDir.cleanPath(
QFileInfo(file_names[index]).absoluteFilePath()))
self.setSelectedFileNames(file_names)
def setSelectedFileNames(self, file_names: List[str]) -> None:
if file_names:
for index in range(len(file_names)):
file_names[index] = os.path.normpath(
self.relativePath(file_names[index], True))
self.setFilePaths(file_names)
def setFilePaths(self, file_names: List[str]) -> None:
if not self._mStorageMode == CustomFileWidget.GetMultipleFiles:
self.setFilePath(file_names[0])
else:
if len(file_names) > 1:
self.setFilePath(f'''"{'" "'.join(file_names)}"''')
else:
self.setFilePath(file_names[0])
def relativePath(self, file_path: str, remove_relative: bool) -> str:
relative_path = QDir.toNativeSeparators(
QDir.cleanPath(self._defaultRoot))
if relative_path:
return QDir.cleanPath(
QDir(relative_path).relativeFilePath(file_path)) \
if remove_relative else QDir.cleanPath(
QDir(relative_path).filePath(file_path))
return file_path
def minimumSizeHint(self) -> QSize:
size = self.file_lineEdit.minimumSizeHint()
btn_size = self.browse_btn.minimumSizeHint()
size.setWidth(size.width() + btn_size.width())
size.setHeight(max(size.height(), btn_size.height()))
return size
GetFile = 0
GetMultipleFiles = 1
SaveFile = 2
GetDirectory = 3