-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathbook_status.py
6988 lines (5925 loc) · 295 KB
/
book_status.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
#!/usr/bin/env python
# coding: utf-8
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2013, Greg Riker <griker@hotmail.com>'
__docformat__ = 'restructuredtext en'
import base64, cStringIO, hashlib, importlib, inspect, json
import locale, operator, os, cPickle as pickle, re, sqlite3, sys, time
from collections import OrderedDict
from datetime import datetime, timedelta
from dateutil import tz
from functools import partial
from lxml import etree
from threading import Timer
from xml.sax.saxutils import escape
try:
from PyQt5 import QtCore
from PyQt5.Qt import (Qt, QAbstractTableModel,
QApplication, QBrush,
QColor, QCursor, QDialogButtonBox, QEvent,
QFont, QFontMetrics, QGridLayout,
QHeaderView, QHBoxLayout, QIcon,
QItemSelectionModel, QLabel, QLineEdit, QMenu, QModelIndex,
QPainter, QPixmap, QProgressDialog, QPushButton,
QSize, QSizePolicy, QSpacerItem,
QTableView, QTableWidget, QTableWidgetItem, QTimer, QToolButton,
QVBoxLayout, QWidget,
pyqtSignal)
except ImportError:
from PyQt4 import QtCore
from PyQt4.Qt import (Qt, QAbstractTableModel,
QApplication, QBrush,
QColor, QCursor, QDialogButtonBox, QEvent,
QFont, QFontMetrics, QGridLayout,
QHeaderView, QHBoxLayout, QIcon,
QItemSelectionModel, QLabel, QLineEdit, QMenu, QModelIndex,
QPainter, QPixmap, QProgressDialog, QPushButton,
QSize, QSizePolicy, QSpacerItem,
QTableView, QTableWidget, QTableWidgetItem, QTimer, QToolButton,
QVBoxLayout, QWidget,
pyqtSignal)
from calibre import strftime
from calibre.constants import islinux, isosx, iswindows
from calibre.devices.errors import UserFeedback
from calibre.devices.usbms.driver import debug_print
from calibre.ebooks.BeautifulSoup import BeautifulSoup, BeautifulStoneSoup, Tag, UnicodeDammit
from calibre.ebooks.oeb.iterator import EbookIterator
from calibre.gui2 import Application, Dispatcher, error_dialog, warning_dialog
from calibre.gui2.dialogs.message_box import MessageBox
from calibre.gui2.dialogs.progress import ProgressDialog
from calibre.gui2.progress_indicator import ProgressIndicator
from calibre.utils.config import config_dir, JSONConfig
from calibre.utils.date import strptime
from calibre.utils.icu import sort_key
from calibre.utils.magick.draw import thumbnail
from calibre.utils.wordcount import get_wordcount_obj
from calibre.utils.zipfile import ZipFile
from calibre_plugins.marvin_manager.annotations import (
ANNOTATIONS_HTML_TEMPLATE, BookNotes, BookmarkNotes,
merge_annotations)
from calibre_plugins.marvin_manager.common_utils import (
AbortRequestException, AnnotationStruct, Book, BookStruct, CommandHandler, InventoryCollections,
Logger, MyBlockingBusy, ProgressBar, RowFlasher, SizePersistedDialog,
get_cc_mapping, get_icon, updateCalibreGUIView, is_qt4,
FULL_STAR)
dialog_resources_path = os.path.join(config_dir, 'plugins', 'Marvin_XD_resources', 'dialogs')
class MyTableView(QTableView):
def __init__(self, parent):
super(MyTableView, self).__init__(parent)
self.parent = parent
# Hook header context menu events separately
self.horizontalHeader().setContextMenuPolicy(Qt.CustomContextMenu)
self.horizontalHeader().customContextMenuRequested.connect(self.header_event)
def contextMenuEvent(self, event):
index = self.indexAt(event.pos())
col = index.column()
row = index.row()
selected_books = self.parent._selected_books()
menu = QMenu(self)
if self.parent.busy:
# Don't show context menu if busy
pass
elif col == self.parent.ANNOTATIONS_COL:
calibre_cids = False
for row in selected_books:
if selected_books[row]['cid'] is not None:
calibre_cids = True
break
afn = get_cc_mapping('annotations', 'combobox', None)
no_annotations = not selected_books[row]['has_annotations']
ac = menu.addAction("View annotations")
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'annotations.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "show_highlights", row))
if len(selected_books) > 1 or no_annotations:
ac.setEnabled(False)
# Fetch Annotations if custom field specified
enabled = False
if afn:
# Do any of the selected books have annotations?
if len(selected_books) > 1 and calibre_cids:
for sr in selected_books:
if selected_books[sr]['has_annotations']:
enabled = True
break
elif len(selected_books) == 1 and selected_books[row]['has_annotations'] and calibre_cids:
enabled = True
ac = menu.addAction("Add annotations to '{0}' column".format(afn))
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'annotations.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "fetch_annotations", row))
else:
ac = menu.addAction("No custom column specified for 'Annotations'")
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'annotations.png')))
ac.setEnabled(enabled)
elif col == self.parent.ARTICLES_COL:
try:
no_articles = not selected_books[row]['has_articles']
ac = menu.addAction("View articles")
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'articles.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "show_deep_view_articles", row))
if len(selected_books) > 1 or no_articles:
ac.setEnabled(False)
except:
pass
elif col == self.parent.COLLECTIONS_COL:
cfl = get_cc_mapping('collections', 'field', None)
ac = menu.addAction("Add collection assignments")
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'star.png')))
ac.triggered.connect(self.parent.show_add_collections_dialog)
ac = menu.addAction("View collection assignments")
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'update_metadata.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "show_collections", row))
if len(selected_books) > 1:
ac.setEnabled(False)
ac = menu.addAction("Export calibre collections to Marvin")
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'from_calibre.png')))
if cfl:
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "export_collections", row))
else:
ac.setEnabled(False)
ac = menu.addAction("Import Marvin collections to calibre")
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'from_marvin.png')))
if cfl:
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "import_collections", row))
else:
ac.setEnabled(False)
ac = menu.addAction("Merge collections")
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'sync_collections.png')))
if cfl:
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "synchronize_collections", row))
else:
ac.setEnabled(False)
ac = menu.addAction("Remove from all collections")
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'clear_all.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "clear_all_collections", row))
menu.addSeparator()
ac = menu.addAction("Manage collections")
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'edit_collections.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "manage_collections", row))
elif col == self.parent.DEEP_VIEW_COL:
try:
no_dv_content = False
for row in selected_books:
if not selected_books[row]['has_dv_content']:
no_dv_content = True
break
ac = menu.addAction("Generate Deep View content")
ac.setIcon(QIcon(I('exec.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "generate_deep_view", row))
ac.setEnabled(no_dv_content)
menu.addSeparator()
ac = menu.addAction("Deep View articles")
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'deep_view.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event,
"show_deep_view_articles", row))
no_articles = not selected_books[row]['has_articles']
if len(selected_books) > 1 or no_articles:
ac.setEnabled(False)
ac = menu.addAction("Deep View items, sorted alphabetically")
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'deep_view.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event,
"show_deep_view_alphabetically", row))
if len(selected_books) > 1 or no_dv_content:
ac.setEnabled(False)
ac = menu.addAction("Deep View items, sorted by importance")
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'deep_view.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event,
"show_deep_view_by_importance", row))
if len(selected_books) > 1 or no_dv_content:
ac.setEnabled(False)
ac = menu.addAction("Deep View items, sorted by order of appearance")
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'deep_view.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event,
"show_deep_view_by_appearance", row))
if len(selected_books) > 1 or no_dv_content:
ac.setEnabled(False)
ac = menu.addAction("Deep View items, notes and flags first")
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'deep_view.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event,
"show_deep_view_by_annotations", row))
if len(selected_books) > 1 or no_dv_content:
ac.setEnabled(False)
except:
pass
elif col == self.parent.FLAGS_COL:
ac = menu.addAction("Clear all")
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'clear_all.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "clear_all_flags", row))
ac = menu.addAction("Clear New")
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'clear_new.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "clear_new_flag", row))
ac = menu.addAction("Clear Reading list")
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'clear_reading.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "clear_reading_list_flag", row))
ac = menu.addAction("Clear Read")
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'clear_read.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "clear_read_flag", row))
menu.addSeparator()
ac = menu.addAction("Set New")
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'set_new.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "set_new_flag", row))
ac = menu.addAction("Set Reading list")
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'set_reading.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "set_reading_list_flag", row))
ac = menu.addAction("Set Read")
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'set_read.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "set_read_flag", row))
# Add Synchronize option
calibre_cids = False
for row in selected_books:
if selected_books[row]['cid'] is not None:
calibre_cids = True
break
read_field = get_cc_mapping('read', 'combobox', None)
reading_list_field = get_cc_mapping('reading_list', 'combobox', None)
if read_field or reading_list_field:
menu.addSeparator()
label = 'Synchronize Reading list, Read'
if reading_list_field and not read_field:
label = 'Synchronize Reading list'
elif read_field and not reading_list_field:
label = 'Synchronize Read'
ac = menu.addAction(label)
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'sync_collections.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "synchronize_flags", row))
ac.setEnabled(bool(calibre_cids))
elif col == self.parent.LAST_OPENED_COL:
date_read_field = get_cc_mapping('date_read', 'combobox', None)
# Test for calibre cids
calibre_cids = False
for row in selected_books:
if selected_books[row]['cid'] is not None:
calibre_cids = True
break
# Test for active last_opened dates
last_opened = False
for row in selected_books:
if selected_books[row]['last_opened'] > '':
last_opened = True
break
title = "No custom column specified for 'Last read'"
if date_read_field:
title = "Apply to '%s' column" % date_read_field
ac = menu.addAction(title)
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'from_marvin.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "apply_date_read", row))
if (not date_read_field) or (not calibre_cids) or (not last_opened):
ac.setEnabled(False)
elif col == self.parent.LOCKED_COL:
any_ids_locked = False
for row in selected_books:
if selected_books[row]['locked']:
any_ids_locked = True
break
any_ids_unlocked = False
for row in selected_books:
if not selected_books[row]['locked']:
any_ids_unlocked = True
break
ac = menu.addAction("Lock")
ac.setEnabled(any_ids_unlocked)
if any_ids_unlocked:
icon = QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'lock_enabled.png'))
else:
icon = QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'lock_disabled.png'))
ac.setIcon(icon)
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "set_locked", row))
ac = menu.addAction("Unlock")
ac.setEnabled(any_ids_locked)
if any_ids_locked:
icon = QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'unlock_enabled.png'))
else:
icon = QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'unlock_disabled.png'))
ac.setIcon(icon)
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "set_unlocked", row))
elif col == self.parent.PROGRESS_COL:
progress_field = get_cc_mapping('progress', 'combobox', None)
# Test for calibre cids
calibre_cids = False
for row in selected_books:
if selected_books[row]['cid'] is not None:
calibre_cids = True
break
# Test for active Progress
progress = True
# for row in selected_books:
# if selected_books[row]['progress'] > 0:
# progress = True
# break
title = "No custom column specified for 'Progress'"
if progress_field:
title = "Apply to '{0}' column".format(progress_field)
ac = menu.addAction(title)
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'from_marvin.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "apply_progress", row))
if (not progress_field) or (not calibre_cids) or (not progress):
ac.setEnabled(False)
elif col == self.parent.RATING_COL:
ac = menu.addAction('Remove rating')
#ac.setIcon(QIcon(I('exec.png')))
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path,
'icons',
'clear_all.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "set_rating", 0))
for x in range(1,6):
ans = ''
for y in range(x):
ans += FULL_STAR
ac = menu.addAction(ans)
#ac.setIcon(QIcon(I('exec.png')))
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path,
'icons',
'sync_collections.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "set_rating", x))
elif col in [self.parent.TITLE_COL, self.parent.AUTHOR_COL]:
ac = menu.addAction("View metadata")
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'update_metadata.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "show_metadata", row))
if len(selected_books) > 1:
ac.setEnabled(False)
# If match_quality < YELLOW, metadata updates disabled
enable_metadata_updates = True
if len(selected_books) == 1 and self.parent.tm.get_match_quality(row) < BookStatusDialog.MATCH_COLORS.index('YELLOW'):
enable_metadata_updates = False
ac = menu.addAction("Export metadata from calibre to Marvin")
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'from_calibre.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "export_metadata", row))
ac.setEnabled(enable_metadata_updates)
ac = menu.addAction("Import metadata from Marvin to calibre")
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'from_marvin.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "import_metadata", row))
ac.setEnabled(enable_metadata_updates)
# #mark ~~~ Add books to calibre library ~~~
menu.addSeparator()
# Test for calibre cids
in_library = True
for row in selected_books:
if selected_books[row]['cid'] is None:
in_library = False
break
ac = menu.addAction("Add to calibre library")
ac.setIcon(QIcon(I('plus.png')))
ac.triggered.connect(self.parent._add_books_to_library)
ac.setEnabled(not in_library)
menu.addSeparator()
ac = menu.addAction("Delete from Marvin library")
ac.setIcon(QIcon(I('trash.png')))
ac.triggered.connect(self.parent._delete_books)
elif col == self.parent.VOCABULARY_COL:
try:
no_vocabulary = not selected_books[row]['has_vocabulary']
ac = menu.addAction("View vocabulary for this book")
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'vocabulary.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "show_vocabulary", row))
if len(selected_books) > 1 or no_vocabulary:
ac.setEnabled(False)
ac = menu.addAction("View all vocabulary words")
ac.setIcon(QIcon(I('books_in_series.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "show_global_vocabulary", row))
except:
pass
elif col == self.parent.WORD_COUNT_COL:
word_count_field = get_cc_mapping('word_count', 'combobox', None)
# Test for calibre cids
calibre_cids = False
for row in selected_books:
if selected_books[row]['cid'] is not None:
calibre_cids = True
break
# Test for active word counts
word_counts = False
for row in selected_books:
#print(repr(selected_books[row]['word_count']))
if selected_books[row]['word_count']:
word_counts = True
break
ac = menu.addAction("Calculate word count")
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'word_count.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "calculate_word_count", row))
title = "No custom column specified for 'Word count'"
if word_count_field:
title = "Apply to '{0}' column".format(word_count_field)
ac = menu.addAction(title)
ac.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'from_marvin.png')))
ac.triggered.connect(partial(self.parent.dispatch_context_menu_event, "apply_word_count", row))
if (not word_count_field) or (not calibre_cids) or (not word_counts):
ac.setEnabled(False)
menu.exec_(event.globalPos())
def header_event(self, pos):
'''
Context menu event handler for header
Allow user to toggle column visibility
'''
menu = QMenu(self)
for col, title in self.parent.USER_CONTROLLED_COLUMNS:
visible = not self.isColumnHidden(col) and self.columnWidth(col) > 0
ac = menu.addAction(title)
ac.setCheckable(True)
ac.setChecked(visible)
ac.triggered.connect(partial(self.toggle_column_visibility, col))
action = menu.exec_(self.mapToGlobal(pos))
def keyPressEvent(self, event):
'''
If user uses up/down keys, update Refresh button in MXD window
'''
super(MyTableView, self).keyPressEvent(event)
if event.key() in [Qt.Key_Up, Qt.Key_Down]:
self.parent._update_refresh_button()
def toggle_column_visibility(self, col):
'''
Toggle visible state of col, resize to contents
'''
invisible = self.isColumnHidden(col) or self.columnWidth(col) == 0
if invisible:
self.showColumn(col)
# Set width of shown column
if col in [self.parent.AUTHOR_COL, self.parent.SUBJECTS_COL]:
self.setColumnWidth(col, self.columnWidth(self.parent.TITLE_COL))
elif col in [self.parent.WORD_COUNT_COL, self.parent.COLLECTIONS_COL]:
width = self.columnWidth(self.parent.LAST_OPENED_COL)
if not width:
width = 87
self.setColumnWidth(col, width)
elif col in [self.parent.ANNOTATIONS_COL, self.parent.VOCABULARY_COL,
self.parent.DEEP_VIEW_COL, self.parent.ARTICLES_COL]:
width = self.columnWidth(self.parent.FLAGS_COL)
if not width:
width = 53
self.setColumnWidth(col, width)
else:
self.resizeColumnToContents(col)
else:
self.hideColumn(col)
# Update Refresh button label based upon column visibility
self.parent._update_refresh_button()
class SortableImageWidgetItem(QWidget):
def __init__(self, path, sort_key):
super(SortableImageWidgetItem, self).__init__()
self.picture = QPixmap(path)
self.sort_key = sort_key
def __lt__(self, other):
return self.sort_key < other.sort_key
class SortableTableWidgetItem(QTableWidgetItem):
"""
Subclass widget sortable by sort_key
"""
def __init__(self, text, sort_key):
super(SortableTableWidgetItem, self).__init__(text)
self.sort_key = sort_key
def __lt__(self, other):
return self.sort_key < other.sort_key
class MarkupTableModel(QAbstractTableModel):
#http://www.saltycrane.com/blog/2007/12/pyqt-43-qtableview-qabstracttablemodel/
SATURATION = 0.40
HSVALUE = 1.0
RED_HUE = 0.0 # 0/360
ORANGE_HUE = 0.08325 # 30/360
YELLOW_HUE = 0.1665 # 60/360
GREEN_HUE = 0.333 # 120/360
CYAN_HUE = 0.500 # 180/360
MAGENTA_HUE = 0.875 # 315/360
WHITE_HUE = 1.0
dataChanged = pyqtSignal(object, object)
layoutChanged = pyqtSignal(object)
def __init__(self, parent=None, centered_columns=[], right_aligned_columns=[], *args):
"""
datain: a list of lists
headerdata: a list of strings
"""
QAbstractTableModel.__init__(self, parent, *args)
self.parent = parent
self.arraydata = parent.tabledata
self.centered_columns = centered_columns
self.right_aligned_columns = right_aligned_columns
self.headerdata = parent.LIBRARY_HEADER
self.show_match_colors = parent.show_match_colors
def all_rows(self):
return self.arraydata
def columnCount(self, parent):
return len(self.headerdata)
def data(self, index, role):
row, col = index.row(), index.column()
if not index.isValid():
return None
elif role == Qt.ForegroundRole and self.show_match_colors:
match_quality = self.get_match_quality(row)
if match_quality == BookStatusDialog.MATCH_COLORS.index('DARK_GRAY'):
return QBrush(Qt.white)
elif role == Qt.BackgroundRole and self.show_match_colors:
match_quality = self.get_match_quality(row)
if match_quality == BookStatusDialog.MATCH_COLORS.index('LIGHT_GRAY'):
return QBrush(QColor(0xD8, 0xD8,0xD8))
elif match_quality == BookStatusDialog.MATCH_COLORS.index('DARK_GRAY'):
return QBrush(QColor(0x98, 0x98,0x98))
elif match_quality == BookStatusDialog.MATCH_COLORS.index('GREEN'):
return QBrush(QColor.fromHsvF(self.GREEN_HUE, self.SATURATION, self.HSVALUE))
elif match_quality == BookStatusDialog.MATCH_COLORS.index('MAGENTA'):
return QBrush(QColor.fromHsvF(self.MAGENTA_HUE, self.SATURATION, self.HSVALUE))
elif match_quality == BookStatusDialog.MATCH_COLORS.index('ORANGE'):
return QBrush(QColor.fromHsvF(self.ORANGE_HUE, self.SATURATION, self.HSVALUE))
elif match_quality == BookStatusDialog.MATCH_COLORS.index('RED'):
return QBrush(QColor.fromHsvF(self.RED_HUE, self.SATURATION, self.HSVALUE))
elif match_quality == BookStatusDialog.MATCH_COLORS.index('YELLOW'):
return QBrush(QColor.fromHsvF(self.YELLOW_HUE, self.SATURATION, self.HSVALUE))
else:
return QBrush(QColor.fromHsvF(self.WHITE_HUE, 0.0, self.HSVALUE))
elif role == Qt.DecorationRole and col == self.parent.LOCKED_COL:
return self.arraydata[row][self.parent.LOCKED_COL].picture
elif role == Qt.DecorationRole and col == self.parent.FLAGS_COL:
return self.arraydata[row][self.parent.FLAGS_COL].picture
elif role == Qt.DecorationRole and col == self.parent.COLLECTIONS_COL:
return self.arraydata[row][self.parent.COLLECTIONS_COL].picture
elif (role == Qt.DisplayRole and
col == self.parent.PROGRESS_COL
and self.parent.prefs.get('show_progress_as_percentage', False)):
return self.arraydata[row][self.parent.PROGRESS_COL].text()
elif (role == Qt.DecorationRole and
col == self.parent.PROGRESS_COL
and not self.parent.prefs.get('show_progress_as_percentage', False)):
return self.arraydata[row][self.parent.PROGRESS_COL].picture
elif role == Qt.DisplayRole and col == self.parent.SERIES_COL:
return self.arraydata[row][self.parent.SERIES_COL].text()
elif role == Qt.DisplayRole and col == self.parent.RATING_COL:
return self.arraydata[row][self.parent.RATING_COL].text()
elif role == Qt.DisplayRole and col == self.parent.WORD_COUNT_COL:
return self.arraydata[row][self.parent.WORD_COUNT_COL].text()
elif role == Qt.DisplayRole and col == self.parent.TITLE_COL:
return self.arraydata[row][self.parent.TITLE_COL].text()
elif role == Qt.DisplayRole and col == self.parent.AUTHOR_COL:
return self.arraydata[row][self.parent.AUTHOR_COL].text()
elif role == Qt.DisplayRole and col == self.parent.DATE_ADDED_COL:
return self.arraydata[row][self.parent.DATE_ADDED_COL].text()
elif role == Qt.DisplayRole and col == self.parent.LAST_OPENED_COL:
return self.arraydata[row][self.parent.LAST_OPENED_COL].text()
elif role == Qt.DisplayRole and col == self.parent.SUBJECTS_COL:
return self.arraydata[row][self.parent.SUBJECTS_COL].text()
elif role == Qt.DisplayRole and col == self.parent.ANNOTATIONS_COL:
return self.arraydata[row][self.parent.ANNOTATIONS_COL].text()
elif role == Qt.DisplayRole and col == self.parent.VOCABULARY_COL:
return self.arraydata[row][self.parent.VOCABULARY_COL].text()
elif role == Qt.DisplayRole and col == self.parent.ARTICLES_COL:
return self.arraydata[row][self.parent.ARTICLES_COL].text()
elif role == Qt.TextAlignmentRole and (col in self.centered_columns):
return Qt.AlignHCenter
elif role == Qt.TextAlignmentRole and (col in self.right_aligned_columns):
return Qt.AlignRight
elif role == Qt.ToolTipRole:
if self.parent.busy:
return "<p>Please wait until current operation completes</p>"
else:
match_quality = self.get_match_quality(row)
tip = '<p>'
if match_quality == BookStatusDialog.MATCH_COLORS.index('GREEN'):
tip += 'Matched in calibre library'
elif match_quality == BookStatusDialog.MATCH_COLORS.index('YELLOW'):
tip += 'Matched in calibre library with differing metadata'
elif match_quality == BookStatusDialog.MATCH_COLORS.index('ORANGE'):
tip += 'Duplicate of matched book in calibre library'
elif match_quality == BookStatusDialog.MATCH_COLORS.index('LIGHT_GRAY'):
tip += 'Book updated in calibre library'
elif match_quality == BookStatusDialog.MATCH_COLORS.index('DARK_GRAY'):
tip += 'Book updated in Marvin library'
elif match_quality == BookStatusDialog.MATCH_COLORS.index('MAGENTA'):
tip += 'Multiple copies in calibre library'
elif match_quality == BookStatusDialog.MATCH_COLORS.index('RED'):
tip += 'Duplicated in Marvin library'
else:
tip += 'Book in Marvin library only'
# Add the suffix based upon column
if col in [self.parent.TITLE_COL, self.parent.AUTHOR_COL]:
return tip + "<br/>Double-click to view metadata<br/>Right-click for more options</p>"
elif col in [self.parent.ANNOTATIONS_COL,
self.parent.ARTICLES_COL]:
has_content = bool(self.arraydata[row][col])
if has_content:
return tip + "<br/>Double-click to view details<br/>Right-click for more options</p>"
else:
return tip + '</p>'
elif col == self.parent.COLLECTIONS_COL:
has_content = bool(self.arraydata[row][col].sort_key)
if has_content:
return tip + "<br/>Double-click to view details<br/>Right-click for more options</p>"
else:
return tip + '<br/>Right-click for more options</p>'
elif col in [self.parent.DEEP_VIEW_COL]:
has_content = bool(self.arraydata[row][col])
if has_content:
return tip + "<br/>Double-click to view Deep View content<br/>Right-click for more options</p>"
else:
return tip + '<br/>Double-click to generate Deep View content<br/>Right-click for more options</p>'
elif col in [self.parent.FLAGS_COL]:
return tip + "<br/>Right-click for options</p>"
elif col == self.parent.LOCKED_COL:
return ("<p>Double-click to toggle locked status" +
"<br/>Right-click for more options</p>")
elif col in [self.parent.RATING_COL]:
return tip + "<br/>Right-click to set rating</p>"
elif col in [self.parent.VOCABULARY_COL]:
has_content = bool(self.arraydata[row][col])
if has_content:
return tip + "<br/>Double-click to view Vocabulary words<br/>Right-click for more options</p>"
else:
return tip + '<br/>Right-click for options</p>'
elif col in [self.parent.WORD_COUNT_COL]:
return (tip + "<br/>Double-click to generate word count" +
"<br/>Right-click to generate word count for multiple books</p>")
else:
return tip + '</p>'
elif role != Qt.DisplayRole:
return None
return self.arraydata[index.row()][index.column()]
def headerData(self, col, orientation, role):
if role == Qt.DisplayRole:
if orientation == Qt.Horizontal:
return self.headerdata[col]
if role == Qt.ToolTipRole:
if orientation == Qt.Horizontal:
if col == self.parent.ANNOTATIONS_COL:
tip = "<p>Annotations and Highlights.<br/>"
elif col == self.parent.ARTICLES_COL:
tip = "<p>Pinned articles.<br/>"
elif col == self.parent.AUTHOR_COL:
tip = "<p>Book author.<br/>"
elif col == self.parent.COLLECTIONS_COL:
tip = "<p>Collection assignments.<br/>"
elif col == self.parent.DATE_ADDED_COL:
tip = "<p>Date added to Marvin.<br/>"
elif col == self.parent.DEEP_VIEW_COL:
tip = "<p>Deep View items.<br/>"
elif col == self.parent.FLAGS_COL:
tip = "<p><i>New</i>, <i>Reading</i> and <i>Read</i> flags.<br/>"
elif col == self.parent.LAST_OPENED_COL:
tip = "<p>Last opened in Marvin.<br/>"
elif col == self.parent.LOCKED_COL:
tip = "<p>Locked status.<br/>"
elif col == self.parent.PROGRESS_COL:
tip = "<p>Reading progress.<br/>"
elif col == self.parent.SERIES_COL:
tip = "<p>Book series.<br/>"
elif col == self.parent.SUBJECTS_COL:
tip = "<p>Book subjects.<br/>"
elif col == self.parent.TITLE_COL:
tip = "<p>Book title.<br/>"
elif col == self.parent.VOCABULARY_COL:
tip = "<p>Vocabulary words.<br/>"
elif col == self.parent.WORD_COUNT_COL:
tip = "<p>Word count.<br/>"
else:
tip = '<p>'
suffix = "Right-click to show or hide columns.</p>"
return tip + suffix
return None
def refresh(self, show_match_colors):
self.show_match_colors = show_match_colors
self.dataChanged.emit(self.createIndex(0, 0),
self.createIndex(self.rowCount(0), self.columnCount(0)))
def rowCount(self, parent):
return len(self.arraydata)
def setData(self, index, value, role):
row, col = index.row(), index.column()
self.dataChanged = pyqtSignal(object, object)
self.dataChanged.emit(index, index)
return True
def sort(self, Ncol, order):
"""
Sort table by given column number.
"""
self.layoutChanged.emit("layoutAboutToBeChanged")
self.arraydata = sorted(self.arraydata, key=operator.itemgetter(Ncol))
if order == Qt.DescendingOrder:
self.arraydata.reverse()
self.layoutChanged.emit("layoutChanged")
# ~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~
def get_annotations(self, row):
return self.arraydata[row][self.parent.ANNOTATIONS_COL]
def get_articles(self, row):
return self.arraydata[row][self.parent.ARTICLES_COL]
def get_author(self, row):
return self.arraydata[row][self.parent.AUTHOR_COL]
def get_book_id(self, row):
return self.arraydata[row][self.parent.BOOK_ID_COL]
def get_calibre_id(self, row):
return self.arraydata[row][self.parent.CALIBRE_ID_COL]
def set_calibre_id(self, row, value):
self.arraydata[row][self.parent.CALIBRE_ID_COL] = value
def get_collections(self, row):
return self.arraydata[row][self.parent.COLLECTIONS_COL]
def set_collections(self, row, value):
self.arraydata[row][self.parent.COLLECTIONS_COL] = value
self.parent.repaint()
def get_deep_view(self, row):
return self.arraydata[row][self.parent.DEEP_VIEW_COL]
def set_deep_view(self, row, value):
self.arraydata[row][self.parent.DEEP_VIEW_COL] = value
self.parent.repaint()
def get_flags(self, row):
return self.arraydata[row][self.parent.FLAGS_COL]
def set_flags(self, row, value):
self.arraydata[row][self.parent.FLAGS_COL] = value
#self.parent.repaint()
def get_last_opened(self, row):
return self.arraydata[row][self.parent.LAST_OPENED_COL]
def get_locked(self, row):
return self.arraydata[row][self.parent.LOCKED_COL]
def set_locked(self, row, value):
self.arraydata[row][self.parent.LOCKED_COL] = value
#self.parent.repaint()
def get_match_quality(self, row):
return self.arraydata[row][self.parent.MATCHED_COL]
def set_match_quality(self, row, value):
self.arraydata[row][self.parent.MATCHED_COL] = value
self.parent.repaint()
def get_path(self, row):
return self.arraydata[row][self.parent.PATH_COL]
def get_progress(self, row):
return self.arraydata[row][self.parent.PROGRESS_COL]
def set_progress(self, row, value):
self.arraydata[row][self.parent.PROGRESS_COL] = value
#self.parent.repaint()
def get_rating(self, row):
return self.arraydata[row][self.parent.RATING_COL]
def set_rating(self, row, value):
self.arraydata[row][self.parent.RATING_COL] = value
def get_series(self, row):
return self.arraydata[row][self.parent.SERIES_COL]
def get_subjects(self, row):
return self.arraydata[row][self.parent.SUBJECTS_COL]
def get_title(self, row):
return self.arraydata[row][self.parent.TITLE_COL]
def get_uuid(self, row):
return self.arraydata[row][self.parent.UUID_COL]
def get_vocabulary(self, row):
return self.arraydata[row][self.parent.VOCABULARY_COL]
def get_word_count(self, row):
return self.arraydata[row][self.parent.WORD_COUNT_COL]
def set_word_count(self, row, value):
self.arraydata[row][self.parent.WORD_COUNT_COL] = value
self.parent.repaint()
class BookStatusDialog(SizePersistedDialog, Logger):
'''
'''
# CANCEL_NOT_REQUESTED = 0
# CANCEL_REQUESTED = 1
# CANCEL_ACKNOWLEDGED = 2
CHECKMARK = u"\u2713"
CIRCLE_SLASH = u"\u20E0"
DEFAULT_REFRESH_TEXT = 'Refresh custom columns'
DEFAULT_REFRESH_TOOLTIP = "<p>Refresh custom column content in calibre for the selected books.<br/>Assign custom column mappings in the <i>Customize plugin…</i> dialog.</p>"
HASH_CACHE_FS = "content_hashes.db"
HIGHLIGHT_COLORS = ['Pink', 'Yellow', 'Blue', 'Green', 'Purple']
MATCH_COLORS = ['DARK_GRAY', 'LIGHT_GRAY', 'WHITE', 'RED', 'ORANGE', 'MAGENTA', 'YELLOW', 'GREEN']
MATH_TIMES_CIRCLED = u" \u2297 "
MATH_TIMES = u" \u00d7 "
MAX_BOOKS_BEFORE_SPINNER = 4
MAX_ELEMENT_DEPTH = 6
UPDATING_MARVIN_MESSAGE = "Updating Marvin Library…"
UTF_8_BOM = r'\xef\xbb\xbf'
# Flag constants
if True:
FLAGS = {
'new': 'NEW',
'read': 'READ',
'reading_list': 'READING LIST'
}
# Binary values for flag updates
NEW_FLAG = 4
READING_FLAG = 2
READ_FLAG = 1
# Column assignments. When changing order here, also change in:
# _construct_table_data
# USER_CONTROLLED_COLUMNS
if True:
LIBRARY_HEADER = [
'Title', 'Author', 'Series', 'Rating',
'Word count', 'Date added', 'Progress', 'Last read',
'Subjects', 'Collections', MATH_TIMES, 'Flags',
'Ann', 'Voc', 'DV', 'Art',
'Match Quality', 'uuid', 'cid', 'mid', 'path']
ANNOTATIONS_COL = LIBRARY_HEADER.index('Ann')
ARTICLES_COL = LIBRARY_HEADER.index('Art')
AUTHOR_COL = LIBRARY_HEADER.index('Author')
BOOK_ID_COL = LIBRARY_HEADER.index('mid')
CALIBRE_ID_COL = LIBRARY_HEADER.index('cid')
COLLECTIONS_COL = LIBRARY_HEADER.index('Collections')
DATE_ADDED_COL = LIBRARY_HEADER.index('Date added')
DEEP_VIEW_COL = LIBRARY_HEADER.index('DV')
FLAGS_COL = LIBRARY_HEADER.index('Flags')
LAST_OPENED_COL = LIBRARY_HEADER.index('Last read')
LOCKED_COL = LIBRARY_HEADER.index(MATH_TIMES)
MATCHED_COL = LIBRARY_HEADER.index('Match Quality')
PATH_COL = LIBRARY_HEADER.index('path')
PROGRESS_COL = LIBRARY_HEADER.index('Progress')
RATING_COL = LIBRARY_HEADER.index('Rating')
TITLE_COL = LIBRARY_HEADER.index('Title')
SERIES_COL = LIBRARY_HEADER.index('Series')
SUBJECTS_COL = LIBRARY_HEADER.index('Subjects')
UUID_COL = LIBRARY_HEADER.index('uuid')
VOCABULARY_COL = LIBRARY_HEADER.index('Voc')
WORD_COUNT_COL = LIBRARY_HEADER.index('Word count')