-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.py
4087 lines (3644 loc) · 174 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
from boot_config import *
from boot_config import _
import os, sys, re
import gzip
import json
import shutil
import webbrowser
import subprocess
import argparse
import hashlib
from datetime import datetime
from functools import partial
from copy import deepcopy
from collections import defaultdict
from ntpath import normpath
from os.path import (isdir, isfile, join, basename, splitext, dirname, split, getmtime,
abspath, splitdrive)
from pprint import pprint
if QT5:
from PySide2.QtWidgets import (QMainWindow, QHeaderView, QApplication, QMessageBox,
QAction, QMenu, QTableWidgetItem, QListWidgetItem,
QFileDialog, QComboBox)
from PySide2.QtCore import (Qt, QTimer, QThread, QModelIndex, Slot, QPoint, QMimeData,
QByteArray)
from PySide2.QtSql import QSqlDatabase, QSqlQuery
from PySide2.QtGui import QIcon, QPixmap, QTextCursor, QBrush, QColor, QFontDatabase
else: # Qt6
from PySide6.QtWidgets import (QMainWindow, QHeaderView, QApplication, QMessageBox,
QFileDialog, QTableWidgetItem, QMenu, QListWidgetItem,
QComboBox)
from PySide6.QtCore import Qt, QTimer, Slot, QPoint, QThread, QModelIndex, QMimeData
from PySide6.QtGui import (QIcon, QAction, QBrush, QColor, QPixmap, QTextCursor,
QFontDatabase)
from PySide6.QtSql import QSqlDatabase, QSqlQuery
from secondary import *
from gui_main import Ui_Base
from packaging.version import parse as version_parse
import pickle
__author__ = "noEmbryo"
__version__ = "2.3.0.0"
class Base(QMainWindow, Ui_Base):
def __init__(self, parent=None):
super(Base, self).__init__(parent)
# noinspection PyArgumentList
self.app = QApplication.instance()
self.scan_thread = None
self.setupUi(self)
self.version = __version__
self.setWindowTitle(APP_NAME + " portable" if PORTABLE else APP_NAME)
# ___ ________ PREFS SETTINGS ___________
self.theme = THEME_NONE_OLD
self.alt_title_sort = False
self.show_items = [True, True, True, True, True]
self.show_ref_pg = True
self.custom_template = False
self.templ_head = MD_HEAD
self.templ_body = MD_HIGH
self.split_chapters = False
self.head_min = 2
self.head_max = 6
self.high_by_page = True
self.date_format = DATE_FORMAT
# ___ ________ SAVED SETTINGS ___________
self.col_sort = MODIFIED
self.col_sort_asc = False
self.col_sort_h = DATE_H
self.col_sort_asc_h = False
self.highlight_width = None
self.comment_width = None
self.skip_version = "0.0.0.0"
self.opened_times = 0
self.last_dir = os.getcwd()
self.edit_lua_file_warning = True
self.current_view = BOOKS_VIEW
self.db_mode = False
self.toolbar_size = 48
self.high_merge_warning = True
self.archive_warning = True
self.exit_msg = True
self.db_path = join(SETTINGS_DIR, "data.db")
self.date_vacuumed = datetime.now().strftime(DATE_FORMAT)
# ___ ___________________________________
self.file_selection = None
self.sel_idx = None
self.sel_indexes = []
self.high_list_selection = None
self.sel_high_list = []
self.high_view_selection = None
self.sel_high_view = []
self.sync_view_selection = None
self.sel_sync_view = []
self.loaded_paths = set()
self.books2reload = set()
self.parent_book_data = {}
self.custom_book_data = {}
self.reload_highlights = True
self.reload_from_sync = False
self.threads = []
self.query = None
self.db = None
self.books = []
self.sync_groups = []
tooltip = _("Right click to ignore english articles")
self.file_table.horizontalHeaderItem(TITLE).setToolTip(tooltip)
self.file_table.horizontalHeaderItem(TITLE).setStatusTip(tooltip)
self.header_main = self.file_table.horizontalHeader()
self.header_main.setDefaultAlignment(Qt.AlignLeft)
self.header_main.setContextMenuPolicy(Qt.CustomContextMenu)
self.resize_columns = False
self.header_high_view = self.high_table.horizontalHeader()
self.header_high_view.setDefaultAlignment(Qt.AlignLeft)
self.file_table.verticalHeader().setSectionResizeMode(QHeaderView.Fixed)
self.header_main.setSectionsMovable(True)
self.high_table.verticalHeader().setSectionResizeMode(QHeaderView.Fixed)
self.header_high_view.setSectionsMovable(True)
self.splitter.setCollapsible(0, False)
self.splitter.setCollapsible(1, False)
self.info_fields = [self.title_txt, self.author_txt, self.series_txt,
self.lang_txt, self.pages_txt, self.tags_txt]
self.info_keys = ["title", "authors", "series", "language", "pages", "keywords"]
self.kor_text = _("Scanning for KOReader metadata files.")
self.ico_file_save = QIcon(":/stuff/file_save.png")
self.ico_files_merge = QIcon(":/stuff/files_merge.png")
self.ico_files_delete = QIcon(":/stuff/files_delete.png")
self.ico_db_add = QIcon(":/stuff/db_add.png")
self.ico_db_open = QIcon(":/stuff/db_open.png")
self.ico_db_compact = QIcon(":/stuff/db_compact.png")
self.ico_refresh = QIcon(":/stuff/refresh16.png")
self.ico_folder_open = QIcon(":/stuff/folder_open.png")
self.ico_sort = QIcon(":/stuff/sort.png")
self.ico_view_books = QIcon(":/stuff/view_books.png")
self.ico_files_view = QIcon(":/stuff/files_view.png")
self.ico_file_edit = QIcon(":/stuff/file_edit.png")
self.ico_copy = QIcon(":/stuff/copy.png")
self.ico_delete = QIcon(":/stuff/delete.png")
self.def_icons = [self.ico_file_save,
self.ico_files_merge,
self.ico_files_delete,
self.ico_db_add,
self.ico_db_open,
self.ico_refresh,
self.ico_folder_open,
self.ico_sort,
self.ico_view_books,
self.ico_files_view,
self.ico_file_edit,
self.ico_copy,
self.ico_delete,
self.ico_db_compact,
]
self.ico_file_exists = QIcon(":/stuff/file_exists.png")
self.ico_file_missing = QIcon(":/stuff/file_missing.png")
self.ico_label_green = QIcon(":/stuff/label_green.png")
self.ico_app = QIcon(":/stuff/logo64.png")
self.ico_empty = QIcon(":/stuff/trans32.png")
# noinspection PyArgumentList
self.clip = QApplication.clipboard()
self.about = About(self)
self.auto_info = AutoInfo(self)
self.filter = Filter(self)
self.prefs = Prefs(self)
self.toolbar = ToolBar(self)
self.tool_bar.addWidget(self.toolbar)
self.toolbar.open_btn.setEnabled(False)
self.toolbar.merge_btn.setEnabled(False)
self.toolbar.delete_btn.setEnabled(False)
self.export_menu = QMenu(self)
self.export_menu.setTitle(_("Export"))
self.export_menu.setIcon(self.ico_file_save)
self.export_menu.aboutToShow.connect(self.create_export_menu) # assign menu
if QT6: # QT6 requires exec() instead of exec_()
self.export_menu.exec_ = getattr(self.export_menu, "exec")
self.toolbar.export_btn.setMenu(self.export_menu)
self.status = Status(self)
self.statusbar.addPermanentWidget(self.status)
self.edit_high = TextDialog(self)
self.edit_high.setWindowTitle(_("Comment"))
self.description = TextDialog(self)
self.description.setWindowTitle(_("Description"))
self.description.high_edit_txt.setReadOnly(True)
self.description.btn_box.hide()
self.description_btn.setEnabled(False)
self.review_lbl.setVisible(False)
self.review_txt.setVisible(False)
tbar = self.toolbar
self.def_btn_icos = []
self.buttons = [(tbar.scan_btn, "A"),
(tbar.export_btn, "B"),
(tbar.open_btn, "C"),
(tbar.filter_btn, "D"),
(tbar.merge_btn, "E"),
(tbar.add_btn, "X"),
(tbar.delete_btn, "O"),
(tbar.clear_btn, "G"),
(tbar.prefs_btn, "F"),
(tbar.books_view_btn, "H"),
(tbar.high_view_btn, "I"),
(tbar.sync_view_btn, "W"),
(tbar.loaded_btn, "H"),
(tbar.db_btn, "K"),
(self.custom_btn, "Q"),
(self.filter.filter_btn, "D"),
(self.description_btn, "V"),
(self.filter.clear_filter_btn, "G"),
(self.prefs.custom_date_btn, "T"),
(self.prefs.custom_template_btn, "Q"),
]
QTimer.singleShot(10000, self.auto_check4update) # check for updates
main_timer = QTimer(self) # cleanup threads forever
main_timer.timeout.connect(self.thread_cleanup)
main_timer.start(2000)
QTimer.singleShot(0, self.on_load)
def on_load(self):
""" Things that must be done after the initialization
"""
QFontDatabase.addApplicationFont(":/stuff/font.ttf")
# QFontDatabase.removeApplicationFont(0)
self.setup_buttons()
self.settings_load()
self.init_db()
if FIRST_RUN: # on first run
self.toolbar.loaded_btn.click()
self.splitter.setSizes((500, 250))
self.toolbar.merge_btn.setMenu(self.merge_menu()) # assign/create menu
self.toolbar.delete_btn.setMenu(self.delete_menu()) # assign/create menu
self.connect_gui()
self.passed_files()
if len(sys.argv) > 1: # command line arguments exist, open in Loaded mode
self.toolbar.loaded_btn.click()
else: # no extra command line arguments
if not self.db_mode:
self.toolbar.loaded_btn.setChecked(True) # open in Loaded mode
else:
self.toolbar.db_btn.setChecked(True) # open in Archived mode
QTimer.singleShot(0, self.load_db_rows)
self.read_books_from_db() # always load db on start
if self.current_view == BOOKS_VIEW:
self.toolbar.books_view_btn.click() # open in Books view
elif self.current_view == SYNC_VIEW:
self.toolbar.sync_view_btn.click() # open in Sync view
else:
self.toolbar.high_view_btn.click() # open in Highlights view
if app_config:
QTimer.singleShot(0, self.restore_windows)
else:
self.resize(800, 600)
QTimer.singleShot(0, self.show)
QTimer.singleShot(250, self.load_sync_groups)
def load_db_rows(self):
""" Load the rows from the database
"""
self.loading_thread(DBLoader, self.books,
_("Loading {} database.").format(APP_NAME))
def setup_buttons(self):
for btn, char in self.buttons:
self.def_btn_icos.append(btn.icon())
size = btn.iconSize().toTuple()
btn.xig = XIconGlyph(self, {"family": "XFont", "size": size, "char": char})
# btn.glyph = btn.xig.get_icon()
def set_new_icons(self, menus=True):
""" Create the new icons
:type menus: bool
:param menus: Create the new menu icons too
"""
QTimer.singleShot(0, partial(self.delayed_set_new_icons, menus))
def delayed_set_new_icons(self, menus=True):
""" Delay the creation of the icons to allow for the new palette to be set
:type menus: bool
:param menus: Create the menu icons too
"""
for btn, _ in self.buttons:
size = btn.iconSize().toTuple()
btn.setIcon(btn.xig.get_icon({"size": size}))
if menus: # recreate the menu icons
xig = XIconGlyph(self, {"family": "XFont", "size": (16, 16)})
self.ico_file_save = xig.get_icon({"char": "B"})
self.ico_files_merge = xig.get_icon({"char": "E"})
self.ico_files_delete = xig.get_icon({"char": "O"})
self.ico_db_add = xig.get_icon({"char": "L"})
self.ico_db_open = xig.get_icon({"char": "M"})
self.ico_refresh = xig.get_icon({"char": "N"})
self.ico_folder_open = xig.get_icon({"char": "P"})
self.ico_sort = xig.get_icon({"char": "S"})
self.ico_view_books = xig.get_icon({"char": "H"})
self.act_view_book.setIcon(xig.get_icon({"char": "C"}))
self.ico_file_edit = xig.get_icon({"char": "Q"})
self.ico_copy = xig.get_icon({"char": "R"})
self.ico_delete = xig.get_icon({"char": "O"})
self.ico_db_compact = xig.get_icon({"char": "J"})
self.export_menu.setIcon(self.ico_file_save)
def set_old_icons(self):
""" Reload the old icons
"""
for idx, item in enumerate(self.buttons):
btn = item[0]
btn.setIcon(self.def_btn_icos[idx])
self.ico_file_save = self.def_icons[0]
self.ico_files_merge = self.def_icons[1]
self.ico_files_delete = self.def_icons[2]
self.ico_db_add = self.def_icons[3]
self.ico_db_open = self.def_icons[4]
self.ico_refresh = self.def_icons[5]
self.ico_folder_open = self.def_icons[6]
self.ico_sort = self.def_icons[7]
self.ico_view_books = self.def_icons[8]
self.act_view_book.setIcon(self.def_icons[9])
self.ico_file_edit = self.def_icons[10]
self.ico_copy = self.def_icons[11]
self.ico_delete = self.def_icons[12]
self.ico_db_compact = self.def_icons[13]
self.export_menu.setIcon(self.ico_file_save)
def reset_theme_colors(self):
""" Resets the widget colors after a theme change
"""
color = self.app.palette().base().color().name()
self.review_txt.setStyleSheet(f'background-color: "{color}";')
color = self.app.palette().button().color().name()
for row in range(self.sync_table.rowCount()):
wdg = self.sync_table.cellWidget(row, 0)
wdg.setStyleSheet('QFrame#items_frm {background-color: "%s";}' % color)
wdg.setup_icons()
self.setup_buttons()
self.reload_table(_("Reloading books..."))
# ___ ___________________ EVENTS STUFF __________________________
def connect_gui(self):
""" Make all the extra signal/slots connections
"""
self.file_selection = self.file_table.selectionModel()
self.file_selection.selectionChanged.connect(self.file_selection_update)
self.header_main.sectionClicked.connect(self.on_column_clicked)
self.header_main.customContextMenuRequested.connect(self.on_column_right_clicked)
self.high_list_selection = self.high_list.selectionModel()
self.high_list_selection.selectionChanged.connect(self.high_list_selection_update)
self.high_view_selection = self.high_table.selectionModel()
self.high_view_selection.selectionChanged.connect(self.high_view_selection_update)
self.header_high_view.sectionClicked.connect(self.on_highlight_column_clicked)
self.header_high_view.sectionResized.connect(self.on_highlight_column_resized)
self.sync_table.base = self
self.sync_view_selection = self.sync_table.selectionModel()
self.sync_view_selection.selectionChanged.connect(self.sync_view_selection_update)
sys.stdout = LogStream()
sys.stdout.setObjectName("out")
sys.stdout.append_to_log.connect(self.write_to_log)
sys.stderr = LogStream()
sys.stderr.setObjectName("err")
sys.stderr.append_to_log.connect(self.write_to_log)
def keyPressEvent(self, event):
""" Handles the key press events
:type event: QKeyEvent
:param event: The key press event
"""
key, mod = event.key(), event.modifiers()
# print(key, mod, QKeySequence(key).toString())
# if mod == Qt.ControlModifier | Qt.AltModifier: # if control + alt is pressed
if mod == Qt.ControlModifier: # if control is pressed
if key == Qt.Key_Backspace:
self.toolbar.on_clear_btn_clicked()
elif key == Qt.Key_L:
self.toolbar.on_scan_btn_clicked()
elif key == Qt.Key_S:
self.on_export()
elif key == Qt.Key_P:
self.toolbar.on_prefs_btn_clicked()
elif key == Qt.Key_I:
self.toolbar.on_about_btn_clicked()
elif key == Qt.Key_F:
self.toolbar.filter_btn.click()
elif key == Qt.Key_Q:
self.close()
elif self.current_view == HIGHLIGHTS_VIEW and self.sel_high_view:
if key == Qt.Key_C:
self.copy_text_2clip(self.get_highlights()[0])
if mod == Qt.AltModifier: # if alt is pressed
if key == Qt.Key_A:
self.on_archive()
return True
elif self.current_view == HIGHLIGHTS_VIEW and self.sel_high_view:
if key == Qt.Key_C:
self.copy_text_2clip(self.get_highlights()[1])
return True
if key == Qt.Key_Escape:
self.close()
elif key == Qt.Key_Delete:
if self.current_view == BOOKS_VIEW:
self.remove_book_items()
else:
self.toolbar.on_delete_btn_clicked()
def closeEvent(self, event):
""" Accepts or rejects the `exit` command
:type event: QCloseEvent
:param event: The `exit` event
"""
if not self.exit_msg:
self.bye_bye_stuff()
event.accept()
return
popup = self.popup(_("Confirmation"), _("Exit {}?").format(APP_NAME), buttons=2,
check_text=DO_NOT_SHOW)
self.exit_msg = not popup.checked
if popup.buttonRole(popup.clickedButton()) == QMessageBox.AcceptRole:
self.bye_bye_stuff()
event.accept() # let the window close
else:
event.ignore()
def bye_bye_stuff(self):
""" Things to do before exit
"""
self.settings_save()
self.delete_logs()
# ___ ____________________ DATABASE STUFF __________________________
def init_db(self):
""" Initialize the database tables
"""
self.db = QSqlDatabase.addDatabase("QSQLITE")
self.db.setDatabaseName(self.db_path)
if not self.db.open():
print("Could not open database!")
return
self.query = QSqlQuery()
if QT6: # QT6 requires exec() instead of exec_()
self.query.exec_ = getattr(self.query, "exec")
if app_config:
pass
# self.query.exec_("""PRAGMA user_version""") # 2check: enable if db changes
# while self.query.next():
# self.check_db_version(self.query.value(0)) # check the db version
self.set_db_version() if not isfile(self.db_path) else None
self.create_books_table()
def check_db_version(self, db_version):
""" Updates the db to the last version
:type db_version: int
:param db_version: The db file version
"""
if db_version == DB_VERSION or not isfile(self.db_path):
return # the db is up-to-date or does not exist yet
self.update_db(db_version)
def update_db(self, db_version):
""" Updates the db to the last version"""
pass
def set_db_version(self):
""" Set the current database version
"""
self.query.exec_(f"""PRAGMA user_version = {DB_VERSION}""")
def change_db(self, mode):
""" Changes the current db file
:type mode: int
:param mode: Change, create new or reload the current db
"""
if mode == NEW_DB:
# noinspection PyCallByClass
filename = QFileDialog.getSaveFileName(self, _("Type the name of the new db"),
self.db_path,
(_("database files (*.db)")))[0]
elif mode == CHANGE_DB:
# noinspection PyCallByClass
filename = QFileDialog.getOpenFileName(self, _("Select a database file"),
self.db_path,
(_("database files (*.db)")))[0]
elif mode == RELOAD_DB:
filename = self.db_path
else:
return
if filename:
# self.toolbar.loaded_btn.click()
if self.toolbar.db_btn.isChecked():
self.toolbar.update_loaded()
self.delete_data()
self.db_path = filename
self.db_mode = False
self.init_db()
self.read_books_from_db()
if self.toolbar.db_btn.isChecked():
QTimer.singleShot(0, self.toolbar.update_archived)
def delete_data(self):
""" Deletes the database data
"""
self.db.close() # close the db
self.db = None
self.query = None
# print(self.db.connectionNames())
# self.db.removeDatabase(self.db.connectionName())
def create_books_table(self):
""" Create the books table
"""
self.query.exec_("""CREATE TABLE IF NOT EXISTS books (id INTEGER PRIMARY KEY,
md5 TEXT UNIQUE NOT NULL, date TEXT, path TEXT, data TEXT)""")
def add_books2db(self, books):
""" Add some books to the books db table
:type books: list
:param books: The books to add in the db
"""
self.db.transaction()
self.query.prepare("""INSERT OR REPLACE into books (md5, date, path, data)
VALUES (:md5, :date, :path, :data)""")
for book in books:
self.query.bindValue(":md5", book["md5"])
self.query.bindValue(":date", book["date"])
self.query.bindValue(":path", book["path"])
self.query.bindValue(":data", book["data"])
self.query.exec_()
self.db.commit()
def read_books_from_db(self):
""" Reads the contents of the books' db table
"""
# print("Reading data from db")
del self.books[:]
self.query.setForwardOnly(True)
self.query.exec_("""SELECT * FROM books""")
while self.query.next():
book = [self.query.value(i) for i in range(1, 5)] # don't read the id
data = json.loads(book[DB_DATA], object_hook=self.keys2int)
self.books.append({"md5": book[DB_MD5], "date": book[DB_DATE],
"path": book[DB_PATH], "data": data})
@staticmethod
def keys2int(data):
""" ReConverts the numeric keys of the Highlights in the data dictionary
that are converted to strings because of json serialization
:type data: dict
:param data: The books to add in the db
"""
if isinstance(data, dict):
return {int(k) if k.isdigit() else k: v for k, v in data.items()}
return data
def update_book2db(self, data):
""" Updates the data of a book in the db
:type data: dict
:param data: The changed data
"""
self.query.prepare("""UPDATE books SET data = :data WHERE md5 = :md5""")
self.query.bindValue(":md5", data["partial_md5_checksum"])
self.query.bindValue(":data", json.dumps(data))
self.query.exec_()
def delete_books_from_db(self, ids):
""" Deletes multiple books from the db
:type ids: list
:param ids: The MD5s of the books to be deleted
"""
if ids:
self.db.transaction()
self.query.prepare("""DELETE FROM books WHERE md5 = :md5""")
for md5 in ids:
self.query.bindValue(":md5", md5)
self.query.exec_()
self.db.commit()
def get_db_book_count(self):
""" Get the count of the books in the db
"""
self.query.exec_("""SELECT Count(*) FROM books""")
self.query.next()
return self.query.value(0)
def vacuum_db(self, info=True):
self.query.exec_("""VACUUM""")
if info:
self.popup(_("Information"), _("The database has been compacted!"),
QMessageBox.Information)
# ___ ___________________ FILE TABLE STUFF ______________________
@Slot(list)
def on_file_table_fileDropped(self, dropped):
""" When some items are dropped to the TableWidget
:type dropped: list
:param dropped: The items dropped
"""
if len(dropped) == 1:
if splitext(dropped[0])[1] == ".db":
self.db_path = normpath(dropped[0])
self.change_db(RELOAD_DB)
if (self.about.isVisible() and # update db path on System tab text
self.about.about_tabs.currentWidget()
.objectName() == "system_tab"):
self.about.system_txt.setPlainText(self.about.get_system_info())
self.popup(_("Information"), _("Database loaded!"),
QMessageBox.Information)
return
# self.file_table.setSortingEnabled(False)
for i in dropped:
if splitext(i)[1] == ".lua" and basename(i).lower() != "custom_metadata.lua":
self.create_row(normpath(i)) # no highlights in custom_metadata.lua
# self.file_table.setSortingEnabled(True)
folders = [j for j in dropped if isdir(j)]
for folder in folders:
self.loading_thread(Scanner, folder, self.kor_text, clear=False)
# @Slot(QTableWidgetItem) # called indirectly from self.file_selection_update
def on_file_table_itemClicked(self, item, reset=True):
""" When an item of the FileTable is clicked
:type item: QTableWidgetItem
:param item: The item (cell) that is clicked
:type reset: bool
:param reset: Select the first highlight in the list
"""
if not item: # empty list
return
row = item.row()
data = self.file_table.item(row, TITLE).data(Qt.UserRole)
path = self.file_table.item(row, TYPE).data(Qt.UserRole)[0]
self.custom_book_data = {}
self.custom_btn.setChecked(False)
if not self.db_mode:
sdr_path = dirname(self.file_table.item(row, PATH).data(0))
custom_path = join(sdr_path, "custom_metadata.lua")
if isfile(custom_path):
custom = decode_data(custom_path)
self.custom_book_data = deepcopy(data)
self.custom_book_data.get("doc_props", {}).update(custom["custom_props"])
self.high_list.clear()
self.populate_high_list(data, path)
self.populate_book_info(data, row)
self.high_list.setCurrentRow(0) if reset else None
# noinspection PyTestUnpassedFixture
def populate_book_info(self, data, row):
""" Fill in the `Book Info` fields
:type data: dict
:param data: The item's data
:type row: int
:param row: The item's row number
"""
self.description_btn.setEnabled(bool(data.get("doc_props",
{}).get("description")))
self.custom_btn.setEnabled(bool(self.custom_book_data))
stats = "doc_props" if "doc_props" in data else "stats" if "stats" in data else ""
for key, field in zip(self.info_keys, self.info_fields):
try:
if key == "title" and not data[stats][key]:
path = self.file_table.item(row, PATH).data(0)
try:
name = path.split("#] ")[1]
value = splitext(name)[0]
except IndexError: # no "#] " in filename
value = ""
elif key == "pages":
if "doc_pages" in data:
value = data["doc_pages"]
else: # older type file
value = data[stats][key]
# no total pages if reference pages are used
annotations = data.get("annotations") # new type metadata
if self.show_ref_pg and annotations is not None and len(annotations):
annot = annotations[1] # first annotation
ref_page = annot.get("pageref")
if ref_page and ref_page.isdigit(): # there is a ref page number
value = _("|Ref|")
elif key == "keywords":
keywords = data["doc_props"][key].split("\n")
value = "; ".join([i.rstrip("\\") for i in keywords])
else:
value = data.get(stats, {}).get(key)
try:
field.setText(value)
except TypeError: # Needs string only
field.setText(str(value) if value else "") # "" if 0
except KeyError: # older type file or other problems
path = self.file_table.item(row, PATH).data(0)
stats_ = self.get_item_stats(data, path)
if key == "title":
field.setText(stats_["title"])
elif key == "authors":
field.setText(stats_["authors"])
else:
field.setText("")
review = data.get("summary", {}).get("note", "")
self.review_lbl.setVisible(bool(review))
color = self.app.palette().base().color().name()
self.review_txt.setStyleSheet(f'background-color: "{color}";')
self.review_txt.setVisible(bool(review))
self.review_txt.setText(review)
@Slot(QPoint)
def on_file_table_customContextMenuRequested(self, point):
""" When an item of the FileTable is right-clicked
:type point: QPoint
:param point: The point where the right-click happened
"""
if not len(self.file_selection.selectedRows()): # no items selected
return
menu = QMenu(self.file_table)
if QT6: # QT6 requires exec() instead of exec_()
menu.exec_ = getattr(menu, "exec")
row = self.file_table.itemAt(point).row()
self.act_view_book.setEnabled(self.toolbar.open_btn.isEnabled())
self.act_view_book.setData(row)
menu.addAction(self.act_view_book)
menu.addMenu(self.export_menu)
if not self.db_mode:
action = QAction(_("Archive") + "\tAlt+A", menu)
action.setIcon(self.ico_db_add)
action.triggered.connect(self.on_archive)
menu.addAction(action)
if len(self.sel_indexes) == 1:
sync_group = QMenu(self)
sync_group.setTitle(_("Sync"))
sync_group.setIcon(self.ico_files_merge)
action = QAction(_("Create a sync group"), sync_group)
action.setIcon(self.ico_files_merge)
path = self.file_table.item(row, PATH).data(0)
title = self.file_table.item(row, TITLE).data(0)
data = self.file_table.item(row, TITLE).data(Qt.UserRole)
book_data = {"path": path, "data": data}
info = {"title": title,
"sync_pos": False,
"merge": False,
"sync_db": True,
"items": [book_data],
"enabled": True}
action.triggered.connect(partial(self.create_sync_row, info))
sync_group.addAction(action)
if self.check4archive_merge(book_data) is not False:
sync_menu = self.create_archive_merge_menu()
sync_menu.setTitle(_("Sync with archived"))
sync_menu.setIcon(self.ico_files_merge)
sync_group.addMenu(sync_menu)
action = QAction(_("Sync with file"), sync_group)
action.setIcon(self.ico_files_merge)
action.triggered.connect(self.use_meta_files)
sync_group.addAction(action)
book_path, book_exists = self.file_table.item(row, TYPE).data(Qt.UserRole)
if book_exists:
action = QAction(_("ReCalculate MD5"), sync_group)
action.setIcon(self.ico_refresh)
action.triggered.connect(partial(self.recalculate_md5, book_path))
sync_group.addAction(action)
menu.addMenu(sync_group)
action = QAction(_("Open location"), menu)
action.setIcon(self.ico_folder_open)
folder_path = dirname(self.file_table.item(row, PATH).text())
action.triggered.connect(partial(self.open_file, folder_path))
menu.addAction(action)
elif len(self.sel_indexes) == 2:
if self.toolbar.merge_btn.isEnabled():
action = QAction(_("Sync books"), menu)
action.setIcon(self.ico_files_merge)
action.triggered.connect(self.toolbar.on_merge_btn_clicked)
menu.addAction(action)
menu.addSeparator()
delete_menu = self.delete_menu()
delete_menu.setIcon(self.ico_files_delete)
delete_menu.setTitle(_("Delete") + "\tDel")
menu.addMenu(delete_menu)
else:
menu.addSeparator()
action = QAction(_("Delete") + "\tDel", menu)
action.setIcon(self.ico_files_delete)
action.triggered.connect(partial(self.delete_actions, DEL_META))
menu.addAction(action)
menu.exec_(self.file_table.mapToGlobal(point))
@Slot(QTableWidgetItem)
def on_file_table_itemDoubleClicked(self, item):
""" When an item of the FileTable is double-clicked
:type item: QTableWidgetItem
:param item: The item (cell) that is double-clicked
"""
row = item.row()
meta_path = self.file_table.item(row, PATH).data(0)
data = self.file_table.item(row, TITLE).data(Qt.UserRole)
book_path = self.get_book_path(meta_path, data)[0]
self.open_file(book_path)
@staticmethod
def get_book_path(meta_path, data):
""" Returns the filename of the book that the metadata refers to
:type meta_path: str|unicode
:param meta_path: The path of the metadata file
:type data: dict
:param data: The book's metadata
"""
meta_path = splitext(meta_path)[0] # use the metadata file path
ext = splitext(meta_path)[1]
book_path = splitext(split(meta_path)[0])[0] + ext
book_exists = isfile(book_path)
if not book_exists: # use the recorded file path (newer metadata only)
doc_path = data.get("doc_path")
if doc_path:
drive = splitdrive(meta_path)[0]
# noinspection PyTestUnpassedFixture
doc_path = join(drive, os.sep, *(doc_path.split("/")[3:]))
if isfile(doc_path):
book_path = doc_path
return book_path, book_exists
@Slot()
def on_act_view_book_triggered(self):
""" The View Book menu entry is pressed
"""
row = self.sender().data()
if self.current_view == BOOKS_VIEW:
item = self.file_table.itemAt(row, 0)
self.on_file_table_itemDoubleClicked(item)
elif self.current_view == HIGHLIGHTS_VIEW:
data = self.high_table.item(row, HIGHLIGHT_H).data(Qt.UserRole)
self.open_file(data["path"])
# noinspection PyUnusedLocal
def file_selection_update(self, selected, deselected):
""" When a row in FileTable gets selected
:type selected: QModelIndex
:parameter selected: The selected row
:type deselected: QModelIndex
:parameter deselected: The deselected row
"""
try:
if not self.filter.isVisible():
self.sel_indexes = self.file_selection.selectedRows()
else:
self.sel_indexes = [i for i in self.file_selection.selectedRows()
if not self.file_table.isRowHidden(i.row())]
self.sel_idx = self.sel_indexes[-1]
except IndexError: # empty table
self.sel_indexes = []
self.sel_idx = None
if self.sel_indexes:
item = self.file_table.item(self.sel_idx.row(), self.sel_idx.column())
self.on_file_table_itemClicked(item)
else:
self.high_list.clear()
self.description_btn.setEnabled(False)
self.review_txt.hide()
self.review_lbl.hide()
for field in self.info_fields:
field.setText("")
self.toolbar.activate_buttons()
def on_column_clicked(self, column):
""" Sets the current sorting column
:type column: int
:parameter column: The column where the sorting is applied
"""
if column == self.col_sort:
self.col_sort_asc = not self.col_sort_asc
else:
self.col_sort_asc = True
self.col_sort = column
def on_column_right_clicked(self, pos):
""" Creates a sorting menu for the "Title" column
:type pos: QPoint
:parameter pos: The position of the right click
"""
column = self.header_main.logicalIndexAt(pos)
name = self.file_table.horizontalHeaderItem(column).text()
if name == _("Title"):
menu = QMenu(self)
if QT6: # QT6 requires exec() instead of exec_()
menu.exec_ = getattr(menu, "exec")
action = QAction(_("Ignore english articles"), menu)
action.setCheckable(True)
action.setChecked(self.alt_title_sort)
action.triggered.connect(self.toggle_title_sort)
menu.addAction(action)
menu.exec_(self.file_table.mapToGlobal(pos))
def toggle_title_sort(self):
""" Toggles the way titles are sorted (use or not A/The)
"""
self.alt_title_sort = not self.alt_title_sort
self.blocked_change(self.prefs.alt_title_sort_chk, self.alt_title_sort)
self.reload_table(_("ReSorting books..."))
def reload_table(self, text):
""" Reloads the table depending on the current View mode
"""
if not self.db_mode:
self.loading_thread(ReLoader, self.loaded_paths.copy(), text)
else:
self.loading_thread(DBLoader, self.books, text)
@Slot(bool)
def on_fold_btn_toggled(self, pressed):
""" Open/closes the Book info panel
:type pressed: bool
:param pressed: The arrow button's status
"""
if pressed: # Closed
self.fold_btn.setText(_("Show Book Info"))
self.fold_btn.setArrowType(Qt.RightArrow)
else: # Opened
self.fold_btn.setText(_("Hide Book Info"))
self.fold_btn.setArrowType(Qt.DownArrow)
self.book_info.setHidden(pressed)
@Slot(bool)
def on_custom_btn_toggled(self, pressed):