File: planetary_system_stacker.py

package info (click to toggle)
planetary-system-stacker 0.8.32~git20230901.01f3625-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 50,468 kB
  • sloc: python: 14,055; makefile: 3
file content (1470 lines) | stat: -rw-r--r-- 66,169 bytes parent folder | download | duplicates (2)
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
# -*- coding: utf-8; -*-
"""
Copyright (c) 2018 Rolf Hempel, rolf6419@gmx.de

This file is part of the PlanetarySystemStacker tool (PSS).
https://github.com/Rolf-Hempel/PlanetarySystemStacker

PSS is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with PSS.  If not, see <http://www.gnu.org/licenses/>.

Part of this module (in class "AlignmentPointEditor" was copied from
https://stackoverflow.com/questions/35508711/how-to-enable-pan-and-zoom-in-a-qgraphicsview

"""

# The following statement is necessary so that the dependent PSS modules are found when installed
# from PyPI under site_packages.
import sys, os
sys.path.insert(0, os.path.dirname(__file__))

import getpass
import platform
from os import remove
from pathlib import Path
from sys import exit, argv

import cv2
import matplotlib
matplotlib.use('Agg')
import numpy as np
import psutil
from PyQt5 import QtWidgets, QtCore, QtGui
from numpy import uint8, uint16
import scipy
import astropy
import skimage
import pip

from alignment_point_editor import AlignmentPointEditorWidget
from alignment_points import AlignmentPoints
from configuration import Configuration
from configuration_editor import ConfigurationEditor
from display_quickstart import DisplayQuickstart
from exceptions import NotSupportedError
from frame_selector import FrameSelectorWidget
from frame_viewer import FrameViewerWidget
from frames import Frames
from job_editor import JobEditor, FileDialog
from main_gui import Ui_MainWindow
from miscellaneous import Miscellaneous
from postproc_editor import PostprocEditorWidget
from rectangular_patch_editor import RectangularPatchEditorWidget
from shift_distribution_viewer import ShiftDistributionViewerWidget
from workflow import Workflow
from pss_console import PssConsole

QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)
os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1"


class DisplayImage(QtWidgets.QGraphicsView):
    """
    This is an auxiliary class for debugging purposes. It opens a separate window where images
    can be displayed and updated during the computational steps. Activities are triggered from the
    workflow thread using signals.
    """

    def __init__(self):
        """
        Initialize the display window with a standard position and size. The window is resized later
        as required by the images to be displayed.
        """
        super().__init__()
        self.title = 'PyQt5 image'
        self.setWindowTitle(self.title)
        self.left = 100
        self.top = 100
        self.width = 640
        self.height = 480
        self.setGeometry(self.left, self.top, self.width, self.height)

        # Create the window scene and add a (so far undefined) photo object to it.
        self._scene = QtWidgets.QGraphicsScene()
        self._photo = QtWidgets.QGraphicsPixmapItem()
        self._scene.addItem(self._photo)
        self.setScene(self._scene)
        self.show()

    def convert_image_to_pixmap(self, image):
        """
        Convert a color or monochrome image (stored as a Numpy array of type uint8 or uint16) into
        a pixmap object.

        :param image: Numpy array of type uint8 or uint16, size: (size_y, size_x [, 3])
        :return: QPixmap object holding the image
        """

        # Convert image to 8bit if necessary.
        if image.dtype == uint16:
            image_uint8 = (image / 256.).astype(uint8)
        elif image.dtype == uint8:
            image_uint8 = image
        else:
            raise NotSupportedError("Attempt to set a photo with type neither"
                                    " uint8 nor uint16")
        self.shape_y = image_uint8.shape[0]
        self.shape_x = image_uint8.shape[1]

        # The image is monochrome:
        if len(image_uint8.shape) == 2:
            qt_image = QtGui.QImage(image_uint8, self.shape_x, self.shape_y, self.shape_x,
                                    QtGui.QImage.Format_Grayscale8)
        # The image is RGB color.
        else:
            qt_image = QtGui.QImage(image_uint8, self.shape_x, self.shape_y, 3 * self.shape_x,
                                    QtGui.QImage.Format_RGB888)
        return QtGui.QPixmap(qt_image)

    def update_image(self, new_image):
        """
        Replace the image with a new one.

        :param new_image: Image, stored as a Numpy array of type uint8 or uint16,
                          size: (size_y, size_x [, 3])
        :return: -
        """

        pixmap = self.convert_image_to_pixmap(new_image)
        self._photo.setPixmap(pixmap)

        # Fit the display window to the size of the image.
        self.resize(pixmap.width()+10, pixmap.height()+10)
        self.repaint()


class PlanetarySystemStacker(QtWidgets.QMainWindow):
    """
    This is the main class of the "Planetary System Stacker" software. It implements the main GUI
    for the communication with the user. It creates the workflow thread which controls all program
    activities asynchronously.
    """

    signal_reset_masters = QtCore.pyqtSignal()
    signal_load_master_dark = QtCore.pyqtSignal(str)
    signal_load_master_flat = QtCore.pyqtSignal(str)
    signal_frames = QtCore.pyqtSignal(object)
    signal_rank_frames = QtCore.pyqtSignal()
    signal_select_frames = QtCore.pyqtSignal()
    signal_align_frames = QtCore.pyqtSignal(int, int, int, int)
    signal_set_roi = QtCore.pyqtSignal(int, int, int, int)
    signal_set_alignment_points = QtCore.pyqtSignal()
    signal_compute_frame_qualities = QtCore.pyqtSignal()
    signal_stack_frames = QtCore.pyqtSignal()
    signal_save_stacked_image = QtCore.pyqtSignal()
    signal_postprocess_image = QtCore.pyqtSignal()
    signal_save_postprocessed_image = QtCore.pyqtSignal(object)
    signal_set_go_back_activity = QtCore.pyqtSignal(object)

    def __init__(self, parent=None):
        """
        Initialize the Planetary System Stacker environment.

        :param parent: None
        """

        # The (generated) QtGui class is contained in module main_gui.py.
        QtWidgets.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # This line is necessary to show the menubar on Linux. On Windows it does not hurt.
        self.ui.menubar.setNativeMenuBar(False)

        # Make sure that the progress widgets retain their size when hidden.
        size_policy = self.ui.label_current_progress.sizePolicy()
        size_policy.setRetainSizeWhenHidden(True)
        self.ui.label_current_progress.setSizePolicy(size_policy)
        size_policy = self.ui.progressBar_current.sizePolicy()
        size_policy.setRetainSizeWhenHidden(True)
        self.ui.progressBar_current.setSizePolicy(size_policy)

        # Create configuration object and set configuration parameters to standard values.
        self.configuration = Configuration()
        self.configuration.initialize_configuration()

        # Set the window icon to the PSS icon.
        self.setWindowIcon(QtGui.QIcon(self.configuration.window_icon))

        # Look up the location and size of the main GUI. Replace the location parameters with those
        # stored in the configuration file when the GUI was closed last time. This way, the GUI
        # memorizes its location between MPM invocations.
        x0 = self.configuration.hidden_parameters_main_window_x0
        y0 = self.configuration.hidden_parameters_main_window_y0
        width = self.configuration.hidden_parameters_main_window_width
        height = self.configuration.hidden_parameters_main_window_height
        self.setGeometry(x0, y0, width, height)
        if self.configuration.hidden_parameters_main_window_maximized:
            self.showMaximized()

        # Initialize variables.
        self.widget_saved = None

        # Write the program version into the window title.
        self.setWindowTitle(self.configuration.global_parameters_version)

        # Connect GUI events with methods of this class.
        self.ui.actionQuit.triggered.connect(self.closeEvent)
        self.ui.comboBox_back.currentTextChanged.connect(self.go_back)
        self.ui.pushButton_start.clicked.connect(self.play)
        self.ui.pushButton_pause.clicked.connect(self.pause)
        self.ui.pushButton_next_job.clicked.connect(self.go_next)
        self.ui.pushButton_quit.clicked.connect(self.close)
        self.ui.box_automatic.stateChanged.connect(self.automatic_changed)
        self.ui.actionLoad_video_directory.triggered.connect(self.load_video_directory)
        self.ui.actionSave.triggered.connect(self.save_result)
        self.ui.actionSave_as.triggered.connect(self.save_result_as)
        self.ui.actionEdit_configuration.triggered.connect(self.edit_configuration)
        self.ui.actionLoad_config.triggered.connect(self.load_config_file)
        self.ui.actionSave_config.triggered.connect(self.save_config_file)
        self.ui.actionDe_activate_master_frames.triggered.connect(self.reset_masters)
        self.ui.actionLoad_master_dark_frame.triggered.connect(self.load_master_dark)
        self.ui.actionLoad_master_flat_frame.triggered.connect(self.load_master_flat)
        self.ui.actionCreate_new_master_dark_frame.triggered.connect(self.create_master_dark)
        self.ui.actionCreate_new_master_flat_frame.triggered.connect(self.create_master_flat)
        self.ui.actionAbout.triggered.connect(self.about_pss)
        self.ui.actionShow_Quickstart.setChecked(self.configuration.global_parameters_display_quickstart)
        self.ui.actionShow_Quickstart.triggered.connect(self.show_quickstart)

        # Create the workflow thread and start it.
        self.thread = QtCore.QThread()
        self.workflow = Workflow(self)
        self.workflow.setParent(None)
        self.workflow.moveToThread(self.thread)
        self.workflow.master_dark_created_signal.connect(self.master_dark_created)
        self.workflow.master_flat_created_signal.connect(self.master_flat_created)
        self.workflow.calibration.report_calibration_error_signal.connect(
            self.report_calibration_error)
        self.workflow.work_next_task_signal.connect(self.work_next_task)
        self.workflow.report_error_signal.connect(self.report_error)
        self.workflow.abort_job_signal.connect(self.next_job_after_error)
        self.workflow.work_current_progress_signal.connect(self.set_current_progress)
        self.workflow.set_main_gui_busy_signal.connect(self.gui_set_busy)
        self.workflow.set_status_bar_signal.connect(self.write_status_bar)
        self.workflow.create_image_window_signal.connect(self.create_image_window)
        self.workflow.update_image_window_signal.connect(self.update_image_window)
        self.workflow.terminate_image_window_signal.connect(self.terminate_image_window)
        self.thread.start()

        # Connect signals to start activities on the workflow thread (e.g. in method
        # "work_next_task").
        self.signal_reset_masters.connect(self.workflow.calibration.reset_masters)
        self.signal_load_master_dark.connect(self.workflow.calibration.load_master_dark)
        self.signal_load_master_flat.connect(self.workflow.calibration.load_master_flat)
        self.signal_frames.connect(self.workflow.execute_frames)
        self.signal_rank_frames.connect(self.workflow.execute_rank_frames)
        self.signal_select_frames.connect(self.workflow.execute_set_index_translation_table)
        self.signal_align_frames.connect(self.workflow.execute_align_frames)
        self.signal_set_roi.connect(self.workflow.execute_set_roi)
        self.signal_set_alignment_points.connect(self.workflow.execute_set_alignment_points)
        self.signal_compute_frame_qualities.connect(self.workflow.execute_compute_frame_qualities)
        self.signal_stack_frames.connect(self.workflow.execute_stack_frames)
        self.signal_save_stacked_image.connect(self.workflow.execute_save_stacked_image)
        self.signal_postprocess_image.connect(self.workflow.execute_postprocess_image)
        self.signal_save_postprocessed_image.connect(self.workflow.execute_save_postprocessed_image)
        self.signal_set_go_back_activity.connect(self.change_go_back_activity)

        # Initialize status variables
        self.automatic = self.ui.box_automatic.isChecked()
        self.busy = False
        self.pause = False
        self.job_number = 0
        self.job_index = 0
        self.jobs = []
        self.activities = ['Previous job', 'Read frames', 'Rank frames', 'Align frames',
                           'Select stack size', 'Set ROI', 'Set alignment points',
                           'Compute frame qualities', 'Stack frames', 'Save stacked image',
                           'Postprocessing', 'Save postprocessed image', 'Next job']
        self.activity = 'Read frames'
        self.error_occurred = False

        # Initialize the "backwards" combobox: The user can only go back to those program steps
        # which have been executed already.
        self.set_previous_actions_button()

        # Deactivate GUI elements which do not make sense yet.
        self.activate_gui_elements(
            [self.ui.box_automatic, self.ui.comboBox_back, self.ui.pushButton_start,
             self.ui.pushButton_pause,
             self.ui.pushButton_next_job, self.ui.actionSave, self.ui.actionSave_as,
             self.ui.actionLoad_postproc_config, self.ui.actionSave_postproc_config,
             self.ui.actionEdit_postproc_config], False)
        self.show_current_progress_widgets(False)
        self.show_batch_progress_widgets(False)

        # If the configuration was not read in from a previous run (i.e. only default values have
        # been set so far), open the configuration editor GUI to let the user make adjustments if
        # necessary.
        if not self.configuration.config_file_exists:
            # Tell the user to begin with changing / confirming config parameters.
            self.write_status_bar(
                'Adapt configuration to your needs and / or confirm by pressing "OK".', 'red')
            self.edit_configuration()

        else:
            # Tell the user to begin with specifying jobs to be executed.
            self.write_status_bar(
                "Specify video(s) or dir(s) with image files to be stacked, or single image "
                "files for postprocessing (menu: File / Open).", 'red')

        # Show the quickstart guide (if checkbox has not been de-activated.
        if self.configuration.global_parameters_display_quickstart:
            self.display_widget(DisplayQuickstart(self, self.configuration))

        # Initialize objects.
        self.image_window = None

    @QtCore.pyqtSlot()
    def show_quickstart(self):
        """
        If the user requests to re-activate the quickstart guide display at startup, change the
        corresponding gobal parameter.

        :return:
        """

        self.configuration.global_parameters_display_quickstart = \
            self.ui.actionShow_Quickstart.isChecked()

    @QtCore.pyqtSlot()
    def create_image_window(self):
        """
        On request of the workflow thread open a separate window for displaying images in debugging.

        :return: -
        """
        self.image_window = DisplayImage()

    @QtCore.pyqtSlot(object)
    def update_image_window(self, image):
        """
        Replace the image in the image window with a new one sent from the workflow thread.

        :param image: Numpy array of type uint8 or uint16, size: (size_y, size_x [, 3])
        :return: -
        """
        self.image_window.update_image(image)

    @QtCore.pyqtSlot()
    def terminate_image_window(self):
        """
        Close the separate image window on request of the workflow thread.

        :return: -
        """
        del self.image_window

    def automatic_changed(self):
        """
        If the user checks / unchecks the "Automatic" checkbox, change the corresponding status
        variable.

        :return: -
        """

        self.automatic = not self.automatic

    def edit_configuration(self):
        """
        This method is invoked by selecting the "edit stacking config" menu entry.

        :return: -
        """

        # Display the configuration editor widget in the central QFrame.
        self.display_widget(ConfigurationEditor(self))

    def change_go_back_activity(self, phases):
        """
        This method is triggered in the configuration editor if at least one parameter has been
        changed. In this case it may be necessary to reset the workflow to an earlier phase. This
        phase is set as the current activity, and later phases are deleted from the "go back"
        button list.

        :param phases: List of phases after which the workflow has to be invalidated. The
                       earliest phase on the list is relevant.
        :return: -
        """

        # Include the current activity in the list to make sure that the workflow will not jump to
        # a phase which is not yet prepared.
        phases.append(self.activity)

        # Reset the position in the workflow.
        earliest_phase = self.activities[min([self.activities.index(item) for item in phases])]

        # Only if parameters are changed later in the workflow, write a message to the protocol.
        if self.configuration.global_parameters_protocol_level > 1 and self.activity != 'Read frames':
            # If the attached logfile has been closed, re-open it.
            if self.workflow.attached_log_file is not None:
                if self.configuration.global_parameters_store_protocol_with_result and \
                        self.workflow.attached_log_file.closed:
                    try:
                        self.workflow.attached_log_file = open(self.workflow.attached_log_name, 'a')
                    except:
                        pass
            Miscellaneous.protocol(
                "+++ Parameter change: all phases after '" + earliest_phase + "' are invalidated +++",
                self.workflow.attached_log_file, precede_with_timestamp=True)

        # Reset the position in the workflow, and update the "go back" button list.
        self.activity = earliest_phase
        self.set_previous_actions_button()

    def display_widget(self, widget, display=True):
        """
        Display a widget in the central main GUI location, or remove it from there.

        :param widget: Widget object to be displayed.
        :param display: If "True", display the widget. If "False", remove the current widget from
                        the GUI.
        :return: -
        """

        if display:
            if self.widget_saved:
                self.ui.verticalLayout_2.removeWidget(self.widget_saved)
                self.widget_saved.deleteLater()
                self.widget_saved.close()
            self.widget_saved = widget
            self.ui.verticalLayout_2.insertWidget(0, widget)
            self.ui.verticalLayout_2.setStretch(1, 0)
        else:
            if self.widget_saved:
                self.ui.verticalLayout_2.removeWidget(self.widget_saved)
                self.widget_saved.deleteLater()
                self.widget_saved.close()
                self.widget_saved = None

    def load_config_file(self):
        """
        Load a stacking configuration file (extension ".pss").
        :return: -
        """

        options = QtWidgets.QFileDialog.Options()
        filename = QtWidgets.QFileDialog.getOpenFileName(self, "Load configuration file",
                                                 self.configuration.hidden_parameters_current_dir,
                                                 "*.pss", options=options)
        file_name = filename[0]

        # If a valid file was selected, read parameters from the file and open the configuration
        # editor.
        if file_name != '':
            # Read configuration parameters from the selected file.
            self.configuration.read_config(file_name=file_name)
            # Remember the current directory for next file dialog.
            self.configuration.current_dir = str(Path(file_name).parents[0])
            self.display_widget(ConfigurationEditor(self))

            if self.configuration.global_parameters_protocol_level > 1 and \
                    self.configuration.global_parameters_version_imported_from != \
                    self.configuration.global_parameters_version:
                Miscellaneous.protocol("+++ Importing configuration from older version: " +
                                self.configuration.global_parameters_version_imported_from + " +++",
                                self.workflow.attached_log_file)

    def save_config_file(self):
        """
        Save all stacking parameters in a configuration file.

        :return: -
        """

        # Open the file chooser.
        options = QtWidgets.QFileDialog.Options()
        filename = QtWidgets.QFileDialog.getSaveFileName(self, "Save configuration file",
                                                 self.configuration.hidden_parameters_current_dir,
                                                 "Config file (*.pss)",
                                                 options=options)

        # Store file only if the chooser did not return with a cancel.
        file_name = filename[0]
        if file_name != "":
            my_file = Path(file_name)

            # Remember the current directory for next file dialog.
            self.configuration.hidden_parameters_current_dir = str(my_file.parents[0])

            # If the config file exists, delete it first.
            if my_file.is_file():
                remove(str(my_file))
            self.configuration.write_config(file_name=str(my_file))

    def load_video_directory(self):
        """
        This method is invoked by selecting "Open" from the "file" menu.

        :return: -
        """

        # Open the job editor widget.
        self.display_widget(JobEditor(self))

    def reset_masters(self):
        """
        This method is invoked by selecting "Reset master frames" from the "Calibration" menu. The
        signal is caught on the workflow thread, where the method "execute_reset_masters" is
        executed.

        :return: -
        """

        self.signal_reset_masters.emit()
        if self.configuration.global_parameters_protocol_level > 0:
            Miscellaneous.protocol("+++ De-activating master dark / flat frames +++",
                                   self.workflow.attached_log_file)

    def create_master_dark(self):
        """
        Open a file dialog for entering a video file or image directory with dark frames. When the
        FileDialog closes, it sends a signal (with the path name as payload) to the corresponding
        slot on the workflow thread. There the actual master dark computation is performed.

        :return: -
        """

        options = QtWidgets.QFileDialog.Options()
        message = "Select a video file / a folder with image files for computing a master dark" \
                  " frame"

        file_dialog = FileDialog(self, message,
                                 self.configuration.hidden_parameters_current_dir,
                                 "Videos (*.avi *.mov *.mp4 *.ser)", options=options)
        file_dialog.setNameFilters(["Still image folder / video file (*.avi *.mov *.mp4 *.ser)"])

        # The list of strings (length 1) with the path name to the dark frames is sent by the
        # FileDialog via the signal "signal_dialog_ready".
        file_dialog.signal_dialog_ready.connect(self.workflow.execute_create_master_dark)
        file_dialog.exec_()

    @QtCore.pyqtSlot(bool)
    def master_dark_created(self, success):
        """
        Called from the workflow thread when it has created a master dark frame. This method is
        used to save the image to disk.

        :param success: A flag indicating if the dark frame was created successfully. Only if true,
                        write the resulting image to disk.
        :return: -
        """

        if success:
            options = QtWidgets.QFileDialog.Options()
            master_dark_file = QtWidgets.QFileDialog.getSaveFileName(self,
                                                 "Choose a file name for the new master dark frame",
                                                 self.configuration.hidden_parameters_current_dir,
                                                 "Images (*png *.tiff *.fits)",
                                                 options=options)

            if master_dark_file[0]:
                Frames.save_image(master_dark_file[0],
                                  self.workflow.calibration.master_dark_frame,
                                  color=self.workflow.calibration.dark_color,
                                  avoid_overwriting=False,
                                  header=self.configuration.global_parameters_version)
                # Remember the current directory for next file dialog.
                self.configuration.hidden_parameters_current_dir = \
                    str(Path(master_dark_file[0]).parents[0])
                if self.configuration.global_parameters_protocol_level > 1:
                    Miscellaneous.protocol("           The master dark frame was written to: " +
                                           str(master_dark_file[0]),
                                           self.workflow.attached_log_file,
                                           precede_with_timestamp=False)

        # Re-activate GUI elements.
        self.gui_set_busy(False)

    def load_master_dark(self):
        """
        This method is invoked by selecting "Load master dark" from the "Calibration" menu. It
        opens a file dialog for selecting a Png, Tiff or Fits file with a master dark frame.

        :return: -
        """

        options = QtWidgets.QFileDialog.Options()
        master_dark_file = QtWidgets.QFileDialog.getOpenFileName(self,
                                                 "Select image file containing a master dark frame",
                                                 self.configuration.hidden_parameters_current_dir,
                                                 "Images (*png *.tiff *.fits)", options=options)

        if master_dark_file[0]:
            self.signal_load_master_dark.emit(master_dark_file[0])
            # Remember the current directory for next file dialog.
            self.configuration.hidden_parameters_current_dir = str(
                Path(master_dark_file[0]).parents[0])
            if self.configuration.global_parameters_protocol_level > 0:
                Miscellaneous.protocol("+++ Loading master dark frame +++",
                                       self.workflow.attached_log_file)

    def create_master_flat(self):
        """
        Open a file dialog for entering a video file or image directory with flat frames. When the
        FileDialog closes, it sends a signal (with the path name as payload) to the corresponding
        slot on the workflow thread. There the actual master flat computation is performed.

        :return: -
        """

        options = QtWidgets.QFileDialog.Options()
        message = "Select a video file / a folder with image files for computing a master flat" \
                  " frame"

        file_dialog = FileDialog(self, message,
                                 self.configuration.hidden_parameters_current_dir,
                                 "Videos (*.avi *.mov *.mp4 *.ser)", options=options)
        file_dialog.setNameFilters(["Still image folder / video file (*.avi *.mov *.mp4 *.ser)"])

        # The list of strings (length 1) with the path name to the flat frames is sent by the
        # FileDialog via the signal "signal_dialog_ready".
        file_dialog.signal_dialog_ready.connect(self.workflow.execute_create_master_flat)
        file_dialog.exec_()

    @QtCore.pyqtSlot(bool)
    def master_flat_created(self, success):
        """
        Called from the workflow thread when it has created a master flat frame. This method is
        used to save the image to disk.

        :param success: A flag indicating if the dark frame was created successfully. Only if true,
                        write the resulting image to disk.
        :return: -
        """

        if success:
            options = QtWidgets.QFileDialog.Options()
            master_flat_file = QtWidgets.QFileDialog.getSaveFileName(self,
                                                 "Choose a file name for the new master flat frame",
                                                 self.configuration.hidden_parameters_current_dir,
                                                 "Images (*png *.tiff *.fits)",
                                                 options=options)

            if master_flat_file[0]:
                Frames.save_image(master_flat_file[0],
                                  self.workflow.calibration.master_flat_frame,
                                  color=self.workflow.calibration.flat_color,
                                  avoid_overwriting=False,
                                  header=self.configuration.global_parameters_version)
                # Remember the current directory for next file dialog.
                self.configuration.hidden_parameters_current_dir = str(
                    Path(master_flat_file[0]).parents[0])
                if self.configuration.global_parameters_protocol_level > 1:
                    Miscellaneous.protocol("           The master flat frame was written to: " +
                                           str(master_flat_file[0]),
                                           self.workflow.attached_log_file,
                                           precede_with_timestamp=False)

        # Re-activate GUI elements.
        self.gui_set_busy(False)

    def load_master_flat(self):
        """
        This method is invoked by selecting "Load master flat" from the "Calibration" menu. It
        opens a file dialog for selecting a Png, Tiff or Fits file with a master flat frame.

        :return: -
        """

        options = QtWidgets.QFileDialog.Options()
        master_flat_file = QtWidgets.QFileDialog.getOpenFileName(self,
                                                 "Select image file containing a master dark frame",
                                                 self.configuration.hidden_parameters_current_dir,
                                                 "Images (*png *.tiff *.fits)", options=options)

        if master_flat_file[0]:
            self.signal_load_master_flat.emit(master_flat_file[0])
            # Remember the current directory for next file dialog.
            self.configuration.hidden_parameters_current_dir = str(
                Path(master_flat_file[0]).parents[0])
            if self.configuration.global_parameters_protocol_level > 0:
                Miscellaneous.protocol("+++ Loading master flat frame +++",
                                       self.workflow.attached_log_file)

    @QtCore.pyqtSlot(str)
    def report_calibration_error(self, message):
        if self.configuration.global_parameters_protocol_level > 0:
            Miscellaneous.protocol("           " + message,
                                   self.workflow.attached_log_file, precede_with_timestamp=False)

    def go_back(self):
        """
        Repeat processing steps as specified via the choice of the "comboBox_back" button. The user
        can either repeat steps of the current job, or go back to the previous job.

        :return: -
        """

        # Get the choice of the combobox button.
        task = self.ui.comboBox_back.currentText()
        if self.configuration.global_parameters_protocol_level > 0:
            if self.workflow.attached_log_file is not None:
                if self.configuration.global_parameters_store_protocol_with_result and \
                        self.workflow.attached_log_file.closed:
                    try:
                        self.workflow.attached_log_file = open(self.workflow.attached_log_name, 'a')
                    except:
                        pass
            Miscellaneous.protocol("", self.workflow.attached_log_file,
                                   precede_with_timestamp=False)
            Miscellaneous.protocol("+++ Repeating from task: " + task + " +++",
                                   self.workflow.attached_log_file)

        # If the end of the job queue was reached, reverse the last job index increment.
        if self.job_index == self.job_number and self.job_index > 0:
            self.job_index -= 1

        # Restart from the specified task within the current job.
        if task in ['Read frames', 'Rank frames', 'Select frames', 'Align frames',
                    'Select stack size', 'Set ROI', 'Set alignment points',
                    'Compute frame qualities', 'Stack frames', 'Save stacked image',
                    'Postprocessing', 'Save postprocessed image']:
            # Make sure to remove any active interaction widget.
            self.display_widget(None, display=False)
            self.work_next_task(task)

        # Go back to the previous job and start with the first task.
        elif task == 'Previous job':
            self.job_index -= 1
            self.display_widget(None, display=False)
            self.work_next_task("Read frames")

    def play(self):
        """
        This method is invoked when the "Start / Cont." button is pressed.
        :return: -
        """

        # Start the next task.
        self.work_next_task(self.activity)

    def pause(self):
        """
        This method is invoked when the "Pause" button is pressed.
        :return: -
        """

        # If the pause flag is not yet set, append a message to the status bar.
        if not self.pause:
            self.append_status_bar(" Execution will be suspended after current phase.")
        # Set the pause flag.
        self.pause = True

    def go_next(self):
        """
        This method is invoked when the "Next Job" button is pressed.
        :return: -
        """

        self.work_next_task("Next job")

    @QtCore.pyqtSlot(str)
    def work_next_task(self, next_activity):
        """
        This is the central place where all activities are scheduled. Depending on the
         "next_activity" chosen, the appropriate activity is started on the workflow thread.

        :param next_activity: Activity to be performed next.
        :return: -
        """

        # Make sure not to process an empty job list, or a job index out of range.
        if not self.jobs or self.job_index >= self.job_number:
            return

        self.activity = next_activity

        # Deactivate the current progress widgets. They are reactivated when the workflow thread
        # sends a progress signal.
        self.show_current_progress_widgets(False)

        # If the "Pause" button was pressed during the last activity, stop the workflow.
        if self.pause:
            self.pause = False
            self.busy = False

        # Start workflow activities. When a workflow method terminates, it invokes this method on
        # the GUI thread, with "next_activity" denoting the next step in the processing chain.
        elif self.activity == "Read frames":
            # For the first activity (reading all frames from the file system) there is no
            # GUI interaction. Start the workflow action immediately.
            self.signal_frames.emit(self.jobs[self.job_index])
            self.busy = True

        elif self.activity == "Rank frames":
            if not self.automatic:
                pass

            self.signal_rank_frames.emit()
            self.busy = True

        elif self.activity == "Select frames":
            # If the dialog to mark frames to be excluded from stacking was requested, open the
            # dialog now.
            if not self.automatic and self.configuration.frames_add_selection_dialog:
                # Reset frames index translation, if active.
                if self.workflow.frames.index_translation_active:
                    self.workflow.frames.reset_index_translation()
                    self.workflow.rank_frames.reset_index_translation()

                fsw = FrameSelectorWidget(self, self.configuration, self.workflow.frames,
                                          self.workflow.rank_frames,
                                          self.workflow.attached_log_file,
                                          self.signal_select_frames)

                self.display_widget(fsw)
                fsw.listWidget.setFocus()

            else:
                # The dialog to exclude frames is not to be called. Update index translation
                # directly if required.
                self.signal_select_frames.emit()

        elif self.activity == "Align frames":

            # If manual stabilization patch selection was requested in 'Surface' mode, invoke the
            # patch editor.
            if not self.automatic and not self.configuration.align_frames_automation and \
                    self.configuration.align_frames_mode == 'Surface':
                border = self.configuration.align_frames_search_width

                # When the editor is finished, it sends a signal (last argument) to the workflow
                # thread with the four coordinate index bounds.
                rpew = RectangularPatchEditorWidget(self, self.workflow.frames.frames_mono(
                    self.workflow.rank_frames.frame_ranks_max_index)[border:-border,
                                                          border:-border],
                                        "With 'ctrl' and the left mouse button pressed, draw a "
                                        "rectangular patch to be used for frame alignment. Or just "
                                        "press 'OK / Cancel' (automatic selection).",
                                        self.signal_align_frames)

                self.display_widget(rpew)
                rpew.viewer.setFocus()

            else:
                # If all index bounds are set to zero, the stabilization patch is computed
                # automatically by the workflow thread.
                self.signal_align_frames.emit(0, 0, 0, 0)

            self.busy = True

        elif self.activity == "Select stack size":

            if not self.automatic:

                # Reset the ROI, if one was defined before.
                self.workflow.align_frames.reset_roi()

                # When the frame viewer is finished, it sends a signal which invokes this same
                # method on the main thread.
                fvw = FrameViewerWidget(self, self.workflow.configuration, self.workflow.frames,
                                        self.workflow.rank_frames, self.workflow.align_frames,
                                        self.workflow.attached_log_file,
                                        self.workflow.work_next_task_signal, "Set ROI")

                self.display_widget(fvw)
                fvw.frame_viewer.setFocus()

            else:
                # In automatic mode, nothing is to be done in the workflow thread. Start the next
                # activity on the main thread immediately.
                self.workflow.work_next_task_signal.emit("Set ROI")
            self.busy = True

        elif self.activity == "Set ROI":

            # Reset the ROI, if one was defined before.
            self.workflow.align_frames.reset_roi()

            if not self.automatic:

                # When the editor is finished, it sends a signal (last argument) to the workflow
                # thread with the four coordinate index bounds.
                rpew = RectangularPatchEditorWidget(self, self.workflow.align_frames.mean_frame,
                    "With 'ctrl' and the left mouse button pressed, draw a rectangle to set the"
                    " ROI, or just press 'OK' (no ROI).", self.signal_set_roi)

                self.display_widget(rpew)
                rpew.viewer.setFocus()

            else:
                # If all index bounds are set to zero, no ROI is selected.
                self.signal_set_roi.emit(0, 0, 0, 0)
            self.busy = True

        elif self.activity == "Set alignment points":
            # In automatic mode, compute the AP grid automatically in the workflow thread. In this
            # case, the AlignmentPoints object is created there as well.
            if self.automatic:
                self.signal_set_alignment_points.emit()
                self.busy = True
            else:
                # If the APs are created interactively, create the AlignmentPoints object here, but
                # assign it to the workflow object.
                if self.configuration.global_parameters_protocol_level > 0:
                    Miscellaneous.protocol("+++ Start creating alignment points +++",
                                           self.workflow.attached_log_file)
                # Initialize the AlignmentPoints object.
                self.workflow.my_timer.create_no_check('Initialize alignment point object')
                self.workflow.alignment_points = AlignmentPoints(self.workflow.configuration,
                     self.workflow.frames, self.workflow.rank_frames, self.workflow.align_frames,
                     progress_signal=self.workflow.work_current_progress_signal)
                self.workflow.my_timer.stop('Initialize alignment point object')
                # Open the alignment point editor.
                apew = AlignmentPointEditorWidget(self, self.workflow.configuration,
                                                  self.workflow.align_frames,
                                                  self.workflow.alignment_points,
                                                  self.signal_set_alignment_points)

                self.display_widget(apew)
                apew.viewer.setFocus()

        elif self.activity == "Compute frame qualities":
            if not self.automatic:
                pass
            self.signal_compute_frame_qualities.emit()
            self.busy = True

        elif self.activity == "Stack frames":
            if not self.automatic:
                pass
            self.signal_stack_frames.emit()
            self.busy = True

        elif self.activity == "Save stacked image":
            if self.automatic:
                self.signal_save_stacked_image.emit()
            else:
                sdv = ShiftDistributionViewerWidget(self,
                                                    self.workflow.stack_frames.shift_distribution,
                                                    self.workflow.stack_frames.shift_failure_percent,
                                                    self.signal_save_stacked_image)
                self.display_widget(sdv)
            self.busy = True

        elif self.activity == "Postprocessing":
            if self.automatic:
                self.signal_postprocess_image.emit()
            else:
                if self.configuration.global_parameters_protocol_level > 0:
                    Miscellaneous.protocol("+++ Start postprocessing +++",
                                           self.workflow.attached_log_file)
                # In interactive mode the postprocessed image is computed in the GUI thread. The
                # resulting image is sent via the "signal_save_postprocessed_image" signal.
                pew = PostprocEditorWidget(self.workflow.configuration,
                                           self.workflow.postproc_input_image,
                                           self.workflow.postproc_input_name,
                                           self.write_status_bar,
                                           self.signal_save_postprocessed_image)
                self.display_widget(pew)
                pew.frame_viewer.setFocus()
            self.busy = True

        elif self.activity == "Save postprocessed image":
            if not self.automatic:
                pass
            # This path is executed for "automatic" mode. In that case the postprocessed image
            # is available in the workflow object.
            if self.workflow.postprocessed_image is not None:
                self.signal_save_postprocessed_image.emit(self.workflow.postprocessed_image)
            # Otherwise it has been computed in the PostprocEditor on the GUI thread, and stored
            # in the postproc_data_object. If the editor was left with "cancel", the image is set
            # to None. In that case the workflow thread will not save the image.
            else:
                self.signal_save_postprocessed_image.emit(
                    self.workflow.configuration.postproc_data_object.versions[
                        self.workflow.configuration.postproc_data_object.version_selected].image)
            self.busy = True

        elif self.activity == "Next job":
            self.job_index += 1
            if self.job_index < self.job_number:
                # If the end of the queue is not reached yet, start with reading frames of next job.
                self.activity = "Read frames"
                # If an error condition was set during the current job, reset it.
                self.error_occurred = False
                if not self.automatic:
                    pass
                self.signal_frames.emit(self.jobs[self.job_index])
            else:
                # If an error occurred, do not include all phases in "Go back to" combo list. This
                # way the user cannot jump back to a phase of the aborted job which was not
                # executed.
                if self.error_occurred:
                    self.activity = "Read frames"
                    self.error_occurred = False
                # End of queue reached, give control back to the user.
                self.busy = False

        # Activate / Deactivate GUI elements depending on the current situation.
        self.update_status()

    @QtCore.pyqtSlot(str)
    def next_job_after_error(self, message):
        """
        This method is triggered by the workflow thread via a signal when an error causes a job to
        be aborted. In interactive mode a message window shows the error message and asks the user
        for confirmation. Depending on the protocol level, the error message is also written to the
        protocol (file).

        :param message: Error message to be displayed
        :return: -
        """

        # Report the error.
        self.report_error(message)

        # Set the error flag.
        self.error_occurred = True

        # Abort the current job and go to the next one.
        self.work_next_task("Next job")

    @QtCore.pyqtSlot(str)
    def report_error(self, message):
        """
        This method is triggered by the workflow thread via a signal when an error is to be
        reported. In interactive mode a message window shows the error message and asks the user
        for confirmation. Depending on the protocol level, the error message is also written to the
        protocol (file).

        :param message: Error message to be displayed
        :return: -
        """

        # Show a message box and wait for acknowledgement by the user.
        if not self.automatic:
            msg = QtWidgets.QMessageBox()
            msg.setText(message)
            msg.setIcon(QtWidgets.QMessageBox.Critical)
            msg.setWindowTitle(self.configuration.global_parameters_version)
            msg.setWindowIcon(QtGui.QIcon(self.configuration.window_icon))
            msg.setStandardButtons(QtWidgets.QMessageBox.Ok)
            msg.exec_()

        if self.configuration.global_parameters_protocol_level > 0:
            Miscellaneous.protocol(message + "\n", self.workflow.attached_log_file,)

    def save_result(self):
        """
        save the result as 16bit Png, Tiff or Fits file at the standard location.

        :return: -
        """

        Frames.save_image(self.workflow.stacked_image_name,
                          self.workflow.stack_frames.stacked_image,
                          color=self.workflow.frames.color, avoid_overwriting=False,
                          header=self.configuration.global_parameters_version)

    def save_result_as(self):
        """
        save the result as 16bit Png, Tiff or Fits file at a location selected by the user.

        :return: -
        """

        options = QtWidgets.QFileDialog.Options()
        filename, extension = QtWidgets.QFileDialog.getSaveFileName(self,
            "Save result as 16bit Png, Tiff or Fits image", self.workflow.stacked_image_name,
            "Image Files (*png *.tiff *.fits)", options=options)

        if filename and extension:
            Frames.save_image(filename, self.workflow.stack_frames.stacked_image,
                              color=self.workflow.frames.color, avoid_overwriting=False,
                              header=self.configuration.global_parameters_version)

    def place_holder_manual_activity(self, activity):
        # Ask the user for confirmation.
        quit_msg = "This is a placeholder for the manual activity " + activity + \
                   ". press OK when you want to continue with the workflow."
        QtWidgets.QMessageBox.question(self, 'Message', quit_msg,
                                       QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
                                       QtWidgets.QMessageBox.No)

    def show_current_progress_widgets(self, show):
        """
        Show or hide the GUI widgets showing the progress of the current job.

        :param show: If "True", show the widgets, otherwise hide them.
        :return: -
        """

        if show:
            self.ui.progressBar_current.show()
            self.ui.label_current_progress.show()
        else:
            self.ui.progressBar_current.hide()
            self.ui.label_current_progress.hide()

    @QtCore.pyqtSlot(str, int)
    def set_current_progress(self, activity, percent):
        """
        Triggered by signal "work_current_progress_signal" on the workflow thread, show the progress
        of the current activity in a progress bar on the main GUI.

        :param activity: Textual description of the current activity.
        :param percent: Fraction of task finished (in %)
        :return: -
        """

        self.show_current_progress_widgets(True)
        self.ui.label_current_progress.setText(activity)
        self.ui.progressBar_current.setValue(percent)

    def show_batch_progress_widgets(self, show, value=0):
        """
        Show or hide the GUI widgets showing the progress of the batch.

        :param show: If "True", show the widgets, otherwise hide them.
        :return: -
        """

        if show:
            self.ui.progressBar_batch.show()
            self.ui.progressBar_batch.setValue(value)
            self.ui.label_batch_progress.show()
        else:
            self.ui.progressBar_batch.hide()
            self.ui.label_batch_progress.hide()

    def set_previous_actions_button(self):
        """
        Initialize the "backwards" combobox: The user can only go back to those program steps
        which have been executed already.

        :return: -
        """

        standard_activities = ['Read frames', 'Rank frames', 'Select frames', 'Align frames',
                               'Select stack size', 'Set ROI', 'Set alignment points',
                               'Compute frame qualities', 'Stack frames', 'Save stacked image',
                               'Postprocessing', 'Save postprocessed image']

        # Stacking jobs start with 'Read frames', postprocessing jobs with 'Postprocessing'
        if self.workflow.activity == 'stacking':
            # If the optional frame selection dialog is not activated, remove the activity from the list.
            if not self.configuration.frames_add_selection_dialog:
                standard_activities.remove('Select frames')
            start_index = standard_activities.index('Read frames')
            if self.configuration.global_parameters_include_postprocessing:
                stop_index = standard_activities.index('Save postprocessed image')
            else:
                stop_index = standard_activities.index('Save stacked image')
        elif self.workflow.activity == 'postproc':
            start_index = standard_activities.index('Postprocessing')
            stop_index = standard_activities.index('Save postprocessed image')
        else:
            start_index = None
            stop_index = None

        self.ui.comboBox_back.currentTextChanged.disconnect(self.go_back)
        self.ui.comboBox_back.clear()
        self.ui.comboBox_back.addItem('Go back to:')

        # From second job on, add the option to go back to the previous one.
        if self.job_index > 0 and self.job_number > 1:
            self.ui.comboBox_back.addItem('Previous job')

        # Add all activities up to the current one to the combobox.
        if self.activity in standard_activities:
            self.ui.comboBox_back.addItems(
                standard_activities[start_index:standard_activities.index(self.activity) + 1])

        # At the end of a job, execution can resume all activities of the finished job.
        elif self.activity == "Next job":
            self.ui.comboBox_back.addItems(standard_activities[start_index:stop_index + 1])

        self.ui.comboBox_back.setCurrentIndex(0)
        self.ui.comboBox_back.currentTextChanged.connect(self.go_back)

    @QtCore.pyqtSlot(bool)
    def gui_set_busy(self, busy):
        """
        Set the main GUI busy / not busy, and update its status.

        :param busy: Flag indicating if the main GUI is to be set busy.
        :return: -
        """
        self.busy = busy
        self.update_status()

    def update_status(self):
        """
        Activate / Deactivate GUI elements depending on the current processing status.

        :return: -
        """

        # Depending on the current activity, the "previous action button" presents different
        # choices. One can only go back to activities which have been performed already.
        self.set_previous_actions_button()

        # While a computation is going on: Deactivate most buttons and menu entries.
        if self.busy:
            # For tasks with interactive GUI elements, activate the "Go back to:" button. During
            # the interaction, the status line shows the "busy" status, and the workflow is
            # suspended. By pressing "Go back to:", however, the user can restart from a previous
            # task.
            if self.activity in ['Align frames', 'Select frames', 'Select stack size', 'Set ROI',
                                     'Set alignment points']:
                self.activate_gui_elements([self.ui.comboBox_back], True)
            else:
                self.activate_gui_elements([self.ui.comboBox_back], False)
            self.activate_gui_elements([self.ui.pushButton_start,
                                        self.ui.pushButton_next_job, self.ui.menuFile,
                                        self.ui.menuEdit, self.ui.menuCalibrate], False)
            self.activate_gui_elements([self.ui.pushButton_pause], True)
            if self.job_index < self.job_number:
                if self.activity == 'Select frames':
                    self.write_status_bar("Select / de-select frames to be used for stacking.",
                                          "red")
                elif self.activity == 'Select stack size':
                    self.write_status_bar("Select the number / percentage of frames to be stacked.",
                                          "red")
                elif self.activity == 'Rank frames':
                    self.write_status_bar("Select / de-select frames to be used for stacking.",
                                          "red")
                else:
                    self.write_status_bar("Busy processing " + self.jobs[self.job_index].file_name,
                                          "black")

        # In manual mode, activate buttons and menu entries. Update the status bar.
        else:
            self.activate_gui_elements([self.ui.menuFile, self.ui.menuEdit, self.ui.menuCalibrate],
                                       True)
            self.activate_gui_elements([self.ui.pushButton_pause], False)
            if self.activity == "Next job":
                self.activate_gui_elements([self.ui.actionSave, self.ui.actionSave_as], True)
            else:
                self.activate_gui_elements([self.ui.actionSave, self.ui.actionSave_as], False)
            activated_buttons = []
            if self.job_index < self.job_number:
                activated_buttons.append(self.ui.pushButton_start)
            if self.job_index > 0 or self.activity != "Read frames":
                activated_buttons.append(self.ui.comboBox_back)
            if self.job_index < self.job_number - 1:
                activated_buttons.append(self.ui.pushButton_next_job)
            if activated_buttons:
                self.activate_gui_elements(activated_buttons, True)
                message = "To continue, press '" + \
                          self.button_get_description(activated_buttons[0]) + "'"
                if len(activated_buttons) > 1:
                    for button in activated_buttons[1:]:
                        message += ", or '" + self.button_get_description(button) + "'"
                message += ", define new jobs (File/Open), or exit the program with 'Quit'."
                self.write_status_bar(message, "red")
            else:
                self.write_status_bar("Load new jobs, or quit.", "red")
                # self.ui.statusBar.setStyleSheet('color: red')

        self.show_batch_progress_widgets(self.job_number > 1)
        if self.job_number > 0:
            self.ui.progressBar_batch.setValue(int(100 * self.job_index / self.job_number))

    def button_get_description(self, element):
        """
        Get the textual description of a button. Different methods must be used for "pushButton" and
        comboBoxes.

        :param element: Button object
        :return: Text written on the button (string)
        """

        try:
            description = element.text()
            return description
        except:
            pass
        try:
            description = element.currentText()
            return description
        except:
            return ""

    def activate_gui_elements(self, elements, enable):
        """
        Enable / Disable selected GUI elements.

        :param elements: List of GUI elements.
        :param enable: If "True", enable the elements; otherwise disable them.
        :return: -
        """

        for element in elements:
            element.setEnabled(enable)

    @QtCore.pyqtSlot(str, str)
    def write_status_bar(self, message, color):
        """
        Set the text in the status bar to "message".

        :param message: Text to be displayed
        :param color: Color in which the text is to be displayed (string)
        :return: -
        """

        self.ui.statusBar.showMessage(message)
        self.ui.statusBar.setStyleSheet('color: ' + color)

    def append_status_bar(self, append_message):
        """
        Append text to the current status bar message.

        :param append_message: Text to be appended.
        :return: -
        """

        self.ui.statusBar.showMessage(self.ui.statusBar.currentMessage() + append_message)

    def about_pss(self):

        USER = getpass.getuser()
        PC = platform.node()
        OS = '{0} {1} {2}'.format(platform.system(), platform.release(), platform.architecture()[0])
        PYTHON_VERSION = platform.python_version()
        QT_VERSION = QtCore.qVersion()
        CPU = psutil.cpu_count()
        MEMORY = psutil.virtual_memory()[0] / 1024 ** 3
        MATPLOTLIB_VERSION = matplotlib.__version__
        OPENCV_VERSION = cv2.__version__
        NUMPY_VERSION = np.__version__
        PSUTIL_VERSION = psutil.__version__
        SCIPY_VERSION = scipy.__version__
        SKIMAGE_VERSION = skimage.__version__
        ASTROPY_VERSION = astropy.__version__
        PIP_VERSION = pip.__version__

        CONTENT = ('''        <b>{0}</b><br><br>
        Produce a sharp image of a planetary system object (moon, sun, planets)
        from many seeing-affected frames using the "lucky imaging" technique.
        <br><br>
        The program is mainly targeted at extended objects (moon, sun),
        but it has been applied successfully to the imaging of planets as well.
        <br><br>
        Homepage: <a href='https://github.com/Rolf-Hempel/PlanetarySystemStacker'>
        https://github.com/Rolf-Hempel/PlanetarySystemStacker</a>
        <br><br>
        System overview:<br>
        PC: {2}<br>
        CPU Cores: {4}<br>
        Memory: {5:.1f} [GB]<br>
        OS: {3}<br>
        User: {1}<br>
        <br>
        Software versions used:<br>
        Python: {6}<br>
        Qt: {7}<br>
        Matplotlib: {8}<br>
        OpenCV: {9}<br>
        Numpy: {10}<br>
        Psutil: {11}<br>
        Scipy: {12}<br>
        Scikit-image: {13}<br>
        Astropy: {14}<br>
        Pip: {15}'''.format(self.configuration.global_parameters_version, USER, PC, OS, CPU, MEMORY,
                             PYTHON_VERSION,
                             QT_VERSION,
                             MATPLOTLIB_VERSION,
                             OPENCV_VERSION,
                             NUMPY_VERSION,
                             PSUTIL_VERSION,
                             SCIPY_VERSION,
                             SKIMAGE_VERSION,
                             ASTROPY_VERSION,
                             PIP_VERSION
                             ))

        msgBox = QtWidgets.QMessageBox()
        msgBox.setIcon(QtWidgets.QMessageBox.Information)
        msgBox.setWindowIcon(QtGui.QIcon(self.configuration.window_icon))
        msgBox.setText(CONTENT)
        msgBox.setWindowTitle("About PlanetarySystemStacker")
        msgBox.setStandardButtons(QtWidgets.QMessageBox.Ok)
        msgBox.exec()

    def closeEvent(self, event=None):
        """
        This event is triggered when the user closes the main window by clicking on the cross in
        the window corner, or selects 'Quit' in the file menu.

        :param event: event object
        :return: -
        """

        # Ask the user for confirmation.
        quit_msg = "Are you sure you want to exit?"
        reply = QtWidgets.QMessageBox.question(self, self.configuration.global_parameters_version,
                                               quit_msg,
                                               QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
                                               QtWidgets.QMessageBox.No)
        # Positive reply: Do it.
        if reply == QtWidgets.QMessageBox.Yes:
            if event:
                event.accept()

            # If there is an image log file still open, close it.
            if self.workflow.attached_log_file:
                self.workflow.attached_log_file.close()

            # Store the geometry of main window, so it is placed the same at next program start.
            if self.windowState() == QtCore.Qt.WindowMaximized:
                self.configuration.hidden_parameters_main_window_maximized = True
            else:
                (x0, y0, width, height) = self.geometry().getRect()
                self.configuration.hidden_parameters_main_window_x0 = x0
                self.configuration.hidden_parameters_main_window_y0 = y0
                self.configuration.hidden_parameters_main_window_width = width
                self.configuration.hidden_parameters_main_window_height = height
                self.configuration.hidden_parameters_main_window_maximized = False

            # Write the current configuration to the ".ini" file in the user's home directory.
            self.configuration.write_config()
            exit(0)
        else:
            # No confirmation by the user: Don't stop program execution.
            if event:
                event.ignore()


def main():
    # The following steps was required to get the program running on old Linux versions:
    #
    # - Add "export QT_XKB_CONFIG_ROOT=/usr/share/X11/xkb" to file .bashrc.
    #
    # - There is still a problem with fonts: PyInstaller seems to hardcode the path to fonts
    #   which do not make sense on another computer. This leads to error messages
    #   "Fontconfig error: Cannot load default config file", and a standard font is used
    #   instead.
    #
    # To run the PyInstaller, open a Terminal in PyCharm and enter
    # "pyinstaller planetary_system_stacker.spec" on Windows, or
    # "pyinstaller planetary_system_stacker_linux.spec" on Linux
    #

    # If PSS is started without command line arguments, open the GUI.
    if len(argv) <= 1:
        app = QtWidgets.QApplication(argv)
        # app.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
        myapp = PlanetarySystemStacker()
        myapp.show()
        exit(app.exec_())

    # If command line arguments are passed, execute PSS without a GUI.
    else:
        app = QtCore.QCoreApplication(argv)
        PssConsole()
        exit(app.exec_())

if __name__ == "__main__":
    main()