| 1 |
# License: GPLv3 Copyright: 2008, Kovid Goyal <kovid at kovidgoyal.net> |
| 2 |
|
| 3 |
"""The GUI""" |
| 4 |
|
| 5 |
import glob |
| 6 |
import os |
| 7 |
import queue |
| 8 |
import signal |
| 9 |
import sys |
| 10 |
import threading |
| 11 |
from contextlib import contextmanager, suppress |
| 12 |
from functools import lru_cache |
| 13 |
from threading import Lock, RLock |
| 14 |
from typing import cast |
| 15 |
|
| 16 |
from qt.core import ( |
| 17 |
QApplication, |
| 18 |
QBuffer, |
| 19 |
QByteArray, |
| 20 |
QColor, |
| 21 |
QDateTime, |
| 22 |
QDesktopServices, |
| 23 |
QDialog, |
| 24 |
QDialogButtonBox, |
| 25 |
QEvent, |
| 26 |
QFile, |
| 27 |
QFileDialog, |
| 28 |
QFileIconProvider, |
| 29 |
QFileInfo, |
| 30 |
QFont, |
| 31 |
QFontDatabase, |
| 32 |
QFontInfo, |
| 33 |
QFontMetrics, |
| 34 |
QGuiApplication, |
| 35 |
QIcon, |
| 36 |
QImageReader, |
| 37 |
QImageWriter, |
| 38 |
QIODevice, |
| 39 |
QLocale, |
| 40 |
QNetworkProxyFactory, |
| 41 |
QObject, |
| 42 |
QPainterPath, |
| 43 |
QPalette, |
| 44 |
QRectF, |
| 45 |
QResource, |
| 46 |
QSettings, |
| 47 |
QSocketNotifier, |
| 48 |
QStringListModel, |
| 49 |
Qt, |
| 50 |
QThread, |
| 51 |
QTimer, |
| 52 |
QToolBar, |
| 53 |
QToolButton, |
| 54 |
QUrl, |
| 55 |
QWidget, |
| 56 |
pyqtSignal, |
| 57 |
pyqtSlot, |
| 58 |
sip, |
| 59 |
) |
| 60 |
|
| 61 |
import calibre.gui2.pyqt6_compat as pqc |
| 62 |
from calibre import as_unicode, prints, timed_print |
| 63 |
from calibre.constants import ( |
| 64 |
DEBUG, |
| 65 |
__version__, |
| 66 |
builtin_colors_dark, |
| 67 |
builtin_colors_light, |
| 68 |
config_dir, |
| 69 |
is_running_from_develop, |
| 70 |
isbsd, |
| 71 |
isfrozen, |
| 72 |
islinux, |
| 73 |
ismacos, |
| 74 |
iswindows, |
| 75 |
isworker, |
| 76 |
isxp, |
| 77 |
plugins_loc, |
| 78 |
sanitize_env_vars, |
| 79 |
) |
| 80 |
from calibre.constants import __appname__ as APP_UID |
| 81 |
from calibre.ebooks.metadata import MetaInformation |
| 82 |
from calibre.gui2.geometry import geometry_for_restore_as_dict |
| 83 |
from calibre.gui2.linux_file_dialogs import check_for_linux_native_dialogs, linux_native_dialog |
| 84 |
from calibre.gui2.palette import PaletteManager |
| 85 |
from calibre.gui2.qt_file_dialogs import FileDialog |
| 86 |
from calibre.ptempfile import base_dir |
| 87 |
from calibre.utils.config import Config, ConfigProxy, JSONConfig, dynamic |
| 88 |
from calibre.utils.config_base import tweaks |
| 89 |
from calibre.utils.date import UNDEFINED_DATE |
| 90 |
from calibre.utils.file_type_icons import EXT_MAP |
| 91 |
from calibre.utils.img import set_image_allocation_limit |
| 92 |
from calibre.utils.localization import _, get_lang, install_qt_translator |
| 93 |
from calibre.utils.resources import get_image_path as I |
| 94 |
from calibre.utils.resources import get_path as P |
| 95 |
from calibre.utils.resources import user_dir |
| 96 |
from calibre_extensions.progress_indicator import icon_from_name, icon_from_paths, set_icon_theme |
| 97 |
|
| 98 |
del pqc, geometry_for_restore_as_dict |
| 99 |
timed_print # for plugin compat |
| 100 |
NO_URL_FORMATTING = QUrl.UrlFormattingOption.None_ |
| 101 |
BOOK_DETAILS_DISPLAY_DEBOUNCE_DELAY = 100 # 100 ms is threshold for human visual response |
| 102 |
|
| 103 |
|
| 104 |
class IconResourceManager: |
| 105 |
def __init__(self): |
| 106 |
self.override_icon_path = None |
| 107 |
self.initialized = False |
| 108 |
self.dark_theme_name = self.default_dark_theme_name = 'calibre-default-dark' |
| 109 |
self.light_theme_name = self.default_light_theme_name = 'calibre-default-light' |
| 110 |
self.user_any_theme_name = self.user_dark_theme_name = self.user_light_theme_name = None |
| 111 |
self.registered_user_resource_files = () |
| 112 |
self.icon_cache = {} |
| 113 |
|
| 114 |
def user_theme_resource_file(self, which): |
| 115 |
return os.path.join(config_dir, f'icons-{which}.rcc') |
| 116 |
|
| 117 |
def remove_user_theme(self, which): |
| 118 |
path = self.user_theme_resource_file(which) |
| 119 |
if path in self.registered_user_resource_files: |
| 120 |
QResource.unregisterResource(path) |
| 121 |
self.registered_user_resource_files = tuple(x for x in self.registered_user_resource_files if x != path) |
| 122 |
with suppress(FileNotFoundError): |
| 123 |
os.remove(path) |
| 124 |
|
| 125 |
def register_user_resource_files(self): |
| 126 |
self.user_icon_theme_metadata.cache_clear() |
| 127 |
for x in self.registered_user_resource_files: |
| 128 |
QResource.unregisterResource(x) |
| 129 |
r = [] |
| 130 |
self.user_any_theme_name = self.user_dark_theme_name = self.user_light_theme_name = None |
| 131 |
for x in ('any', 'light', 'dark'): |
| 132 |
path = self.user_theme_resource_file(x) |
| 133 |
if os.path.exists(path): |
| 134 |
QResource.registerResource(path) |
| 135 |
r.append(path) |
| 136 |
setattr(self, f'user_{x}_theme_name', f'calibre-user-{x}') |
| 137 |
self.registered_user_resource_files = tuple(r) |
| 138 |
any_dark = (self.user_any_theme_name + '-dark') if self.user_any_theme_name else '' # ty: ignore[redundant-condition] |
| 139 |
any_light = (self.user_any_theme_name + '-light') if self.user_any_theme_name else '' # ty: ignore[redundant-condition] |
| 140 |
self.dark_theme_name = self.user_dark_theme_name or any_dark or self.default_dark_theme_name |
| 141 |
self.light_theme_name = self.user_light_theme_name or any_light or self.default_light_theme_name |
| 142 |
# self.dump_available_icon_resource_names() |
| 143 |
|
| 144 |
@lru_cache(maxsize=4) |
| 145 |
def user_icon_theme_metadata(self, which): |
| 146 |
path = self.user_theme_resource_file(which) |
| 147 |
if path not in self.registered_user_resource_files: |
| 148 |
return {} |
| 149 |
f = QFile(f':/icons/calibre-user-{which}/metadata.json') |
| 150 |
if not f.open(QIODevice.OpenModeFlag.ReadOnly): |
| 151 |
return {} |
| 152 |
try: |
| 153 |
import json |
| 154 |
|
| 155 |
return json.loads(bytes(f.readAll())) |
| 156 |
finally: |
| 157 |
f.close() |
| 158 |
|
| 159 |
@property |
| 160 |
def active_user_theme_metadata(self): |
| 161 |
q = QIcon.themeName() |
| 162 |
if q in (self.default_dark_theme_name, self.default_light_theme_name): |
| 163 |
return {} |
| 164 |
if q == self.user_dark_theme_name: |
| 165 |
return self.user_icon_theme_metadata('dark') |
| 166 |
if q == self.user_light_theme_name: |
| 167 |
return self.user_icon_theme_metadata('light') |
| 168 |
return self.user_icon_theme_metadata('any') |
| 169 |
|
| 170 |
@property |
| 171 |
def user_theme_title(self): |
| 172 |
return self.active_user_theme_metadata.get('title', _('Default icons')) |
| 173 |
|
| 174 |
@property |
| 175 |
def user_theme_name(self): |
| 176 |
return self.active_user_theme_metadata.get('name', 'default') |
| 177 |
|
| 178 |
def dump_available_icon_resource_names(self): |
| 179 |
from qt.core import QDirIterator |
| 180 |
|
| 181 |
it = QDirIterator(':', QDirIterator.IteratorFlag.Subdirectories) |
| 182 |
while it.hasNext(): |
| 183 |
val = it.next() |
| 184 |
if val.startswith(':/icons/calibre-'): |
| 185 |
print(val) |
| 186 |
|
| 187 |
def initialize(self): |
| 188 |
if self.initialized: |
| 189 |
return |
| 190 |
self.icon_cache = {} |
| 191 |
self.initialized = True |
| 192 |
QResource.registerResource(P('icons.rcc', allow_user_override=False)) |
| 193 |
self.override_icon_path = None |
| 194 |
q = os.path.join(user_dir, 'images') |
| 195 |
items = [] |
| 196 |
with suppress(Exception): |
| 197 |
items = os.listdir(q) |
| 198 |
if items: |
| 199 |
self.override_icon_path = q |
| 200 |
legacy_theme_metadata = os.path.join(q, 'icon-theme.json') |
| 201 |
if os.path.exists(legacy_theme_metadata): |
| 202 |
self.migrate_legacy_icon_theme(legacy_theme_metadata) |
| 203 |
items = os.listdir(q) |
| 204 |
self.override_items = {'': frozenset(items)} |
| 205 |
for k in ('devices', 'mimetypes', 'plugins'): |
| 206 |
items = frozenset() |
| 207 |
with suppress(OSError): |
| 208 |
items = frozenset(os.listdir(os.path.join(self.override_icon_path, k))) |
| 209 |
self.override_items[k] = items |
| 210 |
self.register_user_resource_files() |
| 211 |
|
| 212 |
def migrate_legacy_icon_theme(self, legacy_theme_metadata): |
| 213 |
import shutil |
| 214 |
|
| 215 |
from calibre.utils.rcc import compile_icon_dir_as_themes |
| 216 |
|
| 217 |
images = os.path.dirname(legacy_theme_metadata) |
| 218 |
os.replace(legacy_theme_metadata, os.path.join(images, 'metadata.json')) |
| 219 |
compile_icon_dir_as_themes(images, self.user_theme_resource_file('any'), theme_name='calibre-user-any', inherits='calibre-default') |
| 220 |
for x in os.listdir(images): |
| 221 |
q = os.path.join(images, x) |
| 222 |
if os.path.isdir(q) and q != 'textures': |
| 223 |
shutil.rmtree(q) |
| 224 |
else: |
| 225 |
os.remove(q) |
| 226 |
|
| 227 |
def overriden_icon_paths(self, name: str) -> tuple[str, str, str]: |
| 228 |
either = light = dark = '' |
| 229 |
p: str = self.override_icon_path or '' |
| 230 |
parts = name.replace(os.sep, '/').split('/') |
| 231 |
sq = os.path.join(p, name) |
| 232 |
if len(parts) == 1: |
| 233 |
base, ext = os.path.splitext(parts[0]) |
| 234 |
if os.path.basename(sq) in self.override_items['']: |
| 235 |
either = sq |
| 236 |
if (sq := f'{base}-for-light-theme{ext}') in self.override_items['']: |
| 237 |
light = os.path.join(p, sq) |
| 238 |
if (sq := f'{base}-for-dark-theme{ext}') in self.override_items['']: |
| 239 |
dark = os.path.join(p, sq) |
| 240 |
else: |
| 241 |
subfolder = '/'.join(parts[:-1]) |
| 242 |
entries = self.override_items.get(subfolder) |
| 243 |
if entries is None and p: |
| 244 |
try: |
| 245 |
self.override_items[subfolder] = entries = frozenset(os.listdir(os.path.join(p, subfolder))) |
| 246 |
except OSError: |
| 247 |
self.override_items[subfolder] = entries = frozenset() |
| 248 |
if entries: |
| 249 |
if os.path.basename(sq) in entries: |
| 250 |
either = sq |
| 251 |
base, ext = os.path.splitext(parts[-1]) |
| 252 |
if (sq := f'{base}-for-light-theme{ext}') in entries: |
| 253 |
light = os.path.join(p, subfolder, sq) |
| 254 |
if (sq := f'{base}-for-dark-theme{ext}') in entries: |
| 255 |
dark = os.path.join(p, subfolder, sq) |
| 256 |
return either, light, dark |
| 257 |
|
| 258 |
def cached_icon(self, name=''): |
| 259 |
""" |
| 260 |
Keep these icons in a cache. This is intended to be used in dialogs like |
| 261 |
manage categories where thousands of icon instances can be needed. |
| 262 |
|
| 263 |
It is a new method to avoid breaking QIcon.ic() if names are reused |
| 264 |
in different contexts. It isn't clear if this can ever happen. |
| 265 |
""" |
| 266 |
icon = self.icon_cache.get(name) |
| 267 |
if icon is None: |
| 268 |
icon = self.icon_cache[name] = self(name) |
| 269 |
return icon |
| 270 |
|
| 271 |
def __call__(self, name: str | QIcon | None, fallback: bytes = b'') -> QIcon: |
| 272 |
if isinstance(name, QIcon): |
| 273 |
return name |
| 274 |
if not name: |
| 275 |
return QIcon() |
| 276 |
if os.path.isabs(name): |
| 277 |
return QIcon(name) |
| 278 |
if self.override_icon_path: |
| 279 |
either, light, dark = self.overriden_icon_paths(name) |
| 280 |
if either or light or dark: |
| 281 |
return icon_from_paths(either, light, dark) |
| 282 |
icon_name = name.replace('\\', '__').replace('/', '__') |
| 283 |
ans = icon_from_name(icon_name, fallback) |
| 284 |
return ans |
| 285 |
|
| 286 |
def icon_as_png(self, name, as_bytearray=False, compression_level=0): |
| 287 |
ans = self(name) |
| 288 |
ba = QByteArray() |
| 289 |
if ans.availableSizes(): |
| 290 |
pmap = ans.pixmap(ans.availableSizes()[0]) |
| 291 |
buf = QBuffer(ba) |
| 292 |
buf.open(QIODevice.OpenModeFlag.WriteOnly) |
| 293 |
w = QImageWriter(buf, b'PNG') |
| 294 |
cl = min(9, max(0, compression_level)) |
| 295 |
w.setQuality(10 * (9 - cl)) |
| 296 |
w.setQuality(90) |
| 297 |
w.write(pmap.toImage()) |
| 298 |
return ba if as_bytearray else ba.data() |
| 299 |
|
| 300 |
def set_theme(self): |
| 301 |
self.icon_cache = {} |
| 302 |
is_dark = qapplication_or_fail().is_dark_theme |
| 303 |
set_icon_theme(is_dark, bool(self.user_dark_theme_name), bool(self.user_light_theme_name), bool(self.user_any_theme_name)) |
| 304 |
|
| 305 |
|
| 306 |
icon_resource_manager = IconResourceManager() |
| 307 |
QIcon.ic = icon_resource_manager # type: ignore |
| 308 |
QIcon.icon_as_png = icon_resource_manager.icon_as_png # type: ignore |
| 309 |
QIcon.is_ok = lambda self: not self.isNull() and len(self.availableSizes()) > 0 |
| 310 |
QIcon.cached_icon = icon_resource_manager.cached_icon # type: ignore |
| 311 |
qtb_init = QToolBar.__init__ |
| 312 |
|
| 313 |
|
| 314 |
def configure_toolbar_extension_button(self, parent=None): |
| 315 |
qtb_init(self, parent) |
| 316 |
if teb := self.findChild(QToolButton, name='qt_toolbar_ext_button'): |
| 317 |
teb.setToolTip(_('Show more buttons')) |
| 318 |
|
| 319 |
|
| 320 |
QToolBar.__init__ = configure_toolbar_extension_button # type: ignore |
| 321 |
|
| 322 |
# Setup gprefs {{{ |
| 323 |
gprefs = JSONConfig('gui') |
| 324 |
|
| 325 |
native_menubar_defaults = { |
| 326 |
'action-layout-menubar': ( |
| 327 |
'Add Books', |
| 328 |
'Edit Metadata', |
| 329 |
'Convert Books', |
| 330 |
'Choose Library', |
| 331 |
'Save To Disk', |
| 332 |
'Preferences', |
| 333 |
'Help', |
| 334 |
), |
| 335 |
'action-layout-menubar-device': ( |
| 336 |
'Add Books', |
| 337 |
'Edit Metadata', |
| 338 |
'Convert Books', |
| 339 |
'Location Manager', |
| 340 |
'Send To Device', |
| 341 |
'Save To Disk', |
| 342 |
'Preferences', |
| 343 |
'Help', |
| 344 |
), |
| 345 |
} |
| 346 |
|
| 347 |
|
| 348 |
def create_defs(): |
| 349 |
defs = gprefs.defaults |
| 350 |
if ismacos: |
| 351 |
defs['action-layout-menubar'] = native_menubar_defaults['action-layout-menubar'] |
| 352 |
defs['action-layout-menubar-device'] = native_menubar_defaults['action-layout-menubar-device'] |
| 353 |
defs['action-layout-toolbar'] = ( |
| 354 |
'Add Books', |
| 355 |
'Edit Metadata', |
| 356 |
None, |
| 357 |
'Convert Books', |
| 358 |
'View', |
| 359 |
None, |
| 360 |
'Choose Library', |
| 361 |
'Donate', |
| 362 |
None, |
| 363 |
'Fetch News', |
| 364 |
'Store', |
| 365 |
'Save To Disk', |
| 366 |
'Connect Share', |
| 367 |
None, |
| 368 |
'Remove Books', |
| 369 |
'Tweak ePub', |
| 370 |
) |
| 371 |
defs['action-layout-toolbar-device'] = ( |
| 372 |
'Add Books', |
| 373 |
'Edit Metadata', |
| 374 |
None, |
| 375 |
'Convert Books', |
| 376 |
'View', |
| 377 |
'Send To Device', |
| 378 |
None, |
| 379 |
None, |
| 380 |
'Location Manager', |
| 381 |
None, |
| 382 |
None, |
| 383 |
'Fetch News', |
| 384 |
'Store', |
| 385 |
'Save To Disk', |
| 386 |
'Connect Share', |
| 387 |
None, |
| 388 |
'Remove Books', |
| 389 |
) |
| 390 |
else: |
| 391 |
defs['action-layout-menubar'] = () |
| 392 |
defs['action-layout-menubar-device'] = () |
| 393 |
defs['action-layout-toolbar'] = ( |
| 394 |
'Add Books', |
| 395 |
'Edit Metadata', |
| 396 |
None, |
| 397 |
'Convert Books', |
| 398 |
'View', |
| 399 |
None, |
| 400 |
'Store', |
| 401 |
'Donate', |
| 402 |
'Fetch News', |
| 403 |
'Help', |
| 404 |
None, |
| 405 |
'Preferences', |
| 406 |
'Remove Books', |
| 407 |
'Choose Library', |
| 408 |
'Save To Disk', |
| 409 |
'Connect Share', |
| 410 |
'Tweak ePub', |
| 411 |
) |
| 412 |
defs['action-layout-toolbar-device'] = ( |
| 413 |
'Add Books', |
| 414 |
'Edit Metadata', |
| 415 |
None, |
| 416 |
'Convert Books', |
| 417 |
'View', |
| 418 |
'Send To Device', |
| 419 |
None, |
| 420 |
None, |
| 421 |
'Location Manager', |
| 422 |
None, |
| 423 |
None, |
| 424 |
'Fetch News', |
| 425 |
'Save To Disk', |
| 426 |
'Store', |
| 427 |
'Connect Share', |
| 428 |
None, |
| 429 |
'Remove Books', |
| 430 |
None, |
| 431 |
'Help', |
| 432 |
'Preferences', |
| 433 |
) |
| 434 |
|
| 435 |
defs['action-layout-toolbar-child'] = () |
| 436 |
|
| 437 |
defs['action-layout-searchbar'] = ('Saved searches',) |
| 438 |
|
| 439 |
defs['action-layout-context-menu'] = ( |
| 440 |
'Edit Metadata', |
| 441 |
'Send To Device', |
| 442 |
'Save To Disk', |
| 443 |
'Connect Share', |
| 444 |
'Copy To Library', |
| 445 |
None, |
| 446 |
'Convert Books', |
| 447 |
'View', |
| 448 |
'Open Folder', |
| 449 |
'Show Book Details', |
| 450 |
'Similar Books', |
| 451 |
'Tweak ePub', |
| 452 |
None, |
| 453 |
'Remove Books', |
| 454 |
) |
| 455 |
|
| 456 |
defs['action-layout-context-menu-split'] = ( |
| 457 |
'Edit Metadata', |
| 458 |
'Send To Device', |
| 459 |
'Save To Disk', |
| 460 |
'Connect Share', |
| 461 |
'Copy To Library', |
| 462 |
None, |
| 463 |
'Convert Books', |
| 464 |
'View', |
| 465 |
'Open Folder', |
| 466 |
'Show Book Details', |
| 467 |
'Similar Books', |
| 468 |
'Tweak ePub', |
| 469 |
None, |
| 470 |
'Remove Books', |
| 471 |
) |
| 472 |
|
| 473 |
defs['action-layout-context-menu-device'] = ( |
| 474 |
'View', |
| 475 |
'Save To Disk', |
| 476 |
None, |
| 477 |
'Remove Books', |
| 478 |
None, |
| 479 |
'Add To Library', |
| 480 |
'Edit Collections', |
| 481 |
'Match Books', |
| 482 |
'Show Matched Book In Library', |
| 483 |
) |
| 484 |
|
| 485 |
defs['action-layout-context-menu-cover-browser'] = ( |
| 486 |
'Edit Metadata', |
| 487 |
'Send To Device', |
| 488 |
'Save To Disk', |
| 489 |
'Connect Share', |
| 490 |
'Copy To Library', |
| 491 |
None, |
| 492 |
'Convert Books', |
| 493 |
'View', |
| 494 |
'Open Folder', |
| 495 |
'Show Book Details', |
| 496 |
'Similar Books', |
| 497 |
'Tweak ePub', |
| 498 |
None, |
| 499 |
'Remove Books', |
| 500 |
None, |
| 501 |
'Autoscroll Books', |
| 502 |
) |
| 503 |
|
| 504 |
defs['show_splash_screen'] = True |
| 505 |
defs['toolbar_icon_size'] = 'medium' |
| 506 |
defs['automerge'] = 'ignore' |
| 507 |
defs['toolbar_text'] = 'always' |
| 508 |
defs['font'] = None |
| 509 |
defs['tags_browser_partition_method'] = 'first letter' |
| 510 |
defs['tags_browser_collapse_at'] = 100 |
| 511 |
defs['tags_browser_collapse_fl_at'] = 5 |
| 512 |
defs['tag_browser_dont_collapse'] = [] |
| 513 |
defs['edit_metadata_single_layout'] = 'default' |
| 514 |
defs['preserve_date_on_ctl'] = True |
| 515 |
defs['manual_add_auto_convert'] = False |
| 516 |
defs['auto_convert_same_fmt'] = False |
| 517 |
defs['cb_fullscreen'] = False |
| 518 |
defs['worker_max_time'] = 0 |
| 519 |
defs['show_files_after_save'] = True |
| 520 |
defs['auto_add_path'] = None |
| 521 |
defs['auto_add_check_for_duplicates'] = False |
| 522 |
defs['blocked_auto_formats'] = [] |
| 523 |
defs['auto_add_auto_convert'] = True |
| 524 |
defs['auto_add_everything'] = False |
| 525 |
defs['ui_style'] = 'calibre' if iswindows or ismacos else 'system' |
| 526 |
defs['color_palette'] = 'system' |
| 527 |
defs['tag_browser_old_look'] = False |
| 528 |
defs['tag_browser_hide_empty_categories'] = False |
| 529 |
defs['tag_browser_always_autocollapse'] = False |
| 530 |
defs['tag_browser_restore_tree_expansion'] = False |
| 531 |
defs['tag_browser_allow_keyboard_focus'] = False |
| 532 |
defs['book_list_tooltips'] = True |
| 533 |
defs['show_layout_buttons'] = False |
| 534 |
# defs['show_sb_preference_button'] = False |
| 535 |
defs['show_sb_all_actions_button'] = False |
| 536 |
defs['bd_show_cover'] = True |
| 537 |
defs['bd_overlay_cover_size'] = False |
| 538 |
defs['tags_browser_category_icons'] = {} |
| 539 |
defs['tags_browser_value_icons'] = {} |
| 540 |
defs['cover_browser_reflections'] = True |
| 541 |
defs['cover_browser_max_font_size'] = 11 |
| 542 |
defs['book_list_extra_row_spacing'] = 0 |
| 543 |
defs['refresh_book_list_on_bulk_edit'] = True |
| 544 |
defs['cover_grid_width'] = 0 |
| 545 |
defs['cover_grid_height'] = 0 |
| 546 |
defs['cover_grid_spacing'] = 0 |
| 547 |
defs['cover_grid_background'] = { |
| 548 |
'migrated': False, |
| 549 |
'light': (80, 80, 80), |
| 550 |
'dark': (45, 45, 45), |
| 551 |
'light_texture': None, |
| 552 |
'dark_texture': None, |
| 553 |
} |
| 554 |
defs['cover_grid_cache_size_multiple'] = 5 |
| 555 |
defs['cover_grid_disk_cache_size'] = 2500 |
| 556 |
defs['cover_grid_show_title'] = False |
| 557 |
defs['cover_grid_text_flush_bottom'] = False |
| 558 |
defs['cover_corner_radius'] = 0 |
| 559 |
defs['cover_corner_radius_unit'] = 'px' |
| 560 |
defs['show_vl_tabs'] = False |
| 561 |
defs['vl_tabs_closable'] = True |
| 562 |
defs['show_highlight_toggle_button'] = False |
| 563 |
defs['add_comments_to_email'] = False |
| 564 |
defs['cb_preserve_aspect_ratio'] = False |
| 565 |
defs['cb_double_click_to_activate'] = False |
| 566 |
defs['gpm_template_editor_font_size'] = 10 |
| 567 |
defs['emblem_size'] = 32 |
| 568 |
defs['emblem_position'] = 'left' |
| 569 |
defs['emblem_style'] = 'none' |
| 570 |
defs['emblem_emboss_position'] = 'top_left' |
| 571 |
defs['metadata_diff_mark_rejected'] = False |
| 572 |
defs['tag_browser_show_counts'] = True |
| 573 |
defs['tag_browser_show_tooltips'] = True |
| 574 |
defs['row_numbers_in_book_list'] = True |
| 575 |
defs['tag_browser_item_padding'] = 0.5 |
| 576 |
defs['paste_isbn_prefixes'] = ['isbn', 'url', 'amazon', 'google'] |
| 577 |
defs['qv_respects_vls'] = True |
| 578 |
defs['qv_dclick_changes_column'] = True |
| 579 |
defs['qv_retkey_changes_column'] = True |
| 580 |
defs['qv_follows_column'] = False |
| 581 |
defs['book_details_comments_heading_pos'] = 'hide' |
| 582 |
defs['book_list_split'] = False |
| 583 |
defs['wrap_toolbar_text'] = False |
| 584 |
defs['dnd_merge'] = True |
| 585 |
defs['booklist_grid'] = False |
| 586 |
defs['browse_annots_restrict_to_user'] = None |
| 587 |
defs['browse_annots_restrict_to_type'] = None |
| 588 |
defs['browse_annots_use_stemmer'] = True |
| 589 |
defs['browse_notes_use_stemmer'] = True |
| 590 |
defs['browse_annots_group_by'] = None |
| 591 |
defs['fts_library_use_stemmer'] = True |
| 592 |
defs['fts_library_restrict_books'] = False |
| 593 |
defs['fts_visualisation'] = 'cards' |
| 594 |
defs['fts_sort_order'] = 'relevance' |
| 595 |
defs['annots_export_format'] = 'txt' |
| 596 |
defs['books_autoscroll_time'] = 2.0 |
| 597 |
defs['edit_metadata_single_use_2_cols_for_custom_fields'] = True |
| 598 |
defs['edit_metadata_elide_labels'] = True |
| 599 |
defs['edit_metadata_elision_point'] = 'right' |
| 600 |
defs['edit_metadata_bulk_cc_label_length'] = 25 |
| 601 |
defs['edit_metadata_single_cc_label_length'] = 12 |
| 602 |
defs['edit_metadata_templates_only_F2_on_booklist'] = False |
| 603 |
# JSON dumps converts integer keys to strings, so do it explicitly |
| 604 |
defs['tb_search_order'] = {'0': 1, '1': 2, '2': 3, '3': 4, '4': 0} |
| 605 |
defs['search_tool_bar_shows_text'] = True |
| 606 |
defs['allow_keyboard_search_in_library_views'] = True |
| 607 |
defs['keep_search_when_switching_vl'] = False |
| 608 |
defs['show_links_in_tag_browser'] = False |
| 609 |
defs['show_notes_in_tag_browser'] = False |
| 610 |
defs['icons_on_right_in_tag_browser'] = True |
| 611 |
defs['cover_browser_narrow_view_position'] = 'automatic' |
| 612 |
defs['dark_palette_name'] = '' |
| 613 |
defs['light_palette_name'] = '' |
| 614 |
defs['dark_palettes'] = {} |
| 615 |
defs['light_palettes'] = {} |
| 616 |
defs['saved_layouts'] = {} |
| 617 |
defs['book_details_note_link_icon_width'] = 1.0 |
| 618 |
defs['tag_browser_show_category_icons'] = True |
| 619 |
defs['tag_browser_show_value_icons'] = True |
| 620 |
defs['template_editor_run_as_you_type'] = True |
| 621 |
defs['template_editor_show_all_selected_books'] = True |
| 622 |
defs['bookshelf_disk_cache_size'] = 3000 |
| 623 |
defs['bookshelf_cache_size_multiple'] = 5 |
| 624 |
defs['bookshelf_shadow'] = True |
| 625 |
defs['bookshelf_thumbnail'] = 'crops' |
| 626 |
defs['bookshelf_thumbnail_opacity'] = 30 |
| 627 |
defs['bookshelf_variable_height'] = 'variable' |
| 628 |
defs['bookshelf_fade_time'] = 400 |
| 629 |
defs['bookshelf_hover'] = 'shift' |
| 630 |
defs['bookshelf_up_to_down'] = False |
| 631 |
defs['bookshelf_height'] = 119 |
| 632 |
defs['bookshelf_make_space_for_second_line'] = False |
| 633 |
defs['bookshelf_emblem_position'] = 'auto' |
| 634 |
defs['bookshelf_divider_text_right'] = False |
| 635 |
defs['bookshelf_start_with_divider'] = False |
| 636 |
defs['bookshelf_divider_style'] = 'text' |
| 637 |
defs['bookshelf_theme_override'] = 'none' |
| 638 |
defs['bookshelf_use_custom_background'] = False |
| 639 |
defs['bookshelf_custom_background'] = { |
| 640 |
'light': (255, 255, 255), |
| 641 |
'dark': (64, 64, 64), |
| 642 |
'light_texture': None, |
| 643 |
'dark_texture': None, |
| 644 |
} |
| 645 |
defs['bookshelf_min_font_multiplier'] = 0.75 |
| 646 |
defs['bookshelf_max_font_multiplier'] = 1.3 |
| 647 |
defs['bookshelf_outline_width'] = 0 |
| 648 |
defs['bookshelf_font'] = {'family': None, 'style': None} |
| 649 |
defs['bookshelf_use_custom_colors'] = False |
| 650 |
defs['bookshelf_custom_colors'] = { |
| 651 |
'light': {}, |
| 652 |
'dark': {}, |
| 653 |
} |
| 654 |
|
| 655 |
with gprefs: |
| 656 |
# Migrate beta bookshelf_thumbnail |
| 657 |
if isinstance(btv := gprefs.get('bookshelf_thumbnail'), bool): |
| 658 |
gprefs['bookshelf_thumbnail'] = 'full' if btv else 'none' |
| 659 |
|
| 660 |
# Migrate bookshelf_variable_height from bool to enum |
| 661 |
if isinstance(vhv := gprefs.get('bookshelf_variable_height'), bool): |
| 662 |
gprefs['bookshelf_variable_height'] = 'variable' if vhv else 'constant' |
| 663 |
|
| 664 |
def migrate_tweak(tweak_name, pref_name): |
| 665 |
# If the tweak has been changed then leave the tweak in the file so |
| 666 |
# that the user can bounce between versions with and without the |
| 667 |
# migration. For versions before the migration the tweak wins. For |
| 668 |
# versions after the migration any changes win. |
| 669 |
v = tweaks.get(tweak_name, None) |
| 670 |
migrated_tweak_name = pref_name + '_tweak_migrated' |
| 671 |
m = gprefs.get(migrated_tweak_name, None) |
| 672 |
if m is None and v is not None: |
| 673 |
gprefs[pref_name] = v |
| 674 |
gprefs[migrated_tweak_name] = True |
| 675 |
|
| 676 |
migrate_tweak('metadata_edit_elide_labels', 'edit_metadata_elide_labels') |
| 677 |
migrate_tweak('metadata_edit_elision_point', 'edit_metadata_elision_point') |
| 678 |
migrate_tweak('metadata_edit_bulk_cc_label_length', 'edit_metadata_bulk_cc_label_length') |
| 679 |
migrate_tweak('metadata_edit_single_cc_label_length', 'edit_metadata_single_cc_label_length') |
| 680 |
migrate_tweak('metadata_single_use_2_cols_for_custom_fields', 'edit_metadata_single_use_2_cols_for_custom_fields') |
| 681 |
|
| 682 |
if gprefs.get('show_emblems'): |
| 683 |
gprefs['emblem_style'] = 'gutter' |
| 684 |
gprefs.pop('show_emblems', None) |
| 685 |
|
| 686 |
|
| 687 |
create_defs() |
| 688 |
del create_defs |
| 689 |
# }}} |
| 690 |
|
| 691 |
UNDEFINED_QDATETIME = QDateTime( |
| 692 |
UNDEFINED_DATE.year, |
| 693 |
UNDEFINED_DATE.month, |
| 694 |
UNDEFINED_DATE.day, |
| 695 |
UNDEFINED_DATE.hour, |
| 696 |
UNDEFINED_DATE.minute, |
| 697 |
UNDEFINED_DATE.second, |
| 698 |
) |
| 699 |
QT_HIDDEN_CLEAR_ACTION = '_q_qlineeditclearaction' |
| 700 |
ALL_COLUMNS = ['title', 'ondevice', 'authors', 'size', 'timestamp', 'rating', 'publisher', 'tags', 'series', 'pubdate'] |
| 701 |
|
| 702 |
|
| 703 |
def _config(): # {{{ |
| 704 |
c = Config('gui', 'preferences for the calibre GUI') |
| 705 |
c.add_opt( |
| 706 |
'send_to_storage_card_by_default', |
| 707 |
default=False, |
| 708 |
help=_('Send file to storage card instead of main memory by default'), |
| 709 |
) |
| 710 |
c.add_opt('confirm_delete', default=False, help=_('Confirm before deleting')) |
| 711 |
c.add_opt('main_window_geometry', default=None, help=_('Main window geometry')) |
| 712 |
c.add_opt('new_version_notification', default=True, help=_('Notify when a new version is available')) |
| 713 |
c.add_opt('use_roman_numerals_for_series_number', default=True, help=_('Use Roman numerals for series number')) |
| 714 |
c.add_opt('sort_tags_by', default='name', help=_('Sort tags list by name, popularity, or rating')) |
| 715 |
c.add_opt('match_tags_type', default='any', help=_('Match tags by any or all.')) |
| 716 |
c.add_opt('cover_flow_queue_length', default=6, help=_('Number of covers to show in the cover browsing mode')) |
| 717 |
c.add_opt('LRF_conversion_defaults', default=[], help=_('Defaults for conversion to LRF')) |
| 718 |
c.add_opt('LRF_ebook_viewer_options', default=None, help=_('Options for the LRF e-book viewer')) |
| 719 |
c.add_opt( |
| 720 |
'internally_viewed_formats', |
| 721 |
default=[ |
| 722 |
'LRF', |
| 723 |
'EPUB', |
| 724 |
'LIT', |
| 725 |
'MOBI', |
| 726 |
'PRC', |
| 727 |
'POBI', |
| 728 |
'AZW', |
| 729 |
'AZW3', |
| 730 |
'HTML', |
| 731 |
'FB2', |
| 732 |
'FBZ', |
| 733 |
'PDB', |
| 734 |
'RB', |
| 735 |
'SNB', |
| 736 |
'HTMLZ', |
| 737 |
'KEPUB', |
| 738 |
], |
| 739 |
help=_('Formats that are viewed using the internal viewer'), |
| 740 |
) |
| 741 |
c.add_opt('column_map', default=ALL_COLUMNS, help=_('Columns to be displayed in the book list')) |
| 742 |
c.add_opt('autolaunch_server', default=False, help=_('Automatically launch Content server on application startup')) |
| 743 |
c.add_opt('oldest_news', default=60, help=_('Oldest news kept in database')) |
| 744 |
c.add_opt('systray_icon', default=False, help=_('Show system tray icon')) |
| 745 |
c.add_opt('upload_news_to_device', default=True, help=_('Upload downloaded news to device')) |
| 746 |
c.add_opt( |
| 747 |
'delete_news_from_library_on_upload', |
| 748 |
default=False, |
| 749 |
help=_('Delete news books from library after uploading to device'), |
| 750 |
) |
| 751 |
c.add_opt( |
| 752 |
'separate_cover_flow', |
| 753 |
default=False, |
| 754 |
help=_('Show the cover flow in a separate window instead of in the main calibre window'), |
| 755 |
) |
| 756 |
c.add_opt('disable_tray_notification', default=False, help=_('Disable notifications from the system tray icon')) |
| 757 |
c.add_opt( |
| 758 |
'default_send_to_device_action', |
| 759 |
default=None, |
| 760 |
help=_('Default action to perform when the "Send to device" button is clicked'), |
| 761 |
) |
| 762 |
c.add_opt('asked_library_thing_password', default=False, help='Asked library thing password at least once.') |
| 763 |
c.add_opt( |
| 764 |
'search_as_you_type', |
| 765 |
default=False, |
| 766 |
help=_('Start searching as you type. If this is disabled then search will only take place when the Enter key is pressed.'), |
| 767 |
) |
| 768 |
c.add_opt( |
| 769 |
'highlight_search_matches', |
| 770 |
default=False, |
| 771 |
help=_( |
| 772 |
'When searching, show all books with search results ' |
| 773 |
'highlighted instead of showing only the matches. You can use the ' |
| 774 |
'N or F3 keys to go to the next match.' |
| 775 |
), |
| 776 |
) |
| 777 |
c.add_opt('save_to_disk_template_history', default=[], help='Previously used Save to disk templates') |
| 778 |
c.add_opt('send_to_device_template_history', default=[], help='Previously used Send to Device templates') |
| 779 |
c.add_opt('main_search_history', default=[], help='Search history for the main GUI') |
| 780 |
c.add_opt('viewer_search_history', default=[], help='Search history for the e-book viewer') |
| 781 |
c.add_opt('viewer_toc_search_history', default=[], help='Search history for the ToC in the e-book viewer') |
| 782 |
c.add_opt('lrf_viewer_search_history', default=[], help='Search history for the LRF viewer') |
| 783 |
c.add_opt('scheduler_search_history', default=[], help='Search history for the recipe scheduler') |
| 784 |
c.add_opt('plugin_search_history', default=[], help='Search history for the plugin preferences') |
| 785 |
c.add_opt('shortcuts_search_history', default=[], help='Search history for the keyboard preferences') |
| 786 |
c.add_opt('jobs_search_history', default=[], help='Search history for the tweaks preferences') |
| 787 |
c.add_opt('tweaks_search_history', default=[], help='Search history for tweaks') |
| 788 |
c.add_opt( |
| 789 |
'worker_limit', |
| 790 |
default=6, |
| 791 |
help=_('Maximum number of simultaneous conversion/news download jobs. This number is twice the actual value for historical reasons.'), |
| 792 |
) |
| 793 |
c.add_opt('get_social_metadata', default=True, help=_('Download social metadata (tags/rating/etc.)')) |
| 794 |
c.add_opt('overwrite_author_title_metadata', default=True, help=_('Overwrite author and title with new metadata')) |
| 795 |
c.add_opt('auto_download_cover', default=False, help=_('Automatically download the cover, if available')) |
| 796 |
c.add_opt('enforce_cpu_limit', default=True, help=_('Limit max simultaneous jobs to number of CPUs')) |
| 797 |
c.add_opt( |
| 798 |
'gui_layout', |
| 799 |
choices=['wide', 'narrow'], |
| 800 |
help=_('The layout of the user interface. Wide has the Book details panel on the right and narrow has it at the bottom.'), |
| 801 |
default='wide', |
| 802 |
) |
| 803 |
c.add_opt('show_avg_rating', default=True, help=_('Show the average rating per item indication in the Tag browser')) |
| 804 |
c.add_opt('disable_animations', default=False, help=_('Disable UI animations')) |
| 805 |
|
| 806 |
# This option is no longer used. It remains for compatibility with upgrades |
| 807 |
# so the value can be migrated |
| 808 |
c.add_opt('tag_browser_hidden_categories', default=set(), help=_('Tag browser categories not to display')) |
| 809 |
|
| 810 |
c.add_opt |
| 811 |
return ConfigProxy(c) |
| 812 |
|
| 813 |
|
| 814 |
config = _config() |
| 815 |
# }}} |
| 816 |
|
| 817 |
QSettings.setPath(QSettings.Format.IniFormat, QSettings.Scope.UserScope, config_dir) |
| 818 |
QSettings.setPath(QSettings.Format.IniFormat, QSettings.Scope.SystemScope, config_dir) |
| 819 |
QSettings.setDefaultFormat(QSettings.Format.IniFormat) |
| 820 |
|
| 821 |
|
| 822 |
def default_author_link(): |
| 823 |
from calibre.ebooks.metadata.book.render import resolve_default_author_link |
| 824 |
|
| 825 |
return resolve_default_author_link(gprefs.get('default_author_link')) |
| 826 |
|
| 827 |
|
| 828 |
def available_heights(): |
| 829 |
return tuple(s.availableSize().height() for s in QGuiApplication.screens()) |
| 830 |
|
| 831 |
|
| 832 |
def available_height(): |
| 833 |
screen = qapplication_or_fail().primaryScreen() |
| 834 |
assert screen is not None |
| 835 |
return screen.availableSize().height() |
| 836 |
|
| 837 |
|
| 838 |
def available_width(): |
| 839 |
screen = qapplication_or_fail().primaryScreen() |
| 840 |
assert screen is not None |
| 841 |
return screen.availableSize().width() |
| 842 |
|
| 843 |
|
| 844 |
def max_available_height(): |
| 845 |
return max(available_heights()) |
| 846 |
|
| 847 |
|
| 848 |
def min_available_height(): |
| 849 |
return min(available_heights()) |
| 850 |
|
| 851 |
|
| 852 |
def get_screen_dpi(): |
| 853 |
s = qapplication_or_fail().primaryScreen() |
| 854 |
assert s is not None |
| 855 |
return s.logicalDotsPerInchX(), s.logicalDotsPerInchY() |
| 856 |
|
| 857 |
|
| 858 |
_is_widescreen = None |
| 859 |
|
| 860 |
|
| 861 |
def is_widescreen(): |
| 862 |
global _is_widescreen |
| 863 |
if _is_widescreen is None: |
| 864 |
try: |
| 865 |
_is_widescreen = available_width() / available_height() > 1.4 |
| 866 |
except Exception: |
| 867 |
_is_widescreen = False |
| 868 |
return _is_widescreen |
| 869 |
|
| 870 |
|
| 871 |
def extension(path): |
| 872 |
return os.path.splitext(path)[1][1:].lower() |
| 873 |
|
| 874 |
|
| 875 |
def warning_dialog(parent, title, msg, det_msg='', show=False, show_copy_button=True): |
| 876 |
from calibre.gui2.dialogs.message_box import MessageBox |
| 877 |
|
| 878 |
d = MessageBox(MessageBox.WARNING, _('WARNING:') + ' ' + title, msg, det_msg, parent=parent, show_copy_button=show_copy_button) |
| 879 |
if show: |
| 880 |
return d.exec() |
| 881 |
return d |
| 882 |
|
| 883 |
|
| 884 |
def error_dialog(parent, title, msg, det_msg='', show=False, show_copy_button=True): |
| 885 |
from calibre.gui2.dialogs.message_box import MessageBox |
| 886 |
|
| 887 |
d = MessageBox(MessageBox.ERROR, _('ERROR:') + ' ' + title, msg, det_msg, parent=parent, show_copy_button=show_copy_button) |
| 888 |
if show: |
| 889 |
return d.exec() |
| 890 |
return d |
| 891 |
|
| 892 |
|
| 893 |
class Aborted(Exception): |
| 894 |
pass |
| 895 |
|
| 896 |
|
| 897 |
def question_dialog( |
| 898 |
parent, |
| 899 |
title, |
| 900 |
msg, |
| 901 |
det_msg='', |
| 902 |
show_copy_button=False, |
| 903 |
default_yes=True, |
| 904 |
# Skippable dialogs |
| 905 |
# Set skip_dialog_name to a unique name for this dialog |
| 906 |
# Set skip_dialog_msg to a message displayed to the user |
| 907 |
skip_dialog_name=None, |
| 908 |
skip_dialog_msg=_('Show this confirmation again'), |
| 909 |
skip_dialog_skipped_value=True, |
| 910 |
skip_dialog_skip_precheck=True, |
| 911 |
# Override icon (QIcon to be used as the icon for this dialog or string for QIcon.ic()) |
| 912 |
override_icon=None, |
| 913 |
# Change the text/icons of the yes and no buttons. |
| 914 |
# The icons must be QIcon objects or strings for QIcon.ic() |
| 915 |
yes_text=None, |
| 916 |
no_text=None, |
| 917 |
yes_icon=None, |
| 918 |
no_icon=None, |
| 919 |
# Add an Abort button which if clicked will cause this function to raise |
| 920 |
# the Aborted exception |
| 921 |
add_abort_button=False, |
| 922 |
): |
| 923 |
from calibre.gui2.dialogs.message_box import MessageBox |
| 924 |
|
| 925 |
prefs = gui_prefs() |
| 926 |
|
| 927 |
if not isinstance(skip_dialog_name, str): |
| 928 |
skip_dialog_name = None |
| 929 |
try: |
| 930 |
auto_skip = set(prefs.get('questions_to_auto_skip', ())) |
| 931 |
except Exception: |
| 932 |
auto_skip = set() |
| 933 |
if skip_dialog_name is not None and skip_dialog_name in auto_skip: |
| 934 |
return bool(skip_dialog_skipped_value) |
| 935 |
|
| 936 |
d = MessageBox( |
| 937 |
MessageBox.QUESTION, |
| 938 |
title, |
| 939 |
msg, |
| 940 |
det_msg, |
| 941 |
parent=parent, |
| 942 |
show_copy_button=show_copy_button, |
| 943 |
default_yes=default_yes, |
| 944 |
q_icon=override_icon, |
| 945 |
yes_text=yes_text, |
| 946 |
no_text=no_text, |
| 947 |
yes_icon=yes_icon, |
| 948 |
no_icon=no_icon, |
| 949 |
add_abort_button=add_abort_button, |
| 950 |
) |
| 951 |
|
| 952 |
if skip_dialog_name is not None and skip_dialog_msg: |
| 953 |
tc = d.toggle_checkbox |
| 954 |
tc.setVisible(True) |
| 955 |
tc.setText(skip_dialog_msg) |
| 956 |
tc.setChecked(bool(skip_dialog_skip_precheck)) |
| 957 |
d.resize_needed.emit() |
| 958 |
|
| 959 |
ret = d.exec() == QDialog.DialogCode.Accepted |
| 960 |
if add_abort_button and d.aborted: |
| 961 |
raise Aborted() |
| 962 |
|
| 963 |
if skip_dialog_name is not None and not d.toggle_checkbox.isChecked(): |
| 964 |
auto_skip.add(skip_dialog_name) |
| 965 |
prefs.set('questions_to_auto_skip', list(auto_skip)) |
| 966 |
|
| 967 |
return ret |
| 968 |
|
| 969 |
|
| 970 |
def info_dialog(parent, title, msg, det_msg='', show=False, show_copy_button=True, only_copy_details=False): |
| 971 |
from calibre.gui2.dialogs.message_box import MessageBox |
| 972 |
|
| 973 |
d = MessageBox( |
| 974 |
MessageBox.INFO, |
| 975 |
title, |
| 976 |
msg, |
| 977 |
det_msg, |
| 978 |
parent=parent, |
| 979 |
show_copy_button=show_copy_button, |
| 980 |
only_copy_details=only_copy_details, |
| 981 |
) |
| 982 |
|
| 983 |
if show: |
| 984 |
return d.exec() |
| 985 |
return d |
| 986 |
|
| 987 |
|
| 988 |
def show_restart_warning(msg, parent=None): |
| 989 |
d = warning_dialog(parent, _('Restart needed'), msg, show_copy_button=False) |
| 990 |
b = d.bb.addButton(_('&Restart calibre now'), QDialogButtonBox.ButtonRole.AcceptRole) |
| 991 |
b.setIcon(QIcon.ic('lt.png')) |
| 992 |
d.do_restart = False |
| 993 |
|
| 994 |
def rf(): |
| 995 |
d.do_restart = True |
| 996 |
|
| 997 |
b.clicked.connect(rf) |
| 998 |
d.set_details('') |
| 999 |
d.exec() |
| 1000 |
b.clicked.disconnect() |
| 1001 |
return d.do_restart |
| 1002 |
|
| 1003 |
|
| 1004 |
class Dispatcher(QObject): |
| 1005 |
""" |
| 1006 |
Convenience class to use Qt signals with arbitrary python callables. |
| 1007 |
By default, ensures that a function call always happens in the |
| 1008 |
thread this Dispatcher was created in. |
| 1009 |
|
| 1010 |
Note that if you create the Dispatcher in a thread without an event loop of |
| 1011 |
its own, the function call will happen in the GUI thread (I think). |
| 1012 |
""" |
| 1013 |
|
| 1014 |
dispatch_signal = pyqtSignal(object, object) |
| 1015 |
|
| 1016 |
def __init__(self, func, queued=True, parent=None): |
| 1017 |
QObject.__init__(self, parent) |
| 1018 |
self.func = func |
| 1019 |
typ = Qt.ConnectionType.QueuedConnection |
| 1020 |
if not queued: |
| 1021 |
typ = Qt.ConnectionType.AutoConnection if queued is None else Qt.ConnectionType.DirectConnection |
| 1022 |
self.dispatch_signal.connect(self.dispatch, type=typ) |
| 1023 |
|
| 1024 |
def __call__(self, *args, **kwargs): |
| 1025 |
self.dispatch_signal.emit(args, kwargs) |
| 1026 |
|
| 1027 |
def dispatch(self, args, kwargs): |
| 1028 |
self.func(*args, **kwargs) |
| 1029 |
|
| 1030 |
|
| 1031 |
class FunctionDispatcher(QObject): |
| 1032 |
""" |
| 1033 |
Convenience class to use Qt signals with arbitrary python functions. |
| 1034 |
By default, ensures that a function call always happens in the |
| 1035 |
thread this FunctionDispatcher was created in. |
| 1036 |
|
| 1037 |
Note that you must create FunctionDispatcher objects in the GUI thread. |
| 1038 |
""" |
| 1039 |
|
| 1040 |
dispatch_signal = pyqtSignal(object, object, object) |
| 1041 |
|
| 1042 |
def __init__(self, func, queued=True, parent=None): |
| 1043 |
global gui_thread |
| 1044 |
if gui_thread is None: |
| 1045 |
gui_thread = QThread.currentThread() |
| 1046 |
if not is_gui_thread(): |
| 1047 |
raise ValueError('You can only create a FunctionDispatcher in the GUI thread') |
| 1048 |
|
| 1049 |
QObject.__init__(self, parent) |
| 1050 |
self.func = func |
| 1051 |
try: |
| 1052 |
self.func_name = func.__name__ |
| 1053 |
except Exception: |
| 1054 |
self.func_name = 'unnamed_function' |
| 1055 |
typ = Qt.ConnectionType.QueuedConnection |
| 1056 |
if not queued: |
| 1057 |
typ = Qt.ConnectionType.AutoConnection if queued is None else Qt.ConnectionType.DirectConnection |
| 1058 |
self.dispatch_signal.connect(self.dispatch, type=typ) |
| 1059 |
self.q = queue.Queue() |
| 1060 |
self.lock = threading.Lock() |
| 1061 |
|
| 1062 |
def __call__(self, *args, **kwargs): |
| 1063 |
if is_gui_thread(): |
| 1064 |
return self.func(*args, **kwargs) |
| 1065 |
with self.lock: |
| 1066 |
self.dispatch_signal.emit(self.q, args, kwargs) |
| 1067 |
res = self.q.get() |
| 1068 |
return res |
| 1069 |
|
| 1070 |
def dispatch(self, q, args, kwargs): |
| 1071 |
res = None |
| 1072 |
if (f := self.func) is not None: |
| 1073 |
try: |
| 1074 |
res = f(*args, **kwargs) |
| 1075 |
except Exception: |
| 1076 |
print(f'Failed dispatching call to function: {self.func_name}', file=sys.stderr) |
| 1077 |
import traceback |
| 1078 |
|
| 1079 |
traceback.print_exc() |
| 1080 |
q.put(res) |
| 1081 |
|
| 1082 |
|
| 1083 |
class GetMetadata(QObject): |
| 1084 |
""" |
| 1085 |
Convenience class to ensure that metadata readers are used only in the |
| 1086 |
GUI thread. Must be instantiated in the GUI thread. |
| 1087 |
""" |
| 1088 |
|
| 1089 |
edispatch = pyqtSignal(object, object, object) |
| 1090 |
idispatch = pyqtSignal(object, object, object) |
| 1091 |
metadataf = pyqtSignal(object, object) |
| 1092 |
metadata = pyqtSignal(object, object) |
| 1093 |
|
| 1094 |
def __init__(self): |
| 1095 |
QObject.__init__(self) |
| 1096 |
self.edispatch.connect(self._get_metadata, type=Qt.ConnectionType.QueuedConnection) |
| 1097 |
self.idispatch.connect(self._from_formats, type=Qt.ConnectionType.QueuedConnection) |
| 1098 |
|
| 1099 |
def __call__(self, id, *args, **kwargs): |
| 1100 |
self.edispatch.emit(id, args, kwargs) |
| 1101 |
|
| 1102 |
def from_formats(self, id, *args, **kwargs): |
| 1103 |
self.idispatch.emit(id, args, kwargs) |
| 1104 |
|
| 1105 |
def _from_formats(self, id, args, kwargs): |
| 1106 |
from calibre.ebooks.metadata.meta import metadata_from_formats |
| 1107 |
|
| 1108 |
try: |
| 1109 |
mi = metadata_from_formats(*args, **kwargs) |
| 1110 |
except Exception: |
| 1111 |
mi = MetaInformation('', [_('Unknown')]) |
| 1112 |
self.metadataf.emit(id, mi) |
| 1113 |
|
| 1114 |
def _get_metadata(self, id, args, kwargs): |
| 1115 |
from calibre.ebooks.metadata.meta import get_metadata |
| 1116 |
|
| 1117 |
try: |
| 1118 |
mi = get_metadata(*args, **kwargs) |
| 1119 |
except Exception: |
| 1120 |
mi = MetaInformation('', [_('Unknown')]) |
| 1121 |
self.metadata.emit(id, mi) |
| 1122 |
|
| 1123 |
|
| 1124 |
class FileIconProvider(QFileIconProvider): |
| 1125 |
ICONS = EXT_MAP |
| 1126 |
icons: dict[str, str | QIcon] |
| 1127 |
|
| 1128 |
def __init__(self): |
| 1129 |
super().__init__() |
| 1130 |
self.icons = {k: f'mimetypes/{v}.png' for k, v in self.ICONS.items()} |
| 1131 |
self.icons['calibre'] = I('lt.png', allow_user_override=False) |
| 1132 |
for i in ('dir', 'default', 'zero'): |
| 1133 |
self.icons[i] = QIcon.ic(str(self.icons[i])) |
| 1134 |
|
| 1135 |
def key_from_ext(self, ext): |
| 1136 |
key = ext if ext in self.icons else 'default' |
| 1137 |
if key == 'default' and '.' in ext: |
| 1138 |
ext = ext.rpartition('.')[2] |
| 1139 |
key = ext if ext in self.icons else 'default' |
| 1140 |
if key == 'default' and ext.startswith('original_'): |
| 1141 |
ext = ext.partition('_')[2] |
| 1142 |
key = ext if ext in self.icons else 'default' |
| 1143 |
if key == 'default': |
| 1144 |
key = ext |
| 1145 |
return key |
| 1146 |
|
| 1147 |
def cached_icon(self, key): |
| 1148 |
candidate = self.icons.get(key) |
| 1149 |
if isinstance(candidate, QIcon): |
| 1150 |
return candidate |
| 1151 |
candidate = candidate or f'mimetypes/{key}.png' |
| 1152 |
icon = QIcon.ic(candidate) |
| 1153 |
if not icon.is_ok(): |
| 1154 |
icon = self.icons['default'] |
| 1155 |
self.icons[key] = icon |
| 1156 |
return icon |
| 1157 |
|
| 1158 |
def icon_from_ext(self, ext): |
| 1159 |
key = self.key_from_ext(ext.lower() if ext else '') |
| 1160 |
return self.cached_icon(key) |
| 1161 |
|
| 1162 |
def load_icon(self, fileinfo): |
| 1163 |
key = 'default' |
| 1164 |
if fileinfo.isSymLink(): |
| 1165 |
if not fileinfo.exists(): |
| 1166 |
return self.icons['zero'] |
| 1167 |
fileinfo = QFileInfo(fileinfo.symLinkTarget()) |
| 1168 |
if fileinfo.isDir(): |
| 1169 |
key = 'dir' |
| 1170 |
else: |
| 1171 |
ext = str(fileinfo.completeSuffix()).lower() |
| 1172 |
key = self.key_from_ext(ext) |
| 1173 |
return self.cached_icon(key) |
| 1174 |
|
| 1175 |
def icon(self, *args, **kwargs): |
| 1176 |
arg = args[0] if args else None |
| 1177 |
if isinstance(arg, QFileInfo): |
| 1178 |
return self.load_icon(arg) |
| 1179 |
if arg == QFileIconProvider.IconType.Folder: |
| 1180 |
return self.icons['dir'] |
| 1181 |
if arg == QFileIconProvider.IconType.File: |
| 1182 |
return self.icons['default'] |
| 1183 |
return QFileIconProvider.icon(self, *args, **kwargs) |
| 1184 |
|
| 1185 |
|
| 1186 |
_file_icon_provider = None |
| 1187 |
|
| 1188 |
|
| 1189 |
def initialize_file_icon_provider(): |
| 1190 |
global _file_icon_provider |
| 1191 |
if _file_icon_provider is None: |
| 1192 |
_file_icon_provider = FileIconProvider() |
| 1193 |
|
| 1194 |
|
| 1195 |
def file_icon_provider(): |
| 1196 |
global _file_icon_provider |
| 1197 |
initialize_file_icon_provider() |
| 1198 |
return _file_icon_provider |
| 1199 |
|
| 1200 |
|
| 1201 |
has_windows_file_dialog_helper = False |
| 1202 |
if iswindows and 'CALIBRE_NO_NATIVE_FILEDIALOGS' not in os.environ: |
| 1203 |
from calibre.gui2.win_file_dialogs import is_ok as has_windows_file_dialog_helper |
| 1204 |
|
| 1205 |
has_windows_file_dialog_helper = has_windows_file_dialog_helper() |
| 1206 |
has_linux_file_dialog_helper = False |
| 1207 |
if not iswindows and not ismacos and 'CALIBRE_NO_NATIVE_FILEDIALOGS' not in os.environ and getattr(sys, 'frozen', False): |
| 1208 |
has_linux_file_dialog_helper = check_for_linux_native_dialogs() |
| 1209 |
|
| 1210 |
if has_windows_file_dialog_helper: |
| 1211 |
from calibre.gui2.win_file_dialogs import choose_dir, choose_files, choose_images, choose_save_file |
| 1212 |
elif has_linux_file_dialog_helper: |
| 1213 |
choose_dir, choose_files, choose_save_file, choose_images = map(linux_native_dialog, 'dir files save_file images'.split()) |
| 1214 |
else: |
| 1215 |
from calibre.gui2.qt_file_dialogs import choose_dir, choose_files, choose_images, choose_save_file |
| 1216 |
|
| 1217 |
choose_files, choose_images, choose_dir, choose_save_file |
| 1218 |
|
| 1219 |
|
| 1220 |
def choose_files_and_remember_all_files(window, name, title, filters=[], select_only_single_file=False, default_dir='~'): |
| 1221 |
pref_name = f'{name}-last-used-filter-spec-all-files' |
| 1222 |
lufs = dynamic.get(pref_name, False) |
| 1223 |
af = _('All files'), ['*'] |
| 1224 |
filters = list(filters) |
| 1225 |
filters.insert(0, af) if lufs else filters.append(af) |
| 1226 |
paths = choose_files(window, name, title, list(filters), False, select_only_single_file, default_dir) |
| 1227 |
if paths: |
| 1228 |
ext = paths[0].rpartition(os.extsep)[-1].lower() |
| 1229 |
used_all_files = True |
| 1230 |
for i, (name, exts) in enumerate(filters): |
| 1231 |
if ext in exts: |
| 1232 |
used_all_files = False |
| 1233 |
break |
| 1234 |
dynamic.set(pref_name, used_all_files) |
| 1235 |
return paths |
| 1236 |
|
| 1237 |
|
| 1238 |
def is_dark_theme(): |
| 1239 |
app = cast(QApplication, QApplication.instance()) |
| 1240 |
if app is not None: |
| 1241 |
pal = app.palette() |
| 1242 |
return pal.is_dark_theme() |
| 1243 |
return False |
| 1244 |
|
| 1245 |
|
| 1246 |
def choose_osx_app(window, name, title, default_dir='/Applications'): |
| 1247 |
fd = FileDialog(title=title, parent=window, name=name, mode=QFileDialog.FileMode.ExistingFile, default_dir=default_dir) |
| 1248 |
app = fd.get_files() |
| 1249 |
fd.setParent(None) |
| 1250 |
if app: |
| 1251 |
return app |
| 1252 |
|
| 1253 |
|
| 1254 |
def pixmap_to_data(pixmap, format='JPEG', quality=None): |
| 1255 |
""" |
| 1256 |
Return the QPixmap pixmap as a string saved in the specified format. |
| 1257 |
""" |
| 1258 |
if quality is None: |
| 1259 |
if format.upper() == 'PNG': |
| 1260 |
# For some reason on windows with Qt 5.6 using a quality of 90 |
| 1261 |
# generates invalid PNG data. Many other quality values work |
| 1262 |
# but we use -1 for the default quality which is most likely to |
| 1263 |
# work |
| 1264 |
quality = -1 |
| 1265 |
else: |
| 1266 |
quality = 90 |
| 1267 |
ba = QByteArray() |
| 1268 |
buf = QBuffer(ba) |
| 1269 |
buf.open(QIODevice.OpenModeFlag.WriteOnly) |
| 1270 |
pixmap.save(buf, format, quality=quality) |
| 1271 |
return ba.data() |
| 1272 |
|
| 1273 |
|
| 1274 |
def decouple(prefix): |
| 1275 |
"Ensure that config files used by utility code are not the same as those used by the main calibre GUI" |
| 1276 |
dynamic.decouple(prefix) |
| 1277 |
from calibre.gui2.widgets import history |
| 1278 |
|
| 1279 |
history.decouple(prefix) |
| 1280 |
|
| 1281 |
|
| 1282 |
_gui_prefs = gprefs |
| 1283 |
|
| 1284 |
|
| 1285 |
def gui_prefs(): |
| 1286 |
return _gui_prefs |
| 1287 |
|
| 1288 |
|
| 1289 |
def set_gui_prefs(prefs): |
| 1290 |
global _gui_prefs |
| 1291 |
_gui_prefs = prefs |
| 1292 |
|
| 1293 |
|
| 1294 |
class ResizableDialog(QDialog): |
| 1295 |
# This class is present only for backwards compat with third party plugins |
| 1296 |
# that might use it. Do not use it in new code. |
| 1297 |
|
| 1298 |
def __init__(self, *args, **kwargs): |
| 1299 |
QDialog.__init__(self, *args) |
| 1300 |
if s := getattr(self, 'setupUi', None): |
| 1301 |
s(self) |
| 1302 |
screen = self.screen() |
| 1303 |
assert screen is not None |
| 1304 |
geom = screen.availableSize() |
| 1305 |
nh, nw = max(550, geom.height() - 25), max(700, geom.width() - 10) |
| 1306 |
nh = min(self.height(), nh) |
| 1307 |
nw = min(self.width(), nw) |
| 1308 |
self.resize(nw, nh) |
| 1309 |
|
| 1310 |
|
| 1311 |
gui_thread = None |
| 1312 |
qt_app = None |
| 1313 |
builtin_fonts_loaded = False |
| 1314 |
|
| 1315 |
|
| 1316 |
def calibre_font_files(): |
| 1317 |
return glob.glob(P('fonts/liberation/*.?tf')) + [P('fonts/calibreSymbols.otf')] + glob.glob(os.path.join(config_dir, 'fonts', '*.?tf')) |
| 1318 |
|
| 1319 |
|
| 1320 |
def load_builtin_fonts(): |
| 1321 |
global _rating_font, builtin_fonts_loaded |
| 1322 |
# Load the builtin fonts and any fonts added to calibre by the user to |
| 1323 |
# Qt |
| 1324 |
if builtin_fonts_loaded: |
| 1325 |
return |
| 1326 |
builtin_fonts_loaded = True |
| 1327 |
for ff in calibre_font_files(): |
| 1328 |
if ff.rpartition('.')[-1].lower() in {'ttf', 'otf'}: |
| 1329 |
with open(ff, 'rb') as s: |
| 1330 |
# Windows requires font files to be executable for them to be |
| 1331 |
# loaded successfully, so we use the in memory loader |
| 1332 |
fid = QFontDatabase.addApplicationFontFromData(s.read()) |
| 1333 |
if fid > -1: |
| 1334 |
fam = QFontDatabase.applicationFontFamilies(fid) |
| 1335 |
fam = set(map(str, fam)) |
| 1336 |
if 'calibre Symbols' in fam: |
| 1337 |
_rating_font = 'calibre Symbols' |
| 1338 |
|
| 1339 |
|
| 1340 |
def setup_gui_option_parser(parser): |
| 1341 |
if islinux: |
| 1342 |
parser.add_option( |
| 1343 |
'--detach', |
| 1344 |
default=False, |
| 1345 |
action='store_true', |
| 1346 |
help=_('Detach from the controlling terminal, if any (Linux only)'), |
| 1347 |
) |
| 1348 |
|
| 1349 |
|
| 1350 |
def show_temp_dir_error(err): |
| 1351 |
import traceback |
| 1352 |
|
| 1353 |
extra = _('Click "Show details" for more information.') |
| 1354 |
if 'CALIBRE_TEMP_DIR' in os.environ: |
| 1355 |
extra = _('The %s environment variable is set. Try unsetting it.') % 'CALIBRE_TEMP_DIR' |
| 1356 |
error_dialog( |
| 1357 |
None, |
| 1358 |
_('Could not create temporary folder'), |
| 1359 |
_('Could not create temporary folder, calibre cannot start.') + ' ' + extra, |
| 1360 |
det_msg=traceback.format_exc(), |
| 1361 |
show=True, |
| 1362 |
) |
| 1363 |
|
| 1364 |
|
| 1365 |
def setup_unix_signals(self): |
| 1366 |
if hasattr(os, 'pipe2'): |
| 1367 |
read_fd, write_fd = os.pipe2(os.O_CLOEXEC | os.O_NONBLOCK) |
| 1368 |
else: |
| 1369 |
import fcntl |
| 1370 |
|
| 1371 |
read_fd, write_fd = os.pipe() |
| 1372 |
cloexec_flag = getattr(fcntl, 'FD_CLOEXEC', 1) |
| 1373 |
for fd in (read_fd, write_fd): |
| 1374 |
flags = fcntl.fcntl(fd, fcntl.F_GETFD) |
| 1375 |
if flags != -1: |
| 1376 |
fcntl.fcntl(fd, fcntl.F_SETFD, flags | cloexec_flag) |
| 1377 |
flags = fcntl.fcntl(fd, fcntl.F_GETFL) |
| 1378 |
if flags != -1: |
| 1379 |
fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) |
| 1380 |
|
| 1381 |
original_handlers = {} |
| 1382 |
for sig in (signal.SIGINT, signal.SIGTERM): |
| 1383 |
original_handlers[sig] = signal.signal(sig, lambda x, y: None) |
| 1384 |
signal.siginterrupt(sig, False) |
| 1385 |
signal.set_wakeup_fd(write_fd) |
| 1386 |
self.signal_notifier = QSocketNotifier(sip.voidptr(read_fd), QSocketNotifier.Type.Read, self) |
| 1387 |
self.signal_notifier.setEnabled(True) |
| 1388 |
self.signal_notifier.activated.connect(self.signal_received, type=Qt.ConnectionType.QueuedConnection) |
| 1389 |
return original_handlers |
| 1390 |
|
| 1391 |
|
| 1392 |
def setup_to_run_webengine(): |
| 1393 |
# Allow import of webengine after construction of QApplication on new enough PyQt |
| 1394 |
QApplication.setAttribute(Qt.ApplicationAttribute.AA_ShareOpenGLContexts) |
| 1395 |
# this import is needed to have Qt call qt_registerDefaultPlatformBackingStoreOpenGLSupport |
| 1396 |
from qt.core import QOpenGLWidget |
| 1397 |
|
| 1398 |
del QOpenGLWidget |
| 1399 |
from qt.core import QQuickWindow, QSGRendererInterface |
| 1400 |
|
| 1401 |
QQuickWindow.setGraphicsApi(QSGRendererInterface.GraphicsApi.OpenGL) |
| 1402 |
|
| 1403 |
|
| 1404 |
class Application(QApplication): |
| 1405 |
shutdown_signal_received = pyqtSignal() |
| 1406 |
palette_changed = pyqtSignal() |
| 1407 |
if not iswindows: |
| 1408 |
signal_notifier: QSocketNotifier |
| 1409 |
|
| 1410 |
def __init__( |
| 1411 |
self, |
| 1412 |
args=(), |
| 1413 |
force_calibre_style=False, |
| 1414 |
override_program_name=None, |
| 1415 |
headless=False, |
| 1416 |
color_prefs=gprefs, |
| 1417 |
windows_app_uid=None, |
| 1418 |
should_handle_calibre_urls=False, |
| 1419 |
): |
| 1420 |
if not args: |
| 1421 |
args = sys.argv[:1] |
| 1422 |
args = [args[0]] |
| 1423 |
sys.excepthook = simple_excepthook |
| 1424 |
QNetworkProxyFactory.setUseSystemConfiguration(True) |
| 1425 |
setup_to_run_webengine() |
| 1426 |
if iswindows: |
| 1427 |
self.windows_app_uid = None |
| 1428 |
if windows_app_uid: |
| 1429 |
windows_app_uid = str(windows_app_uid) |
| 1430 |
if set_app_uid(windows_app_uid): |
| 1431 |
self.windows_app_uid = windows_app_uid |
| 1432 |
self.file_event_hook = None |
| 1433 |
if override_program_name: |
| 1434 |
args = [override_program_name] + args[1:] |
| 1435 |
self.palette_manager = PaletteManager(force_calibre_style, headless) |
| 1436 |
if headless: |
| 1437 |
args.extend(( |
| 1438 |
'-platformpluginpath', |
| 1439 |
plugins_loc, |
| 1440 |
'-platform', |
| 1441 |
os.environ.get('CALIBRE_HEADLESS_PLATFORM', 'headless'), |
| 1442 |
)) |
| 1443 |
else: |
| 1444 |
args.extend(self.palette_manager.args_to_qt) |
| 1445 |
# We disable GPU acceleration as it causes crashes/black screen in some Windows systems and |
| 1446 |
# isnt really needed for performance for our use cases. |
| 1447 |
if not tweaks['qt_webengine_uses_gpu']: |
| 1448 |
args.extend(('--webEngineArgs', '--disable-gpu')) |
| 1449 |
self.headless = headless |
| 1450 |
from calibre_extensions import progress_indicator |
| 1451 |
|
| 1452 |
self.pi = progress_indicator |
| 1453 |
self._file_open_paths = [] |
| 1454 |
self._file_open_lock = RLock() |
| 1455 |
QApplication.setOrganizationName('calibre-ebook.com') |
| 1456 |
QApplication.setOrganizationDomain(QApplication.organizationName()) |
| 1457 |
QApplication.setApplicationVersion(__version__) |
| 1458 |
QApplication.setApplicationName(APP_UID) |
| 1459 |
if override_program_name and hasattr(QApplication, 'setDesktopFileName'): |
| 1460 |
QApplication.setDesktopFileName(override_program_name) |
| 1461 |
QApplication.setAttribute(Qt.ApplicationAttribute.AA_ShareOpenGLContexts, True) # needed for webengine |
| 1462 |
self._store_args_to_prevent_gc = args # Qt barfs is python garbage collects these |
| 1463 |
QApplication.__init__(self, args) |
| 1464 |
if should_handle_calibre_urls: |
| 1465 |
# See https://bugreports.qt.io/browse/QTBUG-134316 |
| 1466 |
QDesktopServices.setUrlHandler('calibre', self.handle_calibre_url) |
| 1467 |
QDesktopServices.setUrlHandler('http', self.handle_http_url) |
| 1468 |
QDesktopServices.setUrlHandler('https', self.handle_http_url) |
| 1469 |
set_image_allocation_limit() |
| 1470 |
self.palette_manager.initialize() |
| 1471 |
icon_resource_manager.initialize() |
| 1472 |
sh = self.styleHints() |
| 1473 |
if hasattr(sh, 'setShowShortcutsInContextMenus'): |
| 1474 |
sh.setShowShortcutsInContextMenus(True) |
| 1475 |
if ismacos: |
| 1476 |
from calibre_extensions.cocoa import disable_cocoa_ui_elements |
| 1477 |
|
| 1478 |
disable_cocoa_ui_elements() |
| 1479 |
self.setAttribute(Qt.ApplicationAttribute.AA_SynthesizeTouchForUnhandledMouseEvents, False) |
| 1480 |
try: |
| 1481 |
base_dir() |
| 1482 |
except OSError as err: |
| 1483 |
if not headless: |
| 1484 |
show_temp_dir_error(err) |
| 1485 |
raise SystemExit('Failed to create temporary folder') |
| 1486 |
if DEBUG and not headless: |
| 1487 |
prints('QPA platform:', self.platformName()) |
| 1488 |
prints('devicePixelRatio:', self.devicePixelRatio()) |
| 1489 |
s = self.primaryScreen() |
| 1490 |
if s: |
| 1491 |
prints('logicalDpi:', s.logicalDotsPerInchX(), 'x', s.logicalDotsPerInchY()) |
| 1492 |
prints('physicalDpi:', s.physicalDotsPerInchX(), 'x', s.physicalDotsPerInchY()) |
| 1493 |
if not iswindows: |
| 1494 |
self.setup_unix_signals() |
| 1495 |
if islinux or isbsd: |
| 1496 |
self.setAttribute(Qt.ApplicationAttribute.AA_DontUseNativeMenuBar, 'CALIBRE_NO_NATIVE_MENUBAR' in os.environ) |
| 1497 |
self.setAttribute(Qt.ApplicationAttribute.AA_DontShowIconsInMenus, 'CALIBRE_NO_ICONS_IN_MENUS' in os.environ) |
| 1498 |
self.palette_manager.setup_styles() |
| 1499 |
self.setup_ui_font() |
| 1500 |
fi = gprefs['font'] |
| 1501 |
if fi is not None: |
| 1502 |
font = QFont(*(fi[:4])) |
| 1503 |
s = gprefs.get('font_stretch', None) |
| 1504 |
if s is not None: |
| 1505 |
font.setStretch(s) |
| 1506 |
QApplication.setFont(font) |
| 1507 |
if not ismacos and not iswindows: |
| 1508 |
# Qt 5.10.1 on Linux resets the global font on first event loop tick. |
| 1509 |
# So workaround it by setting the font once again in a timer. |
| 1510 |
font_from_prefs = self.font() |
| 1511 |
QTimer.singleShot(0, lambda: QApplication.setFont(font_from_prefs)) |
| 1512 |
self.line_height = max(12, QFontMetrics(self.font()).lineSpacing()) |
| 1513 |
|
| 1514 |
dl = QLocale(get_lang()) |
| 1515 |
if str(dl.bcp47Name()) != 'C': |
| 1516 |
QLocale.setDefault(dl) |
| 1517 |
global gui_thread, qt_app |
| 1518 |
gui_thread = QThread.currentThread() |
| 1519 |
self.load_translations() |
| 1520 |
qt_app = self |
| 1521 |
|
| 1522 |
if not ismacos: |
| 1523 |
# OS X uses a native color dialog that does not support custom |
| 1524 |
# colors |
| 1525 |
self.color_prefs = color_prefs |
| 1526 |
self.read_custom_colors() |
| 1527 |
self.lastWindowClosed.connect(self.save_custom_colors) |
| 1528 |
|
| 1529 |
if isxp: |
| 1530 |
error_dialog( |
| 1531 |
None, |
| 1532 |
_('Windows XP not supported'), |
| 1533 |
'<p>' |
| 1534 |
+ _( |
| 1535 |
'calibre versions newer than 2.0 do not run on Windows XP. This is' |
| 1536 |
' because the graphics toolkit calibre uses (Qt 5) crashes a lot' |
| 1537 |
' on Windows XP. We suggest you stay with <a href="%s">calibre 1.48</a>' |
| 1538 |
' which works well on Windows XP.' |
| 1539 |
) |
| 1540 |
% 'https://download.calibre-ebook.com/1.48.0/', |
| 1541 |
show=True, |
| 1542 |
) |
| 1543 |
raise SystemExit(1) |
| 1544 |
|
| 1545 |
if iswindows: |
| 1546 |
# Prevent text copied to the clipboard from being lost on quit due to |
| 1547 |
# Qt 5 bug: https://bugreports.qt-project.org/browse/QTBUG-41125 |
| 1548 |
self.aboutToQuit.connect(self.flush_clipboard) |
| 1549 |
|
| 1550 |
if ismacos: |
| 1551 |
from calibre_extensions.cocoa import cursor_blink_time |
| 1552 |
|
| 1553 |
cft = cursor_blink_time() |
| 1554 |
if cft >= 0: |
| 1555 |
self.setCursorFlashTime(int(cft)) |
| 1556 |
|
| 1557 |
@property |
| 1558 |
def using_calibre_style(self) -> bool: |
| 1559 |
return self.palette_manager.using_calibre_style |
| 1560 |
|
| 1561 |
@property |
| 1562 |
def is_dark_theme(self): |
| 1563 |
return self.palette_manager.is_dark_theme |
| 1564 |
|
| 1565 |
@property |
| 1566 |
def emphasis_window_background_color(self): |
| 1567 |
return (builtin_colors_dark if self.is_dark_theme else builtin_colors_light)['yellow'] |
| 1568 |
|
| 1569 |
@pyqtSlot(int, result='QIcon') |
| 1570 |
def get_qt_standard_icon(self, standard_pixmap): |
| 1571 |
return self.palette_manager.get_qt_standard_icon(standard_pixmap) |
| 1572 |
|
| 1573 |
def safe_restore_geometry(self, widget, geom): |
| 1574 |
# See https://bugreports.qt.io/browse/QTBUG-77385 |
| 1575 |
if not geom: |
| 1576 |
return |
| 1577 |
restored = widget.restoreGeometry(geom) |
| 1578 |
self.ensure_window_on_screen(widget) |
| 1579 |
return restored |
| 1580 |
|
| 1581 |
def ensure_window_on_screen(self, widget): |
| 1582 |
screen_rect = widget.screen().availableGeometry() |
| 1583 |
g = widget.geometry() |
| 1584 |
w = min(screen_rect.width(), g.width()) |
| 1585 |
h = min(screen_rect.height(), g.height()) |
| 1586 |
if w != g.width() or h != g.height(): |
| 1587 |
widget.resize(w, h) |
| 1588 |
if not widget.geometry().intersects(screen_rect): |
| 1589 |
w = min(widget.width(), screen_rect.width() - 10) |
| 1590 |
h = min(widget.height(), screen_rect.height() - 10) |
| 1591 |
widget.resize(w, h) |
| 1592 |
widget.move((screen_rect.width() - w) // 2, (screen_rect.height() - h) // 2) |
| 1593 |
|
| 1594 |
def setup_ui_font(self): |
| 1595 |
f = QFont(QApplication.font()) |
| 1596 |
q = (f.family(), f.pointSize()) |
| 1597 |
if iswindows: |
| 1598 |
if q == ('MS Shell Dlg 2', 8): # Qt default setting |
| 1599 |
# Microsoft recommends the default font be Segoe UI at 9 pt |
| 1600 |
# https://msdn.microsoft.com/en-us/library/windows/desktop/dn742483(v=vs.85).aspx |
| 1601 |
f.setFamily('Segoe UI') |
| 1602 |
f.setPointSize(9) |
| 1603 |
QApplication.setFont(f) |
| 1604 |
elif q == ('Sans Serif', 9): # Hard coded Qt settings, no user preference detected |
| 1605 |
f.setPointSize(10) |
| 1606 |
QApplication.setFont(f) |
| 1607 |
f = QFontInfo(f) |
| 1608 |
self.original_font = (f.family(), f.pointSize(), f.weight(), f.italic(), 100) |
| 1609 |
|
| 1610 |
def flush_clipboard(self): |
| 1611 |
try: |
| 1612 |
cb = self.clipboard() |
| 1613 |
assert cb is not None |
| 1614 |
if cb.ownsClipboard(): |
| 1615 |
import ctypes |
| 1616 |
|
| 1617 |
ctypes.WinDLL('ole32.dll').OleFlushClipboard() |
| 1618 |
except Exception: |
| 1619 |
import traceback |
| 1620 |
|
| 1621 |
traceback.print_exc() |
| 1622 |
|
| 1623 |
def load_builtin_fonts(self, scan_for_fonts=False): |
| 1624 |
if scan_for_fonts: |
| 1625 |
from calibre.utils.fonts.scanner import font_scanner |
| 1626 |
|
| 1627 |
# Start scanning the users computer for fonts |
| 1628 |
font_scanner |
| 1629 |
|
| 1630 |
load_builtin_fonts() |
| 1631 |
|
| 1632 |
@lru_cache(maxsize=256) |
| 1633 |
def cached_qimage(self, name, device_pixel_ratio=0): |
| 1634 |
return self.cached_qpixmap(name, device_pixel_ratio).toImage() |
| 1635 |
|
| 1636 |
@lru_cache(maxsize=256) |
| 1637 |
def cached_qpixmap(self, name, device_pixel_ratio=0): |
| 1638 |
# get the actual size of the image since QIcon does not tell us this for |
| 1639 |
# icons loaded from a theme |
| 1640 |
path = I(name, allow_user_override=False) |
| 1641 |
r = QImageReader(path) |
| 1642 |
ic = QIcon.ic(name) |
| 1643 |
if not device_pixel_ratio: |
| 1644 |
device_pixel_ratio = self.devicePixelRatio() |
| 1645 |
ans = ic.pixmap(r.size()) |
| 1646 |
ans.setDevicePixelRatio(device_pixel_ratio) |
| 1647 |
return ans |
| 1648 |
|
| 1649 |
def _send_file_open_events(self): |
| 1650 |
with self._file_open_lock: |
| 1651 |
if self._file_open_paths: |
| 1652 |
if callable(self.file_event_hook): |
| 1653 |
self.file_event_hook(self._file_open_paths) |
| 1654 |
self._file_open_paths = [] |
| 1655 |
|
| 1656 |
def get_pending_file_open_events(self): |
| 1657 |
with self._file_open_lock: |
| 1658 |
ans = self._file_open_paths |
| 1659 |
self._file_open_paths = [] |
| 1660 |
return ans |
| 1661 |
|
| 1662 |
def load_translations(self): |
| 1663 |
install_qt_translator() |
| 1664 |
|
| 1665 |
def event(self, a0): |
| 1666 |
etype = a0.type() |
| 1667 |
if etype == QEvent.Type.FileOpen: |
| 1668 |
added_event = False |
| 1669 |
qurl = a0.url() |
| 1670 |
if qurl.isLocalFile(): |
| 1671 |
with self._file_open_lock: |
| 1672 |
path = qurl.toLocalFile() |
| 1673 |
if os.access(path, os.R_OK): |
| 1674 |
self._file_open_paths.append(path) |
| 1675 |
added_event = True |
| 1676 |
elif qurl.isValid(): |
| 1677 |
if qurl.scheme() == 'calibre': |
| 1678 |
self.handle_calibre_url(qurl) |
| 1679 |
if added_event: |
| 1680 |
QTimer.singleShot(1000, self._send_file_open_events) |
| 1681 |
return True |
| 1682 |
else: |
| 1683 |
if etype == QEvent.Type.ApplicationPaletteChange: |
| 1684 |
self.palette_manager.on_qt_palette_change() |
| 1685 |
return QApplication.event(self, a0) |
| 1686 |
|
| 1687 |
@pyqtSlot(QUrl) |
| 1688 |
def handle_calibre_url(self, qurl): |
| 1689 |
url = qurl.toString(QUrl.ComponentFormattingOption.FullyEncoded) |
| 1690 |
with self._file_open_lock: |
| 1691 |
self._file_open_paths.append(url) |
| 1692 |
QTimer.singleShot(100, self._send_file_open_events) |
| 1693 |
|
| 1694 |
@pyqtSlot(QUrl) |
| 1695 |
def handle_http_url(self, qurl): |
| 1696 |
safe_open_url(qurl) |
| 1697 |
|
| 1698 |
@property |
| 1699 |
def current_custom_colors(self): |
| 1700 |
from qt.core import QColorDialog |
| 1701 |
|
| 1702 |
return [col.getRgb() for col in (QColorDialog.customColor(i) for i in range(QColorDialog.customCount()))] |
| 1703 |
|
| 1704 |
@current_custom_colors.setter |
| 1705 |
def current_custom_colors(self, colors): |
| 1706 |
from qt.core import QColorDialog |
| 1707 |
|
| 1708 |
num = min(len(colors), QColorDialog.customCount()) |
| 1709 |
for i in range(num): |
| 1710 |
QColorDialog.setCustomColor(i, QColor(*colors[i])) |
| 1711 |
|
| 1712 |
def read_custom_colors(self): |
| 1713 |
colors = self.color_prefs.get('custom_colors_for_color_dialog', None) |
| 1714 |
if colors is not None: |
| 1715 |
self.current_custom_colors = colors |
| 1716 |
|
| 1717 |
def save_custom_colors(self): |
| 1718 |
# Qt 5 regression, it no longer saves custom colors |
| 1719 |
colors = self.current_custom_colors |
| 1720 |
if colors != self.color_prefs.get('custom_colors_for_color_dialog', None): |
| 1721 |
self.color_prefs.set('custom_colors_for_color_dialog', colors) |
| 1722 |
|
| 1723 |
def __enter__(self): |
| 1724 |
self.setQuitOnLastWindowClosed(False) |
| 1725 |
|
| 1726 |
def __exit__(self, type, value, traceback): |
| 1727 |
self.setQuitOnLastWindowClosed(True) |
| 1728 |
|
| 1729 |
def setup_unix_signals(self): |
| 1730 |
setup_unix_signals(self) |
| 1731 |
|
| 1732 |
def signal_received(self): |
| 1733 |
try: |
| 1734 |
os.read(int(self.signal_notifier.socket()), 1024) |
| 1735 |
except OSError: |
| 1736 |
return |
| 1737 |
self.shutdown_signal_received.emit() |
| 1738 |
|
| 1739 |
|
| 1740 |
_store_app: QApplication | None = None |
| 1741 |
|
| 1742 |
SanitizeLibraryPath = sanitize_env_vars # For old plugins |
| 1743 |
|
| 1744 |
|
| 1745 |
def open_url(qurl): |
| 1746 |
if isinstance(qurl, (str, bytes)): |
| 1747 |
qurl = QUrl(qurl) |
| 1748 |
scheme = qurl.scheme().lower() or 'file' |
| 1749 |
import fnmatch |
| 1750 |
|
| 1751 |
opener = [] |
| 1752 |
with suppress(Exception): |
| 1753 |
for scheme_pat, spec in tweaks['openers_by_scheme'].items(): |
| 1754 |
if fnmatch.fnmatch(scheme, scheme_pat): |
| 1755 |
with suppress(Exception): |
| 1756 |
import shlex |
| 1757 |
|
| 1758 |
opener = shlex.split(spec) |
| 1759 |
break |
| 1760 |
|
| 1761 |
def run_cmd(cmd): |
| 1762 |
import subprocess |
| 1763 |
|
| 1764 |
subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) |
| 1765 |
|
| 1766 |
with sanitize_env_vars(): |
| 1767 |
if opener: |
| 1768 |
cmd = [x.replace('%u', qurl.toString()) for x in opener] |
| 1769 |
if DEBUG: |
| 1770 |
print('Running opener:', cmd) |
| 1771 |
run_cmd(cmd) |
| 1772 |
else: |
| 1773 |
# Qt 5 requires QApplication to be constructed before trying to use |
| 1774 |
# QDesktopServices::openUrl() |
| 1775 |
ensure_app() |
| 1776 |
cmd = [ |
| 1777 |
'xdg-open', |
| 1778 |
qurl.toLocalFile() if qurl.isLocalFile() else qurl.toString(QUrl.ComponentFormattingOption.FullyEncoded), |
| 1779 |
] |
| 1780 |
if isfrozen and qapplication_or_fail().platformName() == 'wayland': |
| 1781 |
# See https://bugreports.qt.io/browse/QTBUG-119438 |
| 1782 |
run_cmd(cmd) |
| 1783 |
ok = True |
| 1784 |
else: |
| 1785 |
ok = QDesktopServices.openUrl(qurl) |
| 1786 |
if not ok: |
| 1787 |
# this happens a lot with Qt 6.5.3. On Wayland, Qt requires |
| 1788 |
# BOTH a QApplication AND a top level window so it can use the |
| 1789 |
# xdg activation token system Wayland imposes. |
| 1790 |
print('QDesktopServices::openUrl() failed for url:', qurl, file=sys.stderr) |
| 1791 |
if islinux: |
| 1792 |
if DEBUG: |
| 1793 |
print('Opening with xdg-open:', cmd) |
| 1794 |
run_cmd(cmd) |
| 1795 |
|
| 1796 |
|
| 1797 |
def safe_open_url(qurl: QUrl | str | bytes) -> None: |
| 1798 |
if isinstance(qurl, bytes): |
| 1799 |
qurl = qurl.decode() |
| 1800 |
if isinstance(qurl, str): |
| 1801 |
qurl = QUrl(qurl) |
| 1802 |
if qurl.scheme() in ('', 'file'): |
| 1803 |
path = qurl.toLocalFile() |
| 1804 |
ext = os.path.splitext(path)[-1].lower()[1:] |
| 1805 |
if ext in ('exe', 'com', 'cmd', 'bat', 'sh', 'psh', 'ps1', 'vbs', 'js', 'wsf', 'vba', 'py', 'rb', 'pl', 'app'): |
| 1806 |
prints('Refusing to open file:', path, file=sys.stderr) |
| 1807 |
return |
| 1808 |
open_url(qurl) |
| 1809 |
|
| 1810 |
|
| 1811 |
def get_current_db(): |
| 1812 |
""" |
| 1813 |
This method will try to return the current database in use by the user as |
| 1814 |
efficiently as possible, i.e. without constructing duplicate |
| 1815 |
LibraryDatabase objects. |
| 1816 |
""" |
| 1817 |
from calibre.gui2.ui import get_gui |
| 1818 |
|
| 1819 |
gui = get_gui() |
| 1820 |
if gui is not None and gui.current_db is not None: |
| 1821 |
return gui.current_db |
| 1822 |
from calibre.library import db |
| 1823 |
|
| 1824 |
return db() |
| 1825 |
|
| 1826 |
|
| 1827 |
def open_local_file(path): |
| 1828 |
if iswindows: |
| 1829 |
with sanitize_env_vars(): |
| 1830 |
os.startfile(os.path.normpath(path)) |
| 1831 |
else: |
| 1832 |
url = QUrl.fromLocalFile(path) |
| 1833 |
open_url(url) |
| 1834 |
|
| 1835 |
|
| 1836 |
_ea_lock = Lock() |
| 1837 |
|
| 1838 |
|
| 1839 |
def simple_excepthook(t, v, tb): |
| 1840 |
return sys.__excepthook__(t, v, tb) |
| 1841 |
|
| 1842 |
|
| 1843 |
def ensure_app(headless=True) -> QApplication: |
| 1844 |
global _store_app |
| 1845 |
with _ea_lock: |
| 1846 |
if _store_app is None: |
| 1847 |
if QApplication.instance() is None: |
| 1848 |
args = sys.argv[:1] |
| 1849 |
if not headless: |
| 1850 |
_store_app = Application([]) |
| 1851 |
sys.excepthook = simple_excepthook |
| 1852 |
return _store_app |
| 1853 |
has_headless = ismacos or islinux or isbsd |
| 1854 |
if headless and has_headless: |
| 1855 |
args += [ |
| 1856 |
'-platformpluginpath', |
| 1857 |
plugins_loc, |
| 1858 |
'-platform', |
| 1859 |
os.environ.get('CALIBRE_HEADLESS_PLATFORM', 'headless'), |
| 1860 |
] |
| 1861 |
# WebEngine GPU not needed in headless mode |
| 1862 |
args += ['--webEngineArgs', '--disable-gpu'] |
| 1863 |
if ismacos: |
| 1864 |
os.environ['QT_MAC_DISABLE_FOREGROUND_APPLICATION_TRANSFORM'] = '1' |
| 1865 |
if headless and iswindows: |
| 1866 |
QApplication.setAttribute(Qt.ApplicationAttribute.AA_UseSoftwareOpenGL, True) |
| 1867 |
QApplication.setAttribute(Qt.ApplicationAttribute.AA_ShareOpenGLContexts) |
| 1868 |
_store_app = QApplication(args) |
| 1869 |
set_image_allocation_limit() |
| 1870 |
if headless and has_headless: |
| 1871 |
setattr(_store_app, 'headless', True) |
| 1872 |
|
| 1873 |
# This is needed because as of PyQt 5.4 if sys.execpthook == |
| 1874 |
# sys.__excepthook__ PyQt will abort the application on an |
| 1875 |
# unhandled python exception in a slot or virtual method. Since ensure_app() |
| 1876 |
# is used in worker processes for background work like rendering html |
| 1877 |
# or running a headless browser, we circumvent this as I really |
| 1878 |
# don't feel like going through all the code and making sure no |
| 1879 |
# unhandled exceptions ever occur. All the actual GUI apps already |
| 1880 |
# override sys.excepthook with a proper error handler. |
| 1881 |
sys.excepthook = simple_excepthook |
| 1882 |
else: |
| 1883 |
_store_app = qapplication_or_fail() |
| 1884 |
return _store_app |
| 1885 |
|
| 1886 |
|
| 1887 |
def qapplication_or_fail() -> Application: |
| 1888 |
ans = QApplication.instance() |
| 1889 |
if ans is None: |
| 1890 |
raise RuntimeError('No QApplication has been constructed') |
| 1891 |
return cast(Application, ans) |
| 1892 |
|
| 1893 |
|
| 1894 |
def destroy_app(): |
| 1895 |
global _store_app |
| 1896 |
_store_app = None |
| 1897 |
|
| 1898 |
|
| 1899 |
def app_is_headless(): |
| 1900 |
return getattr(_store_app, 'headless', False) |
| 1901 |
|
| 1902 |
|
| 1903 |
def must_use_qt(headless=True): |
| 1904 |
"""This function should be called if you want to use Qt for some non-GUI |
| 1905 |
task like rendering HTML/SVG or using a headless browser. It will raise a |
| 1906 |
RuntimeError if using Qt is not possible, which will happen if the current |
| 1907 |
thread is not the main GUI thread. On linux, it uses a special QPA headless |
| 1908 |
plugin, so that the X server does not need to be running.""" |
| 1909 |
global gui_thread |
| 1910 |
ensure_app(headless=headless) |
| 1911 |
if gui_thread is None: |
| 1912 |
gui_thread = QThread.currentThread() |
| 1913 |
if gui_thread is not QThread.currentThread(): |
| 1914 |
raise RuntimeError('Cannot use Qt in non GUI thread') |
| 1915 |
|
| 1916 |
|
| 1917 |
def is_ok_to_use_qt(): |
| 1918 |
try: |
| 1919 |
must_use_qt() |
| 1920 |
except RuntimeError: |
| 1921 |
return False |
| 1922 |
return True |
| 1923 |
|
| 1924 |
|
| 1925 |
def is_gui_thread(): |
| 1926 |
global gui_thread |
| 1927 |
return gui_thread is QThread.currentThread() |
| 1928 |
|
| 1929 |
|
| 1930 |
_rating_font = 'Arial Unicode MS' if iswindows else 'sans-serif' |
| 1931 |
|
| 1932 |
|
| 1933 |
def rating_font(): |
| 1934 |
global _rating_font |
| 1935 |
return _rating_font |
| 1936 |
|
| 1937 |
|
| 1938 |
def elided_text(text, font=None, width=300, pos='middle'): |
| 1939 |
"""Return a version of text that is no wider than width pixels when |
| 1940 |
rendered, replacing characters from the left, middle or right (as per pos) |
| 1941 |
of the string with an ellipsis. Results in a string much closer to the |
| 1942 |
limit than Qt's elidedText().""" |
| 1943 |
from qt.core import QFontMetrics |
| 1944 |
|
| 1945 |
if font is None: |
| 1946 |
font = qapplication_or_fail().font() |
| 1947 |
fm = font if isinstance(font, QFontMetrics) else QFontMetrics(font) |
| 1948 |
delta = 4 |
| 1949 |
ellipsis = '…' |
| 1950 |
|
| 1951 |
def remove_middle(x): |
| 1952 |
mid = len(x) // 2 |
| 1953 |
return x[: max(0, mid - (delta // 2))] + ellipsis + x[mid + (delta // 2) :] |
| 1954 |
|
| 1955 |
chomp = {'middle': remove_middle, 'left': lambda x: ellipsis + x[delta:], 'right': lambda x: x[:-delta] + ellipsis}[pos] |
| 1956 |
while len(text) > delta and fm.horizontalAdvance(text) > width: |
| 1957 |
text = chomp(text) |
| 1958 |
return str(text) |
| 1959 |
|
| 1960 |
|
| 1961 |
if is_running_from_develop and not isworker: |
| 1962 |
from calibre.build_forms import build_forms |
| 1963 |
|
| 1964 |
build_forms(os.path.abspath(os.environ['CALIBRE_DEVELOP_FROM']), check_for_migration=True) |
| 1965 |
|
| 1966 |
|
| 1967 |
def event_type_name(ev_or_etype): |
| 1968 |
etype = ev_or_etype.type() if isinstance(ev_or_etype, QEvent) else ev_or_etype |
| 1969 |
for name, num in vars(QEvent).items(): |
| 1970 |
if num == etype: |
| 1971 |
return name |
| 1972 |
return 'UnknownEventType' |
| 1973 |
|
| 1974 |
|
| 1975 |
empty_model = QStringListModel(['']) |
| 1976 |
empty_index = empty_model.index(0) |
| 1977 |
|
| 1978 |
|
| 1979 |
def set_app_uid(val): |
| 1980 |
import ctypes |
| 1981 |
from ctypes import HRESULT, wintypes |
| 1982 |
|
| 1983 |
try: |
| 1984 |
AppUserModelID = ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID |
| 1985 |
except Exception: # Vista has no app uids |
| 1986 |
return False |
| 1987 |
AppUserModelID.argtypes = [wintypes.LPCWSTR] |
| 1988 |
AppUserModelID.restype = HRESULT |
| 1989 |
try: |
| 1990 |
AppUserModelID(str(val)) |
| 1991 |
except Exception as err: |
| 1992 |
prints('Failed to set app uid with error:', as_unicode(err)) |
| 1993 |
return False |
| 1994 |
return True |
| 1995 |
|
| 1996 |
|
| 1997 |
def add_to_recent_docs(path): |
| 1998 |
from calibre_extensions import winutil |
| 1999 |
|
| 2000 |
app = qapplication_or_fail() |
| 2001 |
winutil.add_to_recent_docs(str(path), app.windows_app_uid) |
| 2002 |
|
| 2003 |
|
| 2004 |
def make_view_use_window_background(view): |
| 2005 |
p = view.palette() |
| 2006 |
p.setColor(QPalette.ColorRole.Base, p.color(QPalette.ColorRole.Window)) |
| 2007 |
p.setColor(QPalette.ColorRole.AlternateBase, p.color(QPalette.ColorRole.Window)) |
| 2008 |
view.setPalette(p) |
| 2009 |
return view |
| 2010 |
|
| 2011 |
|
| 2012 |
def local_path_for_resource(qurl: QUrl, base_qurl: QUrl | None = None) -> str: |
| 2013 |
if base_qurl and qurl.isRelative(): |
| 2014 |
qurl = base_qurl.resolved(qurl) |
| 2015 |
|
| 2016 |
if qurl.isLocalFile(): |
| 2017 |
return qurl.toLocalFile() |
| 2018 |
if qurl.isRelative(): # this means has no scheme |
| 2019 |
return qurl.path() |
| 2020 |
return '' |
| 2021 |
|
| 2022 |
|
| 2023 |
def raise_and_focus(self: QWidget) -> None: |
| 2024 |
self.raise_() |
| 2025 |
self.activateWindow() |
| 2026 |
|
| 2027 |
|
| 2028 |
def raise_without_focus(self: QWidget) -> None: |
| 2029 |
if qapplication_or_fail().platformName() == 'wayland': |
| 2030 |
# On fucking Wayland, we can't raise a dialog without also giving it |
| 2031 |
# keyboard focus. What a joke. |
| 2032 |
self.raise_and_focus() |
| 2033 |
else: |
| 2034 |
self.raise_() |
| 2035 |
|
| 2036 |
|
| 2037 |
QWidget.raise_and_focus = raise_and_focus |
| 2038 |
QWidget.raise_without_focus = raise_without_focus |
| 2039 |
|
| 2040 |
|
| 2041 |
@contextmanager |
| 2042 |
def clip_border_radius(painter, rect): |
| 2043 |
painter.save() |
| 2044 |
r = gprefs['cover_corner_radius'] |
| 2045 |
if r > 0: |
| 2046 |
pp = QPainterPath() |
| 2047 |
pp.addRoundedRect( |
| 2048 |
QRectF(rect), |
| 2049 |
r, |
| 2050 |
r, |
| 2051 |
Qt.SizeMode.RelativeSize if gprefs['cover_corner_radius_unit'] == '%' else Qt.SizeMode.AbsoluteSize, |
| 2052 |
) |
| 2053 |
painter.setClipPath(pp) |
| 2054 |
try: |
| 2055 |
yield |
| 2056 |
finally: |
| 2057 |
painter.restore() |
| 2058 |
|
| 2059 |
|
| 2060 |
def resolve_custom_background(name: str, which='color', for_dark: bool | None = None, use_defaults: bool = False): |
| 2061 |
if use_defaults: |
| 2062 |
s = gprefs.defaults[name] |
| 2063 |
else: |
| 2064 |
s = gprefs[name] |
| 2065 |
if name == 'cover_grid_background' and not s.get('migrated'): |
| 2066 |
s = s.copy() |
| 2067 |
s['migrated'] = True |
| 2068 |
legacy = gprefs.pop('cover_grid_color', None) |
| 2069 |
if legacy is not None and tuple(legacy) != (80, 80, 80): |
| 2070 |
s['light'] = s['dark'] = legacy |
| 2071 |
legacy = gprefs.pop('cover_grid_texture', None) |
| 2072 |
if legacy is not None: |
| 2073 |
s['light_texture'] = s['dark_texture'] = legacy |
| 2074 |
gprefs[name] = s |
| 2075 |
if for_dark is None: |
| 2076 |
for_dark = qapplication_or_fail().is_dark_theme |
| 2077 |
key = 'dark' if for_dark else 'light' |
| 2078 |
if which == 'color': |
| 2079 |
return s[key] |
| 2080 |
return s[f'{key}_texture'] |
| 2081 |
|
| 2082 |
|
| 2083 |
def resolve_grid_color(which='color', for_dark: bool | None = None, use_defaults: bool = False): |
| 2084 |
return resolve_custom_background('cover_grid_background', which=which, for_dark=for_dark, use_defaults=use_defaults) |
| 2085 |
|
| 2086 |
|
| 2087 |
def resolve_bookshelf_color(which='color', for_dark: bool | None = None, use_defaults: bool = False): |
| 2088 |
return resolve_custom_background('bookshelf_custom_background', which=which, for_dark=for_dark, use_defaults=use_defaults) |