def _launch_viewer(self, name=None, viewer='ebook-viewer', internal=True): self.gui.setCursor(Qt.BusyCursor) try: if internal: args = [viewer] if isosx and 'ebook' in viewer: args.append('--raise-window') if name is not None: args.append(name) self.gui.job_manager.launch_gui_app(viewer, kwargs=dict(args=args)) else: if iswindows: from calibre.utils.file_associations import file_assoc_windows ext = name.rpartition('.')[-1] if ext: try: prog = file_assoc_windows(ext) except Exception: prog = None if prog and prog.lower().endswith('calibre.exe'): name = os.path.basename(name) return error_dialog( self.gui, _('No associated program'), _( 'Windows will try to open %s with calibre itself' ' resulting in a duplicate in your calibre library. You' ' should install some program capable of viewing this' ' file format and tell windows to use that program to open' ' files of this type.') % name, show=True) open_local_file(name) time.sleep(2) # User feedback finally: self.gui.unsetCursor()
def updating_metadata_finished(self): if DEBUG: prints('Saved %d books in %.1f seconds' % (len(self.all_book_ids), time.time() - self.start_time)) self.pd.close() self.pd.deleteLater() self.report() self.break_cycles() if gprefs['show_files_after_save']: open_local_file(self.root)
def check(self): if self.thread.is_alive(): return if self.thread.tb or self.thread.log: error_dialog(self, _('Failed to convert to PDF'), _( 'Failed to generate PDF file, click "Show details" for more information.'), det_msg=self.thread.tb or self.thread.log, show=True) else: if self.show_file: open_local_file(self.thread.data['output']) self.accept()
def unpack_ebook(self, kindle_obj): ''' Unpack kindlebook to external folder. ''' outdir = self.directoryChooser() if outdir: try: kindle_obj.unpackMOBI(outdir) except Exception, e: return showErrorDlg(str(e), self.gui, True) open_local_file(outdir)
def combo_split(self, kindle_obj): ''' Split kindlegen output into its AZW3/MOBI pieces. ''' outdir = self.directoryChooser() if outdir: try: kindle_obj.writeSplitCombo(outdir) except Exception, e: return showErrorDlg(str(e), self.gui, True) open_local_file(outdir)
def view_folder(self, *args): rows = self.gui.current_view().selectionModel().selectedRows() if not rows or len(rows) == 0: d = error_dialog(self.gui, _("Cannot open folder"), _("No book selected")) d.exec_() return if not self._view_check(len(rows)): return for row in rows: path = self.gui.library_view.model().db.abspath(row.row()) open_local_file(path)
def delete_requested(self, name, location): loc = location.replace('/', os.sep) self.stats.remove(location) self.build_menus() self.gui.iactions['Copy To Library'].build_menus() info_dialog(self.gui, _('Library removed'), _('The library %s has been removed from calibre. ' 'The files remain on your computer, if you want ' 'to delete them, you will have to do so manually.') % loc, show=True) if os.path.exists(loc): open_local_file(loc)
def run_gui(opts, args, listener, app, gui_debug=None): initialize_file_icon_provider() app.load_builtin_fonts(scan_for_fonts=True) if not dynamic.get('welcome_wizard_was_run', False): from calibre.gui2.wizard import wizard wizard().exec_() dynamic.set('welcome_wizard_was_run', True) from calibre.gui2.ui import Main if isosx: actions = tuple(Main.create_application_menubar()) else: actions = tuple(Main.get_menubar_actions()) runner = GuiRunner(opts, args, actions, listener, app, gui_debug=gui_debug) ret = app.exec_() if getattr(runner.main, 'run_wizard_b4_shutdown', False): from calibre.gui2.wizard import wizard wizard().exec_() if getattr(runner.main, 'restart_after_quit', False): e = sys.executable if getattr(sys, 'frozen', False) else sys.argv[0] if getattr(runner.main, 'debug_on_restart', False) or gui_debug is not None: run_in_debug_mode() else: import subprocess if hasattr(sys, 'frameworks_dir'): app = os.path.dirname(os.path.dirname(os.path.realpath(sys.frameworks_dir))) prints('Restarting with:', app) subprocess.Popen('sleep 3s; open ' + shellquote(app), shell=True) else: if iswindows and hasattr(winutil, 'prepare_for_restart'): winutil.prepare_for_restart() args = ['-g'] if os.path.splitext(e)[0].endswith('-debug') else [] prints('Restarting with:', ' '.join([e] + args)) subprocess.Popen([e] + args) else: if iswindows: try: runner.main.system_tray_icon.hide() except: pass if getattr(runner.main, 'gui_debug', None) is not None: e = sys.executable if getattr(sys, 'frozen', False) else sys.argv[0] debugfile = runner.main.gui_debug from calibre.gui2 import open_local_file if iswindows: with open(debugfile, 'r+b') as f: raw = f.read() raw = re.sub(b'(?<!\r)\n', b'\r\n', raw) f.seek(0) f.truncate() f.write(raw) open_local_file(debugfile) return ret
def run_gui(opts, args, listener, app, gui_debug=None): initialize_file_icon_provider() app.load_builtin_fonts(scan_for_fonts=True) if not dynamic.get("welcome_wizard_was_run", False): from calibre.gui2.wizard import wizard wizard().exec_() dynamic.set("welcome_wizard_was_run", True) from calibre.gui2.ui import Main actions = tuple(Main.create_application_menubar()) runner = GuiRunner(opts, args, actions, listener, app, gui_debug=gui_debug) ret = app.exec_() if getattr(runner.main, "run_wizard_b4_shutdown", False): from calibre.gui2.wizard import wizard wizard().exec_() if getattr(runner.main, "restart_after_quit", False): e = sys.executable if getattr(sys, "frozen", False) else sys.argv[0] if getattr(runner.main, "debug_on_restart", False): run_in_debug_mode() else: import subprocess print "Restarting with:", e, sys.argv if hasattr(sys, "frameworks_dir"): app = os.path.dirname(os.path.dirname(os.path.realpath(sys.frameworks_dir))) subprocess.Popen("sleep 3s; open " + shellquote(app), shell=True) else: if iswindows and hasattr(winutil, "prepare_for_restart"): winutil.prepare_for_restart() subprocess.Popen([e] + sys.argv[1:]) else: if iswindows: try: runner.main.system_tray_icon.hide() except: pass if getattr(runner.main, "gui_debug", None) is not None: e = sys.executable if getattr(sys, "frozen", False) else sys.argv[0] debugfile = runner.main.gui_debug from calibre.gui2 import open_local_file if iswindows: with open(debugfile, "r+b") as f: raw = f.read() raw = re.sub(b"(?<!\r)\n", b"\r\n", raw) f.seek(0) f.truncate() f.write(raw) open_local_file(debugfile) return ret
def view_folder(self, *args): rows = self.gui.current_view().selectionModel().selectedRows() if not rows or len(rows) == 0: d = error_dialog(self.gui, _('Cannot open folder'), _('No book selected')) d.exec_() return if not self._view_check(len(rows)): return for i, row in enumerate(rows): path = self.gui.library_view.model().db.abspath(row.row()) open_local_file(path) if isosx and i < len(rows) - 1: time.sleep(0.1) # Finder cannot handle multiple folder opens
def delete_requested(self, name, location): loc = location.replace('/', os.sep) if not question_dialog( self.gui, _('Library removed'), _( 'The library %s has been removed from calibre. ' 'The files remain on your computer, if you want ' 'to delete them, you will have to do so manually.') % ('<code>%s</code>' % loc), override_icon='dialog_information.png', yes_text=_('&OK'), no_text=_('&Undo'), yes_icon='ok.png', no_icon='edit-undo.png'): return self.stats.remove(location) self.build_menus() self.gui.iactions['Copy To Library'].build_menus() if os.path.exists(loc): open_local_file(loc)
def _launch_viewer(self, name=None, viewer="ebook-viewer", internal=True): self.gui.setCursor(Qt.BusyCursor) try: if internal: args = [viewer] if isosx and "ebook" in viewer: args.append("--raise-window") if name is not None: args.append(name) self.gui.job_manager.launch_gui_app(viewer, kwargs=dict(args=args)) else: open_local_file(name) time.sleep(2) # User feedback finally: self.gui.unsetCursor()
def handle_click(self, link): typ, _, val = link.partition(':') if typ == 'path': self.open_containing_folder.emit(int(val)) elif typ == 'format': id_, fmt = val.split(':') self.view_specific_format.emit(int(id_), fmt) elif typ == 'devpath': open_local_file(val) else: try: open_url(QUrl(link, QUrl.TolerantMode)) except: import traceback traceback.print_exc()
def _books_saved(self, path, failures, error): self._saver = None if error: return error_dialog(self.gui, _('Error while saving'), _('There was an error while saving.'), error, show=True) if failures: failures = [u'%s\n\t%s'% (title, '\n\t'.join(err.splitlines())) for title, err in failures] warning_dialog(self.gui, _('Could not save some books'), _('Could not save some books') + ', ' + _('Click the show details button to see which ones.'), u'\n\n'.join(failures), show=True) if gprefs['show_files_after_save']: open_local_file(path)
def run_gui_(opts, args, app, gui_debug=None): initialize_file_icon_provider() app.load_builtin_fonts(scan_for_fonts=True) if not dynamic.get('welcome_wizard_was_run', False): from calibre.gui2.wizard import wizard wizard().exec_() dynamic.set('welcome_wizard_was_run', True) from calibre.gui2.ui import Main if ismacos: actions = tuple(Main.create_application_menubar()) else: actions = tuple(Main.get_menubar_actions()) runner = GuiRunner(opts, args, actions, app, gui_debug=gui_debug) ret = app.exec_() if getattr(runner.main, 'run_wizard_b4_shutdown', False): from calibre.gui2.wizard import wizard wizard().exec_() if getattr(runner.main, 'restart_after_quit', False): after_quit_actions['restart_after_quit'] = True after_quit_actions['debug_on_restart'] = getattr( runner.main, 'debug_on_restart', False) or gui_debug is not None else: if iswindows: try: runner.main.system_tray_icon.hide() except: pass if getattr(runner.main, 'gui_debug', None) is not None: debugfile = runner.main.gui_debug from calibre.gui2 import open_local_file if iswindows: with open(debugfile, 'r+b') as f: raw = f.read() raw = re.sub(b'(?<!\r)\n', b'\r\n', raw) f.seek(0) f.truncate() f.write(raw) open_local_file(debugfile) return ret
def do_explode(self): from calibre.ebooks.tweak import get_tools, Error, WorkerError tdir = PersistentTemporaryDirectory('_tweak_explode') self._cleanup_dirs.append(tdir) det_msg = None try: src = self.db.format(self.book_id, self.current_format, index_is_id=True, as_path=True) self._cleanup_files.append(src) exploder = get_tools(self.current_format)[0] opf = exploder(src, tdir, question=self.ask_question) except WorkerError as e: det_msg = e.orig_tb except Error as e: return error_dialog(self, _('Failed to unpack'), (_('Could not explode the %s file.')%self.current_format) + ' ' + as_unicode(e), show=True) except: import traceback det_msg = traceback.format_exc() finally: self.hide_msg() if det_msg is not None: return error_dialog(self, _('Failed to unpack'), _('Could not explode the %s file. Click "Show Details" for ' 'more information.')%self.current_format, det_msg=det_msg, show=True) if opf is None: # The question was answered with No return self._exploded = tdir self.explode_button.setEnabled(False) self.preview_button.setEnabled(True) self.rebuild_button.setEnabled(True) open_local_file(tdir)
def _books_saved(self, path, failures, error): self._saver = None if error: return error_dialog(self.gui, _('Error while saving'), _('There was an error while saving.'), error, show=True) if failures: failures = [ u'%s\n\t%s' % (title, '\n\t'.join(err.splitlines())) for title, err in failures ] warning_dialog( self.gui, _('Could not save some books'), _('Could not save some books') + ', ' + _('Click the show details button to see which ones.'), u'\n\n'.join(failures), show=True) if gprefs['show_files_after_save']: open_local_file(path)
def delete_requested(self, name, location): loc = location.replace("/", os.sep) if not question_dialog( self.gui, _("Library removed"), _( "The library %s has been removed from calibre. " "The files remain on your computer, if you want " "to delete them, you will have to do so manually." ) % ("<code>%s</code>" % loc), override_icon="dialog_information.png", yes_text=_("&OK"), no_text=_("&Undo"), yes_icon="ok.png", no_icon="edit-undo.png", ): return self.stats.remove(location) self.build_menus() self.gui.iactions["Copy To Library"].build_menus() if os.path.exists(loc): open_local_file(loc)
def _launch_viewer(self, name=None, viewer='ebook-viewer', internal=True): self.gui.setCursor(Qt.BusyCursor) try: if internal: args = [viewer] if isosx and 'ebook' in viewer: args.append('--raise-window') if name is not None: args.append(name) self.gui.job_manager.launch_gui_app(viewer, kwargs=dict(args=args)) else: if iswindows: winutil = plugins['winutil'][0] ext = name.rpartition('.')[-1] if ext: try: prog = winutil.file_association( unicode_type('.' + ext)) except Exception: prog = None if prog and prog.lower().endswith('calibre.exe'): name = os.path.basename(name) return error_dialog( self.gui, _('No associated program'), _('Windows will try to open %s with calibre itself' ' resulting in a duplicate in your calibre library. You' ' should install some program capable of viewing this' ' file format and tell Windows to use that program to open' ' files of this type.') % name, show=True) open_local_file(name) time.sleep(2) # User feedback finally: self.gui.unsetCursor()
def main(args=sys.argv): from calibre.constants import debug debug() opts, args = option_parser().parse_args(args) if opts.gui: from calibre.gui2.main import main print_basic_debug_info() main(['calibre']) elif opts.gui_debug is not None: run_debug_gui(opts.gui_debug) elif opts.show_gui_debug: import time, re time.sleep(1) from calibre.gui2 import open_local_file if iswindows: with open(opts.show_gui_debug, 'r+b') as f: raw = f.read() raw = re.sub('(?<!\r)\n', '\r\n', raw) f.seek(0) f.truncate() f.write(raw) open_local_file(opts.show_gui_debug) elif opts.viewer: from calibre.gui2.viewer.main import main main(['ebook-viewer'] + args[1:]) elif opts.py_console: from calibre.utils.pyconsole.main import main main() elif opts.command: sys.argv = args exec(opts.command) elif opts.debug_device_driver: debug_device_driver() elif opts.add_simple_plugin is not None: add_simple_plugin(opts.add_simple_plugin) elif opts.paths: prints('CALIBRE_RESOURCES_PATH='+sys.resources_location) prints('CALIBRE_EXTENSIONS_PATH='+sys.extensions_location) prints('CALIBRE_PYTHON_PATH='+os.pathsep.join(sys.path)) elif opts.reinitialize_db is not None: reinit_db(opts.reinitialize_db) elif opts.inspect_mobi: for path in args[1:]: inspect_mobi(path) elif opts.edit_book: from calibre.gui2.tweak_book.main import main main(['ebook-edit'] + args[1:]) elif opts.explode_book: from calibre.ebooks.tweak import tweak tweak(opts.explode_book) elif opts.test_build: from calibre.test_build import test test() elif opts.shutdown_running_calibre: from calibre.gui2.main import shutdown_other shutdown_other() elif opts.subset_font: from calibre.utils.fonts.sfnt.subset import main main(['subset-font']+[opts.subset_font]+args[1:]) elif opts.exec_file: run_script(opts.exec_file, args[1:]) elif opts.run_plugin: from calibre.customize.ui import find_plugin plugin = find_plugin(opts.run_plugin) if plugin is None: prints(_('No plugin named %s found')%opts.run_plugin) raise SystemExit(1) plugin.cli_main([plugin.name] + args[1:]) elif opts.diff: from calibre.gui2.tweak_book.diff.main import main main(['calibre-diff'] + args[1:]) elif len(args) >= 2 and args[1].rpartition('.')[-1] in {'py', 'recipe'}: run_script(args[1], args[2:]) elif len(args) >= 2 and args[1].rpartition('.')[-1] in {'mobi', 'azw', 'azw3', 'docx', 'odt'}: for path in args[1:]: ext = path.rpartition('.')[-1] if ext in {'docx', 'odt'}: from calibre.ebooks.docx.dump import dump dump(path) elif ext in {'mobi', 'azw', 'azw3'}: inspect_mobi(path) else: print ('Cannot dump unknown filetype: %s' % path) else: from calibre import ipython ipython() return 0
def open_config_dir(self, *args): from calibre.utils.config import config_dir open_local_file(config_dir)
def view_folder_for_id(self, id_): path = self.gui.library_view.model().db.abspath(id_, index_is_id=True) open_local_file(path)
def run_gui(opts, args, listener, app, gui_debug=None): si = singleinstance('db') if not si: ext = '.exe' if iswindows else '' error_dialog(None, _('Cannot start calibre'), _( 'Another calibre program that can modify calibre libraries, such as,' ' {} or {} is already running. You must first shut it down, before' ' starting the main calibre program. If you are sure no such' ' program is running, try restarting your computer.').format( 'calibre-server' + ext, 'calibredb' + ext), show=True) return 1 initialize_file_icon_provider() app.load_builtin_fonts(scan_for_fonts=True) if not dynamic.get('welcome_wizard_was_run', False): from calibre.gui2.wizard import wizard wizard().exec_() dynamic.set('welcome_wizard_was_run', True) from calibre.gui2.ui import Main if isosx: actions = tuple(Main.create_application_menubar()) else: actions = tuple(Main.get_menubar_actions()) runner = GuiRunner(opts, args, actions, listener, app, gui_debug=gui_debug) ret = app.exec_() if getattr(runner.main, 'run_wizard_b4_shutdown', False): from calibre.gui2.wizard import wizard wizard().exec_() if getattr(runner.main, 'restart_after_quit', False): e = sys.executable if getattr(sys, 'frozen', False) else sys.argv[0] if getattr(runner.main, 'debug_on_restart', False) or gui_debug is not None: run_in_debug_mode() else: import subprocess if hasattr(sys, 'frameworks_dir'): app = os.path.dirname(os.path.dirname(os.path.realpath(sys.frameworks_dir))) prints('Restarting with:', app) subprocess.Popen('sleep 3s; open ' + shellquote(app), shell=True) else: os.environ[b'CALIBRE_RESTARTING_FROM_GUI'] = b'1' if iswindows and hasattr(winutil, 'prepare_for_restart'): winutil.prepare_for_restart() args = ['-g'] if os.path.splitext(e)[0].endswith('-debug') else [] prints('Restarting with:', ' '.join([e] + args)) subprocess.Popen([e] + args) else: if iswindows: try: runner.main.system_tray_icon.hide() except: pass if getattr(runner.main, 'gui_debug', None) is not None: e = sys.executable if getattr(sys, 'frozen', False) else sys.argv[0] debugfile = runner.main.gui_debug from calibre.gui2 import open_local_file if iswindows: with open(debugfile, 'r+b') as f: raw = f.read() raw = re.sub(b'(?<!\r)\n', b'\r\n', raw) f.seek(0) f.truncate() f.write(raw) open_local_file(debugfile) return ret
def open_cg_cache(self): open_local_file(self.gui.grid_view.thumbnail_cache.location)
def main(args=sys.argv): from calibre.constants import debug debug() if len(args) > 2 and args[1] in ('-e', '--exec-file'): # Load all plugins user defined plugins so the script can import from the # calibre_plugins namespace import calibre.customize.ui as dummy dummy sys.argv = [args[2]] + args[3:] ef = os.path.abspath(args[2]) base = os.path.dirname(ef) sys.path.insert(0, base) g = globals() g['__name__'] = '__main__' g['__file__'] = ef execfile(ef, g) return opts, args = option_parser().parse_args(args) if opts.gui: from calibre.gui2.main import main main(['calibre']) elif opts.gui_debug is not None: run_debug_gui(opts.gui_debug) elif opts.show_gui_debug: import time, re time.sleep(1) from calibre.gui2 import open_local_file if iswindows: with open(opts.show_gui_debug, 'r+b') as f: raw = f.read() raw = re.sub('(?<!\r)\n', '\r\n', raw) f.seek(0) f.truncate() f.write(raw) open_local_file(opts.show_gui_debug) elif opts.viewer: from calibre.gui2.viewer.main import main vargs = ['ebook-viewer', '--debug-javascript'] if len(args) > 1: vargs.append(args[-1]) main(vargs) elif opts.py_console: from calibre.utils.pyconsole.main import main main() elif opts.command: sys.argv = args exec opts.command elif opts.debug_device_driver: debug_device_driver() elif opts.migrate: if len(args) < 3: print 'You must specify the path to library1.db and the path to the new library folder' return 1 migrate(args[1], args[2]) elif opts.add_simple_plugin is not None: add_simple_plugin(opts.add_simple_plugin) elif opts.paths: prints('CALIBRE_RESOURCES_PATH=' + sys.resources_location) prints('CALIBRE_EXTENSIONS_PATH=' + sys.extensions_location) prints('CALIBRE_PYTHON_PATH=' + os.pathsep.join(sys.path)) elif opts.reinitialize_db is not None: sql_dump = None if len(args) > 1 and os.access(args[-1], os.R_OK): sql_dump = args[-1] reinit_db(opts.reinitialize_db, sql_dump=sql_dump) elif opts.inspect_mobi: from calibre.ebooks.mobi.debug.main import inspect_mobi for path in args[1:]: prints('Inspecting:', path) inspect_mobi(path) print elif opts.tweak_book: from calibre.ebooks.tweak import tweak tweak(opts.tweak_book) elif opts.test_build: from calibre.test_build import test test() elif opts.shutdown_running_calibre: from calibre.gui2.main import shutdown_other shutdown_other() else: from calibre import ipython ipython() return 0
def main(args=sys.argv): from calibre.constants import debug debug() opts, args = option_parser().parse_args(args) if opts.gui: from calibre.gui2.main import main print_basic_debug_info() main(["calibre"]) elif opts.gui_debug is not None: run_debug_gui(opts.gui_debug) elif opts.show_gui_debug: import time, re time.sleep(1) from calibre.gui2 import open_local_file if iswindows: with open(opts.show_gui_debug, "r+b") as f: raw = f.read() raw = re.sub("(?<!\r)\n", "\r\n", raw) f.seek(0) f.truncate() f.write(raw) open_local_file(opts.show_gui_debug) elif opts.viewer: from calibre.gui2.viewer.main import main main(["ebook-viewer"] + args[1:]) elif opts.py_console: from calibre.utils.pyconsole.main import main main() elif opts.command: sys.argv = args exec(opts.command) elif opts.debug_device_driver: debug_device_driver() elif opts.add_simple_plugin is not None: add_simple_plugin(opts.add_simple_plugin) elif opts.paths: prints("CALIBRE_RESOURCES_PATH=" + sys.resources_location) prints("CALIBRE_EXTENSIONS_PATH=" + sys.extensions_location) prints("CALIBRE_PYTHON_PATH=" + os.pathsep.join(sys.path)) elif opts.reinitialize_db is not None: reinit_db(opts.reinitialize_db) elif opts.inspect_mobi: for path in args[1:]: inspect_mobi(path) elif opts.edit_book: from calibre.gui2.tweak_book.main import main main(["ebook-edit"] + args[1:]) elif opts.explode_book: from calibre.ebooks.tweak import tweak tweak(opts.explode_book) elif opts.test_build: from calibre.test_build import test test() elif opts.shutdown_running_calibre: from calibre.gui2.main import shutdown_other shutdown_other() elif opts.subset_font: from calibre.utils.fonts.sfnt.subset import main main(["subset-font"] + [opts.subset_font] + args[1:]) elif opts.exec_file: run_script(opts.exec_file, args[1:]) elif opts.run_plugin: from calibre.customize.ui import find_plugin plugin = find_plugin(opts.run_plugin) if plugin is None: prints(_("No plugin named %s found") % opts.run_plugin) raise SystemExit(1) plugin.cli_main([plugin.name] + args[1:]) elif opts.diff: from calibre.gui2.tweak_book.diff.main import main main(["calibre-diff"] + args[1:]) elif len(args) >= 2 and args[1].rpartition(".")[-1] in {"py", "recipe"}: run_script(args[1], args[2:]) elif len(args) >= 2 and args[1].rpartition(".")[-1] in {"mobi", "azw", "azw3", "docx", "odt"}: for path in args[1:]: ext = path.rpartition(".")[-1] if ext in {"docx", "odt"}: from calibre.ebooks.docx.dump import dump dump(path) elif ext in {"mobi", "azw", "azw3"}: inspect_mobi(path) else: print("Cannot dump unknown filetype: %s" % path) else: from calibre import ipython ipython() return 0
def main(args=sys.argv): from calibre.constants import debug debug() if len(args) > 2 and args[1] in ("-e", "--exec-file"): # Load all plugins user defined plugins so the script can import from the # calibre_plugins namespace import calibre.customize.ui as dummy dummy sys.argv = [args[2]] + args[3:] ef = os.path.abspath(args[2]) base = os.path.dirname(ef) sys.path.insert(0, base) g = globals() g["__name__"] = "__main__" g["__file__"] = ef execfile(ef, g) return opts, args = option_parser().parse_args(args) if opts.gui: from calibre.gui2.main import main main(["calibre"]) elif opts.gui_debug is not None: run_debug_gui(opts.gui_debug) elif opts.show_gui_debug: import time, re time.sleep(1) from calibre.gui2 import open_local_file if iswindows: with open(opts.show_gui_debug, "r+b") as f: raw = f.read() raw = re.sub("(?<!\r)\n", "\r\n", raw) f.seek(0) f.truncate() f.write(raw) open_local_file(opts.show_gui_debug) elif opts.viewer: from calibre.gui2.viewer.main import main vargs = ["ebook-viewer", "--debug-javascript"] if len(args) > 1: vargs.append(args[-1]) main(vargs) elif opts.py_console: from calibre.utils.pyconsole.main import main main() elif opts.command: sys.argv = args exec opts.command elif opts.debug_device_driver: debug_device_driver() elif opts.migrate: if len(args) < 3: print "You must specify the path to library1.db and the path to the new library folder" return 1 migrate(args[1], args[2]) elif opts.add_simple_plugin is not None: add_simple_plugin(opts.add_simple_plugin) elif opts.paths: prints("CALIBRE_RESOURCES_PATH=" + sys.resources_location) prints("CALIBRE_EXTENSIONS_PATH=" + sys.extensions_location) prints("CALIBRE_PYTHON_PATH=" + os.pathsep.join(sys.path)) elif opts.reinitialize_db is not None: sql_dump = None if len(args) > 1 and os.access(args[-1], os.R_OK): sql_dump = args[-1] reinit_db(opts.reinitialize_db, sql_dump=sql_dump) elif opts.inspect_mobi: from calibre.ebooks.mobi.debug.main import inspect_mobi for path in args[1:]: prints("Inspecting:", path) inspect_mobi(path) print elif opts.tweak_book: from calibre.ebooks.tweak import tweak tweak(opts.tweak_book) elif opts.test_build: from calibre.test_build import test test() elif opts.shutdown_running_calibre: from calibre.gui2.main import shutdown_other shutdown_other() else: from calibre import ipython ipython() return 0
def __init__(self, parent=None): QWidget.__init__(self, parent) self.l = l = QGridLayout(self) self.setLayout(l) self.enabled = c = QCheckBox(self) l.addWidget(c, l.rowCount(), 0, 1, 2) c.setVisible(False) c.stateChanged.connect(self.changed) self.l1 = l1 = QLabel('') l1.setWordWrap(True) l.addWidget(l1, l.rowCount(), 0, 1, 2) self.add_button = QPushButton(QIcon(I('plus.png')), _('&Add rule'), self) self.remove_button = QPushButton(QIcon(I('minus.png')), _('&Remove rule(s)'), self) self.add_button.clicked.connect(self.add_rule) self.remove_button.clicked.connect(self.remove_rule) l.addWidget(self.add_button, l.rowCount(), 0) l.addWidget(self.remove_button, l.rowCount() - 1, 1) self.g = g = QGridLayout() self.rules_view = RulesView(self, self.do_enable_convert_buttons) self.rules_view.doubleClicked.connect(self.edit_rule) self.rules_view.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection) self.rules_view.setAlternatingRowColors(True) self.rtfd = RichTextDelegate(parent=self.rules_view, max_width=400) self.rules_view.setItemDelegate(self.rtfd) g.addWidget(self.rules_view, 0, 0, 2, 1) self.up_button = b = QToolButton(self) b.setIcon(QIcon(I('arrow-up.png'))) b.setToolTip(_('Move the selected rule up')) b.clicked.connect(self.move_up) g.addWidget(b, 0, 1, 1, 1, Qt.AlignmentFlag.AlignTop) self.down_button = b = QToolButton(self) b.setIcon(QIcon(I('arrow-down.png'))) b.setToolTip(_('Move the selected rule down')) b.clicked.connect(self.move_down) g.addWidget(b, 1, 1, 1, 1, Qt.AlignmentFlag.AlignBottom) l.addLayout(g, l.rowCount(), 0, 1, 2) l.setRowStretch(l.rowCount() - 1, 10) self.add_advanced_button = b = QPushButton(QIcon(I('plus.png')), _('Add ad&vanced rule'), self) b.clicked.connect(self.add_advanced) self.hb = hb = QHBoxLayout() l.addLayout(hb, l.rowCount(), 0, 1, 2) hb.addWidget(b) self.duplicate_rule_button = b = QPushButton(QIcon(I('edit-copy.png')), _('Du&plicate rule'), self) b.clicked.connect(self.duplicate_rule) b.setEnabled(False) hb.addWidget(b) self.convert_to_advanced_button = b = QPushButton(QIcon(I('modified.png')), _('Convert to advanced r&ule'), self) b.clicked.connect(self.convert_to_advanced) b.setEnabled(False) hb.addWidget(b) hb.addStretch(10) self.open_icon_folder_button = b = QPushButton(QIcon(I('icon_choose.png')), _('Open icon directory'), self) connect_lambda(b.clicked, self, lambda _: open_local_file(os.path.join(config_dir, 'cc_icons'))) hb.addWidget(b) hb.addStretch(10) self.export_button = b = QPushButton(_('E&xport'), self) b.clicked.connect(self.export_rules) b.setToolTip(_('Export these rules to a file')) hb.addWidget(b) self.import_button = b = QPushButton(_('&Import'), self) b.setToolTip(_('Import rules from a file')) b.clicked.connect(self.import_rules) hb.addWidget(b)
def main(args=sys.argv): from calibre.constants import debug debug() opts, args = option_parser().parse_args(args) if opts.gui: from calibre.gui2.main import main print_basic_debug_info() main(['calibre']) elif opts.gui_debug is not None: run_debug_gui(opts.gui_debug) elif opts.show_gui_debug: import time, re time.sleep(1) from calibre.gui2 import open_local_file if iswindows: with open(opts.show_gui_debug, 'r+b') as f: raw = f.read() raw = re.sub('(?<!\r)\n', '\r\n', raw) f.seek(0) f.truncate() f.write(raw) open_local_file(opts.show_gui_debug) elif opts.viewer: from calibre.gui2.viewer.main import main vargs = ['ebook-viewer', '--debug-javascript'] if len(args) > 1: vargs.append(args[-1]) main(vargs) elif opts.py_console: from calibre.utils.pyconsole.main import main main() elif opts.command: sys.argv = args exec opts.command elif opts.debug_device_driver: debug_device_driver() elif opts.add_simple_plugin is not None: add_simple_plugin(opts.add_simple_plugin) elif opts.paths: prints('CALIBRE_RESOURCES_PATH=' + sys.resources_location) prints('CALIBRE_EXTENSIONS_PATH=' + sys.extensions_location) prints('CALIBRE_PYTHON_PATH=' + os.pathsep.join(sys.path)) elif opts.reinitialize_db is not None: sql_dump = None if len(args) > 1 and os.access(args[-1], os.R_OK): sql_dump = args[-1] reinit_db(opts.reinitialize_db, sql_dump=sql_dump) elif opts.inspect_mobi: from calibre.ebooks.mobi.debug.main import inspect_mobi for path in args[1:]: prints('Inspecting:', path) inspect_mobi(path) print elif opts.tweak_book: from calibre.ebooks.tweak import tweak tweak(opts.tweak_book) elif opts.test_build: from calibre.test_build import test test() elif opts.shutdown_running_calibre: from calibre.gui2.main import shutdown_other shutdown_other() elif opts.subset_font: from calibre.utils.fonts.sfnt.subset import main main(['subset-font'] + [opts.subset_font] + args[1:]) elif opts.exec_file: run_script(opts.exec_file, args[1:]) elif opts.run_plugin: from calibre.customize.ui import find_plugin plugin = find_plugin(opts.run_plugin) if plugin is None: prints(_('No plugin named %s found') % opts.run_plugin) raise SystemExit(1) plugin.cli_main([plugin.name] + args[1:]) elif len(args) >= 2 and args[1].rpartition('.')[-1] in {'py', 'recipe'}: run_script(args[1], args[2:]) else: from calibre import ipython ipython() return 0
def show_recipe_files(self, *args): bdir = os.path.dirname(custom_recipes.file_path) if not os.path.exists(bdir): return error_dialog(self, _('No recipes'), _('No custom recipes created.'), show=True) open_local_file(bdir)
def run_gui(opts, args, listener, app, gui_debug=None): si = singleinstance('db') if not si: ext = '.exe' if iswindows else '' error_dialog( None, _('Cannot start calibre'), _('Another calibre program that can modify calibre libraries, such as,' ' {} or {} is already running. You must first shut it down, before' ' starting the main calibre program. If you are sure no such' ' program is running, try restarting your computer.').format( 'calibre-server' + ext, 'calibredb' + ext), show=True) return 1 initialize_file_icon_provider() app.load_builtin_fonts(scan_for_fonts=True) if not dynamic.get('welcome_wizard_was_run', False): from calibre.gui2.wizard import wizard wizard().exec_() dynamic.set('welcome_wizard_was_run', True) from calibre.gui2.ui import Main if isosx: actions = tuple(Main.create_application_menubar()) else: actions = tuple(Main.get_menubar_actions()) runner = GuiRunner(opts, args, actions, listener, app, gui_debug=gui_debug) ret = app.exec_() if getattr(runner.main, 'run_wizard_b4_shutdown', False): from calibre.gui2.wizard import wizard wizard().exec_() if getattr(runner.main, 'restart_after_quit', False): e = sys.executable if getattr(sys, 'frozen', False) else sys.argv[0] if getattr(runner.main, 'debug_on_restart', False) or gui_debug is not None: run_in_debug_mode() else: if hasattr(sys, 'frameworks_dir'): app = os.path.dirname( os.path.dirname(os.path.realpath(sys.frameworks_dir))) from calibre.debug import run_calibre_debug prints('Restarting with:', app) run_calibre_debug( '-c', 'import sys, os, time; time.sleep(3); os.execlp("open", "open", sys.argv[-1])', app) else: import subprocess os.environ['CALIBRE_RESTARTING_FROM_GUI'] = environ_item('1') if iswindows and hasattr(winutil, 'prepare_for_restart'): winutil.prepare_for_restart() if hasattr(sys, 'run_local'): cmd = [sys.run_local] if DEBUG: cmd += ['calibre-debug', '-g'] else: cmd.append('calibre') else: args = [ '-g' ] if os.path.splitext(e)[0].endswith('-debug') else [] cmd = [e] + args prints('Restarting with:', ' '.join(cmd)) subprocess.Popen(cmd) else: if iswindows: try: runner.main.system_tray_icon.hide() except: pass if getattr(runner.main, 'gui_debug', None) is not None: e = sys.executable if getattr(sys, 'frozen', False) else sys.argv[0] debugfile = runner.main.gui_debug from calibre.gui2 import open_local_file if iswindows: with open(debugfile, 'r+b') as f: raw = f.read() raw = re.sub(b'(?<!\r)\n', b'\r\n', raw) f.seek(0) f.truncate() f.write(raw) open_local_file(debugfile) return ret
def main(args=sys.argv): from calibre.constants import debug debug() opts, args = option_parser().parse_args(args) if opts.gui: from calibre.gui2.main import main print_basic_debug_info() main(['calibre']) elif opts.gui_debug is not None: run_debug_gui(opts.gui_debug) elif opts.show_gui_debug: import time, re time.sleep(1) from calibre.gui2 import open_local_file if iswindows: with open(opts.show_gui_debug, 'r+b') as f: raw = f.read() raw = re.sub('(?<!\r)\n', '\r\n', raw) f.seek(0) f.truncate() f.write(raw) open_local_file(opts.show_gui_debug) elif opts.viewer: from calibre.gui2.viewer.main import main vargs = ['ebook-viewer', '--debug-javascript'] if len(args) > 1: vargs.append(args[-1]) main(vargs) elif opts.py_console: from calibre.utils.pyconsole.main import main main() elif opts.command: sys.argv = args exec(opts.command) elif opts.debug_device_driver: debug_device_driver() elif opts.add_simple_plugin is not None: add_simple_plugin(opts.add_simple_plugin) elif opts.paths: prints('CALIBRE_RESOURCES_PATH='+sys.resources_location) prints('CALIBRE_EXTENSIONS_PATH='+sys.extensions_location) prints('CALIBRE_PYTHON_PATH='+os.pathsep.join(sys.path)) elif opts.reinitialize_db is not None: reinit_db(opts.reinitialize_db) elif opts.inspect_mobi: for path in args[1:]: inspect_mobi(path) elif opts.tweak_book: from calibre.gui2.tweak_book.main import main main(['ebook-tweak'] + args[1:]) elif opts.test_build: from calibre.test_build import test test() elif opts.shutdown_running_calibre: from calibre.gui2.main import shutdown_other shutdown_other() elif opts.subset_font: from calibre.utils.fonts.sfnt.subset import main main(['subset-font']+[opts.subset_font]+args[1:]) elif opts.exec_file: run_script(opts.exec_file, args[1:]) elif opts.run_plugin: from calibre.customize.ui import find_plugin plugin = find_plugin(opts.run_plugin) if plugin is None: prints(_('No plugin named %s found')%opts.run_plugin) raise SystemExit(1) plugin.cli_main([plugin.name] + args[1:]) elif len(args) >= 2 and args[1].rpartition('.')[-1] in {'py', 'recipe'}: run_script(args[1], args[2:]) elif len(args) >= 2 and args[1].rpartition('.')[-1] in {'mobi', 'azw', 'azw3', 'docx'}: for path in args[1:]: ext = path.rpartition('.')[-1] if ext == 'docx': from calibre.ebooks.docx.dump import dump dump(path) elif ext in {'mobi', 'azw', 'azw3'}: inspect_mobi(path) else: print ('Cannot dump unknown filetype: %s' % path) else: from calibre import ipython ipython() return 0
def main(args=sys.argv): from calibre.constants import debug debug() if len(args) > 2 and args[1] in ('-e', '--exec-file'): # Load all plugins user defined plugins so the script can import from the # calibre_plugins namespace import calibre.customize.ui as dummy dummy sys.argv = [args[2]] + args[3:] ef = os.path.abspath(args[2]) base = os.path.dirname(ef) sys.path.insert(0, base) g = globals() g['__name__'] = '__main__' g['__file__'] = ef execfile(ef, g) return if len(args) > 1 and args[1] in ('-f', '--subset-font'): from calibre.utils.fonts.sfnt.subset import main main(['subset-font']+args[2:]) return opts, args = option_parser().parse_args(args) if opts.gui: from calibre.gui2.main import main print_basic_debug_info() main(['calibre']) elif opts.gui_debug is not None: run_debug_gui(opts.gui_debug) elif opts.show_gui_debug: import time, re time.sleep(1) from calibre.gui2 import open_local_file if iswindows: with open(opts.show_gui_debug, 'r+b') as f: raw = f.read() raw = re.sub('(?<!\r)\n', '\r\n', raw) f.seek(0) f.truncate() f.write(raw) open_local_file(opts.show_gui_debug) elif opts.viewer: from calibre.gui2.viewer.main import main vargs = ['ebook-viewer', '--debug-javascript'] if len(args) > 1: vargs.append(args[-1]) main(vargs) elif opts.py_console: from calibre.utils.pyconsole.main import main main() elif opts.command: sys.argv = args exec opts.command elif opts.debug_device_driver: debug_device_driver() elif opts.add_simple_plugin is not None: add_simple_plugin(opts.add_simple_plugin) elif opts.paths: prints('CALIBRE_RESOURCES_PATH='+sys.resources_location) prints('CALIBRE_EXTENSIONS_PATH='+sys.extensions_location) prints('CALIBRE_PYTHON_PATH='+os.pathsep.join(sys.path)) elif opts.reinitialize_db is not None: sql_dump = None if len(args) > 1 and os.access(args[-1], os.R_OK): sql_dump = args[-1] reinit_db(opts.reinitialize_db, sql_dump=sql_dump) elif opts.inspect_mobi: from calibre.ebooks.mobi.debug.main import inspect_mobi for path in args[1:]: prints('Inspecting:', path) inspect_mobi(path) print elif opts.tweak_book: from calibre.ebooks.tweak import tweak tweak(opts.tweak_book) elif opts.test_build: from calibre.test_build import test test() elif opts.shutdown_running_calibre: from calibre.gui2.main import shutdown_other shutdown_other() else: from calibre import ipython ipython() return 0