-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
310 lines (248 loc) · 12.8 KB
/
app.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
import sys
from PyQt5 import QtGui, QtCore
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QMessageBox, QAction, \
QVBoxLayout, QHBoxLayout, QFileDialog, QListWidget, QLabel, QPlainTextEdit, QSpacerItem, QSizePolicy, QCheckBox, \
QButtonGroup, QProgressDialog, QDialog
from merger import merge_pdf_files, BookmarkMode
_APP_NAME = "JH PDF Merger"
_WEBSITE_URL = "https://github.com/qwinsi/jh-pdf-merger"
class MyPlainTextEdit(QPlainTextEdit):
signal_text_submitted = pyqtSignal(str)
def __init__(self, parent: QWidget):
super().__init__(parent)
def keyPressEvent(self, event: QtGui.QKeyEvent) -> None:
key = event.key()
if key == QtCore.Qt.Key_Return or key == QtCore.Qt.Key_Enter:
text = self.toPlainText()
self.signal_text_submitted.emit(text)
else:
super().keyPressEvent(event)
class UserCancelled(Exception):
pass
translate = QtCore.QCoreApplication.translate
class AboutDialog(QDialog):
def __init__(self, parent: QWidget):
super().__init__(parent)
self.setWindowTitle(self.tr("About") + " " + _APP_NAME)
self.setMinimumSize(360, 120)
layout = QVBoxLayout()
layout.addWidget(QLabel(f"<h1>{_APP_NAME}</h1>"))
layout.addWidget(QLabel("Version 1.0.0"))
layout.addWidget(QLabel("This is an open source PDF merger."))
layout.addWidget(QLabel(f"For more information please visit <a href='{_WEBSITE_URL}'>{_WEBSITE_URL}</a>"))
self.setLayout(layout)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self._initUI()
def _initUI(self):
self.translator = QtCore.QTranslator(self)
# get locale from system
locale = QtCore.QLocale.system().name()
print(f"System locale: {locale}")
if locale in ("zh_CN", "zh_TW"):
# *.qm files are generated by running `lrelease zh_CN.ts zh_TW.ts`
self.translator.load(f"lang/{locale}.qm")
QApplication.instance().installTranslator(self.translator)
self.setWindowTitle(translate("MainWindow", "JH PDF Merger"))
self.setGeometry(100, 100, 600, 400)
self.setWindowIcon(QtGui.QIcon('jh-pdf-merger.ico'))
# Create a QListWidget to display selected filenames
self.fileListWidget = QListWidget(self)
self.fileListWidget.setGeometry(0, 0, 600, 1000)
self.fileListWidget.clicked.connect(self.openFileDialog)
self.bookmark_enabled_checkbox = QCheckBox(translate("MainWindow", "Create bookmark"))
self.bookmark_enabled_checkbox.setChecked(True)
# a group of radio buttons to select bookmark mode
self.bookmark_mode_group = QButtonGroup()
text_both_filename_bookmark = translate("MainWindow", "from selected file's names and bookmarks in each file")
self._both_file_name_and_section_radio = QCheckBox(text_both_filename_bookmark)
self._both_file_name_and_section_radio.setChecked(True)
self.bookmark_mode_group.addButton(self._both_file_name_and_section_radio,
BookmarkMode.FILE_NAME_AND_SECTION_AS_BOOKMARK.value)
self.bookmark_mode_group.setExclusive(True)
text_only_filename = translate("MainWindow", "from only selected file's names")
self._only_file_name_radio = QCheckBox(text_only_filename)
self.bookmark_mode_group.addButton(self._only_file_name_radio, BookmarkMode.FILE_NAME_AS_BOOKMARK.value)
self.bookmark_enabled_checkbox.stateChanged.connect(
lambda state: self._toggleBookmarkMode(state == QtCore.Qt.Checked))
self.output_path_edit = MyPlainTextEdit(None)
self.output_path_edit.signal_text_submitted.connect(self.mergePdfs)
central_widget = QWidget(self)
layout = QVBoxLayout()
layout.addWidget(self.fileListWidget)
verticalSpacer = QSpacerItem(20, 20, QSizePolicy.Minimum, QSizePolicy.Expanding)
layout.addItem(verticalSpacer)
layout.addWidget(self.bookmark_enabled_checkbox)
# There should be an indent for the radio buttons. So that the user can know they are related to the checkbox
hierarchy_layout = QHBoxLayout()
hierarchy_layout.addSpacerItem(QSpacerItem(20, 20, QSizePolicy.Minimum, QSizePolicy.Minimum))
radio_group_layout = QVBoxLayout()
radio_group_layout.addWidget(self._only_file_name_radio)
radio_group_layout.addWidget(self._both_file_name_and_section_radio)
hierarchy_layout.addLayout(radio_group_layout)
layout.addLayout(hierarchy_layout)
output_area_layout = QHBoxLayout()
output_path_label = QLabel(translate("MainWindow", "Output Path:"))
output_area_layout.addWidget(output_path_label)
# height of output_path_edit just fits single line
self.output_path_edit.setFixedHeight(36)
output_area_layout.addWidget(self.output_path_edit)
layout.addLayout(output_area_layout)
central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
self.merge_action = QAction(translate("MainWindow", "Merge Files"), self)
self.merge_action.triggered.connect(self.mergePdfs)
self.merge_action.setShortcut("Ctrl+R")
self.merge_action.setEnabled(False)
self.clear_action = QAction(translate("MainWindow", "Clear Selection"), self)
self.clear_action.triggered.connect(self.clearSelection)
self._setUpMenuBar()
def _setUpMenuBar(self):
# Set up menu bar
menu = self.menuBar()
file_menu = menu.addMenu(translate("MainWindow", translate("MainWindow", "File")))
open_action = QAction(translate("MainWindow", "Add Files"), self)
open_action.triggered.connect(self.openFileDialog)
open_action.setShortcut("Ctrl+O")
file_menu.addAction(open_action)
file_menu.addAction(self.clear_action)
exit_action = QAction(translate("MainWindow", "Exit"), self)
exit_action.triggered.connect(self.close)
# bind ctrl+q on Windows/Linux or cmd+q on Mac to exit
exit_action.setShortcut("Ctrl+Q")
file_menu.addAction(exit_action)
run_menu = menu.addMenu(translate("MainWindow", "Run"))
run_menu.addAction(self.merge_action)
help_menu = menu.addMenu(translate("MainWindow", "Help"))
about_action = QAction(translate("MainWindow", "About"), self)
about_action.triggered.connect(self.openAboutDialog)
help_menu.addAction(about_action)
def _toggleBookmarkMode(self, enabled: bool):
if enabled:
self.bookmark_mode_group.setExclusive(True)
self.bookmark_mode_group.buttons()[0].setChecked(True)
for button in self.bookmark_mode_group.buttons():
button.setEnabled(True)
else:
self.bookmark_mode_group.setExclusive(False)
for button in self.bookmark_mode_group.buttons():
button.setEnabled(False) # the checkbox gets grey
button.setChecked(False)
def getBookmarkMode(self) -> BookmarkMode:
should_make_bookmark = self.bookmark_enabled_checkbox.isChecked()
if should_make_bookmark:
if self._only_file_name_radio.isChecked():
return BookmarkMode.FILE_NAME_AS_BOOKMARK
else:
# assert self._both_file_name_and_section_radio.isChecked()
return BookmarkMode.FILE_NAME_AND_SECTION_AS_BOOKMARK
else:
return BookmarkMode.NO_BOOKMARK
# popup a warning dialog
def request_confirmation(self, msg: str, title: str) -> bool:
msg_box = QMessageBox(self)
msg_box.setWindowTitle(title)
msg_box.setText(msg)
msg_box.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
msg_box.button(QMessageBox.Ok).setText(translate("MainWindow", "Yes"))
msg_box.setDefaultButton(QMessageBox.Cancel)
msg_box.button(QMessageBox.Cancel).setText(translate("MainWindow", "Cancel"))
result = msg_box.exec()
return result == QMessageBox.Ok
# popup a simple message box
def show_message(self, msg: str, title: str):
msg_box = QMessageBox(self)
msg_box.setWindowTitle(title)
msg_box.setText(msg)
msg_box.setStandardButtons(QMessageBox.Ok)
msg_box.exec()
def openAboutDialog(self):
dialog = AboutDialog(self)
dialog.exec()
def openFileDialog(self):
options = QFileDialog.Options()
options |= QFileDialog.ReadOnly # You can add more options as needed
# Display the file dialog and get selected file(s)
file_dialog = QFileDialog(self)
file_dialog.setFileMode(QFileDialog.ExistingFiles)
title_prompt = translate("MainWindow", "Add Files")
text_pdf_files = translate("MainWindow", "PDF Files")
text_all_types = translate("MainWindow", "All Types")
filter_prompt = text_pdf_files + " (*.pdf);;" + text_all_types + " (*.*)"
files, _ = file_dialog.getOpenFileNames(self, title_prompt, "", filter_prompt, options=options)
if len(files) > 0:
# Add selected filenames to the QListWidget
self.fileListWidget.addItems(files)
self.merge_action.setEnabled(True)
output_path = self.output_path_edit.toPlainText()
if not output_path.endswith(".pdf") and not output_path.endswith(".PDF"):
# set default output path to be the same as the last selected file
last_item = files[-1]
index = last_item.rfind('/')
base_path = last_item[:index]
# use the parent directory if possible
if base_path.count('/') > 0:
index = base_path.rfind('/')
base_path = base_path[:index]
default_output_name = translate("MainWindow", "merge-output.pdf")
self.output_path_edit.setPlainText(base_path + "/" + default_output_name)
def clearSelection(self):
self.fileListWidget.clear()
self.merge_action.setEnabled(False)
def mergePdfs(self):
if not self.merge_action.isEnabled():
return
output_path = self.output_path_edit.toPlainText()
# popup a warning dialog if output file name does not end with .pdf
if not output_path.endswith(".pdf") and not output_path.endswith(".PDF"):
msg = translate("MainWindow", 'Output file name is recommended to end with ".pdf" or ".PDF" '
'but what you entered is not.'
'\nContinue to use this file name as output anyway?')
ok = self.request_confirmation(msg, translate("MainWindow", "Additional Confirmation"))
if not ok:
return
# popup a warning dialog if output file already exists
if QtCore.QFile.exists(output_path):
msg = (translate("MainWindow", "A file named ") + output_path
+ translate("MainWindow", " already exists. Continue to overwrite?"))
title = translate("MainWindow", "Additional Confirmation")
ok = self.request_confirmation(msg, title)
if not ok:
return
length = self.fileListWidget.count()
file_paths = [self.fileListWidget.item(i).text() for i in range(length)]
print(f"Starting to merge {length} PDFs: {file_paths}")
msg = translate("MainWindow", "Merging PDFs...")
cancel_button_text = translate("MainWindow", "Cancel")
process_dialog = QProgressDialog(msg, cancel_button_text, 0, len(file_paths), self)
process_dialog.setMinimumSize(450, 100)
process_dialog.setWindowTitle(translate("MainWindow", "Merging PDFs"))
process_dialog.setWindowModality(QtCore.Qt.WindowModal)
def tick_callback():
# For development test use: Sleep 1 seconds to simulate a long-running task
# QtCore.QThread.msleep(100)
process_dialog.setValue(process_dialog.value() + 1)
if process_dialog.wasCanceled():
raise UserCancelled()
try:
merge_pdf_files(file_paths, output_path, self.getBookmarkMode(), tick_callback)
except UserCancelled:
msg = translate("MainWindow", "You have cancelled the merge operation.")
title = translate("MainWindow", "Cancelled")
self.show_message(msg, title)
print("User cancelled the merge operation.")
return
process_dialog.reset()
print("Finished merging PDFs!")
msg = translate("MainWindow", "Finished merging PDFs!")
title = translate("MainWindow", "Finished")
self.show_message(msg, title)
def main():
app = QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()