Debian Codegraph @

src/calibre/gui2/custom_column_widgets.py

raw
1 #!/usr/bin/env python
2 # License: GPLv3 Copyright: 2010, Kovid Goyal <[email protected]>
3
4 import os
5 from collections import OrderedDict
6 from collections.abc import Callable
7 from functools import partial
8 from typing import TYPE_CHECKING, Any, cast
9
10 from qt.core import (
11 QApplication,
12 QCheckBox,
13 QComboBox,
14 QDialog,
15 QFontDatabase,
16 QGridLayout,
17 QGroupBox,
18 QHBoxLayout,
19 QIcon,
20 QLabel,
21 QLineEdit,
22 QMessageBox,
23 QSizePolicy,
24 QSpacerItem,
25 QStyle,
26 Qt,
27 QToolButton,
28 QUrl,
29 QVBoxLayout,
30 QWidget,
31 )
32
33 from calibre.ebooks.metadata import title_sort
34 from calibre.gui2 import UNDEFINED_QDATETIME, elided_text, error_dialog, gprefs, qapplication_or_fail
35 from calibre.gui2.comments_editor import Editor as CommentsEditor
36 from calibre.gui2.complete2 import EditWithComplete as EWC
37 from calibre.gui2.dialogs.tag_editor import TagEditor
38 from calibre.gui2.library.delegates import ClearingDoubleSpinBox, ClearingSpinBox
39 from calibre.gui2.markdown_editor import Editor as MarkdownEditor
40 from calibre.gui2.tweak_book.widgets import PlainTextEdit
41 from calibre.gui2.widgets2 import DateTimeEdit as DateTimeEditBase
42 from calibre.gui2.widgets2 import RatingEditor
43 from calibre.library.comments import comments_to_html
44 from calibre.utils.config import tweaks
45 from calibre.utils.date import as_local_time, as_utc, internal_iso_format_string, is_date_undefined, now, qt_from_dt, qt_to_dt
46 from calibre.utils.icu import lower as icu_lower
47 from calibre.utils.icu import sort_key
48 from calibre.utils.localization import _
49
50
51 class EditWithComplete(EWC):
52 def __init__(self, *a, **kw):
53 super().__init__(*a, **kw)
54 self.set_clear_button_enabled(False)
55 if le := self.lineEdit():
56 le.setMaxLength(655360) # see https://bugs.launchpad.net/bugs/1630944
57
58
59 def safe_disconnect(signal):
60 try:
61 signal.disconnect()
62 except Exception:
63 pass
64
65
66 def label_string(txt):
67 if txt:
68 try:
69 if txt[0].isalnum():
70 return '&' + txt
71 except Exception:
72 pass
73 return txt
74
75
76 def get_tooltip(col_metadata, add_index=False):
77 key = col_metadata['label'] + ('_index' if add_index else '')
78 label = col_metadata['name'] + (_(' index') if add_index else '')
79 description = col_metadata.get('display', {}).get('description', '')
80 return '{} (#{}){} {}'.format(label, key, ':' if description else '', description).strip()
81
82
83 class Base:
84 if TYPE_CHECKING:
85 key: str
86 parent: QWidget | None
87
88 def setup_ui(self, parent):
89 raise NotImplementedError
90
91 def setter(self, val):
92 raise NotImplementedError
93
94 def getter(self):
95 raise NotImplementedError
96
97 def set_to_undefined(self):
98 raise NotImplementedError
99
100 def __init__(self, db, col_id, parent=None):
101 self.db, self.col_id = db, col_id
102 self.book_id = None
103 self.col_metadata = db.custom_column_num_map[col_id]
104 self.initial_val = None
105 self.widgets: list[QWidget] | None = None
106 self.signals_to_disconnect = []
107 self.setup_ui(parent)
108 description = get_tooltip(self.col_metadata)
109 widgets = cast(list[QWidget], self.widgets)
110 try:
111 widgets[0].setToolTip(description)
112 widgets[1].setToolTip(description)
113 except Exception:
114 try:
115 widgets[1].setToolTip(description)
116 except Exception:
117 pass
118
119 @property
120 def field_name(self) -> str:
121 db = self.db
122 assert db is not None
123 return db.field_metadata.label_to_key(self.col_metadata['label'], prefer_custom=True)
124
125 @property
126 def hierarchy_separator(self) -> str:
127 db = self.db
128 assert db is not None
129 return '.' if self.field_name in db.new_api.pref('categories_using_hierarchy', default=()) else ''
130
131 def finish_ui_setup(self, parent, edit_widget):
132 self.was_none = False
133 w = QWidget(parent)
134 widgets = self.widgets
135 assert widgets is not None
136 widgets.append(w)
137 l = QHBoxLayout()
138 l.setContentsMargins(0, 0, 0, 0)
139 w.setLayout(l)
140 self.editor = editor = edit_widget(parent)
141 l.addWidget(editor)
142 self.clear_button = QToolButton(parent)
143 self.clear_button.setIcon(QIcon.ic('trash.png'))
144 self.clear_button.clicked.connect(self.set_to_undefined)
145 self.clear_button.setToolTip(_('Clear {0}').format(self.col_metadata['name']))
146 l.addWidget(self.clear_button)
147
148 def initialize(self, book_id):
149 self.book_id = book_id
150 db = self.db
151 assert db is not None
152 val = db.get_custom(book_id, num=self.col_id, index_is_id=True)
153 val = self.normalize_db_val(val)
154 self.setter(val)
155 self.initial_val = self.current_val # self.current_val might be different from val thanks to normalization
156
157 @property
158 def current_val(self):
159 return self.normalize_ui_val(self.gui_val)
160
161 @property
162 def gui_val(self):
163 return self.getter()
164
165 def commit(self, book_id, notify=False):
166 val = self.current_val
167 if val != self.initial_val:
168 db = self.db
169 assert db is not None
170 return db.set_custom(book_id, val, num=self.col_id, notify=notify, commit=False, allow_case_change=True)
171 else:
172 return set()
173
174 def apply_to_metadata(self, mi):
175 mi.set('#' + self.col_metadata['label'], self.current_val)
176
177 def normalize_db_val(self, val):
178 return val
179
180 def normalize_ui_val(self, val):
181 return val
182
183 def break_cycles(self):
184 self.db = self.initial_val = None
185 self.widgets = None
186 for signal in self.signals_to_disconnect:
187 safe_disconnect(signal)
188 self.signals_to_disconnect = []
189
190 def connect_data_changed(self, slot):
191 pass
192
193 def values_changed(self):
194 return self.getter() != self.initial_val and (self.getter() or self.initial_val)
195
196 def edit(self):
197 if self.values_changed():
198 d = _save_dialog(
199 self.parent,
200 _('Values changed'),
201 _('You have changed the values. In order to use this editor, you must either discard or apply these changes. Apply changes?'),
202 )
203 if d == QMessageBox.StandardButton.Cancel:
204 return
205 if d == QMessageBox.StandardButton.Yes:
206 self.commit(self.book_id)
207 db = self.db
208 assert db is not None
209 db.commit()
210 self.initial_val = self.current_val
211 else:
212 self.setter(self.initial_val)
213 from calibre.gui2.ui import get_gui
214
215 get_gui(fail_if_absent=True).do_tags_list_edit(None, self.key)
216 self.initialize(self.book_id)
217
218
219 class SimpleText(Base):
220 def setup_ui(self, parent):
221 self.widgets = [
222 QLabel(label_string(self.col_metadata['name']), parent),
223 ]
224 self.finish_ui_setup(parent, QLineEdit)
225
226 def set_to_undefined(self):
227 self.editor.setText('')
228
229 def setter(self, val):
230 self.editor.setText(str(val or ''))
231
232 def getter(self):
233 return self.editor.text().strip()
234
235 def connect_data_changed(self, slot):
236 self.editor.textChanged.connect(slot)
237 self.signals_to_disconnect.append(self.editor.textChanged)
238
239
240 class LongText(Base):
241 def setup_ui(self, parent):
242 self._box = QGroupBox(parent)
243 self._box.setTitle(label_string(self.col_metadata['name']))
244 self._layout = QVBoxLayout()
245 self._tb = PlainTextEdit(self._box, use_smarten_punctuation=True)
246 self._tb.setFont(QFontDatabase.systemFont(QFontDatabase.SystemFont.FixedFont))
247 self._tb.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum)
248 self._layout.addWidget(self._tb)
249 self._box.setLayout(self._layout)
250 self.widgets = [self._box]
251
252 def setter(self, val):
253 self._tb.setPlainText(str(val or ''))
254
255 def getter(self):
256 return self._tb.toPlainText()
257
258 def connect_data_changed(self, slot):
259 self._tb.textChanged.connect(slot)
260 self.signals_to_disconnect.append(self._tb.textChanged)
261
262
263 class Bool(Base):
264 def setup_ui(self, parent):
265 name = self.col_metadata['name']
266 self.widgets: list[QWidget] = [QLabel(label_string(name), parent)]
267 w = QWidget(parent)
268 self.widgets.append(w)
269
270 l = QHBoxLayout()
271 l.setContentsMargins(0, 0, 0, 0)
272 w.setLayout(l)
273 self.combobox = QComboBox(parent)
274 l.addWidget(self.combobox)
275
276 c = QToolButton(parent)
277 c.setIcon(QIcon.ic('ok.png'))
278 c.setToolTip(_('Set {} to yes').format(name))
279 l.addWidget(c)
280 c.clicked.connect(self.set_to_yes)
281
282 c = QToolButton(parent)
283 c.setIcon(QIcon.ic('list_remove.png'))
284 c.setToolTip(_('Set {} to no').format(name))
285 l.addWidget(c)
286 c.clicked.connect(self.set_to_no)
287
288 db = self.db
289 assert db is not None
290 if db.new_api.pref('bools_are_tristate'):
291 c = QToolButton(parent)
292 c.setIcon(QIcon.ic('trash.png'))
293 c.setToolTip(_('Clear {}').format(name))
294 l.addWidget(c)
295 c.clicked.connect(self.set_to_cleared)
296
297 w = self.combobox
298 items = [_('Yes'), _('No'), _('Undefined')]
299 icons = ['ok.png', 'list_remove.png', 'blank.png']
300 if not db.new_api.pref('bools_are_tristate'):
301 items = items[:-1]
302 icons = icons[:-1]
303 for icon, text in zip(icons, items):
304 w.addItem(QIcon.ic(icon), text)
305
306 def setter(self, val):
307 val = {None: 2, False: 1, True: 0}[val]
308 db = self.db
309 assert db is not None
310 if not db.new_api.pref('bools_are_tristate') and val == 2:
311 val = 1
312 self.combobox.setCurrentIndex(val)
313
314 def getter(self):
315 val = self.combobox.currentIndex()
316 return {2: None, 1: False, 0: True}[val]
317
318 def set_to_yes(self):
319 self.combobox.setCurrentIndex(0)
320
321 def set_to_no(self):
322 self.combobox.setCurrentIndex(1)
323
324 def set_to_cleared(self):
325 self.combobox.setCurrentIndex(2)
326
327 def connect_data_changed(self, slot):
328 self.combobox.currentTextChanged.connect(slot)
329 self.signals_to_disconnect.append(self.combobox.currentTextChanged)
330
331
332 class Int(Base):
333 def setup_ui(self, parent):
334 self.widgets = [QLabel(label_string(self.col_metadata['name']), parent)]
335 self.finish_ui_setup(parent, ClearingSpinBox)
336 self.editor.setRange(-1000000, 100000000)
337
338 def finish_ui_setup(self, parent, edit_widget):
339 Base.finish_ui_setup(self, parent, edit_widget)
340 self.editor.setSpecialValueText(_('Undefined'))
341 self.editor.setSingleStep(1)
342 self.editor.valueChanged.connect(self.valueChanged)
343
344 def setter(self, val):
345 if val is None:
346 val = self.editor.minimum()
347 self.editor.setValue(val)
348 self.was_none = val == self.editor.minimum()
349
350 def getter(self):
351 val = self.editor.value()
352 if val == self.editor.minimum():
353 val = None
354 return val
355
356 def valueChanged(self, to_what):
357 if self.was_none and to_what == -999999:
358 self.setter(0)
359 self.was_none = to_what == self.editor.minimum()
360
361 def connect_data_changed(self, slot):
362 self.editor.valueChanged.connect(slot)
363 self.signals_to_disconnect.append(self.editor.valueChanged)
364
365 def set_to_undefined(self):
366 self.editor.setValue(-1000000)
367
368
369 class Float(Int):
370 def setup_ui(self, parent):
371 self.widgets = [QLabel(label_string(self.col_metadata['name']), parent)]
372 self.finish_ui_setup(parent, ClearingDoubleSpinBox)
373 self.editor.setRange(-1000000.0, float(100000000))
374 self.editor.setDecimals(int(self.col_metadata['display'].get('decimals', 2)))
375
376
377 class Rating(Base):
378 def setup_ui(self, parent):
379 allow_half_stars = self.col_metadata['display'].get('allow_half_stars', False)
380 self.widgets = [QLabel(label_string(self.col_metadata['name']), parent)]
381 self.finish_ui_setup(parent, partial(RatingEditor, is_half_star=allow_half_stars))
382
383 def set_to_undefined(self):
384 self.editor.setCurrentIndex(0)
385
386 def setter(self, val):
387 val = max(0, min(int(val or 0), 10))
388 self.editor.rating_value = val
389
390 def getter(self):
391 return self.editor.rating_value or None
392
393 def connect_data_changed(self, slot):
394 self.editor.currentTextChanged.connect(slot)
395 self.signals_to_disconnect.append(self.editor.currentTextChanged)
396
397
398 class DateTimeEdit(DateTimeEditBase):
399 def focusInEvent(self, e):
400 self.setSpecialValueText('')
401 DateTimeEditBase.focusInEvent(self, e)
402
403 def focusOutEvent(self, e):
404 self.setSpecialValueText(_('Undefined'))
405 DateTimeEditBase.focusOutEvent(self, e)
406
407 def set_to_today(self):
408 self.setDateTime(qt_from_dt(now()))
409
410 def set_to_clear(self):
411 self.setDateTime(UNDEFINED_QDATETIME)
412
413
414 class DateTime(Base):
415 def setup_ui(self, parent):
416 cm = self.col_metadata
417 self.widgets: list[QWidget] = [QLabel(label_string(cm['name']), parent)]
418 w = QWidget(parent)
419 self.widgets.append(w)
420 l = QHBoxLayout()
421 l.setContentsMargins(0, 0, 0, 0)
422 w.setLayout(l)
423 self.dte = dte = DateTimeEdit(parent)
424 format_ = cm['display'].get('date_format', '')
425 if not format_:
426 format_ = 'dd MMM yyyy hh:mm'
427 elif format_ == 'iso':
428 format_ = internal_iso_format_string()
429 dte.setDisplayFormat(format_)
430 dte.setCalendarPopup(True)
431 dte.setMinimumDateTime(UNDEFINED_QDATETIME)
432 dte.setSpecialValueText(_('Undefined'))
433 l.addWidget(dte)
434
435 self.today_button = QToolButton(parent)
436 self.today_button.setText(_('Today'))
437 self.today_button.clicked.connect(dte.set_to_today)
438 l.addWidget(self.today_button)
439
440 self.clear_button = QToolButton(parent)
441 self.clear_button.setIcon(QIcon.ic('trash.png'))
442 self.clear_button.clicked.connect(dte.set_to_clear)
443 self.clear_button.setToolTip(_('Clear {0}').format(self.col_metadata['name']))
444 l.addWidget(self.clear_button)
445 self.connect_data_changed(self.set_tooltip)
446
447 def set_tooltip(self, val):
448 if is_date_undefined(val):
449 self.dte.setToolTip(get_tooltip(self.col_metadata, False))
450 else:
451 self.dte.setToolTip(get_tooltip(self.col_metadata, False) + '\n' + _('Exact time: {}').format(as_local_time(qt_to_dt(val))))
452
453 def setter(self, val):
454 if val is None:
455 val = self.dte.minimumDateTime()
456 else:
457 val = qt_from_dt(val)
458 self.dte.setDateTime(val)
459
460 def getter(self):
461 val = self.dte.dateTime()
462 if is_date_undefined(val):
463 val = None
464 else:
465 val = qt_to_dt(val)
466 return val
467
468 def normalize_db_val(self, val):
469 return as_local_time(val) if val is not None else None
470
471 def normalize_ui_val(self, val):
472 return as_utc(val) if val is not None else None
473
474 def connect_data_changed(self, slot):
475 self.dte.dateTimeChanged.connect(slot)
476 self.signals_to_disconnect.append(self.dte.dateTimeChanged)
477
478
479 class Comments(Base):
480 def setup_ui(self, parent):
481 self._box = QGroupBox(parent)
482 self._box.setTitle(label_string(self.col_metadata['name']))
483 self._layout = QVBoxLayout()
484 self._tb = CommentsEditor(self._box, toolbar_prefs_name='metadata-comments-editor-widget-hidden-toolbars')
485 self._tb.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum)
486 # self._tb.setTabChangesFocus(True)
487 self._layout.addWidget(self._tb)
488 self._box.setLayout(self._layout)
489 self.widgets = [self._box]
490
491 def initialize(self, book_id):
492 db = self.db
493 assert db is not None
494 path = db.abspath(book_id, index_is_id=True)
495 if path:
496 self._tb.set_base_url(QUrl.fromLocalFile(os.path.join(path, 'metadata.html')))
497 return Base.initialize(self, book_id)
498
499 def setter(self, val):
500 if not val or not val.strip():
501 val = ''
502 else:
503 val = comments_to_html(val)
504 self._tb.html = val
505 self._tb.wyswyg_dirtied()
506
507 def getter(self):
508 val = str(self._tb.html).strip()
509 if not val:
510 val = None
511 return val
512
513 @property
514 def tab(self):
515 return self._tb.tab
516
517 @tab.setter
518 def tab(self, val):
519 self._tb.tab = val
520
521 def connect_data_changed(self, slot):
522 self._tb.data_changed.connect(slot)
523 self.signals_to_disconnect.append(self._tb.data_changed)
524
525
526 class Markdown(Base):
527 def setup_ui(self, parent):
528 self._box = QGroupBox(parent)
529 self._box.setTitle(label_string(self.col_metadata['name']))
530 self._layout = QVBoxLayout()
531 self._tb = MarkdownEditor(self._box)
532 self._tb.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum)
533 # self._tb.setTabChangesFocus(True)
534 self._layout.addWidget(self._tb)
535 self._box.setLayout(self._layout)
536 self.widgets = [self._box]
537
538 def initialize(self, book_id):
539 db = self.db
540 assert db is not None
541 path = db.abspath(book_id, index_is_id=True)
542 if path:
543 self._tb.set_base_url(QUrl.fromLocalFile(os.path.join(path, 'metadata.html')))
544 return super().initialize(book_id)
545
546 def setter(self, val):
547 self._tb.markdown = str(val or '').strip()
548
549 def getter(self):
550 val = self._tb.markdown.strip()
551 if not val:
552 val = None
553 return val
554
555 @property
556 def tab(self):
557 return self._tb.tab
558
559 @tab.setter
560 def tab(self, val):
561 self._tb.tab = val
562
563 def connect_data_changed(self, slot):
564 self._tb.editor.textChanged.connect(slot)
565 self.signals_to_disconnect.append(self._tb.editor.textChanged)
566
567
568 class MultipleWidget(QWidget):
569 def __init__(self, parent, only_manage_items=False, widget=EditWithComplete, name=None):
570 QWidget.__init__(self, parent)
571 layout = QHBoxLayout()
572 layout.setSpacing(5)
573 layout.setContentsMargins(0, 0, 0, 0)
574
575 self.edit_widget = widget(parent)
576 layout.addWidget(self.edit_widget, stretch=1000)
577 self.editor_button = QToolButton(self)
578 if name is None:
579 name = _('items')
580 if only_manage_items:
581 self.editor_button.setToolTip(_('Open the Manage {} window').format(name))
582 else:
583 self.editor_button.setToolTip(_('Open the {0} editor. If Ctrl or Shift is pressed, open the Manage {0} window').format(name))
584 self.editor_button.setIcon(QIcon.ic('chapters.png'))
585 layout.addWidget(self.editor_button)
586 self.setLayout(layout)
587
588 def get_editor_button(self):
589 return self.editor_button
590
591 def update_items_cache(self, values):
592 self.edit_widget.update_items_cache(values)
593
594 def clear(self):
595 self.edit_widget.clear()
596
597 def setEditText(self, text: str = '') -> None:
598 self.edit_widget.setEditText(text)
599
600 def addItem(self, itm):
601 self.edit_widget.addItem(itm)
602
603 def set_separator(self, sep):
604 self.edit_widget.set_separator(sep)
605
606 def set_hierarchy_separator(self, sep):
607 if hasattr(self.edit_widget, 'set_hierarchy_separator'):
608 self.edit_widget.set_hierarchy_separator(sep)
609
610 def set_add_separator(self, sep):
611 self.edit_widget.set_add_separator(sep)
612
613 def set_space_before_sep(self, v):
614 self.edit_widget.set_space_before_sep(v)
615
616 def setSizePolicy(self, *args, **kwargs):
617 self.edit_widget.setSizePolicy(*args, **kwargs)
618
619 def setText(self, v):
620 self.edit_widget.setText(v)
621
622 def text(self):
623 return self.edit_widget.text()
624
625
626 def _save_dialog(parent, title, msg, det_msg=''):
627 d = QMessageBox(parent)
628 d.setWindowTitle(title)
629 d.setText(msg)
630 d.setStandardButtons(QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No | QMessageBox.StandardButton.Cancel)
631 return d.exec()
632
633
634 class Text(Base):
635 def set_to_undefined(self):
636 self.editor.clear()
637
638 def setup_ui(self, parent):
639 self.sep = self.col_metadata['multiple_seps']
640 db = self.db
641 assert db is not None
642 self.key = db.field_metadata.label_to_key(self.col_metadata['label'], prefer_custom=True)
643 self.parent = parent
644
645 if self.col_metadata['is_multiple']:
646 w = MultipleWidget(parent, name=self.col_metadata['name'])
647 w.set_separator(self.sep['ui_to_list'])
648 if self.sep['ui_to_list'] == '&':
649 w.set_space_before_sep(True)
650 w.set_add_separator(tweaks['authors_completer_append_separator'])
651 w.get_editor_button().clicked.connect(self.edit)
652 else:
653 w = MultipleWidget(parent, only_manage_items=True, name=self.col_metadata['name'])
654 w.set_separator(None)
655 w.get_editor_button().clicked.connect(super().edit)
656 w.set_hierarchy_separator(self.hierarchy_separator)
657 w.setSizePolicy(QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Fixed)
658 self.widgets = [QLabel(label_string(self.col_metadata['name']), parent)]
659 self.finish_ui_setup(parent, lambda parent: w)
660
661 def initialize(self, book_id):
662 db = self.db
663 assert db is not None
664 values = list(db.all_custom(num=self.col_id))
665 values.sort(key=sort_key)
666 self.book_id = book_id
667 self.editor.clear()
668 self.editor.update_items_cache(values)
669 val = db.get_custom(book_id, num=self.col_id, index_is_id=True)
670 if isinstance(val, list):
671 if not self.col_metadata.get('display', {}).get('is_names', False):
672 val.sort(key=sort_key)
673 val = self.normalize_db_val(val)
674
675 if self.col_metadata['is_multiple']:
676 self.setter(val)
677 else:
678 self.editor.setText(val)
679 self.initial_val = self.current_val
680
681 def setter(self, val):
682 if self.col_metadata['is_multiple']:
683 if not val:
684 val = []
685 self.editor.setText(self.sep['list_to_ui'].join(val))
686
687 def getter(self):
688 val = str(self.editor.text()).strip()
689 if self.col_metadata['is_multiple']:
690 ans = [x.strip() for x in val.split(self.sep['ui_to_list']) if x.strip()]
691 if not ans:
692 ans = None
693 return ans
694 if not val:
695 val = None
696 return val
697
698 def edit(self):
699 ctrl_or_shift_pressed = QApplication.keyboardModifiers() & (Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.ShiftModifier)
700 if self.getter() != self.initial_val and (self.getter() or self.initial_val):
701 d = _save_dialog(
702 self.parent,
703 _('Values changed'),
704 _('You have changed the values. In order to use this editor, you must either discard or apply these changes. Apply changes?'),
705 )
706 if d == QMessageBox.StandardButton.Cancel:
707 return
708 if d == QMessageBox.StandardButton.Yes:
709 self.commit(self.book_id)
710 db = self.db
711 assert db is not None
712 db.commit()
713 self.initial_val = self.current_val
714 else:
715 self.setter(self.initial_val)
716 if ctrl_or_shift_pressed:
717 from calibre.gui2.ui import get_gui
718
719 get_gui(fail_if_absent=True).do_tags_list_edit(None, self.key)
720 self.initialize(self.book_id)
721 else:
722 d = TagEditor(self.parent, self.db, self.book_id, self.key)
723 if d.exec() == QDialog.DialogCode.Accepted:
724 self.setter(d.tags)
725
726 def connect_data_changed(self, slot):
727 s = self.editor.edit_widget.currentTextChanged
728 s.connect(slot)
729 self.signals_to_disconnect.append(s)
730
731
732 class Series(Base):
733 def setup_ui(self, parent):
734 self.parent = parent
735 db = self.db
736 assert db is not None
737 self.key = db.field_metadata.label_to_key(self.col_metadata['label'], prefer_custom=True)
738 w = MultipleWidget(parent, only_manage_items=True, name=self.col_metadata['name'])
739 w.get_editor_button().clicked.connect(self.edit)
740 w.setSizePolicy(QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Fixed)
741 w.set_separator(None)
742 w.set_hierarchy_separator(self.hierarchy_separator)
743 self.name_widget = w.edit_widget
744 self.widgets = [QLabel(label_string(self.col_metadata['name']), parent)]
745 self.finish_ui_setup(parent, lambda parent: w)
746 self.name_widget.editTextChanged.connect(self.series_changed)
747
748 w = QLabel(label_string(self.col_metadata['name']) + _(' index'), parent)
749 w.setToolTip(get_tooltip(self.col_metadata, add_index=True))
750 self.widgets.append(w)
751 w = ClearingDoubleSpinBox(parent)
752 w.setRange(-10000.0, float(100000000))
753 w.setDecimals(2)
754 w.setSingleStep(1)
755 self.idx_widget = w
756 w.setToolTip(get_tooltip(self.col_metadata, add_index=True))
757 self.widgets.append(w)
758
759 def set_to_undefined(self):
760 self.editor.clear()
761 self.name_widget.clearEditText()
762 self.idx_widget.setValue(1.0)
763
764 def initialize(self, book_id):
765 self.book_id = book_id
766 db = self.db
767 assert db is not None
768 values = list(db.all_custom(num=self.col_id))
769 values.sort(key=sort_key)
770 val = db.get_custom(book_id, num=self.col_id, index_is_id=True)
771 s_index = db.get_custom_extra(book_id, num=self.col_id, index_is_id=True)
772 try:
773 s_index = float(s_index)
774 except ValueError, TypeError:
775 s_index = 1.0
776 self.idx_widget.setValue(s_index)
777 val = self.normalize_db_val(val)
778 self.name_widget.blockSignals(True)
779 self.name_widget.update_items_cache(values)
780 self.name_widget.setText(val)
781 self.name_widget.blockSignals(False)
782 self.initial_val, self.initial_index = self.current_val
783
784 def getter(self):
785 n = str(self.name_widget.currentText()).strip()
786 i = self.idx_widget.value()
787 return n, i
788
789 def series_changed(self, val):
790 val, s_index = self.gui_val
791 if tweaks['series_index_auto_increment'] == 'no_change':
792 pass
793 elif tweaks['series_index_auto_increment'] == 'const':
794 s_index = 1.0
795 else:
796 db = self.db
797 assert db is not None
798 s_index = db.get_next_cc_series_num_for(val, num=self.col_id)
799 self.idx_widget.setValue(s_index)
800
801 def values_changed(self):
802 val, s_index = self.current_val
803 return val != self.initial_val or s_index != self.initial_index
804
805 @property
806 def current_val(self):
807 val, s_index = self.gui_val
808 val = self.normalize_ui_val(val)
809 return val, s_index
810
811 def commit(self, book_id, notify=False):
812 val, s_index = self.current_val
813 if val != self.initial_val or s_index != self.initial_index:
814 if not val:
815 val = s_index = None
816 db = self.db
817 assert db is not None
818 return db.set_custom(book_id, val, extra=s_index, num=self.col_id, notify=notify, commit=False, allow_case_change=True)
819 else:
820 return set()
821
822 def apply_to_metadata(self, mi):
823 val, s_index = self.current_val
824 mi.set('#' + self.col_metadata['label'], val, extra=s_index)
825
826 def connect_data_changed(self, slot):
827 for s in self.name_widget.editTextChanged, self.idx_widget.valueChanged:
828 s.connect(slot)
829 self.signals_to_disconnect.append(s)
830
831
832 class Enumeration(Base):
833 def setup_ui(self, parent):
834 self.parent = parent
835 db = self.db
836 assert db is not None
837 self.key = db.field_metadata.label_to_key(self.col_metadata['label'], prefer_custom=True)
838 w = MultipleWidget(parent, only_manage_items=True, widget=QComboBox, name=self.col_metadata['name'])
839 w.set_hierarchy_separator(self.hierarchy_separator)
840 w.get_editor_button().clicked.connect(self.edit)
841 w.setSizePolicy(QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Fixed)
842 self.widgets = [QLabel(label_string(self.col_metadata['name']), parent)]
843 self.finish_ui_setup(parent, lambda parent: w)
844 self.editor = w.edit_widget
845 vals = self.col_metadata['display']['enum_values']
846 self.editor.addItem('')
847 for v in vals:
848 self.editor.addItem(v)
849
850 def initialize(self, book_id):
851 self.book_id = book_id
852 db = self.db
853 assert db is not None
854 val = db.get_custom(book_id, num=self.col_id, index_is_id=True)
855 val = self.normalize_db_val(val)
856 idx = self.editor.findText(val)
857 if idx < 0:
858 error_dialog(
859 self.parent,
860 '',
861 _('The enumeration "{0}" contains an invalid value that will be set to the default').format(self.col_metadata['name']),
862 show=True,
863 show_copy_button=False,
864 )
865
866 idx = 0
867 self.editor.setCurrentIndex(idx)
868 self.initial_val = val
869
870 def setter(self, val):
871 self.editor.setCurrentIndex(self.editor.findText(val))
872
873 def getter(self):
874 return str(self.editor.currentText())
875
876 def normalize_db_val(self, val):
877 if val is None:
878 val = ''
879 return val
880
881 def normalize_ui_val(self, val):
882 if not val:
883 val = None
884 return val
885
886 def set_to_undefined(self):
887 self.editor.setCurrentIndex(0)
888
889 def connect_data_changed(self, slot):
890 self.editor.currentIndexChanged.connect(slot)
891 self.signals_to_disconnect.append(self.editor.currentIndexChanged)
892
893
894 def comments_factory(db, key, parent):
895 fm = db.custom_column_num_map[key]
896 ctype = fm.get('display', {}).get('interpret_as', 'html')
897 if ctype == 'short-text':
898 return SimpleText(db, key, parent)
899 if ctype == 'long-text':
900 return LongText(db, key, parent)
901 if ctype == 'markdown':
902 return Markdown(db, key, parent)
903 return Comments(db, key, parent)
904
905
906 widgets = {
907 'bool': Bool,
908 'rating': Rating,
909 'int': Int,
910 'float': Float,
911 'datetime': DateTime,
912 'text': Text,
913 'comments': comments_factory,
914 'series': Series,
915 'enumeration': Enumeration,
916 }
917
918
919 def field_sort_key(y, fm=None):
920 assert fm is not None
921 m1 = fm[y]
922 name = icu_lower(m1['name'])
923 n1 = 'zzzzz' + name if column_is_comments(y, fm) else name
924 return sort_key(n1)
925
926
927 def column_is_comments(key, fm):
928 return fm[key]['datatype'] == 'comments' and fm[key].get('display', {}).get('interpret_as') != 'short-text'
929
930
931 def get_field_list(db, use_defaults=False, pref_data_override=None):
932 fm = db.field_metadata
933 fields = fm.custom_field_keys(include_composites=False)
934 if pref_data_override is not None:
935 displayable = pref_data_override
936 else:
937 displayable = db.prefs.get('edit_metadata_custom_columns_to_display', None)
938 if use_defaults or displayable is None:
939 fields.sort(key=partial(field_sort_key, fm=fm))
940 return [(k, True) for k in fields]
941 else:
942 field_set = set(fields)
943 result = OrderedDict({k: v for k, v in displayable if k in field_set})
944 for k in fields:
945 if k not in result:
946 result[k] = True
947 return list(result.items())
948
949
950 def get_custom_columns_to_display_in_editor(db):
951 return [k[0] for k in get_field_list(db, use_defaults=db.prefs['edit_metadata_ignore_display_order']) if k[1]]
952
953
954 def populate_metadata_page(layout, db, book_id, bulk=False, two_column=False, parent=None):
955 def widget_factory(typ, key):
956 if bulk:
957 w = bulk_widgets[typ](db, key, parent)
958 else:
959 w = widgets[typ](db, key, parent)
960 if book_id is not None:
961 w.initialize(book_id)
962 return w
963
964 fm = db.field_metadata
965
966 # Get list of all non-composite custom fields. We must make widgets for these
967 cols = get_custom_columns_to_display_in_editor(db)
968 # This deals with the historical behavior where comments fields go to the
969 # bottom, starting on the left hand side. If a comment field is moved to
970 # somewhere else then it isn't moved to either side.
971 comments_at_end = 0
972 for k in cols[::-1]:
973 if not column_is_comments(k, fm):
974 break
975 comments_at_end += 1
976 comments_not_at_end = len([k for k in cols if column_is_comments(k, fm)]) - comments_at_end
977
978 count = len(cols)
979 layout_rows_for_comments = 9
980 if two_column:
981 turnover_point = int(((count - comments_at_end + 1) + int(comments_not_at_end * (layout_rows_for_comments - 1))) / 2)
982 else:
983 # Avoid problems with multi-line widgets
984 turnover_point = count + 1000
985 ans = []
986 column = row = base_row = max_row = 0
987 label_width = 0
988 do_elision = gprefs['edit_metadata_elide_labels']
989 elide_pos = gprefs['edit_metadata_elision_point']
990 elide_pos = elide_pos if elide_pos in {'left', 'middle', 'right'} else 'right'
991 # make room on the right side for the scrollbar
992 app_style = qapplication_or_fail().style()
993 assert app_style is not None
994 sb_width = app_style.pixelMetric(QStyle.PixelMetric.PM_ScrollBarExtent)
995 layout.setContentsMargins(0, 0, sb_width, 0)
996 for key in cols:
997 if not fm[key]['is_editable']:
998 continue # The job spy plugin can change is_editable
999 dt = fm[key]['datatype']
1000 if dt == 'composite' or (bulk and dt == 'comments'):
1001 continue
1002 is_comments = column_is_comments(key, fm)
1003 w = widget_factory(dt, fm[key]['colnum'])
1004 ans.append(w)
1005 if two_column and is_comments:
1006 # Here for compatibility with old layout. Comments always started
1007 # in the left column
1008 comments_not_at_end -= 1
1009 # no special processing if the comment field was named in the tweak
1010 if comments_not_at_end < 0 and comments_at_end > 0:
1011 # Force a turnover, adding comments widgets below max_row.
1012 # Save the row to return to if we turn over again
1013 column = 0
1014 row = max_row
1015 base_row = row
1016 turnover_point = row + int((comments_at_end * layout_rows_for_comments) / 2)
1017 comments_at_end = 0
1018
1019 l = QGridLayout()
1020 if is_comments:
1021 layout.addLayout(l, row, column, layout_rows_for_comments, 1)
1022 layout.setColumnStretch(column, 100)
1023 # All multiline fields should grow with the window
1024 for i in range(layout_rows_for_comments):
1025 layout.setRowStretch(row + i, 100)
1026 row += layout_rows_for_comments
1027 else:
1028 layout.addLayout(l, row, column, 1, 1)
1029 layout.setColumnStretch(column, 100)
1030 row += 1
1031 for c in range(0, len(w.widgets), 2):
1032 if not is_comments:
1033 # Set the label column width to a fixed size. Elide labels that
1034 # don't fit
1035 wij = w.widgets[c]
1036 if label_width == 0:
1037 font_metrics = wij.fontMetrics()
1038 colon_width = font_metrics.horizontalAdvance(':')
1039 if bulk:
1040 label_width = (font_metrics.averageCharWidth() * gprefs['edit_metadata_bulk_cc_label_length']) - colon_width
1041 else:
1042 label_width = (font_metrics.averageCharWidth() * gprefs['edit_metadata_single_cc_label_length']) - colon_width
1043 wij.setMaximumWidth(label_width)
1044 if c == 0:
1045 wij.setSizePolicy(QSizePolicy.Policy.Maximum, QSizePolicy.Policy.Preferred)
1046 l.setColumnMinimumWidth(0, label_width)
1047 wij.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
1048 t = str(wij.text())
1049 if t:
1050 if do_elision:
1051 wij.setText(elided_text(t, font=font_metrics, width=label_width, pos=elide_pos) + ':')
1052 else:
1053 wij.setText(t + ':')
1054 wij.setWordWrap(True)
1055 wij.setBuddy(w.widgets[c + 1])
1056 l.addWidget(wij, c, 0)
1057 l.addWidget(w.widgets[c + 1], c, 1)
1058 else:
1059 l.addWidget(w.widgets[0], 0, 0, 1, 2)
1060 max_row = max(max_row, row)
1061 if row >= turnover_point:
1062 column = 1
1063 turnover_point = count + 1000
1064 row = base_row
1065
1066 items = []
1067 if len(ans) > 0:
1068 items.append(QSpacerItem(10, 10, QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Expanding))
1069 layout.addItem(items[-1], layout.rowCount(), 0, 1, 1)
1070 layout.setRowStretch(layout.rowCount() - 1, 100)
1071 return ans, items
1072
1073
1074 class BulkBase(Base):
1075 if TYPE_CHECKING:
1076 bools_are_tristate: bool
1077
1078 @property
1079 def gui_val(self):
1080 if not hasattr(self, '_cached_gui_val_'):
1081 self._cached_gui_val_ = self.getter()
1082 return self._cached_gui_val_
1083
1084 def get_initial_value(self, book_ids):
1085 values = set()
1086 db = self.db
1087 assert db is not None
1088 for book_id in book_ids:
1089 val = db.get_custom(book_id, num=self.col_id, index_is_id=True)
1090 if isinstance(val, list):
1091 val = frozenset(val)
1092 values.add(val)
1093 if len(values) > 1:
1094 break
1095 ans = None
1096 if len(values) == 1:
1097 ans = next(iter(values))
1098 if isinstance(ans, frozenset):
1099 ans = list(ans)
1100 return ans
1101
1102 def finish_ui_setup(
1103 self,
1104 parent,
1105 edit_widget: bool = False,
1106 add_edit_tags_button: tuple[bool, Callable] | tuple[bool] = (False,),
1107 is_bool: bool = False,
1108 ):
1109 self.was_none = False
1110 widgets = self.widgets
1111 assert widgets is not None
1112 l = widgets[1].layout()
1113 assert isinstance(l, QHBoxLayout)
1114 if not is_bool or self.bools_are_tristate:
1115 self.clear_button = QToolButton(parent)
1116 self.clear_button.setIcon(QIcon.ic('trash.png'))
1117 self.clear_button.setToolTip(_('Clear {0}').format(self.col_metadata['name']))
1118 self.clear_button.clicked.connect(self.set_to_undefined)
1119 l.insertWidget(1, self.clear_button)
1120 if is_bool:
1121 self.set_no_button = QToolButton(parent)
1122 self.set_no_button.setIcon(QIcon.ic('list_remove.png'))
1123 self.set_no_button.clicked.connect(lambda: self.main_widget.setCurrentIndex(1))
1124 self.set_no_button.setToolTip(_('Set {0} to No').format(self.col_metadata['name']))
1125 l.insertWidget(1, self.set_no_button)
1126 self.set_yes_button = QToolButton(parent)
1127 self.set_yes_button.setIcon(QIcon.ic('ok.png'))
1128 self.set_yes_button.clicked.connect(lambda: self.main_widget.setCurrentIndex(0))
1129 self.set_yes_button.setToolTip(_('Set {0} to Yes').format(self.col_metadata['name']))
1130 l.insertWidget(1, self.set_yes_button)
1131 if add_edit_tags_button[0]:
1132 self.edit_tags_button = QToolButton(parent)
1133 self.edit_tags_button.setToolTip(_('Open Item editor'))
1134 self.edit_tags_button.setIcon(QIcon.ic('chapters.png'))
1135 self.edit_tags_button.clicked.connect(cast(Any, add_edit_tags_button)[1])
1136 l.insertWidget(1, self.edit_tags_button)
1137 l.insertStretch(2)
1138
1139 def initialize(self, book_id):
1140 self.initial_val = val = self.get_initial_value(book_id)
1141 val = self.normalize_db_val(val)
1142 self.setter(val)
1143
1144 def commit(self, book_id, notify=False):
1145 if not self.a_c_checkbox.isChecked():
1146 return
1147 val = self.gui_val
1148 val = self.normalize_ui_val(val)
1149 db = self.db
1150 assert db is not None
1151 db.set_custom_bulk(book_id, val, num=self.col_id, notify=notify)
1152
1153 def make_widgets(self, parent, main_widget_class):
1154 w = QWidget(parent)
1155 self.widgets = [QLabel(label_string(self.col_metadata['name']), w), w]
1156 l = QHBoxLayout()
1157 l.setContentsMargins(0, 0, 0, 0)
1158 w.setLayout(l)
1159 self.main_widget = main_widget_class(w)
1160 if (hs := self.hierarchy_separator) and hasattr(self.main_widget, 'set_hierarchy_separator'):
1161 self.main_widget.set_hierarchy_separator(hs)
1162 l.addWidget(self.main_widget)
1163 l.setStretchFactor(self.main_widget, 10)
1164 self.a_c_checkbox = QCheckBox(_('Apply changes'), w)
1165 l.addWidget(self.a_c_checkbox)
1166 self.ignore_change_signals = True
1167
1168 # connect to the various changed signals so we can auto-update the
1169 # apply changes checkbox
1170 if hasattr(self.main_widget, 'editTextChanged'):
1171 # editable combobox widgets
1172 self.main_widget.editTextChanged.connect(self.a_c_checkbox_changed)
1173 if hasattr(self.main_widget, 'textChanged'):
1174 # lineEdit widgets
1175 self.main_widget.textChanged.connect(self.a_c_checkbox_changed)
1176 if hasattr(self.main_widget, 'currentIndexChanged'):
1177 # combobox widgets
1178 self.main_widget.currentIndexChanged.connect(self.a_c_checkbox_changed)
1179 if hasattr(self.main_widget, 'valueChanged'):
1180 # spinbox widgets
1181 self.main_widget.valueChanged.connect(self.a_c_checkbox_changed)
1182 if hasattr(self.main_widget, 'dateTimeChanged'):
1183 # dateEdit widgets
1184 self.main_widget.dateTimeChanged.connect(self.a_c_checkbox_changed)
1185
1186 def a_c_checkbox_changed(self):
1187 if not self.ignore_change_signals:
1188 self.a_c_checkbox.setChecked(True)
1189
1190
1191 class BulkBool(BulkBase, Bool):
1192 def get_initial_value(self, book_ids):
1193 value = None
1194 db = self.db
1195 assert db is not None
1196 for book_id in book_ids:
1197 val = db.get_custom(book_id, num=self.col_id, index_is_id=True)
1198 if not db.new_api.pref('bools_are_tristate') and val is None:
1199 val = False
1200 if value is not None and value != val:
1201 return None
1202 value = val
1203 return value
1204
1205 def setup_ui(self, parent):
1206 self.make_widgets(parent, QComboBox)
1207 items = [_('Yes'), _('No')]
1208 db = self.db
1209 assert db is not None
1210 self.bools_are_tristate = db.new_api.pref('bools_are_tristate')
1211 if not self.bools_are_tristate:
1212 items.append('')
1213 else:
1214 items.append(_('Undefined'))
1215 icons = ['ok.png', 'list_remove.png', 'blank.png']
1216 self.main_widget.blockSignals(True)
1217 for icon, text in zip(icons, items):
1218 self.main_widget.addItem(QIcon.ic(icon), text)
1219 self.main_widget.blockSignals(False)
1220 self.finish_ui_setup(parent, is_bool=True)
1221
1222 def set_to_undefined(self):
1223 # Only called if bools are tristate
1224 self.main_widget.setCurrentIndex(2)
1225
1226 def getter(self):
1227 val = self.main_widget.currentIndex()
1228 if not self.bools_are_tristate:
1229 return {2: False, 1: False, 0: True}[val]
1230 else:
1231 return {2: None, 1: False, 0: True}[val]
1232
1233 def setter(self, val):
1234 val = {None: 2, False: 1, True: 0}[val]
1235 self.main_widget.setCurrentIndex(val)
1236 self.ignore_change_signals = False
1237
1238 def commit(self, book_id, notify=False):
1239 if not self.a_c_checkbox.isChecked():
1240 return
1241 val = self.gui_val
1242 val = self.normalize_ui_val(val)
1243 if not self.bools_are_tristate and val is None:
1244 val = False
1245 db = self.db
1246 assert db is not None
1247 db.set_custom_bulk(book_id, val, num=self.col_id, notify=notify)
1248
1249 def a_c_checkbox_changed(self):
1250 if not self.ignore_change_signals:
1251 if not self.bools_are_tristate and self.main_widget.currentIndex() == 2:
1252 self.a_c_checkbox.setChecked(False)
1253 else:
1254 self.a_c_checkbox.setChecked(True)
1255
1256
1257 class BulkInt(BulkBase):
1258 def setup_ui(self, parent):
1259 self.make_widgets(parent, ClearingSpinBox)
1260 self.main_widget.setRange(-1000000, 100000000)
1261 self.finish_ui_setup(parent)
1262
1263 def finish_ui_setup(
1264 self,
1265 parent,
1266 edit_widget: bool = False,
1267 add_edit_tags_button: tuple[bool, Callable] | tuple[bool] = (False,),
1268 is_bool: bool = False,
1269 ):
1270 BulkBase.finish_ui_setup(self, parent)
1271 self.main_widget.setSpecialValueText(_('Undefined'))
1272 self.main_widget.setSingleStep(1)
1273 self.main_widget.valueChanged.connect(self.valueChanged)
1274
1275 def setter(self, val):
1276 if val is None:
1277 val = self.main_widget.minimum()
1278 self.main_widget.setValue(val)
1279 self.ignore_change_signals = False
1280 self.was_none = val == self.main_widget.minimum()
1281
1282 def getter(self):
1283 val = self.main_widget.value()
1284 if val == self.main_widget.minimum():
1285 val = None
1286 return val
1287
1288 def valueChanged(self, to_what):
1289 if self.was_none and to_what == -999999:
1290 self.setter(0)
1291 self.was_none = to_what == self.main_widget.minimum()
1292
1293 def set_to_undefined(self):
1294 self.main_widget.setValue(-1000000)
1295
1296
1297 class BulkFloat(BulkInt):
1298 def setup_ui(self, parent):
1299 self.make_widgets(parent, ClearingDoubleSpinBox)
1300 self.main_widget.setRange(-1000000.0, float(100000000))
1301 self.main_widget.setDecimals(int(self.col_metadata['display'].get('decimals', 2)))
1302 self.finish_ui_setup(parent)
1303
1304 def set_to_undefined(self):
1305 self.main_widget.setValue(-1000000.0)
1306
1307
1308 class BulkRating(BulkBase):
1309 def setup_ui(self, parent):
1310 allow_half_stars = self.col_metadata['display'].get('allow_half_stars', False)
1311 self.make_widgets(parent, partial(RatingEditor, is_half_star=allow_half_stars))
1312 self.finish_ui_setup(parent)
1313
1314 def set_to_undefined(self):
1315 self.main_widget.setCurrentIndex(0)
1316
1317 def setter(self, val):
1318 val = max(0, min(int(val or 0), 10))
1319 self.main_widget.rating_value = val
1320 self.ignore_change_signals = False
1321
1322 def getter(self):
1323 return self.main_widget.rating_value or None
1324
1325
1326 class BulkDateTime(BulkBase):
1327 def setup_ui(self, parent):
1328 cm = self.col_metadata
1329 self.make_widgets(parent, DateTimeEdit)
1330 widgets = self.widgets
1331 assert widgets is not None
1332 l = widgets[1].layout()
1333 assert isinstance(l, QHBoxLayout)
1334 self.today_button = QToolButton(parent)
1335 self.today_button.setText(_('Today'))
1336 l.insertWidget(1, self.today_button)
1337 self.clear_button = QToolButton(parent)
1338 self.clear_button.setIcon(QIcon.ic('trash.png'))
1339 self.clear_button.setToolTip(_('Clear {0}').format(self.col_metadata['name']))
1340 l.insertWidget(2, self.clear_button)
1341 l.insertStretch(3)
1342
1343 w = self.main_widget
1344 format_ = cm['display'].get('date_format', '')
1345 if not format_:
1346 format_ = 'dd MMM yyyy'
1347 elif format_ == 'iso':
1348 format_ = internal_iso_format_string()
1349 w.setDisplayFormat(format_)
1350 w.setCalendarPopup(True)
1351 w.setMinimumDateTime(UNDEFINED_QDATETIME)
1352 w.setSpecialValueText(_('Undefined'))
1353 self.today_button.clicked.connect(w.set_to_today)
1354 self.clear_button.clicked.connect(w.set_to_clear)
1355
1356 def setter(self, val):
1357 if val is None:
1358 val = self.main_widget.minimumDateTime()
1359 else:
1360 val = qt_from_dt(val)
1361 self.main_widget.setDateTime(val)
1362 self.ignore_change_signals = False
1363
1364 def getter(self):
1365 val = self.main_widget.dateTime()
1366 if is_date_undefined(val):
1367 val = None
1368 else:
1369 val = qt_to_dt(val)
1370 return val
1371
1372 def normalize_db_val(self, val):
1373 return as_local_time(val) if val is not None else None
1374
1375 def normalize_ui_val(self, val):
1376 return as_utc(val) if val is not None else None
1377
1378
1379 class BulkSeries(BulkBase):
1380 def setup_ui(self, parent):
1381 self.make_widgets(parent, partial(EditWithComplete, sort_func=title_sort))
1382 db = self.db
1383 assert db is not None
1384 values = self.all_values = list(db.all_custom(num=self.col_id))
1385 values.sort(key=sort_key)
1386 self.main_widget.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon)
1387 self.main_widget.setMinimumContentsLength(25)
1388 widgets = self.widgets
1389 assert widgets is not None
1390 widgets.append(QLabel('', parent))
1391 w = QWidget(parent)
1392 layout = QHBoxLayout(w)
1393 layout.setContentsMargins(0, 0, 0, 0)
1394 self.remove_series = QCheckBox(parent)
1395 self.remove_series.setText(_('Clear series'))
1396 layout.addWidget(self.remove_series)
1397 self.idx_widget = QCheckBox(parent)
1398 self.idx_widget.setText(_('Automatically number books'))
1399 self.idx_widget.setToolTip(
1400 '<p>'
1401 + _(
1402 'If not checked, the series number for the books will be set to 1. '
1403 'If checked, selected books will be automatically numbered, '
1404 'in the order you selected them. So if you selected '
1405 'Book A and then Book B, Book A will have series number 1 '
1406 'and Book B series number 2.'
1407 )
1408 + '</p>'
1409 )
1410 layout.addWidget(self.idx_widget)
1411 self.force_number = QCheckBox(parent)
1412 self.force_number.setText(_('Force numbers to start with '))
1413 self.force_number.setToolTip(
1414 '<p>'
1415 + _(
1416 'Series will normally be renumbered from the highest '
1417 'number in the database for that series. Checking this '
1418 'box will tell calibre to start numbering from the value '
1419 'in the box'
1420 )
1421 + '</p>'
1422 )
1423 layout.addWidget(self.force_number)
1424 self.series_start_number = ClearingDoubleSpinBox(parent)
1425 self.series_start_number.setMinimum(0.0)
1426 self.series_start_number.setMaximum(9999999.0)
1427 self.series_start_number.setProperty('value', 1.0)
1428 layout.addWidget(self.series_start_number)
1429 self.series_increment = ClearingDoubleSpinBox(parent)
1430 self.series_increment.setMinimum(0.00)
1431 self.series_increment.setMaximum(99999.0)
1432 self.series_increment.setProperty('value', 1.0)
1433 self.series_increment.setToolTip(
1434 '<p>' + _('The amount by which to increment the series number for successive books. Only applicable when using force series numbers.') + '</p>'
1435 )
1436 self.series_increment.setPrefix('+')
1437 layout.addWidget(self.series_increment)
1438 layout.addItem(QSpacerItem(20, 10, QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum))
1439 widgets.append(w)
1440 self.idx_widget.stateChanged.connect(self.a_c_checkbox_changed)
1441 self.force_number.stateChanged.connect(self.a_c_checkbox_changed)
1442 self.series_start_number.valueChanged.connect(self.a_c_checkbox_changed)
1443 self.series_increment.valueChanged.connect(self.a_c_checkbox_changed)
1444 self.remove_series.stateChanged.connect(self.a_c_checkbox_changed)
1445 self.main_widget
1446 self.ignore_change_signals = False
1447
1448 def a_c_checkbox_changed(self):
1449 def disable_numbering_checkboxes(idx_widget_enable):
1450 if idx_widget_enable:
1451 self.idx_widget.setEnabled(True)
1452 else:
1453 self.idx_widget.setChecked(False)
1454 self.idx_widget.setEnabled(False)
1455 self.force_number.setChecked(False)
1456 self.force_number.setEnabled(False)
1457 self.series_start_number.setEnabled(False)
1458 self.series_increment.setEnabled(False)
1459
1460 if self.ignore_change_signals:
1461 return
1462 self.ignore_change_signals = True
1463 apply_changes = False
1464 if self.remove_series.isChecked():
1465 self.main_widget.setText('')
1466 self.main_widget.setEnabled(False)
1467 disable_numbering_checkboxes(idx_widget_enable=False)
1468 apply_changes = True
1469 elif self.main_widget.text():
1470 self.remove_series.setEnabled(False)
1471 self.idx_widget.setEnabled(True)
1472 apply_changes = True
1473 else: # no text, no clear. Basically reinitialize
1474 self.main_widget.setEnabled(True)
1475 self.remove_series.setEnabled(True)
1476 disable_numbering_checkboxes(idx_widget_enable=False)
1477 apply_changes = False
1478
1479 self.force_number.setEnabled(self.idx_widget.isChecked())
1480 self.series_start_number.setEnabled(self.force_number.isChecked())
1481 self.series_increment.setEnabled(self.force_number.isChecked())
1482
1483 self.ignore_change_signals = False
1484 self.a_c_checkbox.setChecked(apply_changes)
1485
1486 def initialize(self, book_id):
1487 self.idx_widget.setChecked(False)
1488 self.main_widget.set_separator(None)
1489 self.main_widget.update_items_cache(self.all_values)
1490 self.main_widget.setEditText('')
1491 self.a_c_checkbox.setChecked(False)
1492
1493 def getter(self):
1494 n = str(self.main_widget.currentText()).strip()
1495 autonumber = self.idx_widget.isChecked()
1496 force = self.force_number.isChecked()
1497 start = self.series_start_number.value()
1498 remove = self.remove_series.isChecked()
1499 increment = self.series_increment.value()
1500 return n, autonumber, force, start, remove, increment
1501
1502 def commit(self, book_id, notify=False):
1503 if not self.a_c_checkbox.isChecked():
1504 return
1505 val, update_indices, force_start, at_value, clear, increment = self.gui_val
1506 val = None if clear else self.normalize_ui_val(val)
1507 db = self.db
1508 assert db is not None
1509 if clear or val != '':
1510 extras = []
1511 for bid in book_id:
1512 if clear:
1513 extras.append(None)
1514 continue
1515 if update_indices:
1516 if force_start:
1517 s_index = at_value
1518 at_value += increment
1519 elif tweaks['series_index_auto_increment'] != 'const':
1520 s_index = db.get_next_cc_series_num_for(val, num=self.col_id)
1521 else:
1522 s_index = 1.0
1523 else:
1524 s_index = db.get_custom_extra(bid, num=self.col_id, index_is_id=True)
1525 extras.append(s_index)
1526 db.set_custom_bulk(book_id, val, extras=extras, num=self.col_id, notify=notify)
1527
1528
1529 class BulkEnumeration(BulkBase, Enumeration):
1530 def get_initial_value(self, book_ids):
1531 value = None
1532 first = True
1533 dialog_shown = False
1534 db = self.db
1535 assert db is not None
1536 for book_id in book_ids:
1537 val = db.get_custom(book_id, num=self.col_id, index_is_id=True)
1538 if val and val not in self.col_metadata['display']['enum_values']:
1539 if not dialog_shown:
1540 error_dialog(
1541 self.parent,
1542 '',
1543 _('The enumeration "{0}" contains invalid values that will not appear in the list').format(self.col_metadata['name']),
1544 show=True,
1545 show_copy_button=False,
1546 )
1547 dialog_shown = True
1548 if first:
1549 value = val
1550 first = False
1551 elif value != val:
1552 value = None
1553 if not value:
1554 self.ignore_change_signals = False
1555 return value
1556
1557 def setup_ui(self, parent):
1558 self.parent = parent
1559 self.make_widgets(parent, QComboBox)
1560 self.finish_ui_setup(parent)
1561 vals = self.col_metadata['display']['enum_values']
1562 self.main_widget.blockSignals(True)
1563 self.main_widget.addItem('')
1564 self.main_widget.addItems(vals)
1565 self.main_widget.blockSignals(False)
1566
1567 def set_to_undefined(self):
1568 self.main_widget.setCurrentIndex(0)
1569
1570 def getter(self):
1571 return str(self.main_widget.currentText())
1572
1573 def setter(self, val):
1574 if val is None:
1575 self.main_widget.setCurrentIndex(0)
1576 else:
1577 self.main_widget.setCurrentIndex(self.main_widget.findText(val))
1578 self.ignore_change_signals = False
1579
1580
1581 class RemoveTags(QWidget):
1582 def __init__(self, parent, values):
1583 QWidget.__init__(self, parent)
1584 layout = QHBoxLayout()
1585 layout.setSpacing(5)
1586 layout.setContentsMargins(0, 0, 0, 0)
1587
1588 self.tags_box = EditWithComplete(parent)
1589 self.tags_box.update_items_cache(values)
1590 layout.addWidget(self.tags_box, stretch=3)
1591 self.remove_tags_button = QToolButton(parent)
1592 self.remove_tags_button.setToolTip(_('Open Item editor'))
1593 self.remove_tags_button.setIcon(QIcon.ic('chapters.png'))
1594 layout.addWidget(self.remove_tags_button)
1595 self.checkbox = QCheckBox(_('Remove all tags'), parent)
1596 layout.addWidget(self.checkbox)
1597 layout.addStretch(1)
1598 self.setLayout(layout)
1599 self.checkbox.stateChanged[int].connect(self.box_touched)
1600
1601 def box_touched(self, state):
1602 if state:
1603 self.tags_box.setText('')
1604 self.tags_box.setEnabled(False)
1605 else:
1606 self.tags_box.setEnabled(True)
1607
1608
1609 class BulkText(BulkBase):
1610 def setup_ui(self, parent):
1611 db = self.db
1612 assert db is not None
1613 values = self.all_values = list(db.all_custom(num=self.col_id))
1614 values.sort(key=sort_key)
1615 is_tags = False
1616 if self.col_metadata['is_multiple']:
1617 is_tags = not self.col_metadata['display'].get('is_names', False)
1618 self.make_widgets(parent, EditWithComplete)
1619 self.main_widget.setSizePolicy(QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Preferred)
1620 self.adding_widget = self.main_widget
1621
1622 if is_tags:
1623 w = RemoveTags(parent, values)
1624 w.remove_tags_button.clicked.connect(self.edit_remove)
1625 l = QLabel(label_string(self.col_metadata['name']) + ': ' + _('tags to remove'), parent)
1626 tt = get_tooltip(self.col_metadata) + ': ' + _('tags to remove')
1627 l.setToolTip(tt)
1628 bulk_text_widgets = self.widgets
1629 assert bulk_text_widgets is not None
1630 bulk_text_widgets.append(l)
1631 w.setToolTip(tt)
1632 bulk_text_widgets.append(w)
1633 self.removing_widget = w
1634 self.main_widget.set_separator(',')
1635 w.tags_box.textChanged.connect(self.a_c_checkbox_changed)
1636 w.checkbox.stateChanged.connect(self.a_c_checkbox_changed)
1637 else:
1638 self.main_widget.set_separator('&')
1639 self.main_widget.set_space_before_sep(True)
1640 self.main_widget.set_add_separator(tweaks['authors_completer_append_separator'])
1641 else:
1642 self.make_widgets(parent, EditWithComplete)
1643 self.main_widget.set_separator(None)
1644 self.main_widget.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon)
1645 self.main_widget.setMinimumContentsLength(25)
1646 self.ignore_change_signals = False
1647 self.parent = parent
1648 self.finish_ui_setup(parent, add_edit_tags_button=(is_tags, self.edit_add))
1649
1650 def set_to_undefined(self):
1651 self.main_widget.clearEditText()
1652
1653 def initialize(self, book_id):
1654 self.main_widget.update_items_cache(self.all_values)
1655 if not self.col_metadata['is_multiple']:
1656 val = self.get_initial_value(book_id)
1657 self.initial_val = val = self.normalize_db_val(val)
1658 self.ignore_change_signals = True
1659 self.main_widget.blockSignals(True)
1660 self.main_widget.setText(val)
1661 self.main_widget.blockSignals(False)
1662 self.ignore_change_signals = False
1663
1664 def commit(self, book_id, notify=False):
1665 if not self.a_c_checkbox.isChecked():
1666 return
1667 db = self.db
1668 assert db is not None
1669 if self.col_metadata['is_multiple']:
1670 ism = self.col_metadata['multiple_seps']
1671 if self.col_metadata['display'].get('is_names', False):
1672 val = self.gui_val
1673 add = [v.strip() for v in val.split(ism['ui_to_list']) if v.strip()]
1674 db.set_custom_bulk(book_id, add, num=self.col_id)
1675 else:
1676 remove_all, adding, rtext = self.gui_val
1677 remove = set()
1678 if remove_all:
1679 remove = set(db.all_custom(num=self.col_id))
1680 else:
1681 txt = rtext
1682 if txt:
1683 remove = {v.strip() for v in txt.split(ism['ui_to_list'])}
1684 txt = adding
1685 if txt:
1686 add = {v.strip() for v in txt.split(ism['ui_to_list'])}
1687 else:
1688 add = set()
1689 db.set_custom_bulk_multiple(book_id, add=add, remove=remove, num=self.col_id)
1690 else:
1691 val = self.gui_val
1692 val = self.normalize_ui_val(val)
1693 db.set_custom_bulk(book_id, val, num=self.col_id, notify=notify)
1694
1695 def getter(self):
1696 if self.col_metadata['is_multiple']:
1697 if not self.col_metadata['display'].get('is_names', False):
1698 return (
1699 self.removing_widget.checkbox.isChecked(),
1700 str(self.adding_widget.text()),
1701 str(self.removing_widget.tags_box.text()),
1702 )
1703 return str(self.adding_widget.text())
1704 val = str(self.main_widget.currentText()).strip()
1705 if not val:
1706 val = None
1707 return val
1708
1709 def edit_remove(self):
1710 self.edit(widget=self.removing_widget.tags_box)
1711
1712 def edit_add(self):
1713 self.edit(widget=self.main_widget)
1714
1715 def edit(self, widget=None):
1716 if widget is None:
1717 return
1718 if widget.text():
1719 d = _save_dialog(
1720 self.parent,
1721 _('Values changed'),
1722 _('You have entered values. In order to use this editor you must first discard them. Discard the values?'),
1723 )
1724 if d in (QMessageBox.StandardButton.Cancel, QMessageBox.StandardButton.No):
1725 return
1726 widget.setText('')
1727 d = TagEditor(self.parent, self.db, key=('#' + self.col_metadata['label']))
1728 if d.exec() == QDialog.DialogCode.Accepted:
1729 val = d.tags
1730 if not val:
1731 val = []
1732 widget.setText(self.col_metadata['multiple_seps']['list_to_ui'].join(val))
1733
1734
1735 bulk_widgets = {
1736 'bool': BulkBool,
1737 'rating': BulkRating,
1738 'int': BulkInt,
1739 'float': BulkFloat,
1740 'datetime': BulkDateTime,
1741 'text': BulkText,
1742 'series': BulkSeries,
1743 'enumeration': BulkEnumeration,
1744 }