-
Notifications
You must be signed in to change notification settings - Fork 6
/
secondary.py
2605 lines (2256 loc) · 98.6 KB
/
secondary.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, re
import webbrowser
import platform
from functools import partial
from ntpath import normpath
from os.path import join, basename, splitext, isfile, abspath
from copy import deepcopy
from pprint import pprint
if QT5: # ___ ______________ DEPENDENCIES __________________________
from PySide2.QtCore import (QObject, Qt, Signal, QPoint, Slot, QSize, QEvent, QRect,
QTimer, QUrl)
from PySide2.QtGui import (QFont, QMovie, QIcon, QCursor, QPalette, QColor, QPixmap,
QPainter, QPen)
from PySide2.QtWidgets import (QTableWidgetItem, QTableWidget, QMessageBox, QLineEdit,
QApplication, QWidget, QDialog, QFileDialog,
QStyleFactory, QActionGroup, QMenu, QAction,
QToolButton, QCheckBox)
else: # Qt6
from PySide6.QtCore import (QObject, Qt, Signal, QEvent, QPoint, Slot, QSize, QRect,
QTimer, QUrl)
from PySide6.QtGui import (QFont, QActionGroup, QAction, QCursor, QMovie, QIcon,
QPalette, QColor, QPixmap, QPainter, QPen)
from PySide6.QtWidgets import (QTableWidgetItem, QTableWidget, QApplication,
QLineEdit, QToolButton, QWidget, QMenu, QFileDialog,
QDialog, QMessageBox, QCheckBox, QStyleFactory)
import requests
from bs4 import BeautifulSoup
from future.moves.urllib.parse import unquote, urlencode
from packaging.version import parse as version_parse
from slppu import slppu as lua # https://github.com/noembryo/slppu
__author__ = "noEmbryo"
def decode_data(path):
""" Converts a lua table to a Python dict
:type path: str|unicode
:param path: The path to the lua file
"""
with open(path, "r", encoding="utf8", newline="\n") as txt_file:
header, data = txt_file.read().split("\n", 1)
data = lua.decode(data[7:].replace("--", "—"))
if type(data) is dict:
data["original_header"] = header
return data
def encode_data(path, data):
""" Converts a Python dict to a lua table
:type path: str|unicode
:param path: The path to the lua file
:type data: dict
:param data: The dictionary to be encoded as lua table
"""
with open(path, "w+", encoding="utf8", newline="") as txt_file:
lua_text = f'{data.pop("original_header", "")}\nreturn '
lua_text += lua.encode(data)
txt_file.write(lua_text)
def sanitize_filename(filename):
""" Creates a safe filename
:type filename: str|unicode
:param filename: The filename to be sanitized
"""
filename = re.sub(r'[/:*?"<>|\\]', "_", filename)
return filename
def get_csv_row(data):
""" Return an RFC 4180 compliant csv row
:type data: dict
:param data: The highlight's data
"""
values = []
for key in CSV_KEYS:
value = data[key].replace('"', '""')
if "\n" in value or '"' in value:
value = '"' + value.lstrip() + '"'
values.append(value if value else "")
return "\t".join(values)
def create_chapter_map(all_chapter_parts):
""" Create the chapter map
:type all_chapter_parts: list
:param all_chapter_parts: The list of all chapter parts
"""
chapter_map = {}
# Build the chapter map
for chapter_parts in all_chapter_parts:
current_level = chapter_map
highlight = chapter_parts[-1]["Highlight"]
parts = chapter_parts[:-1]
for part in parts:
if part not in current_level:
current_level[part] = {}
current_level = current_level[part]
# Initialize highlights list if not present
if "highlight" not in current_level:
current_level["highlight"] = []
current_level["highlight"].append(highlight)
# Construct the final chapter map
final_chapter_map = []
for part, chapters in chapter_map.items():
part_structure = [part]
for chapter, details in chapters.items():
chapter_structure = [chapter]
if "highlight" in details: # If highlights exist, add them to the structure
chapter_structure.extend(details["highlight"])
chapter_structure.extend(build_structure(details))
part_structure.append(chapter_structure)
final_chapter_map.append(part_structure)
return final_chapter_map
def build_structure(mapping):
""" Construct the final nested list structure
:type mapping: dict
:param mapping: The mapping to be processed
"""
result = []
for key, value in mapping.items():
if key != "highlight":
sub_structure = [key]
# If there are highlights, include them in the structure
if "highlight" in value and value["highlight"]:
sub_structure.extend(value["highlight"])
# Recursively build sub-structures for deeper levels
sub_structure.extend(build_structure(value))
result.append(sub_structure)
return result
def generate_markdown(chapter_list, level=1, max_level=6):
""" Generate a markdown string from a chapter list
"""
markdown = ""
for item in chapter_list:
if isinstance(item, list):
# Determine the appropriate heading level
current_level = level if level <= max_level else max_level
markdown += f"{'#' * current_level} {item[0]}\n\n"
# Recursively process the sub-chapters
markdown += generate_markdown(item[1:], level + 1, max_level)
else:
# Add highlight texts without any heading
markdown += f"{item}\n"
return markdown
def get_book_text(args):
""" Create the book's contents
"""
title = args["title"]
authors = args["authors"]
highlights = args["highlights"]
format_ = args["format_"]
line_break = args["line_break"]
space = args["space"]
text = args["text"]
custom_template = args.get("custom_template", {})
customize = custom_template.get("active")
templ_head = custom_template.get("templ_head")
templ_body = custom_template.get("templ_body")
split_chapters = custom_template.get("split_chapters")
head_min = custom_template.get("head_min")
head_max = custom_template.get("head_max")
nl = os.linesep
if format_ == ONE_TEXT:
name = title
if authors:
name = f"{authors} - {title}"
line = "-" * 80
text += line + nl + name + nl + line + nl
highlights = [i[HI_PAGE] + space + i[HI_DATE] + line_break
+ (f"[{i[HI_CHAPTER]}]{nl}" if i[HI_CHAPTER] else "")
+ i[HI_TEXT] + i[HI_COMMENT] for i in highlights]
text += (nl * 2).join(highlights) + nl * 2
elif format_ == ONE_HTML:
text += BOOK_BLOCK % {"title": title, "authors": authors}
for high in highlights:
date_text, high_comment, high_text, page_text, chapter = high
text += HIGH_BLOCK % {"page": page_text, "date": date_text,
"highlight": high_text, "comment": high_comment,
"chapter": chapter}
text += "</div>\n"
elif format_ == ONE_CSV:
for high in highlights:
date_text, high_comment, high_text, page_text, chapter = high
data = {"title": title, "authors": authors, "page": page_text,
"date": date_text, "text": high_text, "comment": high_comment,
"chapter": chapter}
# data = {k.encode("utf8"): v.encode("utf8") for k, v in data.items()}
text += get_csv_row(data) + "\n"
elif format_ == ONE_MD:
highs = []
if not customize:
text += f"\n---\n## {title} \n##### {authors} \n---\n"
for i in highlights:
comment = i[HI_COMMENT].replace(nl, " " + nl)
# if comment:
# comment = " " + comment
chapter = i[HI_CHAPTER]
if chapter:
chapter = f"***{chapter}***{nl}{nl}".replace(nl, " " + nl)
high = i[HI_TEXT].replace(nl, " " + nl)
hi_text = ("*" + i[HI_PAGE] + space + i[HI_DATE] + line_break + chapter +
high + comment + " \n \n")
highs.append(hi_text.replace("-", "\\-"))
else: # use custom markdown template
text += templ_head.format(title, authors)
do_split = False
if split_chapters:
for i in highlights:
if SPLITTER in i[HI_CHAPTER]:
do_split = True
break
if do_split:
all_chapter_parts = []
for idx, i in enumerate(highlights):
if SPLITTER in i[HI_CHAPTER]:
chap_parts = [j.rstrip(SPLITTER)
for j in i[HI_CHAPTER].split(SPLITTER)]
# get the highlight's formated text
comment = i[HI_COMMENT].replace(nl, " " + nl).replace("-", "\\-")
high = i[HI_TEXT].replace(nl, " " + nl).replace("-", "\\-")
date_ = i[HI_DATE].replace("-", "\\-")
hi_text = templ_body.format(date_, comment, high, i[HI_PAGE], "")
chap_parts.append({"Highlight": hi_text})
all_chapter_parts.append(chap_parts)
chapter_map = create_chapter_map(all_chapter_parts)
text += generate_markdown(chapter_map, head_min, head_max)
else:
for i in highlights:
comment = i[HI_COMMENT].replace(nl, " " + nl).replace("-", "\\-")
# comment = " " + comment if comment.strip() else ""
high = i[HI_TEXT].replace(nl, " " + nl).replace("-", "\\-")
date_ = i[HI_DATE].replace("-", "\\-")
highs.append(templ_body.format(date_, comment, high,
i[HI_PAGE], i[HI_CHAPTER]))
text += nl.join(highs) + "\n---\n"
return text
def save_file(args):
""" Saves the book's exported file
"""
ext = text = ""
encoding = "utf-8"
title = name = args["title"]
authors = args["authors"]
format_ = args["format_"]
if authors:
name = f"{authors} - {name}"
if format_ == MANY_TEXT:
ext = ".txt"
elif format_ == MANY_HTML:
ext = ".html"
text = HTML_HEAD
elif format_ == MANY_CSV:
ext = ".csv"
text = CSV_HEAD
encoding = "utf-8-sig"
elif format_ == MANY_MD:
ext = ".md"
args["text"] = text
filename = join(args["dir_path"], sanitize_filename(name))
if NO_TITLE in title: # don't overwrite unknown title files
while isfile(filename + ext):
match = re.match(r"(.+?) \[(\d+?)]$", filename)
if match:
filename = "{} [{:02}]".format(match.group(1), int(match.group(2)) + 1)
else:
filename += " [01]"
filename = filename + ext
with open(filename, "w+", encoding=encoding, newline="") as text_file:
args["format_"] += 1 # the format is changed to the MERGED file, to get the text
text = get_book_text(args)
if format_ == MANY_HTML:
text += "\n</body>\n</html>"
text_file.write(text)
__all__ = ("decode_data", "encode_data", "sanitize_filename", "get_csv_row",
"get_book_text", "save_file", "XTableWidgetIntItem", "XTableWidgetPercentItem",
"XTableWidgetTitleItem", "DropTableWidget", "XMessageBox", "About", "AutoInfo",
"ToolBar", "TextDialog", "Status", "LogStream", "Scanner", "HighlightScanner",
"ReLoader", "DBLoader", "XToolButton", "Filter", "XThemes", "XIconGlyph",
"SyncGroup", "SyncItem", "XTableWidget", "Prefs")
# ___ _______________________ SUBCLASSING ___________________________
class XTableWidgetIntItem(QTableWidgetItem):
""" Sorts numbers writen as strings (after 1 is 2 not 11)
"""
def __lt__(self, value):
parts1 = re.split(r'(\d+)', self.data(Qt.DisplayRole))
parts2 = re.split(r'(\d+)', value.data(Qt.DisplayRole))
for part1, part2 in zip(parts1, parts2):
if part1 != part2:
if part1.isdigit() and part2.isdigit():
return int(part1) < int(part2)
else:
return part1 < part2
# If we reach this point, it means that the string have a common prefix,
# so we need to check the lengths of the remaining parts
return len(parts1) < len(parts2)
class XTableWidgetPercentItem(QTableWidgetItem):
""" Sorts percentages writen as strings (e.g. 35%)
"""
def __lt__(self, value):
return int(self.data(Qt.DisplayRole)[:-1]) < int(value.data(Qt.DisplayRole)[:-1])
class XTableWidgetTitleItem(QTableWidgetItem):
""" Sorts titles ignoring the leading "A" or "The"
"""
def __lt__(self, value):
t1 = self.data(Qt.DisplayRole).lower()
t1 = (t1[2:] if t1.startswith("a ") else
t1[4:] if t1.startswith("the ") else
t1[3:] if t1.startswith("an ") else t1)
t2 = value.data(Qt.DisplayRole).lower()
t2 = (t2[2:] if t2.startswith("a ") else
t2[4:] if t2.startswith("the ") else
t2[3:] if t2.startswith("an ") else t2)
return t1 < t2
class DropTableWidget(QTableWidget):
fileDropped = Signal(list)
def __init__(self, parent=None):
super(DropTableWidget, self).__init__(parent)
# noinspection PyArgumentList
self.app = QApplication.instance()
def dragEnterEvent(self, event):
# if event.mimeData().hasUrls and not self.app.base.db_mode:
if event.mimeData().hasUrls:
if self.app.base.db_mode:
links = [i.toLocalFile() for i in event.mimeData().urls()]
if len(links) == 1 and splitext(links[0])[1].lower() == ".db":
event.accept()
return True
event.ignore()
return False
else:
event.accept()
return True
else:
event.ignore()
return False
def dragMoveEvent(self, event):
if event.mimeData().hasUrls:
event.accept()
return True
else:
event.ignore()
return False
def dropEvent(self, event):
if event.mimeData().hasUrls:
links = []
for url in event.mimeData().urls():
links.append(url.toLocalFile())
self.fileDropped.emit(links)
event.accept()
return True
else:
event.ignore()
return False
class XTableWidget(QTableWidget):
""" QTableWidget with support for drag and drop move of rows that contain widgets
"""
def __init__(self, *args, **kwargs):
super(XTableWidget, self).__init__(*args, **kwargs)
self.viewport().setAcceptDrops(True)
self.selection = self.selectionModel()
self.base = None
def dropEvent(self, event):
if not event.isAccepted() and event.source() == self:
drop_row = self.drop_on(event)
# rows = sorted(set(i.row() for i in self.selectedItems()))
rows = sorted(set(i.row() for i in self.selection.selectedRows()))
rows_to_move = []
for row in rows:
items = dict()
for col in range(self.columnCount()):
# get the widget or item of current cell
widget = self.cellWidget(row, col)
if isinstance(widget, type(None)): # a normal QTableWidgetItem
items[col] = {"kind": "QTableWidgetItem",
"item": QTableWidgetItem(self.item(row, col))}
else: # another kind of widget.
# So we catch the widget's unique characteristics
items[col] = {"kind": "QWidget", "item": widget.data}
rows_to_move.append(items)
for row in reversed(rows):
self.removeRow(row)
# if row < drop_row:
# drop_row -= 1
for row, data in enumerate(rows_to_move):
row += drop_row
self.insertRow(row)
for col, info in data.items():
if info["kind"] == "QTableWidgetItem":
# for QTableWidgetItem we can re-create the item directly
self.setItem(row, col, info["item"])
else: # for other widgets we call
# the parent's callback function to get them
widget = self.base.create_sync_widget(info["item"])
widget.idx = row
self.base.sync_table.setRowHeight(row, widget.sizeHint().height())
self.setCellWidget(row, col, widget)
self.base.update_sync_groups()
event.accept()
super(XTableWidget, self).dropEvent(event)
def drop_on(self, event):
index = self.indexAt(event.pos())
if not index.isValid():
return self.rowCount() - 1
return index.row() + 1 if self.is_below(event.pos(), index) else index.row()
def is_below(self, pos, index):
rect = self.visualRect(index)
margin = 2
if pos.y() - rect.top() < margin:
return False
elif rect.bottom() - pos.y() < margin:
return True
# noinspection PyTypeChecker
return rect.contains(pos, True) and not (int(self.model().flags(
index)) & Qt.ItemIsDropEnabled) and pos.y() >= rect.center().y()
class XMessageBox(QMessageBox):
""" A QMessageBox with a QCheckBox
"""
def __init__(self, parent=None):
super(XMessageBox, self).__init__(parent)
self.check_box = QCheckBox()
self.check_box.stateChanged.connect(self.checkbox_state_changed)
self.checked = False
self.input = QLineEdit()
self.input.textChanged.connect(self.input_text_changed)
self.typed_text = ""
def set_check(self, text):
""" Sets the Popup's CheckBox
:type text: str|unicode
:param text: The CheckBox's text
"""
self.add_to_layout(self.check_box)
self.check_box.setText(text)
def checkbox_state_changed(self, state):
""" Update the checked variable
:type state: bool
:param state: The CheckBox's state
"""
self.checked = bool(state)
def set_input(self, text):
""" Sets the Popup's text input
:type text: str|unicode|bool
:param text: The QLineEdit's text
"""
self.add_to_layout(self.input)
if not isinstance(text, bool):
self.input.setText(text)
def input_text_changed(self, text):
""" Update the typed_text variable
:type text: str|unicode
:param text: The QLineEdit's text
"""
self.typed_text = text
def add_to_layout(self, widget):
""" Add the given widget to the popup's layout
Only one widget can be added in a popup instance
:type widget: QWidget
:param widget: The widget to be added
"""
# noinspection PyArgumentList
self.layout().addWidget(widget, 1, 2)
class XToolButton(QToolButton):
right_clicked = Signal()
def __init__(self, parent=None):
super(XToolButton, self).__init__(parent)
self.installEventFilter(self)
# def mousePressEvent(self, QMouseEvent):
# if QMouseEvent.button() == Qt.RightButton:
# # do what you want here
# print("Right Button Clicked")
# QMouseEvent.accept()
def eventFilter(self, obj, event):
if obj.objectName() == "db_btn":
if event.type() == QEvent.ContextMenu:
self.right_clicked.emit()
return True
else:
return False
else:
# pass the event on to the parent class
return QToolButton.eventFilter(self, obj, event)
# ___ _______________________ WORKERS _______________________________
class LogStream(QObject):
append_to_log = Signal(str)
# def __init__(self):
# super(LogStream, self).__init__()
# # noinspection PyArgumentList
# self.base = QtGui.QApplication.instance().base
def write(self, text):
self.append_to_log.emit(text)
class Scanner(QObject):
found = Signal(str)
finished = Signal()
def __init__(self, path):
super(Scanner, self).__init__()
self.path = path
def process(self):
try:
for dir_path, dirs, files in os.walk(self.path):
if dir_path.lower().endswith(".sdr"): # a book's metadata folder
if dir_path.lower().endswith("evernote.sdr"):
continue
for file_ in files: # get the .lua file not the .old (backup)
if splitext(file_)[1].lower() == ".lua":
if file_.lower() == "custom_metadata.lua":
continue # no highlights in custom_metadata.lua
self.found.emit(join(dir_path, file_))
# older metadata storage or android history folder
elif (dir_path.lower().endswith(join("koreader", "history"))
or basename(dir_path).lower() == "history"):
for file_ in files:
if splitext(file_)[1].lower() == ".lua":
self.found.emit(join(dir_path, file_))
continue
except UnicodeDecodeError: # os.walk error
pass
self.finished.emit()
class ReLoader(QObject):
found = Signal(str)
finished = Signal()
def __init__(self, paths):
super(ReLoader, self).__init__()
self.paths = paths
def process(self):
# print("Loading data from files")
for path in self.paths:
self.found.emit(path)
self.finished.emit()
class DBLoader(QObject):
found = Signal(str, dict, str)
finished = Signal()
def __init__(self, books):
super(DBLoader, self).__init__()
self.books = books
def process(self):
for book in self.books:
self.found.emit(book["path"], book["data"], book["date"])
self.finished.emit()
class HighlightScanner(QObject):
found = Signal(dict)
finished = Signal()
def __init__(self):
super(HighlightScanner, self).__init__()
# noinspection PyArgumentList
self.base = QApplication.instance().base
def process(self):
for row in range(self.base.file_table.rowCount()):
data = self.base.file_table.item(row, TITLE).data(Qt.UserRole)
path = self.base.file_table.item(row, TYPE).data(Qt.UserRole)[0]
meta_path = self.base.file_table.item(row, PATH).data(0)
highlights = self.base.get_highlights_from_data(data, path, meta_path)
for highlight in highlights:
self.found.emit(highlight)
self.finished.emit()
class XThemes(QObject):
""" Dark and light theme palettes
"""
def __init__(self, parent=None):
super(XThemes, self).__init__(parent)
# noinspection PyArgumentList
self.app = QApplication.instance()
self.def_style = str(self.app.style())
# noinspection PyArgumentList
themes = QStyleFactory.keys()
if "Fusion" in themes:
self.app_style = "Fusion"
elif "Plastique" in themes:
self.app_style = "Plastique"
else:
self.app_style = self.def_style
self.def_colors = self.get_current()
# self.def_palette = self.app.palette()
def dark(self):
""" Apply a dark theme
"""
dark_palette = QPalette()
# base
text = 250
dark_palette.setColor(QPalette.WindowText, QColor(text, text, text))
dark_palette.setColor(QPalette.Button, QColor(53, 53, 53))
dark_palette.setColor(QPalette.Light, QColor(text, text, text))
dark_palette.setColor(QPalette.Midlight, QColor(90, 90, 90))
dark_palette.setColor(QPalette.Dark, QColor(35, 35, 35))
dark_palette.setColor(QPalette.Text, QColor(text, text, text))
dark_palette.setColor(QPalette.BrightText, QColor(text, text, text))
dark_palette.setColor(QPalette.ButtonText, QColor(text, text, text))
dark_palette.setColor(QPalette.Base, QColor(25, 25, 25))
# dark_palette.setColor(QPalette.Text, QColor(180, 180, 180))
# dark_palette.setColor(QPalette.BrightText, QColor(180, 180, 180))
# dark_palette.setColor(QPalette.ButtonText, QColor(180, 180, 180))
# dark_palette.setColor(QPalette.Base, QColor(42, 42, 42))
dark_palette.setColor(QPalette.Window, QColor(53, 53, 53))
dark_palette.setColor(QPalette.Shadow, QColor(10, 10, 10))
# dark_palette.setColor(QPalette.Highlight, QColor(42, 130, 218))
dark_palette.setColor(QPalette.Highlight, QColor(20, 50, 80))
dark_palette.setColor(QPalette.HighlightedText, QColor(text, text, text))
dark_palette.setColor(QPalette.Link, QColor(56, 252, 196))
dark_palette.setColor(QPalette.AlternateBase, QColor(66, 66, 66))
dark_palette.setColor(QPalette.ToolTipBase, QColor(53, 53, 53))
dark_palette.setColor(QPalette.ToolTipText, QColor(text, text, text))
dark_palette.setColor(QPalette.LinkVisited, QColor(80, 80, 80))
# disabled
gray = QColor(100, 100, 100)
dark_palette.setColor(QPalette.Disabled, QPalette.WindowText, gray)
dark_palette.setColor(QPalette.Disabled, QPalette.Text, gray)
dark_palette.setColor(QPalette.Disabled, QPalette.ButtonText, gray)
dark_palette.setColor(QPalette.Disabled, QPalette.HighlightedText, gray)
dark_palette.setColor(QPalette.Disabled, QPalette.Highlight,
QColor(80, 80, 80))
self.app.style().unpolish(self.app)
self.app.setPalette(dark_palette)
# self.app.setStyle("Fusion")
self.app.setStyle(self.app_style)
def light(self):
""" Apply a light theme
"""
light_palette = QPalette()
# base
light_palette.setColor(QPalette.WindowText, QColor(0, 0, 0))
light_palette.setColor(QPalette.Button, QColor(240, 240, 240))
# light_palette.setColor(QPalette.Light, QColor(180, 180, 180))
# light_palette.setColor(QPalette.Midlight, QColor(200, 200, 200))
# light_palette.setColor(QPalette.Dark, QColor(225, 225, 225))
light_palette.setColor(QPalette.Dark, QColor(180, 180, 180))
light_palette.setColor(QPalette.Midlight, QColor(200, 200, 200))
light_palette.setColor(QPalette.Light, QColor(250, 250, 250))
light_palette.setColor(QPalette.Text, QColor(0, 0, 0))
light_palette.setColor(QPalette.BrightText, QColor(0, 0, 0))
light_palette.setColor(QPalette.ButtonText, QColor(0, 0, 0))
light_palette.setColor(QPalette.Base, QColor(237, 237, 237))
light_palette.setColor(QPalette.Window, QColor(240, 240, 240))
light_palette.setColor(QPalette.Shadow, QColor(20, 20, 20))
# light_palette.setColor(QPalette.Highlight, QColor(76, 163, 224))
light_palette.setColor(QPalette.Highlight, QColor(200, 230, 255))
light_palette.setColor(QPalette.HighlightedText, QColor(0, 0, 0))
light_palette.setColor(QPalette.Link, QColor(0, 162, 232))
light_palette.setColor(QPalette.AlternateBase, QColor(225, 225, 225))
light_palette.setColor(QPalette.ToolTipBase, QColor(240, 240, 240))
light_palette.setColor(QPalette.ToolTipText, QColor(0, 0, 0))
light_palette.setColor(QPalette.LinkVisited, QColor(222, 222, 222))
# disabled
light_palette.setColor(QPalette.Disabled, QPalette.WindowText,
QColor(115, 115, 115))
light_palette.setColor(QPalette.Disabled, QPalette.Text,
QColor(115, 115, 115))
light_palette.setColor(QPalette.Disabled, QPalette.ButtonText,
QColor(115, 115, 115))
light_palette.setColor(QPalette.Disabled, QPalette.Highlight,
QColor(190, 190, 190))
light_palette.setColor(QPalette.Disabled, QPalette.HighlightedText,
QColor(115, 115, 115))
self.app.style().unpolish(self.app)
self.app.setPalette(light_palette)
# self.app.setStyle("Fusion")
self.app.setStyle(self.app_style)
def normal(self):
""" Apply the normal theme
"""
normal_palette = QPalette()
normal_palette.setColor(QPalette.WindowText, self.def_colors["WindowText"])
normal_palette.setColor(QPalette.Button, self.def_colors["Button"])
normal_palette.setColor(QPalette.Light, self.def_colors["Light"])
normal_palette.setColor(QPalette.Midlight, self.def_colors["Midlight"])
normal_palette.setColor(QPalette.Dark, self.def_colors["Dark"])
normal_palette.setColor(QPalette.Text, self.def_colors["Text"])
normal_palette.setColor(QPalette.BrightText, self.def_colors["BrightText"])
normal_palette.setColor(QPalette.ButtonText, self.def_colors["ButtonText"])
normal_palette.setColor(QPalette.Base, self.def_colors["Base"])
normal_palette.setColor(QPalette.Window, self.def_colors["Window"])
normal_palette.setColor(QPalette.Shadow, self.def_colors["Shadow"])
normal_palette.setColor(QPalette.Highlight, self.def_colors["Highlight"])
normal_palette.setColor(QPalette.HighlightedText,
self.def_colors["HighlightedText"])
normal_palette.setColor(QPalette.Link, self.def_colors["Link"])
normal_palette.setColor(QPalette.AlternateBase,
self.def_colors["AlternateBase"])
normal_palette.setColor(QPalette.ToolTipBase, self.def_colors["ToolTipBase"])
normal_palette.setColor(QPalette.ToolTipText, self.def_colors["ToolTipText"])
normal_palette.setColor(QPalette.LinkVisited, self.def_colors["LinkVisited"])
# # disabled
# normal_palette.setColor(QPalette.Disabled, QPalette.WindowText,
# QColor(115, 115, 115))
# normal_palette.setColor(QPalette.Disabled, QPalette.Text,
# QColor(115, 115, 115))
# normal_palette.setColor(QPalette.Disabled, QPalette.ButtonText,
# QColor(115, 115, 115))
# normal_palette.setColor(QPalette.Disabled, QPalette.Highlight,
# QColor(190, 190, 190))
# normal_palette.setColor(QPalette.Disabled, QPalette.HighlightedText,
# QColor(115, 115, 115))
self.app.style().unpolish(self.app.base)
self.app.setPalette(normal_palette)
# self.app.setPalette(self.def_palette)
self.app.setStyle(self.def_style)
@staticmethod
def get_current():
""" Return the current theme's data
"""
light_palette = QPalette()
data = {'WindowText': (light_palette.color(QPalette.WindowText)),
'Button': (light_palette.color(QPalette.Button)),
'Light': (light_palette.color(QPalette.Light)),
'Midlight': (light_palette.color(QPalette.Midlight)),
'Dark': (light_palette.color(QPalette.Dark)),
'Text': (light_palette.color(QPalette.Text)),
'BrightText': (light_palette.color(QPalette.BrightText)),
'ButtonText': (light_palette.color(QPalette.ButtonText)),
'Base': (light_palette.color(QPalette.Base)),
'Window': (light_palette.color(QPalette.Window)),
'Shadow': (light_palette.color(QPalette.Shadow)),
'Highlight': (light_palette.color(QPalette.Highlight)),
'HighlightedText': (light_palette.color(QPalette.HighlightedText)),
'Link': (light_palette.color(QPalette.Link)),
'AlternateBase': (light_palette.color(QPalette.AlternateBase)),
'ToolTipBase': (light_palette.color(QPalette.ToolTipBase)),
'ToolTipText': (light_palette.color(QPalette.ToolTipText)),
'LinkVisited': (light_palette.color(QPalette.LinkVisited))}
return data
class XIconGlyph(QObject):
""" A Font char to QIcon converter
* Usage in Base:
QFontDatabase.addApplicationFont(":/stuff/font.ttf") # add custom font or use existing
# pprint(QFontDatabase.families())
self.font_ico = XIconGlyph(self, glyph=None)
ico = self.font_ico.get_icon({"char": "✓",
"size": (32, 32),
"size_ratio": 1.2,
"offset": (0, -2),
"family": "XFont",
"color": "#FF0000",
"active": "orange",
"hover": (160, 50, 255),
})
self.tool_btn.setIcon(ico)
"""
def __init__(self, parent, glyph=None):
super(XIconGlyph, self).__init__(parent)
self.char = ""
self.family = ""
self.color = parent.palette().text().color().name() # use the default
self.active = None
self.hover = None
self.disabled = parent.palette().dark().color().name()
self.icon_size = 16, 16
self.size_ratio = 1
self.offset = 0, 0
self.glyph = glyph
if glyph:
self._parse_glyph(glyph)
def _parse_glyph(self, glyph):
""" Set the glyph options
:type glyph: dict
"""
if self.glyph:
self.glyph.update(glyph)
family = glyph.get("family")
if family:
self.family = family
char = glyph.get("char")
if char:
self.char = char
icon_size = glyph.get("size")
if icon_size:
self.icon_size = icon_size
offset = glyph.get("offset")
if offset:
self.offset = offset
size_ratio = glyph.get("size_ratio")
if size_ratio:
self.size_ratio = size_ratio
active = glyph.get("active")
if active:
self.active = active
hover = glyph.get("hover")
if hover:
self.hover = hover
color = glyph.get("color")
if color:
self.color = color
disabled = glyph.get("disabled")
if disabled:
self.disabled = disabled
def _get_char_pixmap(self, color):
""" Create an icon from a font character
:type color: str|tuple
:param color: The color of the icon
:return: QPixmap
"""
if isinstance(color, tuple):
color = QColor(*color)
else:
color = QColor(color)
font = QFont()
if self.family:
font.setFamily(self.family)
font.setPixelSize(self.icon_size[1] * self.size_ratio)
pixmap = QPixmap(*self.icon_size)
pixmap.fill(QColor(0, 0, 0, 0)) # fill with transparency
painter = QPainter(pixmap)
painter.setFont(font)
pen = QPen()
pen.setColor(color)
painter.setPen(pen)
painter.drawText(QRect(QPoint(*self.offset), QSize(*self.icon_size)),
Qt.AlignCenter | Qt.AlignVCenter, self.char)
painter.end()
return pixmap
def get_icon(self, glyph=None):
""" Get the icon from the glyph
:type glyph: dict
:return: QIcon
"""
if glyph:
self._parse_glyph(glyph)
icon = QIcon()
icon.addPixmap(self._get_char_pixmap(self.color), QIcon.Normal, QIcon.Off)
if self.active: # the checkable down state icon
icon.addPixmap(self._get_char_pixmap(self.active),
QIcon.Active, QIcon.On)
if self.hover: # the mouse hover state icon
icon.addPixmap(self._get_char_pixmap(self.hover),
QIcon.Active, QIcon.Off)
if self.disabled: # the disabled state icon
icon.addPixmap(self._get_char_pixmap(self.disabled),
QIcon.Disabled, QIcon.Off)
return icon
# ___ _______________________ GUI STUFF _____________________________
from gui_about import Ui_About
from gui_auto_info import Ui_AutoInfo
from gui_toolbar import Ui_ToolBar
from gui_status import Ui_Status
from gui_edit import Ui_TextDialog
from gui_filter import Ui_Filter
from gui_sync_group import Ui_SyncGroup
from gui_sync_item import Ui_SyncItem
from gui_prefs import Ui_Prefs
from gui_edit_template import Ui_EditTemplate
class ToolBar(QWidget, Ui_ToolBar):
def __init__(self, parent=None):
""" The Toolbar
:type parent: Base
"""
super(ToolBar, self).__init__(parent)
self.setupUi(self)
self.base = parent
self.buttons = (self.scan_btn, self.export_btn, self.open_btn, self.merge_btn,
self.delete_btn, self.clear_btn, self.about_btn, self.filter_btn,
self.books_view_btn, self.high_view_btn, self.sync_view_btn,
self.add_btn, self.prefs_btn)
self.size_menu = QMenu(self)
# self.size_menu.aboutToShow.connect(self.create_size_menu)
self.db_menu = QMenu()