| 1 |
#!/usr/bin/env python |
| 2 |
# License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> |
| 3 |
|
| 4 |
import atexit |
| 5 |
import os |
| 6 |
import re |
| 7 |
import sys |
| 8 |
import time |
| 9 |
import traceback |
| 10 |
|
| 11 |
import apsw |
| 12 |
from qt.core import QCoreApplication, QIcon, QObject, QTimer, sip |
| 13 |
|
| 14 |
from calibre import force_unicode, prints, timed_print |
| 15 |
from calibre.constants import DEBUG, MAIN_APP_UID, __appname__, filesystem_encoding, get_portable_base, islinux, ismacos, iswindows |
| 16 |
from calibre.gui2 import Application, choose_dir, error_dialog, gprefs, initialize_file_icon_provider, question_dialog, setup_gui_option_parser |
| 17 |
from calibre.gui2.listener import send_message_in_process |
| 18 |
from calibre.gui2.main_window import option_parser as _option_parser |
| 19 |
from calibre.gui2.splash_screen import SplashScreen |
| 20 |
from calibre.utils.config import dynamic, prefs |
| 21 |
from calibre.utils.localization import _ |
| 22 |
from calibre.utils.lock import SingleInstance |
| 23 |
from calibre.utils.monotonic import monotonic |
| 24 |
from calibre.utils.resources import get_image_path as I |
| 25 |
from polyglot.builtins import as_bytes, environ_item |
| 26 |
|
| 27 |
after_quit_actions = {'debug_on_restart': False, 'restart_after_quit': False, 'no_plugins_on_restart': False} |
| 28 |
if iswindows: |
| 29 |
from calibre_extensions import winutil |
| 30 |
|
| 31 |
|
| 32 |
class AbortInit(Exception): |
| 33 |
pass |
| 34 |
|
| 35 |
|
| 36 |
def option_parser(): |
| 37 |
parser = _option_parser( |
| 38 |
_('''\ |
| 39 |
%prog [options] [path_to_ebook or calibre url ...] |
| 40 |
|
| 41 |
Launch the main calibre Graphical User Interface and optionally add the e-book at |
| 42 |
path_to_ebook to the database. You can also specify calibre URLs to perform various |
| 43 |
different actions, than just adding books. For example: |
| 44 |
|
| 45 |
calibre://view-book/test_library/1842/epub |
| 46 |
|
| 47 |
Will open the book with id 1842 in the EPUB format from the library |
| 48 |
"test_library" in the calibre E-book viewer. Library names are the folder names of the |
| 49 |
libraries with spaces replaced by underscores. A full description of the |
| 50 |
various URL based actions is in the User Manual. |
| 51 |
''') |
| 52 |
) |
| 53 |
parser.add_option('--with-library', default=None, action='store', help=_('Use the library located at the specified path.')) |
| 54 |
parser.add_option('--start-in-tray', default=False, action='store_true', help=_('Start minimized to system tray.')) |
| 55 |
parser.add_option('-v', '--verbose', default=0, action='count', help=_('Ignored, do not use. Present only for legacy reasons')) |
| 56 |
parser.add_option('--no-update-check', default=False, action='store_true', help=_('Do not check for updates')) |
| 57 |
parser.add_option( |
| 58 |
'--ignore-plugins', |
| 59 |
default=False, |
| 60 |
action='store_true', |
| 61 |
help=_('Ignore custom plugins, useful if you installed a plugin that is preventing calibre from starting'), |
| 62 |
) |
| 63 |
parser.add_option( |
| 64 |
'-s', |
| 65 |
'--shutdown-running-calibre', |
| 66 |
default=False, |
| 67 |
action='store_true', |
| 68 |
help=_( |
| 69 |
'Cause a running calibre instance, if any, to be shutdown. Note that if there are running jobs, they will be silently aborted, so use with care.' |
| 70 |
), |
| 71 |
) |
| 72 |
parser.add_option( |
| 73 |
'--add-and-delete', |
| 74 |
default=[], |
| 75 |
action='append', |
| 76 |
dest='add_and_delete', |
| 77 |
help=_('Add the book at the specified path to the library and then delete it. Works only for files inside the temporary folder of the system.'), |
| 78 |
) |
| 79 |
setup_gui_option_parser(parser) |
| 80 |
return parser |
| 81 |
|
| 82 |
|
| 83 |
# Books to be added and deleted are passed on as arguments in this form, so |
| 84 |
# that they reach both a newly started calibre GUI and, via communicate(), one |
| 85 |
# that is already running. |
| 86 |
ADD_AND_DELETE_PREFIX = '--add-and-delete=' |
| 87 |
|
| 88 |
|
| 89 |
def args_for_add_and_delete(paths: list[str]) -> list[str]: |
| 90 |
from calibre.ptempfile import is_in_system_tempdir |
| 91 |
|
| 92 |
ans = [] |
| 93 |
for path in paths: |
| 94 |
path = os.path.abspath(os.path.expanduser(path)) |
| 95 |
# Deleting files is only safe to do for the temporary files this option |
| 96 |
# exists for, see calibre.gui2.cyoa.read.ReadStoryDialog.export_epub() |
| 97 |
if is_in_system_tempdir(path) and os.path.isfile(path): |
| 98 |
ans.append(ADD_AND_DELETE_PREFIX + path) |
| 99 |
else: |
| 100 |
prints(f'Ignoring {path!r} as it is not a file in the temporary folder of the system', file=sys.stderr) |
| 101 |
return ans |
| 102 |
|
| 103 |
|
| 104 |
def find_portable_library(): |
| 105 |
base = get_portable_base() |
| 106 |
if base is None: |
| 107 |
return |
| 108 |
import glob |
| 109 |
|
| 110 |
candidates = [os.path.basename(os.path.dirname(x)) for x in glob.glob(os.path.join(base, f'*{os.sep}metadata.db'))] |
| 111 |
if not candidates: |
| 112 |
candidates = ['Calibre Library'] |
| 113 |
lp = prefs['library_path'] |
| 114 |
if not lp: |
| 115 |
lib = os.path.join(base, candidates[0]) |
| 116 |
else: |
| 117 |
lib = None |
| 118 |
q = os.path.basename(lp) |
| 119 |
for c in candidates: |
| 120 |
if c.lower() == q.lower(): |
| 121 |
lib = os.path.join(base, c) |
| 122 |
break |
| 123 |
if lib is None: |
| 124 |
lib = os.path.join(base, candidates[0]) |
| 125 |
|
| 126 |
if len(lib) > 74: |
| 127 |
error_dialog( |
| 128 |
None, |
| 129 |
_('Path too long'), |
| 130 |
_('Path to Calibre Portable (%s) too long. It must be less than 59 characters.') % base, |
| 131 |
show=True, |
| 132 |
) |
| 133 |
raise AbortInit() |
| 134 |
|
| 135 |
prefs.set('library_path', lib) |
| 136 |
if not os.path.exists(lib): |
| 137 |
os.mkdir(lib) |
| 138 |
|
| 139 |
|
| 140 |
def init_qt(args): |
| 141 |
parser = option_parser() |
| 142 |
opts, args = parser.parse_args(args) |
| 143 |
if os.environ.pop('CALIBRE_IGNORE_PLUGINS_ON_RESTART', '') == '1': |
| 144 |
opts.ignore_plugins = True |
| 145 |
find_portable_library() |
| 146 |
if opts.with_library is not None: |
| 147 |
libpath = os.path.expanduser(opts.with_library) |
| 148 |
if not os.path.exists(libpath): |
| 149 |
os.makedirs(libpath) |
| 150 |
if os.path.isdir(libpath): |
| 151 |
prefs.set('library_path', os.path.abspath(libpath)) |
| 152 |
prints('Using library at', prefs['library_path']) |
| 153 |
if opts.add_and_delete: |
| 154 |
args += args_for_add_and_delete(opts.add_and_delete) |
| 155 |
override = 'calibre-gui' if islinux else None |
| 156 |
app = Application(args, override_program_name=override, windows_app_uid=MAIN_APP_UID, should_handle_calibre_urls=True) |
| 157 |
|
| 158 |
app.file_event_hook = EventAccumulator() |
| 159 |
try: |
| 160 |
is_x11 = app.platformName() == 'xcb' |
| 161 |
except Exception: |
| 162 |
import traceback |
| 163 |
|
| 164 |
traceback.print_exc() |
| 165 |
is_x11 = False |
| 166 |
# Ancient broken VNC servers cannot handle icons of size greater than 256 |
| 167 |
# https://www.mobileread.com/forums/showthread.php?t=278447 |
| 168 |
ic = 'lt.png' if is_x11 else 'library.png' |
| 169 |
if not ismacos: |
| 170 |
app.setWindowIcon(QIcon(I(ic, allow_user_override=False))) |
| 171 |
return app, opts, args |
| 172 |
|
| 173 |
|
| 174 |
def get_default_library_path(): |
| 175 |
fname = _('Calibre Library') |
| 176 |
if iswindows: |
| 177 |
fname = 'Calibre Library' |
| 178 |
if isinstance(fname, str): |
| 179 |
try: |
| 180 |
fname.encode(filesystem_encoding) |
| 181 |
except Exception: |
| 182 |
fname = 'Calibre Library' |
| 183 |
x = os.path.expanduser(os.path.join('~', fname)) |
| 184 |
if not os.path.exists(x): |
| 185 |
try: |
| 186 |
os.makedirs(x) |
| 187 |
except Exception: |
| 188 |
x = os.path.expanduser('~') |
| 189 |
return x |
| 190 |
|
| 191 |
|
| 192 |
def try_other_known_library_paths(): |
| 193 |
stats = gprefs.get('library_usage_stats', {}) |
| 194 |
if stats: |
| 195 |
for candidate in sorted(stats.keys(), key=stats.__getitem__, reverse=True): |
| 196 |
candidate = os.path.abspath(candidate) |
| 197 |
if os.path.exists(candidate): |
| 198 |
return candidate |
| 199 |
|
| 200 |
|
| 201 |
def get_library_path(gui_runner): |
| 202 |
library_path = prefs['library_path'] |
| 203 |
if library_path is None: # Need to migrate to new database layout |
| 204 |
base = os.path.expanduser('~') |
| 205 |
if not base or not os.path.exists(base): |
| 206 |
from qt.core import QDir |
| 207 |
|
| 208 |
base = str(QDir.homePath()).replace('/', os.sep) |
| 209 |
candidate = gui_runner.choose_dir(base) |
| 210 |
if not candidate: |
| 211 |
candidate = os.path.join(base, 'Calibre Library') |
| 212 |
library_path = os.path.abspath(candidate) |
| 213 |
elif not os.path.exists(library_path): |
| 214 |
q = try_other_known_library_paths() |
| 215 |
if q: |
| 216 |
library_path = q |
| 217 |
if not os.path.exists(library_path): |
| 218 |
try: |
| 219 |
os.makedirs(library_path) |
| 220 |
except Exception: |
| 221 |
gui_runner.show_error( |
| 222 |
_('Failed to create library'), |
| 223 |
_('Failed to create calibre library at: %r.\nYou will be asked to choose a new library location.') % library_path, |
| 224 |
det_msg=traceback.format_exc(), |
| 225 |
) |
| 226 |
library_path = gui_runner.choose_dir(get_default_library_path()) |
| 227 |
return library_path |
| 228 |
|
| 229 |
|
| 230 |
def repair_library(library_path): |
| 231 |
from calibre.gui2.dialogs.restore_library import repair_library_at |
| 232 |
|
| 233 |
return repair_library_at(library_path) |
| 234 |
|
| 235 |
|
| 236 |
def windows_repair(library_path=None): |
| 237 |
import subprocess |
| 238 |
|
| 239 |
from calibre.utils.serialize import json_dumps, json_loads |
| 240 |
from polyglot.binary import as_hex_unicode, from_hex_bytes |
| 241 |
|
| 242 |
if library_path: |
| 243 |
library_path = as_hex_unicode(json_dumps(library_path)) |
| 244 |
winutil.prepare_for_restart() |
| 245 |
os.environ['CALIBRE_REPAIR_CORRUPTED_DB'] = environ_item(library_path) |
| 246 |
subprocess.Popen([sys.executable]) |
| 247 |
else: |
| 248 |
try: |
| 249 |
app = Application([]) |
| 250 |
from calibre.gui2.dialogs.restore_library import repair_library_at |
| 251 |
|
| 252 |
library_path = json_loads(from_hex_bytes(os.environ.pop('CALIBRE_REPAIR_CORRUPTED_DB'))) |
| 253 |
done = repair_library_at(library_path, wait_time=4) |
| 254 |
except Exception: |
| 255 |
done = False |
| 256 |
error_dialog( |
| 257 |
None, |
| 258 |
_('Failed to repair library'), |
| 259 |
_('Could not repair library. Click "Show details" for more information.'), |
| 260 |
det_msg=traceback.format_exc(), |
| 261 |
show=True, |
| 262 |
) |
| 263 |
if done: |
| 264 |
subprocess.Popen([sys.executable]) |
| 265 |
app.quit() |
| 266 |
|
| 267 |
|
| 268 |
class EventAccumulator: |
| 269 |
def __init__(self): |
| 270 |
self.events = [] |
| 271 |
|
| 272 |
def __call__(self, ev): |
| 273 |
self.events.append(ev) |
| 274 |
|
| 275 |
|
| 276 |
class GuiRunner(QObject): |
| 277 |
"""Make sure an event loop is running before starting the main work of |
| 278 |
initialization""" |
| 279 |
|
| 280 |
def __init__(self, opts, args, actions, app, gui_debug=None): |
| 281 |
self.startup_time = monotonic() |
| 282 |
timed_print('Starting up...') |
| 283 |
self.opts, self.args, self.app = opts, args, app |
| 284 |
self.gui_debug = gui_debug |
| 285 |
self.actions = actions |
| 286 |
self.main = None |
| 287 |
QObject.__init__(self) |
| 288 |
self.splash_screen = None |
| 289 |
self.timer = QTimer.singleShot(1, self.initialize) |
| 290 |
|
| 291 |
def start_gui(self, db): |
| 292 |
from calibre.gui2.ui import Main |
| 293 |
|
| 294 |
timed_print('Constructing main UI...') |
| 295 |
if self.splash_screen is not None: |
| 296 |
self.splash_screen.show_message(_('Initializing user interface...')) |
| 297 |
main = self.main = Main(self.opts, gui_debug=self.gui_debug) |
| 298 |
try: |
| 299 |
with gprefs: # Only write gui.json after initialization is complete |
| 300 |
main.initialize(self.library_path, db, self.actions) |
| 301 |
finally: |
| 302 |
timed_print('main UI initialized...') |
| 303 |
if self.splash_screen is not None: |
| 304 |
timed_print('Hiding splash screen') |
| 305 |
self.splash_screen.finish(main) |
| 306 |
timed_print('splash screen hidden') |
| 307 |
self.splash_screen = None |
| 308 |
timed_print(f'Started up in {monotonic() - self.startup_time:.2f} seconds', 'with', len(db.data), 'books') |
| 309 |
main.set_exception_handler() |
| 310 |
if len(self.args) > 1: |
| 311 |
main.handle_cli_args(self.args[1:]) |
| 312 |
for event in self.app.file_event_hook.events: |
| 313 |
main.handle_cli_args(event) |
| 314 |
self.app.file_event_hook = main.handle_cli_args |
| 315 |
|
| 316 |
def choose_dir(self, initial_dir): |
| 317 |
self.hide_splash_screen() |
| 318 |
return choose_dir( |
| 319 |
self.splash_screen, |
| 320 |
'choose calibre library', |
| 321 |
_('Choose a location for your new calibre e-book library'), |
| 322 |
default_dir=initial_dir, |
| 323 |
) |
| 324 |
|
| 325 |
def show_error(self, title, msg, det_msg=''): |
| 326 |
print(det_msg, file=sys.stderr) |
| 327 |
self.hide_splash_screen() |
| 328 |
with self.app: |
| 329 |
error_dialog(self.splash_screen, title, msg, det_msg=det_msg, show=True) |
| 330 |
|
| 331 |
def initialization_failed(self): |
| 332 |
print('Catastrophic failure initializing GUI, bailing out...') |
| 333 |
QCoreApplication.exit(1) |
| 334 |
raise SystemExit(1) |
| 335 |
|
| 336 |
def initialize_db_stage2(self, db, tb): |
| 337 |
from calibre.db.legacy import LibraryDatabase |
| 338 |
|
| 339 |
if db is None and tb is not None: |
| 340 |
# DB Repair failed |
| 341 |
self.show_error(_('Repairing failed'), _('The database repair failed. Starting with a new empty library.'), det_msg=tb) |
| 342 |
if db is None: |
| 343 |
candidate = self.choose_dir(get_default_library_path()) |
| 344 |
if not candidate: |
| 345 |
self.initialization_failed() |
| 346 |
|
| 347 |
try: |
| 348 |
self.library_path = candidate |
| 349 |
db = LibraryDatabase(candidate) |
| 350 |
except Exception: |
| 351 |
self.show_error( |
| 352 |
_('Bad database location'), |
| 353 |
_('Bad database location %r. calibre will now quit.') % self.library_path, |
| 354 |
det_msg=traceback.format_exc(), |
| 355 |
) |
| 356 |
self.initialization_failed() |
| 357 |
|
| 358 |
timed_print('db initialized') |
| 359 |
try: |
| 360 |
self.start_gui(db) |
| 361 |
except Exception: |
| 362 |
try: |
| 363 |
details = traceback.format_exc() |
| 364 |
except Exception: |
| 365 |
details = '' |
| 366 |
self.show_error( |
| 367 |
_('Startup error'), |
| 368 |
_('There was an error during {0} startup. Parts of {0} may not function. Click "Show details" to learn more.').format(__appname__), |
| 369 |
det_msg=details, |
| 370 |
) |
| 371 |
|
| 372 |
def initialize_db(self): |
| 373 |
from calibre.db.legacy import LibraryDatabase |
| 374 |
|
| 375 |
db = None |
| 376 |
timed_print('Initializing db...') |
| 377 |
try: |
| 378 |
db = LibraryDatabase(self.library_path) |
| 379 |
except apsw.Error: |
| 380 |
with self.app: |
| 381 |
self.hide_splash_screen() |
| 382 |
repair = question_dialog( |
| 383 |
self.splash_screen, |
| 384 |
_('Corrupted database'), |
| 385 |
_( |
| 386 |
'The library database at %s appears to be corrupted. Do ' |
| 387 |
'you want calibre to try and rebuild it automatically? ' |
| 388 |
'The rebuild may not be completely successful. ' |
| 389 |
'If you say No, a new empty calibre library will be created.' |
| 390 |
) |
| 391 |
% force_unicode(self.library_path, filesystem_encoding), |
| 392 |
det_msg=traceback.format_exc(), |
| 393 |
) |
| 394 |
if repair: |
| 395 |
if iswindows: |
| 396 |
# On some windows systems the existing db file gets locked |
| 397 |
# by something when running restore from the main process. |
| 398 |
# So run the restore in a separate process. |
| 399 |
atexit.register(windows_repair, self.library_path) |
| 400 |
self.app.quit() |
| 401 |
return |
| 402 |
if repair_library(self.library_path): |
| 403 |
db = LibraryDatabase(self.library_path) |
| 404 |
except Exception: |
| 405 |
self.show_error( |
| 406 |
_('Bad database location'), |
| 407 |
_('Bad database location %r. Will start with a new, empty calibre library') % self.library_path, |
| 408 |
det_msg=traceback.format_exc(), |
| 409 |
) |
| 410 |
|
| 411 |
self.initialize_db_stage2(db, None) |
| 412 |
|
| 413 |
def show_splash_screen(self): |
| 414 |
timed_print('Showing splash screen...') |
| 415 |
self.splash_screen = SplashScreen() |
| 416 |
self.splash_screen.show() |
| 417 |
self.splash_screen.show_message(_('Starting %s: Loading books...') % __appname__) |
| 418 |
timed_print('splash screen shown') |
| 419 |
|
| 420 |
def hide_splash_screen(self): |
| 421 |
if self.splash_screen is not None: |
| 422 |
self.splash_screen.hide() |
| 423 |
self.splash_screen = None |
| 424 |
|
| 425 |
def initialize(self, *args): |
| 426 |
if gprefs['show_splash_screen'] and not self.opts.start_in_tray: |
| 427 |
self.show_splash_screen() |
| 428 |
self.library_path = get_library_path(self) |
| 429 |
if not self.library_path: |
| 430 |
self.initialization_failed() |
| 431 |
|
| 432 |
self.initialize_db() |
| 433 |
|
| 434 |
|
| 435 |
def run_in_debug_mode(): |
| 436 |
import subprocess |
| 437 |
|
| 438 |
from calibre.constants import cache_dir |
| 439 |
from calibre.debug import run_calibre_debug |
| 440 |
|
| 441 |
logpath = os.path.join(cache_dir(), 'calibre-debug-log.txt') |
| 442 |
run_calibre_debug('--gui-debug', logpath, stdout=open(logpath, 'wb'), stderr=subprocess.STDOUT, stdin=open(os.devnull, 'rb')) |
| 443 |
|
| 444 |
|
| 445 |
def run_gui(opts, args, app, gui_debug=None): |
| 446 |
with SingleInstance('db') as si: |
| 447 |
if not si: |
| 448 |
ext = '.exe' if iswindows else '' |
| 449 |
error_dialog( |
| 450 |
None, |
| 451 |
_('Cannot start calibre'), |
| 452 |
_( |
| 453 |
'Another calibre program that can modify calibre libraries, such as,' |
| 454 |
' {0} or {1} is already running. You must first shut it down, before' |
| 455 |
' starting the main calibre program. If you are sure no such' |
| 456 |
' program is running, try restarting your computer.' |
| 457 |
).format('calibre-server' + ext, 'calibredb' + ext), |
| 458 |
show=True, |
| 459 |
) |
| 460 |
return 1 |
| 461 |
run_gui_(opts, args, app, gui_debug) |
| 462 |
|
| 463 |
|
| 464 |
def workaround_windows_shutdown_hang(timeout: float = 1.0, exit_code: int = 0): |
| 465 |
# On Windows we get a mysterious deadlock that hangs the process on |
| 466 |
# exit even if we call os._exit(0), once the wireless device driver connects. |
| 467 |
# See https://bugs.launchpad.net/bugs/2141994 |
| 468 |
# Started in calibre 9 probably because of a new regression in Python/Qt |
| 469 |
# Getting process properties via process explorer causes the process to exit. |
| 470 |
# So it is likely a hang in the Loader Lock. Or memory corruption during exit. |
| 471 |
# So we run a child process that will wait a second for the parent process |
| 472 |
# to exit and if it hasnt, will kill it. |
| 473 |
# We pass an inheritable process handle so the child does not accidentally |
| 474 |
# kill the wrong process due to PID reuse. |
| 475 |
import ctypes |
| 476 |
|
| 477 |
from calibre.utils.ipc.simple_worker import start_pipe_worker |
| 478 |
|
| 479 |
SYNCHRONIZE = 0x00100000 |
| 480 |
PROCESS_TERMINATE = 0x0001 |
| 481 |
kernel32 = ctypes.windll.kernel32 |
| 482 |
# Use OpenProcess on our own PID with bInheritHandle=True to get a real, |
| 483 |
# inheritable handle. We set the restype to c_void_p so the 64-bit handle |
| 484 |
# value is not truncated on x64 systems. |
| 485 |
kernel32.OpenProcess.restype = ctypes.c_void_p |
| 486 |
handle = kernel32.OpenProcess(SYNCHRONIZE | PROCESS_TERMINATE, True, os.getpid()) |
| 487 |
if handle: |
| 488 |
try: |
| 489 |
start_pipe_worker( |
| 490 |
f'from calibre.utils import *; kill_parent_if_needed({handle!r}, {timeout!r}, {exit_code!r})', |
| 491 |
pass_fds=(handle,), |
| 492 |
) |
| 493 |
finally: |
| 494 |
kernel32.CloseHandle(handle) |
| 495 |
|
| 496 |
|
| 497 |
def run_gui_(opts, args, app, gui_debug=None): |
| 498 |
initialize_file_icon_provider() |
| 499 |
app.load_builtin_fonts(scan_for_fonts=True) |
| 500 |
if not dynamic.get('welcome_wizard_was_run', False): |
| 501 |
from calibre.gui2.wizard import wizard |
| 502 |
|
| 503 |
wizard().exec() |
| 504 |
dynamic.set('welcome_wizard_was_run', True) |
| 505 |
if iswindows: |
| 506 |
# registered first so it runs last |
| 507 |
atexit.register(workaround_windows_shutdown_hang) |
| 508 |
from calibre.gui2.ui import Main |
| 509 |
|
| 510 |
if ismacos: |
| 511 |
actions = tuple(Main.create_application_menubar()) |
| 512 |
else: |
| 513 |
actions = tuple(Main.get_menubar_actions()) |
| 514 |
runner = GuiRunner(opts, args, actions, app, gui_debug=gui_debug) |
| 515 |
ret = app.exec() |
| 516 |
timed_print('Application event loop quit') |
| 517 |
if getattr(runner.main, 'run_wizard_b4_shutdown', False): |
| 518 |
from calibre.gui2.wizard import wizard |
| 519 |
|
| 520 |
wizard().exec() |
| 521 |
if getattr(runner.main, 'restart_after_quit', False): |
| 522 |
after_quit_actions['restart_after_quit'] = True |
| 523 |
after_quit_actions['debug_on_restart'] = getattr(runner.main, 'debug_on_restart', False) or gui_debug is not None |
| 524 |
after_quit_actions['no_plugins_on_restart'] = getattr(runner.main, 'no_plugins_on_restart', False) |
| 525 |
elif iswindows: |
| 526 |
try: |
| 527 |
_main = runner.main |
| 528 |
assert _main is not None |
| 529 |
_tray = _main.system_tray_icon |
| 530 |
assert _tray is not None |
| 531 |
_tray.hide() |
| 532 |
except Exception: |
| 533 |
pass |
| 534 |
if getattr(runner.main, 'gui_debug', None) is not None: |
| 535 |
_main_ref = runner.main |
| 536 |
assert _main_ref is not None |
| 537 |
debugfile = _main_ref.gui_debug |
| 538 |
from calibre.gui2 import open_local_file |
| 539 |
|
| 540 |
if iswindows: |
| 541 |
# detach the stdout/stderr/stdin handles |
| 542 |
winutil.prepare_for_restart() |
| 543 |
assert isinstance(debugfile, str) |
| 544 |
with open(debugfile, 'r+b') as f: |
| 545 |
raw = f.read() |
| 546 |
raw = re.sub(rb'(?<!\r)\n', b'\r\n', raw) |
| 547 |
f.seek(0) |
| 548 |
f.truncate() |
| 549 |
f.write(raw) |
| 550 |
open_local_file(debugfile) |
| 551 |
if runner.main: |
| 552 |
sip.delete(runner.main) |
| 553 |
runner.main = None |
| 554 |
del runner |
| 555 |
return ret |
| 556 |
|
| 557 |
|
| 558 |
singleinstance_name = 'GUI' |
| 559 |
|
| 560 |
|
| 561 |
class FailedToCommunicate(Exception): |
| 562 |
pass |
| 563 |
|
| 564 |
|
| 565 |
def send_message(msg): |
| 566 |
fail_err = None |
| 567 |
try: |
| 568 |
send_message_in_process(msg) |
| 569 |
return True |
| 570 |
except Exception: |
| 571 |
# can happen if Qt LocalServer has not yet started, typically happens on Windows |
| 572 |
st = time.monotonic() |
| 573 |
while time.monotonic() - st < 6: |
| 574 |
try: |
| 575 |
send_message_in_process(msg) |
| 576 |
return True |
| 577 |
except Exception as err: |
| 578 |
fail_err = err |
| 579 |
time.sleep(0.05) |
| 580 |
with SingleInstance(singleinstance_name) as si: |
| 581 |
if si: |
| 582 |
print(_('Other instance of calibre shutdown'), file=sys.stderr) |
| 583 |
raise SystemExit(0) |
| 584 |
|
| 585 |
print(_('Failed to contact running instance of calibre'), file=sys.stderr, flush=True) |
| 586 |
print(fail_err, file=sys.stderr, flush=True) |
| 587 |
if Application.instance(): |
| 588 |
error_dialog( |
| 589 |
None, |
| 590 |
_('Contacting calibre failed'), |
| 591 |
_('Failed to contact running instance of calibre, try restarting calibre'), |
| 592 |
det_msg=str(fail_err or '') + '\n\n' + repr(msg), |
| 593 |
show=True, |
| 594 |
) |
| 595 |
return False |
| 596 |
|
| 597 |
|
| 598 |
def shutdown_other(): |
| 599 |
if send_message('shutdown:'): |
| 600 |
print(_('Shutdown command sent, waiting for shutdown...'), flush=True) |
| 601 |
for i in range(50): |
| 602 |
with SingleInstance(singleinstance_name) as si: |
| 603 |
if si: |
| 604 |
return |
| 605 |
time.sleep(0.1) |
| 606 |
raise SystemExit(_('Failed to shutdown running calibre instance')) |
| 607 |
|
| 608 |
|
| 609 |
def communicate(opts, args): |
| 610 |
if opts.shutdown_running_calibre: |
| 611 |
shutdown_other() |
| 612 |
else: |
| 613 |
if len(args) > 1: |
| 614 |
args[1:] = [os.path.abspath(x) if os.path.exists(x) else x for x in args[1:]] |
| 615 |
if opts.with_library and os.path.isdir(os.path.expanduser(opts.with_library)): |
| 616 |
libpath = os.path.abspath(os.path.expanduser(opts.with_library)) |
| 617 |
args.insert(1, 'calibre://switch-library-by-path/_hex_-' + libpath.encode('utf-8').hex()) |
| 618 |
import json |
| 619 |
|
| 620 |
if not send_message(b'launched:' + as_bytes(json.dumps(args))): |
| 621 |
raise SystemExit(_('Failed to contact running instance of calibre')) |
| 622 |
raise SystemExit(0) |
| 623 |
|
| 624 |
|
| 625 |
def restart_after_quit(): |
| 626 |
e = sys.executable if getattr(sys, 'frozen', False) else sys.argv[0] |
| 627 |
is_calibre_debug_exe = os.path.splitext(e)[0].endswith('-debug') |
| 628 |
if iswindows and not is_calibre_debug_exe: |
| 629 |
# detach the stdout/stderr/stdin handles |
| 630 |
winutil.prepare_for_restart() |
| 631 |
if after_quit_actions['no_plugins_on_restart']: |
| 632 |
os.environ['CALIBRE_IGNORE_PLUGINS_ON_RESTART'] = '1' |
| 633 |
if after_quit_actions['debug_on_restart']: |
| 634 |
run_in_debug_mode() |
| 635 |
return |
| 636 |
if hasattr(sys, 'frameworks_dir'): |
| 637 |
app = os.path.dirname(os.path.dirname(os.path.realpath(sys.frameworks_dir))) |
| 638 |
from calibre.debug import run_calibre_debug |
| 639 |
|
| 640 |
prints('Restarting with:', app) |
| 641 |
run_calibre_debug('-c', 'import sys, os, time; time.sleep(3); os.execlp("open", "open", sys.argv[-1])', app) |
| 642 |
else: |
| 643 |
import subprocess |
| 644 |
|
| 645 |
if hasattr(sys, 'run_local'): |
| 646 |
cmd = [sys.run_local] |
| 647 |
if DEBUG: |
| 648 |
cmd += ['calibre-debug', '-g'] |
| 649 |
else: |
| 650 |
cmd.append('calibre') |
| 651 |
else: |
| 652 |
cmd = [e] |
| 653 |
if is_calibre_debug_exe: |
| 654 |
cmd.append('-g') |
| 655 |
prints('Restarting with:', ' '.join(cmd)) |
| 656 |
subprocess.Popen(cmd) |
| 657 |
|
| 658 |
|
| 659 |
def main(args=sys.argv): |
| 660 |
if iswindows and 'CALIBRE_REPAIR_CORRUPTED_DB' in os.environ: |
| 661 |
windows_repair() |
| 662 |
return 0 |
| 663 |
gui_debug = None |
| 664 |
if args[0] == '__CALIBRE_GUI_DEBUG__': |
| 665 |
gui_debug = args[1] |
| 666 |
args = ['calibre'] |
| 667 |
|
| 668 |
try: |
| 669 |
app, opts, args = init_qt(args) |
| 670 |
except AbortInit: |
| 671 |
return 1 |
| 672 |
with SingleInstance(singleinstance_name) as si: |
| 673 |
if si and opts.shutdown_running_calibre: |
| 674 |
return 0 |
| 675 |
run_main(app, opts, args, gui_debug, si) |
| 676 |
if after_quit_actions['restart_after_quit']: |
| 677 |
restart_after_quit() |
| 678 |
sip.delete(app) |
| 679 |
del app |
| 680 |
import gc |
| 681 |
|
| 682 |
gc.collect(), gc.collect() |
| 683 |
|
| 684 |
|
| 685 |
def run_main(app, opts, args, gui_debug, si): |
| 686 |
if si: |
| 687 |
return run_gui(opts, args, app, gui_debug=gui_debug) |
| 688 |
communicate(opts, args) |
| 689 |
return 0 |
| 690 |
|
| 691 |
|
| 692 |
if __name__ == '__main__': |
| 693 |
try: |
| 694 |
sys.exit(main()) |
| 695 |
except Exception as err: |
| 696 |
if not iswindows: |
| 697 |
raise |
| 698 |
tb = traceback.format_exc() |
| 699 |
from qt.core import QErrorMessage |
| 700 |
|
| 701 |
logfile = os.path.join(os.path.expanduser('~'), 'calibre.log') |
| 702 |
if os.path.exists(logfile): |
| 703 |
with open(logfile) as f: |
| 704 |
log = f.read() |
| 705 |
d = QErrorMessage() |
| 706 |
d.showMessage( |
| 707 |
('<b>Error:</b>{}<br><b>Traceback:</b><br>{}<b>Log:</b><br>{}').format(str(err), str(tb).replace('\n', '<br>'), log.replace('\n', '<br>')) |
| 708 |
) |