-
Notifications
You must be signed in to change notification settings - Fork 102
/
main.py
1808 lines (1437 loc) · 63.3 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
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
# -*- coding: utf-8 -*-
"""Web2Executable
An application that creates cross platform executables from HTML and Nodejs
web applications powered by NW.js.
This is the main module that handles all the GUI interaction and generation.
The GUI is automatically generated from the config file located in
`files/settings.cfg`.
Since the GUI is automatically generated, the settings.cfg contains many
configuration options for each element. Also, this class is set up so that
any time a user interacts with an element in the GUI, the underlying data
is modified and can be accessed via
``self.get_setting("setting_name_from_settings_cfg").value``.
Run Example:
All that is needed to run the following after running instructions in
`SETUP.md`.
$ python3.4 main.py
"""
import os
import glob
import sys
import re
import logging
import platform
import config
import utils
from utils import log, open_folder_in_explorer, is_windows
from config import get_file
from config import __version__ as __gui_version__
from util_classes import ExistingProjectDialog
from util_classes import BackgroundThread, Validator
from util_classes import CompleterLineEdit, TagsCompleter
from util_classes import TreeBrowser
from PySide6 import QtGui, QtCore, QtWidgets
from PySide6.QtWidgets import QApplication, QHBoxLayout, QVBoxLayout, QMainWindow
from PySide6 import QtNetwork
from PySide6.QtCore import Qt, QUrl, QFile, QIODevice, QCoreApplication
from PySide6.QtNetwork import QNetworkReply, QNetworkRequest, QNetworkAccessManager
from image_utils.pycns import pngs_from_icns
from command_line import CommandBase
class MainWindow(QMainWindow, CommandBase):
"""The main window of Web2Executable."""
def update_nw_versions(self, button=None):
"""Update NW version list in the background."""
self.get_versions_in_background()
def update_recent_files(self):
"""Update the recent files list in the menu bar."""
previous_files = utils.load_recent_projects()
self.recent_separator.setVisible(len(previous_files) > 0)
for i, prev_file in enumerate(previous_files):
text = "{} - {}".format(i + 1, os.path.basename(prev_file))
action = self.recent_file_actions[i]
action.setText(text)
action.setData(prev_file)
action.setVisible(True)
def __init__(self, width, height, app, parent=None):
super(MainWindow, self).__init__(parent)
CommandBase.__init__(self, quiet=True)
self.script_line = None
self.output_line = None
self.output_name_line = None
self.download_bar_widget = None
self.app_settings_widget = None
self.comp_settings_widget = None
self.win_settings_widget = None
self.ex_settings_widget = None
self.dl_settings_widget = None
self.project_info_widget = None
self.warning_settings_icon = None
self.app_settings_icon = None
self.win_settings_icon = None
self.ex_settings_icon = None
self.comp_settings_icon = None
self.download_settings_icon = None
self.tab_icons = None
self.progress_label = None
self.progress_bar = None
self.cancel_button = None
self.open_export_button = None
self.http = None
self.ex_button = None
self.extract_error = None
self.options_enabled = False
self.output_package_json = True
self.update_json = False
self.original_packagejson = {}
self.thread = None
self.readonly = False
self.recent_file_actions = []
self.project_path = ""
self.tab_index_dict = {
"app_settings": 0,
"webkit_settings": 0,
"window_settings": 1,
"export_settings": 2,
"web2exe_settings": 2,
"compression": 3,
"download_settings": 4,
}
recent_projects = utils.load_recent_projects()
self.existing_dialog = ExistingProjectDialog(
recent_projects, self.load_project, parent=self
)
# initialize application to middle of screen
drect = app.primaryScreen().availableGeometry()
center = drect.center()
self.move(center.x() - self.width() * 0.5, center.y() - self.height() * 0.5)
self.icon_style = (
"width:48px;height:48px;background-color:white;"
"border-radius:5px;border:1px solid rgb(50,50,50);"
)
self.last_project_dir = utils.load_last_project_path()
status_bar = QtWidgets.QStatusBar()
self.setStatusBar(status_bar)
self.setup_project_menu()
self.logger = config.getLogger(__name__)
self.gui_app = app
self.desktop_width = drect.width()
self.desktop_height = drect.height()
self.setWindowIcon(QtGui.QIcon(get_file(config.ICON_PATH)))
self.setup_nw_versions()
self.resize(width, height)
self.create_application_layout()
self.option_settings_enabled(False)
self.setWindowTitle("Web2Executable {}".format(__gui_version__))
self.update_nw_versions(None)
def setup_project_menu(self):
"""Set up the project menu bar with actions."""
self.project_menu = self.menuBar().addMenu("File")
self.edit_menu = self.menuBar().addMenu("Edit")
browse_action = QtGui.QAction(
"Open Project",
self.project_menu,
shortcut=QtGui.QKeySequence.Open,
statusTip="Open an existing or new project.",
triggered=self.browse_dir,
)
toggle_readonly_action = QtGui.QAction(
"Toggle Readonly",
self.edit_menu,
shortcut="Ctrl+R",
statusTip="Toggle Readonly",
triggered=self.toggle_readonly,
)
self.edit_menu.addAction(toggle_readonly_action)
self.project_menu.addAction(browse_action)
self.project_menu.addSeparator()
# Display last 10 projects
for i in range(config.MAX_RECENT):
if i == 9:
# Display 0 last
key = 0
else:
key = i + 1
action = QtGui.QAction(
self,
visible=False,
triggered=self.open_recent_file,
shortcut=QtGui.QKeySequence("Ctrl+{}".format(key)),
)
self.recent_file_actions.append(action)
self.project_menu.addAction(action)
self.recent_separator = self.project_menu.addSeparator()
self.update_recent_files()
exit_action = QtGui.QAction("Exit", self.project_menu)
exit_action.triggered.connect(self.close)
self.project_menu.addAction(exit_action)
def open_recent_file(self):
"""Loads a project based on the most recent file selected."""
action = self.sender()
if action:
self.load_project(action.data())
def create_application_layout(self):
"""Create all widgets and set the central widget."""
self.main_layout = QtWidgets.QVBoxLayout()
self.tab_widget = QtWidgets.QTabWidget()
self.main_layout.setContentsMargins(10, 5, 10, 5)
self.create_layout_widgets()
self.add_widgets_to_main_layout()
w = QtWidgets.QWidget()
w.setLayout(self.main_layout)
self.setCentralWidget(w)
def create_layout_widgets(self):
"""Create individual layouts that are displayed in tabs."""
self.download_bar_widget = self.create_download_bar()
self.app_settings_widget = self.create_application_settings()
self.comp_settings_widget = self.create_compression_settings()
self.win_settings_widget = self.create_window_settings()
self.ex_settings_widget = self.create_export_settings()
self.dl_settings_widget = self.create_download_settings()
self.project_info_widget = self.create_project_info()
def add_widgets_to_main_layout(self):
"""Add all of the widgets and icons to the main layout."""
self.warning_settings_icon = QtGui.QIcon(get_file(config.WARNING_ICON))
self.app_settings_icon = QtGui.QIcon(get_file(config.APP_SETTINGS_ICON))
self.win_settings_icon = QtGui.QIcon(get_file(config.WINDOW_SETTINGS_ICON))
self.ex_settings_icon = QtGui.QIcon(get_file(config.EXPORT_SETTINGS_ICON))
self.comp_settings_icon = QtGui.QIcon(get_file(config.COMPRESS_SETTINGS_ICON))
self.download_settings_icon = QtGui.QIcon(
get_file(config.DOWNLOAD_SETTINGS_ICON)
)
self.tab_icons = [
self.app_settings_icon,
self.win_settings_icon,
self.ex_settings_icon,
self.comp_settings_icon,
self.download_settings_icon,
]
self.main_layout.addWidget(self.project_info_widget)
self.tab_widget.addTab(
self.app_settings_widget, self.app_settings_icon, "App Settings"
)
self.tab_widget.addTab(
self.win_settings_widget, self.win_settings_icon, "Window Settings"
)
self.tab_widget.addTab(
self.ex_settings_widget, self.ex_settings_icon, "Export Settings"
)
self.tab_widget.addTab(
self.comp_settings_widget, self.comp_settings_icon, "Compression Settings"
)
self.tab_widget.addTab(
self.dl_settings_widget, self.download_settings_icon, "Download Settings"
)
self.main_layout.addWidget(self.tab_widget)
self.main_layout.addLayout(self.download_bar_widget)
def toggle_readonly(self):
self.readonly = not self.readonly
self.app_settings_widget.setEnabled(not self.readonly)
self.win_settings_widget.setEnabled(not self.readonly)
def option_settings_enabled(self, is_enabled):
"""
Set all settings widgets to either be enabled or disabled.
This is used to enable/disable the entire GUI except for loading
new projects so the user can't interact with it.
"""
self.ex_button.setEnabled(is_enabled)
self.app_settings_widget.setEnabled(is_enabled)
self.win_settings_widget.setEnabled(is_enabled)
if self.readonly:
self.app_settings_widget.setEnabled(False)
self.win_settings_widget.setEnabled(False)
self.ex_settings_widget.setEnabled(is_enabled)
self.comp_settings_widget.setEnabled(is_enabled)
self.dl_settings_widget.setEnabled(is_enabled)
self.options_enabled = is_enabled
def export(self):
"""Start an export after the user clicks 'Export'."""
self.get_files_to_download()
self.try_to_download_files()
def open_export(self):
"""Open the export folder in the file explorer."""
open_folder_in_explorer(self.output_dir())
def try_to_download_files(self):
"""
If there are files that need to be downloaded, this attempts to
retrieve them. If any errors occur, display them, cancel the
download and reenable the UI.
"""
if self.files_to_download:
self.progress_bar.setVisible(True)
self.cancel_button.setEnabled(True)
self.disable_ui_while_working()
self.download_file_with_error_handling()
else:
# This shouldn't happen since we disable the UI if there are no
# options selected
# But in the weird event that this does happen, we are prepared!
QtWidgets.QMessageBox.information(
self,
"Export Options Empty!",
("Please choose one of " "the export options!"),
)
def selected_version(self):
"""Get the currently selected version."""
return self.get_setting("nw_version").value
def enable_ui_after_error(self):
"""
This will reenable the UI and hide the progress bar in the event
of an error.
"""
self.enable_ui()
self.progress_text = ""
self.progress_bar.setVisible(False)
self.cancel_button.setEnabled(False)
def show_error(self, exception):
"""
Show an error with QMessageBox. Does not work when not
in the UI thread (ie: when downloading files)!
Args:
exception (Exception): an error that has occurred
"""
QtWidgets.QMessageBox.information(self, "Error!", exception)
def disable_ui_while_working(self):
self.option_settings_enabled(False)
self.project_info_widget.setEnabled(False)
def enable_ui(self):
self.option_settings_enabled(True)
self.project_info_widget.setEnabled(True)
def get_tab_index_for_setting_name(self, name):
"""Return the tab index based on the name of the setting."""
for setting_group_name, setting_group in self._setting_items:
if name in setting_group:
return self.tab_index_dict.get(setting_group_name, None)
def required_settings_filled(self, ignore_options=False):
"""
Determines if there are any issues in the currently filled out
settings. If there are issues, error fields are highlighted.
"""
if not self.options_enabled and not ignore_options:
return False
settings_valid = self.settings_valid()
export_chosen = False
for setting in self.settings["export_settings"].values():
if setting.value:
export_chosen = True
if not settings_valid:
return export_chosen and settings_valid
# check export settings to make sure at least one is checked
for setting in self.settings["export_settings"].values():
if not export_chosen:
widget = self.find_child_by_name(setting.name)
if widget is not None:
widget.setStyleSheet(
"QCheckBox{border:3px solid "
"rgba(238, 68, 83, 200); "
"border-radius:5px;}"
)
widget.setToolTip(
"At least one of these " "options should be selected."
)
tab = self.get_tab_index_for_setting_name(setting.name)
self.tab_widget.setTabIcon(tab, self.warning_settings_icon)
else:
widget = self.find_child_by_name(setting.name)
if widget is not None:
widget.setStyleSheet("")
widget.setToolTip("")
tab = self.get_tab_index_for_setting_name(setting.name)
self.tab_widget.setTabIcon(tab, self.tab_icons[tab])
return export_chosen and settings_valid
def settings_valid(self):
"""Determines if settings that are filled out in the GUI are valid.
Displays a red border on any setting that is invalid and a warning
icon on the corresponding tab.
"""
red_border = (
"QLineEdit{border:3px solid rgba(238, 68, 83, 200); " "border-radius:5px;}"
)
settings_valid = True
for sgroup in self.settings["setting_groups"] + [
self.settings["web2exe_settings"]
]:
for _, setting in sgroup.items():
if setting.value:
if setting.type in set(["file", "folder"]) and os.path.isabs(
setting.value
):
setting_path = setting.value
else:
setting_path = utils.path_join(
self.project_dir(), setting.value
)
if setting.required and not setting.value:
settings_valid = False
widget = self.find_child_by_name(setting.name)
if widget is not None:
widget.setStyleSheet(red_border)
widget.setToolTip("This setting is required.")
tab = self.get_tab_index_for_setting_name(setting.name)
self.tab_widget.setTabIcon(tab, self.warning_settings_icon)
if setting.type == "int" and setting.value != "":
try:
int(setting.value or "0")
except ValueError:
settings_valid = False
widget = self.find_child_by_name(setting.name)
if widget is not None:
widget.setStyleSheet(red_border)
tip = "The value {} must be an integer.".format(
setting.value
)
widget.setToolTip(tip)
tab = self.get_tab_index_for_setting_name(setting.name)
self.tab_widget.setTabIcon(tab, self.warning_settings_icon)
if setting.type == "file" and setting.value:
setting_path_invalid = not os.path.exists(setting_path)
setting_url_invalid = not utils.url_exists(setting.value)
if setting_path_invalid and setting_url_invalid:
log(setting.value, "does not exist")
settings_valid = False
widget = self.find_child_by_name(setting.name)
if widget is not None:
widget.setStyleSheet(red_border)
tip = 'The file or url "{}" does not exist.'.format(
setting.value
)
widget.setToolTip(tip)
tab = self.get_tab_index_for_setting_name(setting.name)
self.tab_widget.setTabIcon(tab, self.warning_settings_icon)
if (
setting.type == "folder"
and setting.value
and not os.path.exists(setting_path)
):
settings_valid = False
widget = self.find_child_by_name(setting.name)
if widget is not None:
widget.setStyleSheet(red_border)
widget.setToolTip(
'The folder "{}" does not exist'.format(setting_path)
)
tab = self.get_tab_index_for_setting_name(setting.name)
self.tab_widget.setTabIcon(tab, self.warning_settings_icon)
if settings_valid:
widget = self.find_child_by_name(setting.name)
if widget is not None:
widget.setStyleSheet("")
widget.setToolTip("")
tab = self.get_tab_index_for_setting_name(setting.name)
self.tab_widget.setTabIcon(tab, self.tab_icons[tab])
return settings_valid
def project_dir(self):
return self.project_path
def output_dir(self):
"""Get the project output directory."""
if hasattr(self, "output_line"):
if os.path.isabs(self.output_line.text()):
return self.output_line.text()
else:
return utils.path_join(self.project_dir(), self.output_line.text())
return ""
def create_download_bar(self):
"""
Create the bottom bar of the GUI with the progress bar and
export button.
"""
hlayout = QtWidgets.QHBoxLayout()
vlayout = QtWidgets.QVBoxLayout()
vlayout.setContentsMargins(5, 5, 5, 5)
vlayout.setSpacing(5)
hlayout.setSpacing(5)
hlayout.setContentsMargins(5, 5, 5, 5)
progress_label = QtWidgets.QLabel("")
progress_bar = QtWidgets.QProgressBar()
progress_bar.setVisible(False)
progress_bar.setContentsMargins(5, 5, 5, 5)
vlayout.addWidget(progress_label)
vlayout.addWidget(progress_bar)
vlayout.addWidget(QtWidgets.QLabel(""))
ex_button = QtWidgets.QPushButton("Export")
ex_button.setEnabled(False)
cancel_button = QtWidgets.QPushButton("Cancel Download")
cancel_button.setEnabled(False)
open_export_button = QtWidgets.QPushButton()
open_export_button.setEnabled(False)
open_export_button.setIcon(QtGui.QIcon(get_file(config.FOLDER_OPEN_ICON)))
open_export_button.setToolTip("Open Export Folder")
open_export_button.setStatusTip("Open Export Folder")
open_export_button.setMaximumWidth(30)
open_export_button.setMaximumHeight(30)
ex_button.clicked.connect(self.export)
cancel_button.clicked.connect(self.cancel_download)
open_export_button.clicked.connect(self.open_export)
button_box = QtWidgets.QDialogButtonBox()
button_box.addButton(open_export_button, QtWidgets.QDialogButtonBox.NoRole)
button_box.addButton(cancel_button, QtWidgets.QDialogButtonBox.RejectRole)
button_box.addButton(ex_button, QtWidgets.QDialogButtonBox.AcceptRole)
hlayout.addLayout(vlayout)
hlayout.addWidget(button_box)
self.progress_label = progress_label
self.progress_bar = progress_bar
self.cancel_button = cancel_button
self.open_export_button = open_export_button
self.http_request_aborted = True
self.download_error = None
self.downloading_file = QFile()
self.current_download_request = None
self.net_manager = QNetworkAccessManager()
self.net_manager.finished[QNetworkReply].connect(self.download_finished)
self.ex_button = ex_button
return hlayout
def download_finished(self, *args, **kwargs):
"""
After the request is finished, keep downloading files if they exist.
If all files are done downloading, start extracting them.
"""
self.downloading_file.close()
self.current_download_request.deleteLater()
self.http_request_aborted = True
self.enable_ui()
self.progress_bar.reset()
self.progress_bar.setVisible(False)
if not self.download_error:
self.continue_downloading_or_extract()
else:
self.download_error = None
def continue_downloading_or_extract(self):
"""Keep downloading files if they exist, otherwise extract."""
if self.files_to_download:
self.progress_bar.setValue(0)
self.progress_bar.setVisible(True)
self.cancel_button.setEnabled(True)
self.disable_ui_while_working()
self.download_file_with_error_handling()
else:
self.progress_text = "Done."
self.cancel_button.setEnabled(False)
self.progress_bar.setValue(0)
self.progress_bar.setVisible(False)
self.extract_files_in_background()
@property
def progress_text(self):
"""Lets the user see progress on the GUI as tasks are performed."""
return self.progress_label.text()
@progress_text.setter
def progress_text(self, value):
self.progress_label.setText(value)
def run_in_background(self, method_name, callback):
"""
Run any method in this class in the background, then
call the callback.
Args:
method_name (string): the name of a method on self
callback (function): the function to run in the background
"""
self.thread = BackgroundThread(self, method_name)
self.thread.finished.connect(callback)
self.thread.start()
def get_versions_in_background(self):
self.ex_button.setEnabled(False)
self.run_in_background("get_versions", self.done_getting_versions)
def done_getting_versions(self):
"""
After getting versions, enable the UI and update the
versions combobox.
"""
self.ex_button.setEnabled(self.required_settings_filled())
self.progress_text = "Done retrieving versions."
nw_version = self.get_setting("nw_version")
combo = self.find_child_by_name(nw_version.name)
combo.clear()
combo.addItems(nw_version.values)
def make_output_files_in_background(self):
self.ex_button.setEnabled(False)
self.run_in_background("make_output_dirs", self.done_making_files)
def run_custom_script(self):
"""Run the custom script setting"""
script = self.get_setting("custom_script").value
self.run_script(script)
def script_done(self):
self.ex_button.setEnabled(self.required_settings_filled())
self.enable_ui()
self.progress_text = "Done!"
def done_making_files(self):
"""
After creating files and directories, show an error if it exists,
otherwise run the user's custom script.
"""
self.ex_button.setEnabled(self.required_settings_filled())
self.tree_browser.refresh()
self.progress_text = "Done Exporting."
self.delete_files()
if self.output_err:
self.show_error(self.output_err)
self.enable_ui_after_error()
self.output_err = ""
else:
self.progress_text = "Running custom script..."
self.ex_button.setEnabled(False)
self.run_in_background("run_custom_script", self.script_done)
def extract_files_in_background(self):
self.progress_text = "Extracting."
self.ex_button.setEnabled(False)
self.run_in_background("extract_files", self.done_extracting)
def done_extracting(self):
self.ex_button.setEnabled(self.required_settings_filled())
if self.extract_error:
self.progress_text = "Error extracting."
self.show_error(
"There were one or more errors with your "
"zip/tar files. They were deleted. Please "
"try to export again."
)
self.enable_ui_after_error()
else:
self.progress_text = "Done extracting."
self.make_output_files_in_background()
def cancel_download(self):
"""Cancel downloading if the user presses the cancel button."""
self.progress_text = "Download cancelled."
self.cancel_button.setEnabled(False)
self.current_download_request.abort()
def update_progress_bar(self, bytes_read, total_bytes):
"""Show progress of download on the progress bar."""
self.progress_bar.setMaximum(total_bytes)
self.progress_bar.setValue(bytes_read)
def download_file(self, path, setting):
"""Download an NW archive file.
Args:
path (string): the URL path of the file
setting (Setting): The file setting to download
"""
if is_windows():
path = path.replace("https", "http")
version_file = self.settings["base_url"].format(self.selected_version())
sdk_build_setting = self.get_setting("sdk_build")
sdk_build = sdk_build_setting.value
location = self.get_setting("download_dir").value or config.download_path()
if sdk_build:
# Switch the download URL if an sdk build is selected
path = utils.replace_right(path, "nwjs", "nwjs-sdk", 1)
self.progress_text = "Downloading {}".format(path.replace(version_file, ""))
url = QUrl(path)
file_name = setting.save_file_path(self.selected_version(), location, sdk_build)
archive_exists = QFile.exists(file_name)
forced = self.get_setting("force_download").value
# Don't download if file already exists
if archive_exists and not forced:
self.continue_downloading_or_extract()
return
self.downloading_file.setFileName(file_name)
# If the file could not be opened, show the error and abort!
if not self.downloading_file.open(QIODevice.WriteOnly):
error = self.downloading_file.error().name
self.show_error("Unable to save the file {}: {}.".format(file_name, error))
self.enable_ui()
return
request = QNetworkRequest()
request.setUrl(url)
request.setRawHeader(b"User-Agent", b"Firefox 16.0")
reply = self.net_manager.get(request)
reply.readyRead.connect(self.ready_read_file)
reply.error[QNetworkReply.NetworkError].connect(self.network_error)
reply.sslErrors.connect(self.network_ssl_error)
reply.downloadProgress.connect(self.update_progress_bar)
self.current_download_request = reply
def network_ssl_error(self, error):
self.download_error = error
self.downloading_file.remove()
self.show_error(f"Download failed: {error}.")
self.http_request_aborted = True
self.enable_ui_after_error()
def network_error(self, error):
self.download_error = error
self.downloading_file.remove()
self.show_error(f"Download failed: {error}.")
self.http_request_aborted = True
self.enable_ui_after_error()
def ready_read_file(self):
data = self.current_download_request.readAll()
self.downloading_file.write(data)
def create_icon_box(self, name, text):
style = (
"width:48px;height:48px;background-color:white;"
"border-radius:5px;border:1px solid rgb(50,50,50);"
)
icon_label = QtWidgets.QLabel()
icon_label.setStyleSheet(style)
icon_label.setMaximumWidth(48)
icon_label.setMinimumWidth(48)
icon_label.setMaximumHeight(48)
icon_label.setMinimumHeight(48)
setattr(self, name, icon_label)
icon_text = QtWidgets.QLabel(text)
icon_text.setStyleSheet("font-size:10px;")
icon_text.setAlignment(QtCore.Qt.AlignCenter)
vbox = QVBoxLayout()
vbox.setAlignment(QtCore.Qt.AlignCenter)
vbox.addWidget(icon_label)
vbox.addWidget(icon_text)
vbox.setContentsMargins(0, 0, 0, 0)
w = QtWidgets.QWidget()
w.setLayout(vbox)
w.setMaximumWidth(70)
return w
def create_project_info(self):
"""Create the GroupBox that shows the user's project name and icons."""
group_box = QtWidgets.QGroupBox("An awesome web project called:")
title_hbox = QHBoxLayout()
title_hbox.setContentsMargins(10, 10, 10, 10)
win_icon = self.create_icon_box("window_icon", "Window Icon")
exe_icon = self.create_icon_box("exe_icon", "Exe Icon")
mac_icon = self.create_icon_box("mac_icon", "Mac Icon")
self.title_label = QtWidgets.QLabel("TBD")
self.title_label.setStyleSheet("font-size:20px; font-weight:bold;")
title_hbox.addWidget(self.title_label)
title_hbox.addWidget(QtWidgets.QLabel())
title_hbox.addWidget(win_icon)
title_hbox.addWidget(exe_icon)
title_hbox.addWidget(mac_icon)
vlayout = QtWidgets.QVBoxLayout()
vlayout.setSpacing(5)
vlayout.setContentsMargins(10, 5, 10, 5)
vlayout.addLayout(title_hbox)
group_box.setLayout(vlayout)
return group_box
def set_window_icon(self):
icon_setting = self.get_setting("icon")
mac_icon_setting = self.get_setting("mac_icon")
exe_icon_setting = self.get_setting("exe_icon")
self.set_icon(icon_setting.value, self.window_icon)
if not mac_icon_setting.value:
self.set_icon(icon_setting.value, self.mac_icon)
if not exe_icon_setting.value:
self.set_icon(icon_setting.value, self.exe_icon)
def set_exe_icon(self):
icon_setting = self.get_setting("exe_icon")
self.set_icon(icon_setting.value, self.exe_icon)
def set_mac_icon(self):
icon_setting = self.get_setting("mac_icon")
self.set_icon(icon_setting.value, self.mac_icon)
def set_icon(self, icon_path, icon):
"""
Set the icon to the icon widget specified.
Args:
icon_path (string): the path to the new icon
icon (QWidget): the widget to set the icon for
"""
if icon_path:
icon_path = utils.path_join(self.project_dir(), icon_path)
if os.path.exists(icon_path):
if icon_path.endswith(".icns"):
pngs = pngs_from_icns(icon_path)
if pngs:
bdata = QtCore.QByteArray(pngs[-1].data)
image = QtGui.QImage.fromData(bdata, "PNG")
else:
return
else:
image = QtGui.QImage(icon_path)
trans = QtCore.Qt.SmoothTransformation
if image.width() >= image.height():
image = image.scaledToWidth(48, trans)
else:
image = image.scaledToHeight(48, trans)
icon.setPixmap(QtGui.QPixmap.fromImage(image))
icon.setStyleSheet("")
return
icon.setPixmap(None)
icon.setStyleSheet(self.icon_style)
def call_with_object(self, name, obj, *args, **kwargs):
"""
Allows arguments to be passed to click events so the calling object
is not lost.
"""
def call(*cargs, **ckwargs):
if hasattr(self, name):
func = getattr(self, name)
kwargs.update(ckwargs)
func(obj, *(args + cargs), **kwargs)
return call
def find_child_by_name(self, name):
"""Finds a GUI element by setting name"""
return self.findChild(QtCore.QObject, name)
def find_all_children(self, names):
"""
Find all children referenced by the names list.
Args:
names (list): a list of strings that are setting names
"""
children = []
for child in self.find_children(QtCore.QObject):
if child.object_name() in names:
children.append(child)
return children
def project_name(self):
"""Get the current GUI project name field."""
return self.find_child_by_name("app_name").text()
def browse_dir(self):
"""
Open a directory browsing window for the user to choose a
directory.
"""
dir_func = QtWidgets.QFileDialog.getExistingDirectory
directory = dir_func(
self, "Find Project Directory", self.project_dir() or self.last_project_dir
)
if directory:
self.load_project(directory)
def load_project(self, directory, readonly=False):
"""Load a new project from a directory."""
self.update_json = False
self.readonly = readonly
self.project_path = directory
utils.save_recent_project(directory)
utils.save_project_path(directory)
self.update_recent_files()
self.reset_settings()
proj_name = os.path.basename(directory)
self.title_label.setText(proj_name)
self.init_main_field(directory)
self.init_input_fields(proj_name)
# Load the global json and then overwrite the settings with user
# chosen values
self.load_package_json()
self.load_package_json(utils.get_data_file_path(config.GLOBAL_JSON_FILE))
self.load_package_json(
utils.path_join(self.project_dir(), config.WEB2EXE_JSON_FILE)
)
default_dir = "output"
export_dir_setting = self.get_setting("export_dir")
default_dir = export_dir_setting.value or default_dir
self.output_line.setText(default_dir)
script_setting = self.get_setting("custom_script")
self.script_line.setText(script_setting.value)
# Setup output name setting