Debian Codegraph @

planetary_system_stacker/job_editor.py

raw symbols SCIP
1 # -*- coding: utf-8; -*-
2 """
3 Copyright (c) 2019 Rolf Hempel, [email protected]
4
5 This file is part of the PlanetarySystemStacker tool (PSS).
6 https://github.com/Rolf-Hempel/PlanetarySystemStacker
7
8 PSS is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with PSS. If not, see <http://www.gnu.org/licenses/>.
20
21 """
22
23 from copy import deepcopy
24 from pathlib import Path
25
26 from PyQt5 import QtWidgets, QtCore, QtGui
27
28 from exceptions import InternalError
29 from job_dialog import Ui_JobDialog
30
31 # The following lists define the allowed file extensions for still images and videos.
32 image_extensions = ['.tif', '.tiff', '.fit', '.fits', '.jpg', '.png']
33 video_extensions = ['.avi', '.mov', '.mp4', '.ser']
34 extensions = image_extensions + video_extensions
35
36
37 class FileDialog(QtWidgets.QFileDialog):
38 """
39 This is a variant of the regular FileDialog class which allows to choose files and directories
40 at the same time.
41 """
42
43 signal_dialog_ready = QtCore.pyqtSignal(list)
44
45 def __init__(self, *args, **kwargs):
46 super(FileDialog, self).__init__(*args, **kwargs)
47 # Do not use the native dialog of the OS. Otherwise the selection model tree is not
48 # available as expected.
49 self.setOption(QtWidgets.QFileDialog.DontUseNativeDialog, True)
50 self.setFileMode(QtWidgets.QFileDialog.ExistingFiles)
51 self.tree = self.findChild(QtWidgets.QTreeView)
52
53 def accept(self):
54 """
55 When the selection of files and directories is acknowledged, construct a list of strings
56 with their names and send them via a signal to the job editor.
57
58 :return: -
59 """
60
61 files = [self.directory().filePath(str(i.data())) for i in
62 self.tree.selectionModel().selectedIndexes() if i.column() == 0]
63 self.signal_dialog_ready.emit(files)
64 self.close()
65
66
67 class Job(object):
68 """
69 Objects of this class encapsulate all information describing a PSS job.
70 """
71
72 def __init__(self, job_name):
73 """
74 Initialize a Job object, given its name. The following instance variables are set:
75 - name: Path name string coming from the file chooser.
76 - file_name: File name string without path.
77 - type: Either 'video', or 'image' for stacking jobs, or 'postproc' for postprocessing.
78 - bayer_option_selected: Initialized to 'Auto detect color' for file types for which
79 debayering is supported. Otherwise None.
80 - bayer_pattern: Initialized to None
81
82 :param job_name: Name of the job (str)
83 """
84
85 self.name = job_name
86 path = Path(self.name)
87 self.file_name = path.name
88
89 # Bayer patterns are only defined for type 'video'.
90 self.bayer_pattern = None
91 self.bayer_option_selected = None
92
93 # Set the type of the job based on the file name extension.
94 if path.is_file():
95 extension = path.suffix.lower()
96 if extension in video_extensions:
97 self.type = 'video'
98 self.bayer_option_selected = 'Auto detect color'
99 elif extension in image_extensions:
100 self.type = 'postproc'
101 else:
102 raise InternalError(
103 "Unsupported file type '" + extension + "' specified for job")
104 elif path.is_dir():
105 self.type = 'image'
106 self.bayer_option_selected = 'Auto detect color'
107 else:
108 raise InternalError("Cannot decide if input file is video or image directory")
109
110
111 class JoblistWidget(QtWidgets.QListWidget):
112 """
113 This is a customized version of the standard QListWidget which accepts "drag and drop" of
114 picture files and directories. Dropped items are sent to the higher-level class as a list
115 via the signal "signal_job_entries".
116 """
117
118 signal_job_entries = QtCore.pyqtSignal(list)
119
120 def __init__(self, parent=None):
121 super().__init__(parent)
122
123 self.setAcceptDrops(True)
124 self.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
125 self.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
126
127 def dragEnterEvent(self, event):
128 if event.mimeData().hasUrls:
129 event.accept()
130 else:
131 event.ignore()
132
133 def dragMoveEvent(self, event):
134 if event.mimeData().hasUrls():
135 event.setDropAction(QtCore.Qt.CopyAction)
136 event.accept()
137 else:
138 event.ignore()
139
140 def dropEvent(self, event):
141 """
142 Handle a drop event if its mime type fits.
143
144 :param event: Drop event
145 :return: -
146 """
147
148 if event.mimeData().hasUrls():
149 event.setDropAction(QtCore.Qt.CopyAction)
150 event.accept()
151
152 # Construct a list with the job names received by the drop event.
153 links = []
154 for url in event.mimeData().urls():
155 # Only local files (with appropriate extensions) and directories are accepted.
156 if url.isLocalFile():
157 file_path = Path(str(url.toLocalFile()))
158 if file_path.is_dir() or file_path.suffix in extensions:
159 links.append(str(url.toLocalFile()))
160 # Send the job name list to the upper-level method "get_input_names".
161 self.signal_job_entries.emit(links)
162 else:
163 event.ignore()
164
165
166 class JobEditor(QtWidgets.QFrame, Ui_JobDialog):
167 """
168 Manage the list of jobs. Each item is either the name of a video file (.avi .mov .mp4 .ser) or a directory
169 containing image files of the same shape. Ask the user to add jobs to the list, or to remove
170 existing entries. The interaction with the user is through the JobDialog class.
171 """
172
173 def __init__(self, parent_gui, parent=None):
174 """
175 Initialize the job editor. The widget has a fixed size and is rendered as a QFrame.
176
177 :param parent_gui: GUI object by which the editor is invoked.
178 :param parent: Parent object
179 """
180
181 QtWidgets.QFrame.__init__(self, parent)
182 self.setupUi(self)
183 self.setWindowIcon(QtGui.QIcon('../PSS-Icon-64.ico'))
184
185 # Replace the standard QListWidget with a customized version which implements
186 # "drag and drop". It sends dropped items via its signal "signal_job_entries".
187 self.job_list_widget = JoblistWidget()
188 self.gridLayout.addWidget(self.job_list_widget, 0, 0, 1, 6)
189 self.job_list_widget.signal_job_entries.connect(self.get_input_names)
190
191 self.setFrameShape(QtWidgets.QFrame.Panel)
192 self.setFrameShadow(QtWidgets.QFrame.Sunken)
193 self.setObjectName("configuration_editor")
194
195 # The following line was deactivated. Otherwise the instructions under the joblist
196 # would not show completely on full HD monitors.
197 # self.setFixedSize(900, 600)
198
199 self.parent_gui = parent_gui
200 self.configuration = self.parent_gui.configuration
201
202 # De-activate main gui menu entries while the job editor is active. They will be
203 # re-activated upon leaving the editor with "OK" or "Cancel".
204 self.parent_gui.activate_gui_elements(
205 [self.parent_gui.ui.menuFile, self.parent_gui.ui.menuEdit,
206 self.parent_gui.ui.menuCalibrate], False)
207
208 # Set the window icon to the PSS icon.
209 self.setWindowIcon(QtGui.QIcon(self.configuration.window_icon))
210
211 # Get a copy of the jobs constructed so far. The editor only works on the copy, so
212 # that in the case of "cancel" the original list is not changed.
213 self.jobs = deepcopy(self.parent_gui.jobs)
214
215 self.messageLabel.setStyleSheet('color: red')
216
217 self.buttonBox.accepted.connect(self.accept)
218 self.buttonBox.rejected.connect(self.reject)
219 self.button_remove_jobs.clicked.connect(self.remove_job_list)
220 self.button_add_jobs.clicked.connect(self.add_jobs)
221
222 # Install an event filter on the job list to enable the context menu.
223 self.job_list_widget.installEventFilter(self)
224
225 # Populate the job list widget with the current job list.
226 self.populate_job_list()
227
228 # If the job list is empty, open the input file dialog.
229 if not self.jobs:
230 self.add_jobs()
231
232 def populate_job_list(self):
233 """
234 Fill the central QListWidget with the current list of job names.
235
236 :return: -
237 """
238 self.job_list_widget.clear()
239 for job in self.jobs:
240 item = QtWidgets.QListWidgetItem(job.name)
241 self.job_list_widget.addItem(item)
242
243 def add_jobs(self):
244 """
245 Open a file dialog for entering additional job names. Entries can either be video files or
246 directories for stacking, or single image files for postprocessing.
247
248 :return: -
249 """
250
251 options = QtWidgets.QFileDialog.Options()
252 message = "Select video file(s)/folders with image files for stacking, and/or " \
253 "image files for postprocessing"
254
255 self.file_dialog = FileDialog(self, message,
256 self.configuration.hidden_parameters_current_dir,
257 "Videos (*.avi *.mov *.mp4 *.ser)", options=options)
258 self.file_dialog.setNameFilters(["Still image folders / video files for stacking (*.avi *.mov *.mp4 *.ser)",
259 "Images for postprocessing (*.tiff *.tif *.fit *.fits *.png *.jpg)"])
260 self.file_dialog.selectNameFilter("Still image folders / video files for stacking (*.avi *.mov *.mp4 *.ser)")
261
262 # The list of strings with the new job names is sent by the FileDialog via the signal.
263 self.file_dialog.signal_dialog_ready.connect(self.get_input_names)
264 self.file_dialog.exec_()
265
266 def get_input_names(self, input_names):
267 """
268 Receive the list of new job names from the FileDialog.
269
270 :param input_names: List of strings with job names
271 :return: -
272 """
273 if input_names:
274 for input_name in input_names:
275 if input_name not in [job.name for job in self.jobs]:
276 try:
277 new_job = Job(input_name)
278 new_job.bayer_option_selected = self.configuration.frames_debayering_default
279 self.jobs.append(new_job)
280 except:
281 pass
282
283 # Save the current directory location. The next dialog will open at this position.
284 self.configuration.hidden_parameters_current_dir = str(Path(input_names[0]).parents[0])
285 self.populate_job_list()
286
287 def remove_job_list(self):
288 """
289 Remove the job entries which are currently selected.
290
291 :return: -
292 """
293
294 # Get the selected items from the central job list widget.
295 remove_list = [str(item.text()) for item in self.job_list_widget.selectedItems()]
296
297 # Update the current job list, and re-draw the job list widget.
298 self.jobs = [job for job in self.jobs if job.name not in remove_list]
299 self.populate_job_list()
300
301 def eventFilter(self, source, event):
302 """
303 The event filter intercepts context menu events on job list items. It is used to specify
304 Bayer patterns explicitly.
305
306 :param source: The widget for which the filter is activated
307 (in this case "self.job_list_widget")
308 :param event: The event type for this filter ("QtCore.QEvent.ContextMenu")
309 :return: True
310 """
311
312 # Restrict the selected items to the subset for which debayering is supported.
313 selected_items = [item for item in self.job_list_widget.selectedItems() if
314 self.jobs[source.row(item)].type == 'video']
315
316 self.pattern = None
317
318 # If a context menu item is pressed, remember the pattern.
319 def action1_triggered(state):
320 self.pattern = 'Auto detect color'
321
322 def action2_triggered(state):
323 self.pattern = 'RGB'
324
325 def action3_triggered(state):
326 self.pattern = 'BGR'
327
328 def action4_triggered(state):
329 self.pattern = 'Grayscale'
330
331 def action5_triggered(state):
332 self.pattern = 'Force Bayer RGGB'
333
334 def action6_triggered(state):
335 self.pattern = 'Force Bayer GRBG'
336
337 def action7_triggered(state):
338 self.pattern = 'Force Bayer GBRG'
339
340 def action8_triggered(state):
341 self.pattern = 'Force Bayer BGGR'
342
343 # The context menu is opened on a job list entry.
344 if (event.type() == QtCore.QEvent.ContextMenu and
345 source is self.job_list_widget):
346
347 # Show the context menu only if job items are selected for which debayering is
348 # supported.
349 if selected_items:
350 # Create a list of patterns which are checked by the selected items initially.
351 checked_patterns = [self.jobs[source.row(item)].bayer_option_selected
352 for item in selected_items]
353
354 # Create the context menu. Mark those patterns checked which have been set for at least
355 # one selected job list entry.
356 menu = QtWidgets.QMenu()
357 action1 = QtWidgets.QAction('Auto detect color', menu, checkable=True)
358 action1.triggered.connect(action1_triggered)
359 if 'Auto detect color' in checked_patterns:
360 action1.setChecked(True)
361 menu.addAction(action1)
362 menu.addSeparator()
363 action2 = QtWidgets.QAction('RGB', menu, checkable=True)
364 action2.triggered.connect(action2_triggered)
365 if 'RGB' in checked_patterns:
366 action2.setChecked(True)
367 menu.addAction(action2)
368 action3 = QtWidgets.QAction('BGR', menu, checkable=True)
369 action3.triggered.connect(action3_triggered)
370 if 'BGR' in checked_patterns:
371 action3.setChecked(True)
372 menu.addAction(action3)
373 action4 = QtWidgets.QAction('Grayscale', menu, checkable=True)
374 action4.triggered.connect(action4_triggered)
375 if 'Grayscale' in checked_patterns:
376 action4.setChecked(True)
377 menu.addAction(action4)
378 action5 = QtWidgets.QAction('Force Bayer RGGB', menu, checkable=True)
379 action5.triggered.connect(action5_triggered)
380 if 'Force Bayer RGGB' in checked_patterns:
381 action5.setChecked(True)
382 menu.addAction(action5)
383 action6 = QtWidgets.QAction('Force Bayer GRBG', menu, checkable=True)
384 action6.triggered.connect(action6_triggered)
385 if 'Force Bayer GRBG' in checked_patterns:
386 action6.setChecked(True)
387 menu.addAction(action6)
388 action7 = QtWidgets.QAction('Force Bayer GBRG', menu, checkable=True)
389 action7.triggered.connect(action7_triggered)
390 if 'Force Bayer GBRG' in checked_patterns:
391 action7.setChecked(True)
392 menu.addAction(action7)
393 action8 = QtWidgets.QAction('Force Bayer BGGR', menu, checkable=True)
394 action8.triggered.connect(action8_triggered)
395 if 'Force Bayer BGGR' in checked_patterns:
396 action8.setChecked(True)
397 menu.addAction(action8)
398
399 # Identify the selected items and their locations in the job list. Set the selected
400 # Bayer pattern in the corresponding job objects.
401 if menu.exec_(event.globalPos()) and self.pattern is not None:
402 for item in selected_items:
403 row = source.row(item)
404 self.jobs[row].bayer_option_selected = self.pattern
405 return True
406
407 return super(JobEditor, self).eventFilter(source, event)
408
409 def keyPressEvent(self, event):
410 """
411 The + and - keys are used for zooming.
412
413 :param event: event object
414 :return: -
415 """
416
417 # If the "+" key is pressed, zoom in. If "-" is pressed, zoom out.
418 if event.key() == QtCore.Qt.Key_Delete:
419 self.remove_job_list()
420 else:
421 super(JobEditor, self).keyPressEvent(event)
422
423 def accept(self):
424 """
425 If the OK button is clicked and the job list has been changed update the job list in the
426 parent object.
427
428 :return: -
429 """
430
431 # Update the job list and reset the current job index to the first entry.
432 self.parent_gui.jobs = self.jobs
433 self.parent_gui.job_number = len(self.jobs)
434 self.parent_gui.job_index = 0
435 self.parent_gui.activity = "Read frames"
436
437 # Re-activate the main GUI menus, and activate the "Automatic" checkbox.
438 self.parent_gui.activate_gui_elements(
439 [self.parent_gui.ui.menuFile, self.parent_gui.ui.menuEdit,
440 self.parent_gui.ui.menuCalibrate, self.parent_gui.ui.box_automatic], True)
441 self.parent_gui.update_status()
442 self.close()
443
444 def reject(self):
445 """
446 The Cancel button is pressed, discard the changes and close the GUI window.
447 :return: -
448 """
449
450 # Re-activate the main GUI menus.
451 self.parent_gui.activate_gui_elements(
452 [self.parent_gui.ui.menuFile, self.parent_gui.ui.menuEdit,
453 self.parent_gui.ui.menuCalibrate], True)
454 self.close()
455
456 def closeEvent(self, event):
457 """
458 Remove the job editor widget from the parent GUI and close the editor.
459
460 :param event: Close event object
461 :return: -
462 """
463
464 self.parent_gui.display_widget(None, display=False)
465 self.close()