Ejemplo n.º 1
0
 def _tjob_djvu_convert(self, db, book_id, fpath, ftype, abort, log, notifications):
     #NODOC
     if book_id:
         find_plugin('djvumaker')._postimport(book_id, ftype, db, log, fork_job=False,
                                             abort=abort, notifications=notifications)
     elif fpath:
         # TODO: proper english
         raise NotImplementedError('Connot convert book outside of library.'
                                   ' Add book to your library and then start conversion.')
Ejemplo n.º 2
0
 def select_book(self, row):
     book_id = int(self.books_table.item(row, self.title_column).data(Qt.UserRole))
     self.view.select_rows([book_id])
     modifiers = int(QApplication.keyboardModifiers())
     if modifiers in (Qt.CTRL, Qt.SHIFT):
         em = find_plugin('Edit Metadata')
         if em is not None:
             em.actual_plugin_.edit_metadata(None)
Ejemplo n.º 3
0
 def load_last_template_text(self):
     from calibre.customize.ui import find_plugin
     tt = find_plugin('Template Tester')
     if tt and tt.actual_plugin_:
         self.textbox.setPlainText(tt.actual_plugin_.last_template_text())
     else:
         # I don't think we can get here, but just in case ...
         self.textbox.setPlainText(_('No Template tester text is available'))
Ejemplo n.º 4
0
 def select_book(self, row):
     book_id = int(
         self.books_table.item(row, self.title_column).data(Qt.UserRole))
     self.view.select_rows([book_id])
     modifiers = int(QApplication.keyboardModifiers())
     if modifiers in (Qt.CTRL, Qt.SHIFT):
         em = find_plugin('Edit Metadata')
         if em is not None:
             em.actual_plugin_.edit_metadata(None)
Ejemplo n.º 5
0
 def edit_metadata(self, book_id, follow_library_view=True):
     try:
         self.follow_library_view = follow_library_view
         self.view.select_rows([book_id])
         em = find_plugin('Edit Metadata')
         if em and em.actual_plugin_:
             em.actual_plugin_.edit_metadata(None)
     finally:
         self.follow_library_view = True
Ejemplo n.º 6
0
 def book_doubleclicked(self, row, column):
     if self.no_valid_items:
         return
     book_id = self.books_table.item(row, self.title_column).data(Qt.UserRole).toInt()[0]
     self.view.select_rows([book_id])
     modifiers = int(QApplication.keyboardModifiers())
     if modifiers in (Qt.CTRL, Qt.SHIFT):
         em = find_plugin("Edit Metadata")
         if em is not None:
             em.actual_plugin_.edit_metadata(None)
Ejemplo n.º 7
0
 def book_doubleclicked(self, row, column):
     if self.no_valid_items:
         return
     book_id = self.books_table.item(row, 0).data(Qt.UserRole).toInt()[0]
     self.view.select_rows([book_id])
     modifiers = int(QApplication.keyboardModifiers())
     if modifiers in (Qt.CTRL, Qt.SHIFT):
         em = find_plugin('Edit Metadata')
         if em is not None:
             em.actual_plugin_.edit_metadata(None)
Ejemplo n.º 8
0
 def refresh_books_after_metadata_edit(self, book_ids, previous=None):
     m = self.gui.library_view.model()
     m.refresh_ids(list(book_ids))
     current = self.gui.library_view.currentIndex()
     self.gui.refresh_cover_browser()
     m.current_changed(current, previous or current)
     self.gui.tags_view.recount_with_position_based_index()
     qv = find_plugin('Show Quickview')
     if qv is not None:
         qv.actual_plugin_.refill_quickview()
Ejemplo n.º 9
0
def install_new_plugins():
    from calibre.utils.config import JSONConfig
    prefs = JSONConfig('newly-installed-editor-plugins')
    pl = prefs.get('newly_installed_plugins', ())
    if pl:
        for name in pl:
            plugin = find_plugin(name)
            if plugin is not None:
                install_plugin(plugin)
        prefs['newly_installed_plugins'] = []
Ejemplo n.º 10
0
    def column_header_context_handler(self, action=None, column=None):
        if not action or not column:
            return
        try:
            idx = self.column_map.index(column)
        except:
            return
        h = self.column_header

        if action == 'hide':
            if h.hiddenSectionCount() >= h.count():
                return error_dialog(self,
                                    _('Cannot hide all columns'),
                                    _('You must not hide all columns'),
                                    show=True)
            h.setSectionHidden(idx, True)
        elif action == 'show':
            h.setSectionHidden(idx, False)
            if h.sectionSize(idx) < 3:
                sz = h.sectionSizeHint(idx)
                h.resizeSection(idx, sz)
        elif action == 'ascending':
            self.sort_by_column_and_order(idx, True)
        elif action == 'descending':
            self.sort_by_column_and_order(idx, False)
        elif action == 'defaults':
            self.apply_state(self.get_default_state())
        elif action == 'addcustcol':
            self.add_column_signal.emit()
        elif action.startswith('align_'):
            alignment = action.partition('_')[-1]
            self._model.change_alignment(column, alignment)
        elif action == 'quickview':
            from calibre.customize.ui import find_plugin
            qv = find_plugin('Show Quickview')
            if qv:
                rows = self.selectionModel().selectedRows()
                if len(rows) > 0:
                    current_row = rows[0].row()
                    current_col = self.column_map.index(column)
                    index = self.model().index(current_row, current_col)
                    qv.actual_plugin_.change_quickview_column(index)

        self.save_state()
Ejemplo n.º 11
0
 def select_book(self, row, column):
     '''
     row and column both refer the qv table. In particular, column is not
     the logical column in the book list.
     '''
     item = self.books_table.item(row, column)
     if item is None:
         return
     book_id = int(self.books_table.item(row, column).data(Qt.UserRole))
     key = self.column_order[column]
     modifiers = int(QApplication.keyboardModifiers())
     if modifiers in (Qt.CTRL, Qt.SHIFT):
         self.view.select_rows([book_id])
         em = find_plugin('Edit Metadata')
         if em and em.actual_plugin_:
             em.actual_plugin_.edit_metadata(None)
     else:
         self.view.select_cell(self.db.data.id_to_index(book_id),
                               self.view.column_map.index(key))
Ejemplo n.º 12
0
 def select_book(self, row, column):
     '''
     row and column both refer the qv table. In particular, column is not
     the logical column in the book list.
     '''
     item = self.books_table.item(row, column)
     if item is None:
         return
     book_id = int(self.books_table.item(row, column).data(Qt.UserRole))
     key = self.column_order[column]
     modifiers = int(QApplication.keyboardModifiers())
     if modifiers in (Qt.CTRL, Qt.SHIFT):
         self.view.select_rows([book_id])
         em = find_plugin('Edit Metadata')
         if em is not None:
             em.actual_plugin_.edit_metadata(None)
     else:
         self.view.select_cell(self.db.data.id_to_index(book_id),
                               self.view.column_map.index(key))
Ejemplo n.º 13
0
 def refresh_gui(self, gui):
     m = gui.library_view.model()
     m.beginResetModel(), m.endResetModel()
     self.update_font_display()
     gui.tags_view.set_look_and_feel()
     gui.tags_view.reread_collapse_parameters()
     gui.library_view.refresh_book_details()
     gui.library_view.set_row_header_visibility()
     gui.cover_flow.setShowReflections(gprefs['cover_browser_reflections'])
     gui.cover_flow.setPreserveAspectRatio(gprefs['cb_preserve_aspect_ratio'])
     gui.update_cover_flow_subtitle_font()
     gui.cover_flow.template_inited = False
     for view in 'library memory card_a card_b'.split():
         getattr(gui, view + '_view').set_row_header_visibility()
     gui.library_view.refresh_row_sizing()
     gui.grid_view.refresh_settings()
     qv = find_plugin('Show Quickview')
     if qv is not None:
         qv.actual_plugin_.refill_quickview()
Ejemplo n.º 14
0
    def column_header_context_handler(self, action=None, column=None):
        if not action or not column:
            return
        try:
            idx = self.column_map.index(column)
        except:
            return
        h = self.column_header

        if action == 'hide':
            if h.hiddenSectionCount() >= h.count():
                return error_dialog(self, _('Cannot hide all columns'), _(
                    'You must not hide all columns'), show=True)
            h.setSectionHidden(idx, True)
        elif action == 'show':
            h.setSectionHidden(idx, False)
            if h.sectionSize(idx) < 3:
                sz = h.sectionSizeHint(idx)
                h.resizeSection(idx, sz)
        elif action == 'ascending':
            self.sort_by_column_and_order(idx, True)
        elif action == 'descending':
            self.sort_by_column_and_order(idx, False)
        elif action == 'defaults':
            self.apply_state(self.get_default_state())
        elif action == 'addcustcol':
            self.add_column_signal.emit()
        elif action.startswith('align_'):
            alignment = action.partition('_')[-1]
            self._model.change_alignment(column, alignment)
        elif action == 'quickview':
            from calibre.customize.ui import find_plugin
            qv = find_plugin('Show Quickview')
            if qv:
                rows = self.selectionModel().selectedRows()
                if len(rows) > 0:
                    current_row = rows[0].row()
                    current_col = self.column_map.index(column)
                    index = self.model().index(current_row, current_col)
                    qv.actual_plugin_.change_quickview_column(index)

        self.save_state()
Ejemplo n.º 15
0
def call_plugin_callback(plugin_callback, parent, plugin_results=None):
    '''
    This function executes a callback to a calling plugin. Because this 
    can be called after a job has been run, the plugin and callback function 
    are passed as strings.
    
    The parameters are:

      plugin_callback - This is a dictionary definging the callbak function.
          The elements are:
              plugin_name - name of the plugin to be called
              func_name - name of the functio to be called
              args - Arguments to be passedd to the callback function. Will be
                  passed as "*args" so must be a collection if it is supplied.
              kwargs - Keyword arguments to be passedd to the callback function.
                  Will be passed as "**kargs" so must be a dictionary if it 
                  is supplied.

      parent - parent gui needed to find the plugin.

      plugin_results - Results to be passed to the plugin.
      
    If the kwargs dictionary contains an entry for "plugin_results", the value
    will be replaced by the parameter "plugin_results". This allows the results
    of the called plugin to be passed to the callback. 
    '''
    print("call_plugin_callback: have callback:", plugin_callback)
    from calibre.customize.ui import find_plugin
    plugin = find_plugin (plugin_callback['plugin_name'])
    if plugin is not None:
        print("call_plugin_callback: have plugin for callback:", plugin)
        callback_func = getattr(plugin.load_actual_plugin(parent), plugin_callback['func_name'])
        args = plugin_callback['args'] if 'args'  in plugin_callback else []
        kwargs = plugin_callback['kwargs'] if 'kwargs' in plugin_callback else {}
        if 'plugin_results' in kwargs and plugin_results:
            kwargs['plugin_results'] = plugin_results
        print("call_plugin_callback: about to call callback - kwargs=", kwargs)
        callback_func(*args, **kwargs)
Ejemplo n.º 16
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.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
Ejemplo n.º 17
0
    def init_layout_mixin(self):
        self.vl_tabs = VLTabs(self)
        self.centralwidget.layout().addWidget(self.vl_tabs)

        if config['gui_layout'] == 'narrow':  # narrow {{{
            self.book_details = BookDetails(False, self)
            self.stack = Stack(self)
            self.bd_splitter = Splitter('book_details_splitter',
                    _('Book details'), I('book.png'),
                    orientation=Qt.Orientation.Vertical, parent=self, side_index=1,
                    shortcut='Shift+Alt+D')
            self.bd_splitter.addWidget(self.stack)
            self.bd_splitter.addWidget(self.book_details)
            self.bd_splitter.setCollapsible(self.bd_splitter.other_index, False)
            self.centralwidget.layout().addWidget(self.bd_splitter)
            button_order = ('sb', 'tb', 'bd', 'gv', 'cb', 'qv')
        # }}}
        else:  # wide {{{
            self.bd_splitter = Splitter('book_details_splitter',
                    _('Book details'), I('book.png'), initial_side_size=200,
                    orientation=Qt.Orientation.Horizontal, parent=self, side_index=1,
                    shortcut='Shift+Alt+D')
            self.stack = Stack(self)
            self.bd_splitter.addWidget(self.stack)
            self.book_details = BookDetails(True, self)
            self.bd_splitter.addWidget(self.book_details)
            self.bd_splitter.setCollapsible(self.bd_splitter.other_index, False)
            self.bd_splitter.setSizePolicy(QSizePolicy(QSizePolicy.Policy.Expanding,
                QSizePolicy.Policy.Expanding))
            self.centralwidget.layout().addWidget(self.bd_splitter)
            button_order = ('sb', 'tb', 'cb', 'gv', 'qv', 'bd')
        # }}}

        # This must use the base method to find the plugin because it hasn't
        # been fully initialized yet
        self.qv = find_plugin('Quickview')
        if self.qv and self.qv.actual_plugin_:
            self.qv = self.qv.actual_plugin_

        self.status_bar = StatusBar(self)
        stylename = str(self.style().objectName())
        self.grid_view_button = GridViewButton(self)
        self.search_bar_button = SearchBarButton(self)
        self.grid_view_button.toggled.connect(self.toggle_grid_view)
        self.search_bar_button.toggled.connect(self.toggle_search_bar)

        self.layout_buttons = []
        for x in button_order:
            if hasattr(self, x + '_splitter'):
                button = getattr(self, x + '_splitter').button
            else:
                if x == 'gv':
                    button = self.grid_view_button
                elif x == 'qv':
                    if self.qv is None:
                        continue
                    button = self.qv.qv_button
                else:
                    button = self.search_bar_button
            self.layout_buttons.append(button)
            button.setVisible(False)
            if ismacos and stylename != 'Calibre':
                button.setStyleSheet('''
                        QToolButton { background: none; border:none; padding: 0px; }
                        QToolButton:checked { background: rgba(0, 0, 0, 25%); }
                ''')
            self.status_bar.addPermanentWidget(button)
        if gprefs['show_layout_buttons']:
            for b in self.layout_buttons:
                b.setVisible(True)
                self.status_bar.addPermanentWidget(b)
        else:
            self.layout_button = b = QToolButton(self)
            b.setAutoRaise(True), b.setCursor(Qt.CursorShape.PointingHandCursor)
            b.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup)
            b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
            b.setText(_('Layout')), b.setIcon(QIcon(I('config.png')))
            b.setMenu(LayoutMenu(self))
            b.setToolTip(_(
                'Show and hide various parts of the calibre main window'))
            self.status_bar.addPermanentWidget(b)
        self.status_bar.addPermanentWidget(self.jobs_button)
        self.setStatusBar(self.status_bar)
        self.status_bar.update_label.linkActivated.connect(self.update_link_clicked)
Ejemplo n.º 18
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
        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
Ejemplo n.º 19
0
def main(args=sys.argv):
    from calibre.constants import debug
    debug()

    opts, args = option_parser().parse_args(args)
    if opts.gui:
        from calibre.gui_launch import calibre
        print_basic_debug_info()
        calibre(['calibre'])
    elif opts.gui_debug is not None:
        run_debug_gui(opts.gui_debug)
    elif opts.viewer:
        from calibre.gui_launch import ebook_viewer
        ebook_viewer(['ebook-viewer', '--debug-javascript'] + 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.gui_launch import ebook_edit
        ebook_edit(['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'] + 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 opts.default_programs:
        if not iswindows:
            raise SystemExit('Can only be run on Microsoft Windows')
        if opts.default_programs == 'register':
            from calibre.utils.winreg.default_programs import register as func
        else:
            from calibre.utils.winreg.default_programs import unregister as func
        print 'Running', func.__name__, '...'
        func()
    elif opts.new_server:
        from calibre.srv.standalone import main
        main(args)
    elif opts.export_all_calibre_data:
        from calibre.utils.exim import run_exporter
        run_exporter()
    elif opts.import_calibre_data:
        from calibre.utils.exim import run_importer
        run_importer()
    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)
    elif len(args) >= 2 and os.path.exists(os.path.join(args[1], '__main__.py')):
        sys.path.insert(0, args[1])
        run_script(os.path.join(args[1], '__main__.py'), args[2:])
    else:
        from calibre import ipython
        ipython()

    return 0
Ejemplo n.º 20
0
 def genesis(self):
     StorePlugin.genesis(self)
     from calibre.customize.ui import find_plugin
     pi = find_plugin('Amazon UK Kindle')
     pi.affiliate = False
Ejemplo n.º 21
0
def enable_integration():
    tm.inject_into_goodreads()
    plugin = find_plugin(GoodreadsMoreTags.name)
    plugin.is_integrated = True
Ejemplo n.º 22
0
def main(args=sys.argv):
    from calibre.constants import debug
    debug()

    opts, args = option_parser().parse_args(args)
    if opts.gui:
        from calibre.gui_launch import calibre
        calibre(['calibre'] + args[1:])
    elif opts.gui_debug is not None:
        run_debug_gui(opts.gui_debug)
    elif opts.viewer:
        from calibre.gui_launch import ebook_viewer
        ebook_viewer(['ebook-viewer', '--debug-javascript'] + args[1:])
    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.gui_launch import ebook_edit
        ebook_edit(['ebook-edit'] + args[1:])
    elif opts.explode_book or opts.implode_book:
        from calibre.ebooks.tweak import explode, implode
        try:
            a1, a2 = args[1:]
        except Exception:
            raise SystemExit('Must provide exactly two arguments')
        f = explode if opts.explode_book else implode
        f(a1, a2)
    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'] + 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 opts.default_programs:
        if not iswindows:
            raise SystemExit('Can only be run on Microsoft Windows')
        if opts.default_programs == 'register':
            from calibre.utils.winreg.default_programs import register as func
        else:
            from calibre.utils.winreg.default_programs import unregister as func
        print('Running', func.__name__, '...')
        func()
    elif opts.export_all_calibre_data:
        args = args[1:]
        from calibre.utils.exim import run_exporter
        run_exporter(args=args)
    elif opts.import_calibre_data:
        from calibre.utils.exim import run_importer
        run_importer()
    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)
    elif len(args) >= 2 and os.path.exists(os.path.join(
            args[1], '__main__.py')):
        sys.path.insert(0, args[1])
        run_script(os.path.join(args[1], '__main__.py'), args[2:])
    else:
        load_user_plugins()
        from calibre import ipython
        ipython()

    return 0
Ejemplo n.º 23
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
        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
Ejemplo n.º 24
0
    def initialize(self, library_path, db, listener, actions, show_gui=True):
        opts = self.opts
        self.preferences_action, self.quit_action = actions
        self.library_path = library_path
        self.library_broker = GuiLibraryBroker(db)
        self.content_server = None
        self.server_change_notification_timer = t = QTimer(self)
        self.server_changes = Queue()
        t.setInterval(1000), t.timeout.connect(self.handle_changes_from_server_debounced), t.setSingleShot(True)
        self._spare_pool = None
        self.must_restart_before_config = False
        self.listener = Listener(listener)
        self.check_messages_timer = QTimer()
        self.check_messages_timer.timeout.connect(self.another_instance_wants_to_talk)
        self.check_messages_timer.start(1000)

        for ac in self.iactions.values():
            try:
                ac.do_genesis()
            except Exception:
                # Ignore errors in third party plugins
                import traceback
                traceback.print_exc()
                if getattr(ac, 'plugin_path', None) is None:
                    raise
        self.donate_action = QAction(QIcon(I('donate.png')),
                _('&Donate to support calibre'), self)
        for st in self.istores.values():
            st.do_genesis()
        MainWindowMixin.init_main_window_mixin(self, db)

        # Jobs Button {{{
        self.job_manager = JobManager()
        self.jobs_dialog = JobsDialog(self, self.job_manager)
        self.jobs_button = JobsButton(parent=self)
        self.jobs_button.initialize(self.jobs_dialog, self.job_manager)
        # }}}

        LayoutMixin.init_layout_mixin(self)
        DeviceMixin.init_device_mixin(self)

        self.progress_indicator = ProgressIndicator(self)
        self.progress_indicator.pos = (0, 20)
        self.verbose = opts.verbose
        self.get_metadata = GetMetadata()
        self.upload_memory = {}
        self.metadata_dialogs = []
        self.default_thumbnail = None
        self.tb_wrapper = textwrap.TextWrapper(width=40)
        self.viewers = collections.deque()
        self.system_tray_icon = None
        if config['systray_icon']:
            self.system_tray_icon = factory(app_id='com.calibre-ebook.gui').create_system_tray_icon(parent=self, title='calibre')
        if self.system_tray_icon is not None:
            self.system_tray_icon.setIcon(QIcon(I('lt.png', allow_user_override=False)))
            if not (iswindows or isosx):
                self.system_tray_icon.setIcon(QIcon.fromTheme('calibre-gui', self.system_tray_icon.icon()))
            self.system_tray_icon.setToolTip(self.jobs_button.tray_tooltip())
            self.system_tray_icon.setVisible(True)
            self.jobs_button.tray_tooltip_updated.connect(self.system_tray_icon.setToolTip)
        elif config['systray_icon']:
            prints('Failed to create system tray icon, your desktop environment probably does not support the StatusNotifier spec')
        self.system_tray_menu = QMenu(self)
        self.toggle_to_tray_action = self.system_tray_menu.addAction(QIcon(I('page.png')), '')
        self.toggle_to_tray_action.triggered.connect(self.system_tray_icon_activated)
        self.system_tray_menu.addAction(self.donate_action)
        self.eject_action = self.system_tray_menu.addAction(
                QIcon(I('eject.png')), _('&Eject connected device'))
        self.eject_action.setEnabled(False)
        self.addAction(self.quit_action)
        self.system_tray_menu.addAction(self.quit_action)
        self.keyboard.register_shortcut('quit calibre', _('Quit calibre'),
                default_keys=('Ctrl+Q',), action=self.quit_action)
        if self.system_tray_icon is not None:
            self.system_tray_icon.setContextMenu(self.system_tray_menu)
            self.system_tray_icon.activated.connect(self.system_tray_icon_activated)
        self.quit_action.triggered[bool].connect(self.quit)
        self.donate_action.triggered[bool].connect(self.donate)
        self.minimize_action = QAction(_('Minimize the calibre window'), self)
        self.addAction(self.minimize_action)
        self.keyboard.register_shortcut('minimize calibre', self.minimize_action.text(),
                default_keys=(), action=self.minimize_action)
        self.minimize_action.triggered.connect(self.showMinimized)

        self.esc_action = QAction(self)
        self.addAction(self.esc_action)
        self.keyboard.register_shortcut('clear current search',
                _('Clear the current search'), default_keys=('Esc',),
                action=self.esc_action)
        self.esc_action.triggered.connect(self.esc)

        self.shift_esc_action = QAction(self)
        self.addAction(self.shift_esc_action)
        self.keyboard.register_shortcut('focus book list',
                _('Focus the book list'), default_keys=('Shift+Esc',),
                action=self.shift_esc_action)
        self.shift_esc_action.triggered.connect(self.shift_esc)

        self.ctrl_esc_action = QAction(self)
        self.addAction(self.ctrl_esc_action)
        self.keyboard.register_shortcut('clear virtual library',
                _('Clear the virtual library'), default_keys=('Ctrl+Esc',),
                action=self.ctrl_esc_action)
        self.ctrl_esc_action.triggered.connect(self.ctrl_esc)

        self.alt_esc_action = QAction(self)
        self.addAction(self.alt_esc_action)
        self.keyboard.register_shortcut('clear additional restriction',
                _('Clear the additional restriction'), default_keys=('Alt+Esc',),
                action=self.alt_esc_action)
        self.alt_esc_action.triggered.connect(self.clear_additional_restriction)

        # ###################### Start spare job server ########################
        QTimer.singleShot(1000, self.create_spare_pool)

        # ###################### Location Manager ########################
        self.location_manager.location_selected.connect(self.location_selected)
        self.location_manager.unmount_device.connect(self.device_manager.umount_device)
        self.location_manager.configure_device.connect(self.configure_connected_device)
        self.location_manager.update_device_metadata.connect(self.update_metadata_on_device)
        self.eject_action.triggered.connect(self.device_manager.umount_device)

        # ################### Update notification ###################
        UpdateMixin.init_update_mixin(self, opts)

        # ###################### Search boxes ########################
        SearchRestrictionMixin.init_search_restriction_mixin(self)
        SavedSearchBoxMixin.init_saved_seach_box_mixin(self)

        # ###################### Library view ########################
        LibraryViewMixin.init_library_view_mixin(self, db)
        SearchBoxMixin.init_search_box_mixin(self)  # Requires current_db

        self.library_view.model().count_changed_signal.connect(
                self.iactions['Choose Library'].count_changed)
        if not gprefs.get('quick_start_guide_added', False):
            try:
                add_quick_start_guide(self.library_view)
            except:
                import traceback
                traceback.print_exc()
        for view in ('library', 'memory', 'card_a', 'card_b'):
            v = getattr(self, '%s_view' % view)
            v.selectionModel().selectionChanged.connect(self.update_status_bar)
            v.model().count_changed_signal.connect(self.update_status_bar)

        self.library_view.model().count_changed()
        self.bars_manager.database_changed(self.library_view.model().db)
        self.library_view.model().database_changed.connect(self.bars_manager.database_changed,
                type=Qt.QueuedConnection)

        # ########################## Tags Browser ##############################
        TagBrowserMixin.init_tag_browser_mixin(self, db)
        self.library_view.model().database_changed.connect(self.populate_tb_manage_menu, type=Qt.QueuedConnection)

        # ######################## Search Restriction ##########################
        if db.prefs['virtual_lib_on_startup']:
            self.apply_virtual_library(db.prefs['virtual_lib_on_startup'])
        self.rebuild_vl_tabs()

        # ########################## Cover Flow ################################

        CoverFlowMixin.init_cover_flow_mixin(self)

        self._calculated_available_height = min(max_available_height()-15,
                self.height())
        self.resize(self.width(), self._calculated_available_height)

        self.build_context_menus()

        for ac in self.iactions.values():
            try:
                ac.gui_layout_complete()
            except:
                import traceback
                traceback.print_exc()
                if ac.plugin_path is None:
                    raise

        if config['autolaunch_server']:
            self.start_content_server()

        self.read_settings()

        self.finalize_layout()
        self.bars_manager.start_animation()
        self.set_window_title()

        for ac in self.iactions.values():
            try:
                ac.initialization_complete()
            except:
                import traceback
                traceback.print_exc()
                if ac.plugin_path is None:
                    raise
        self.set_current_library_information(current_library_name(), db.library_id,
                                             db.field_metadata)

        register_keyboard_shortcuts()
        self.keyboard.finalize()
        if show_gui:
            # Note this has to come after restoreGeometry() because of
            # https://bugreports.qt.io/browse/QTBUG-56831
            self.show()
        if self.system_tray_icon is not None and self.system_tray_icon.isVisible() and opts.start_in_tray:
            self.hide_windows()
        self.auto_adder = AutoAdder(gprefs['auto_add_path'], self)

        # Now that the gui is initialized we can restore the quickview state
        # The same thing will be true for any action-based operation with a
        # layout button
        qv = find_plugin('Show Quickview')
        if qv is not None:
            qv.actual_plugin_.qv_button.restore_state()
        self.save_layout_state()

        # Collect cycles now
        gc.collect()

        QApplication.instance().shutdown_signal_received.connect(self.quit)
        if show_gui and self.gui_debug is not None:
            QTimer.singleShot(10, self.show_gui_debug_msg)

        self.iactions['Connect Share'].check_smartdevice_menus()
        QTimer.singleShot(1, self.start_smartdevice)
        QTimer.singleShot(100, self.update_toggle_to_tray_action)
Ejemplo n.º 25
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
Ejemplo n.º 26
0
    def init_layout_mixin(self):
        self.vl_tabs = VLTabs(self)
        self.centralwidget.layout().addWidget(self.vl_tabs)

        if config['gui_layout'] == 'narrow':  # narrow {{{
            self.book_details = BookDetails(False, self)
            self.stack = Stack(self)
            self.bd_splitter = Splitter('book_details_splitter',
                    _('Book details'), I('book.png'),
                    orientation=Qt.Vertical, parent=self, side_index=1,
                    shortcut='Shift+Alt+D')
            self.bd_splitter.addWidget(self.stack)
            self.bd_splitter.addWidget(self.book_details)
            self.bd_splitter.setCollapsible(self.bd_splitter.other_index, False)
            self.centralwidget.layout().addWidget(self.bd_splitter)
            button_order = ('sb', 'tb', 'bd', 'gv', 'cb', 'qv')
        # }}}
        else:  # wide {{{
            self.bd_splitter = Splitter('book_details_splitter',
                    _('Book details'), I('book.png'), initial_side_size=200,
                    orientation=Qt.Horizontal, parent=self, side_index=1,
                    shortcut='Shift+Alt+D')
            self.stack = Stack(self)
            self.bd_splitter.addWidget(self.stack)
            self.book_details = BookDetails(True, self)
            self.bd_splitter.addWidget(self.book_details)
            self.bd_splitter.setCollapsible(self.bd_splitter.other_index, False)
            self.bd_splitter.setSizePolicy(QSizePolicy(QSizePolicy.Expanding,
                QSizePolicy.Expanding))
            self.centralwidget.layout().addWidget(self.bd_splitter)
            button_order = ('sb', 'tb', 'cb', 'gv', 'qv', 'bd')
        # }}}

        # This must use the base method to find the plugin because it hasn't
        # been fully initialized yet
        self.qv = find_plugin('Quickview')
        if self.qv and self.qv.actual_plugin_:
            self.qv = self.qv.actual_plugin_

        self.status_bar = StatusBar(self)
        stylename = unicode(self.style().objectName())
        self.grid_view_button = GridViewButton(self)
        self.search_bar_button = SearchBarButton(self)
        self.grid_view_button.toggled.connect(self.toggle_grid_view)
        self.search_bar_button.toggled.connect(self.toggle_search_bar)

        self.layout_buttons = []
        for x in button_order:
            if hasattr(self, x + '_splitter'):
                button = getattr(self, x + '_splitter').button
            else:
                if x == 'gv':
                    button = self.grid_view_button
                elif x == 'qv':
                    if self.qv is None:
                        continue
                    button = self.qv.qv_button
                else:
                    button = self.search_bar_button
            self.layout_buttons.append(button)
            button.setVisible(False)
            if isosx and stylename != u'Calibre':
                button.setStyleSheet('''
                        QToolButton { background: none; border:none; padding: 0px; }
                        QToolButton:checked { background: rgba(0, 0, 0, 25%); }
                ''')
            self.status_bar.addPermanentWidget(button)
        if gprefs['show_layout_buttons']:
            for b in self.layout_buttons:
                b.setVisible(True)
                self.status_bar.addPermanentWidget(b)
        else:
            self.layout_button = b = QToolButton(self)
            b.setAutoRaise(True), b.setCursor(Qt.PointingHandCursor)
            b.setPopupMode(b.InstantPopup)
            b.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
            b.setText(_('Layout')), b.setIcon(QIcon(I('config.png')))
            b.setMenu(LayoutMenu(self))
            b.setToolTip(_(
                'Show and hide various parts of the calibre main window'))
            self.status_bar.addPermanentWidget(b)
        self.status_bar.addPermanentWidget(self.jobs_button)
        self.setStatusBar(self.status_bar)
        self.status_bar.update_label.linkActivated.connect(self.update_link_clicked)
Ejemplo n.º 27
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