Exemple #1
0
    def catalog_generated(self, job):
        if job.result:
            # Problems during catalog generation
            # jobs.results is a list - the first entry is the intended title for the dialog
            # Subsequent strings are error messages
            dialog_title = job.result.pop(0)
            if re.search('warning', job.result[0].lower()):
                msg = _("Catalog generation complete, with warnings.")
                warning_dialog(self.gui,
                               dialog_title,
                               msg,
                               det_msg='\n'.join(job.result),
                               show=True)
            else:
                job.result.append("Catalog generation terminated.")
                error_dialog(self.gui,
                             dialog_title,
                             '\n'.join(job.result),
                             show=True)
                return

        if job.failed:
            return self.gui.job_exception(job)
        if dynamic.get('catalog_add_to_library', True):
            id = self.gui.library_view.model().add_catalog(
                job.catalog_file_path, job.catalog_title)
            self.gui.library_view.model().beginResetModel(
            ), self.gui.library_view.model().endResetModel()
            if job.catalog_sync:
                sync = dynamic.get('catalogs_to_be_synced', set())
                sync.add(id)
                dynamic.set('catalogs_to_be_synced', sync)
        self.gui.status_bar.show_message(_('Catalog generated.'), 3000)
        self.gui.sync_catalogs()
        if not dynamic.get('catalog_add_to_library', True) or job.fmt not in {
                'EPUB', 'MOBI', 'AZW3'
        }:
            export_dir = choose_dir(
                self.gui, _('Export catalog folder'),
                _('Select destination for %(title)s.%(fmt)s') %
                dict(title=job.catalog_title, fmt=job.fmt.lower()))
            if export_dir:
                destination = os.path.join(
                    export_dir, '%s.%s' %
                    (sanitize_file_name(job.catalog_title), job.fmt.lower()))
                try:
                    shutil.copyfile(job.catalog_file_path, destination)
                except OSError as err:
                    if getattr(err, 'errno',
                               None) == errno.EACCES:  # Permission denied
                        import traceback
                        error_dialog(
                            self.gui,
                            _('Permission denied'),
                            _('Could not open %s. Is it being used by another'
                              ' program?') % destination,
                            det_msg=traceback.format_exc(),
                            show=True)
                        return
                    raise
Exemple #2
0
 def export_key(self):
     if not self.listy.currentItem():
         errmsg = u"No keyfile selected to export. Highlight a keyfile first."
         r = error_dialog(None,
                          "{0} {1}".format(PLUGIN_NAME, PLUGIN_VERSION),
                          _(errmsg),
                          show=True,
                          show_copy_button=False)
         return
     filter = QString(u"{0} Files (*.{1})".format(self.key_type_name,
                                                  self.keyfile_ext))
     keyname = unicode(self.listy.currentItem().text().toUtf8(), 'utf8')
     if dynamic.get(PLUGIN_NAME + 'save_dir'):
         defaultname = os.path.join(
             dynamic.get(PLUGIN_NAME + 'save_dir'),
             u"{0}.{1}".format(keyname, self.keyfile_ext))
     else:
         defaultname = os.path.join(
             os.path.expanduser('~'),
             u"{0}.{1}".format(keyname, self.keyfile_ext))
     filename = unicode(
         QtGui.QFileDialog.getSaveFileName(
             self, u"Save {0} File as...".format(self.key_type_name),
             defaultname,
             u"{0} Files (*.{1})".format(self.key_type_name,
                                         self.keyfile_ext), filter))
     if filename:
         dynamic[PLUGIN_NAME + 'save_dir'] = os.path.split(filename)[0]
         with file(filename, 'w') as fname:
             if self.binary_file:
                 fname.write(self.plugin_keys[keyname].decode('hex'))
             elif self.json_file:
                 fname.write(json.dumps(self.plugin_keys[keyname]))
             else:
                 fname.write(self.plugin_keys[keyname])
Exemple #3
0
 def initializePage(self):
     self.label.setText(_('Choose your e-book device. If your device is'
         ' not in the list, choose a "%s" device.')%Device.manufacturer)
     self.man_model = ManufacturerModel()
     self.manufacturer_view.setModel(self.man_model)
     previous = dynamic.get('welcome_wizard_device', False)
     if previous:
         previous = [x for x in get_devices() if x.id == previous]
         if not previous:
             previous = [Device]
         previous = previous[0]
     else:
         previous = Device
     idx = self.man_model.index_of(previous.manufacturer)
     if idx is None:
         idx = self.man_model.index_of(Device.manufacturer)
         previous = Device
     self.manufacturer_view.selectionModel().select(idx,
             QItemSelectionModel.Select)
     self.dev_model = DeviceModel(self.man_model.data(idx, Qt.UserRole))
     idx = self.dev_model.index_of(previous)
     self.device_view.setModel(self.dev_model)
     self.device_view.selectionModel().select(idx,
             QItemSelectionModel.Select)
     self.manufacturer_view.selectionModel().selectionChanged[(QItemSelection, QItemSelection)].connect(self.manufacturer_changed)
    def __init__(self):
        self.search.initialize(
            'main_search_history',
            colorize=True,
            help_text=_(
                'Search (For Advanced Search click the button to the left)'))
        self.search.cleared.connect(self.search_box_cleared)
        # Queued so that search.current_text will be correct
        self.search.changed.connect(self.search_box_changed,
                                    type=Qt.QueuedConnection)
        self.search.focus_to_library.connect(self.focus_to_library)
        self.clear_button.clicked.connect(self.search.clear_clicked)
        self.advanced_search_button.clicked[bool].connect(
            self.do_advanced_search)

        self.search.clear()
        self.search.setMaximumWidth(self.width() - 150)
        self.action_focus_search = QAction(self)
        shortcuts = QKeySequence.keyBindings(QKeySequence.Find)
        shortcuts = list(shortcuts) + [
            QKeySequence('/'), QKeySequence('Alt+S')
        ]
        self.action_focus_search.setShortcuts(shortcuts)
        self.action_focus_search.triggered.connect(self.focus_search_box)
        self.addAction(self.action_focus_search)
        self.search.setStatusTip(
            re.sub(r'<\w+>', ' ', unicode(self.search.toolTip())))
        self.advanced_search_button.setStatusTip(
            self.advanced_search_button.toolTip())
        self.clear_button.setStatusTip(self.clear_button.toolTip())
        self.search_highlight_only.stateChanged.connect(
            self.highlight_only_changed)
        self.search_highlight_only.setChecked(
            dynamic.get('search_highlight_only', False))
Exemple #5
0
    def catalog_generated(self, job):
        if job.result:
            # Problems during catalog generation
            # jobs.results is a list - the first entry is the intended title for the dialog
            # Subsequent strings are error messages
            dialog_title = job.result.pop(0)
            if re.match('warning:', job.result[0].lower()):
                msg = _("Catalog generation complete, with warnings.")
                warning_dialog(self.gui, dialog_title, msg, det_msg='\n'.join(job.result), show=True)
            else:
                job.result.append("Catalog generation terminated.")
                error_dialog(self.gui, dialog_title,'\n'.join(job.result),show=True)
                return

        if job.failed:
            return self.gui.job_exception(job)
        id = self.gui.library_view.model().add_catalog(job.catalog_file_path, job.catalog_title)
        self.gui.library_view.model().reset()
        if job.catalog_sync:
            sync = dynamic.get('catalogs_to_be_synced', set([]))
            sync.add(id)
            dynamic.set('catalogs_to_be_synced', sync)
        self.gui.status_bar.show_message(_('Catalog generated.'), 3000)
        self.gui.sync_catalogs()
        if job.fmt not in ['EPUB','MOBI']:
            export_dir = choose_dir(self.gui, _('Export Catalog Directory'),
                    _('Select destination for %(title)s.%(fmt)s') % dict(
                        title=job.catalog_title, fmt=job.fmt.lower()))
            if export_dir:
                destination = os.path.join(export_dir, '%s.%s' % (
                    sanitize_file_name_unicode(job.catalog_title), job.fmt.lower()))
                shutil.copyfile(job.catalog_file_path, destination)
Exemple #6
0
 def initializePage(self):
     self.label.setText(_('Choose your e-book device. If your device is'
         ' not in the list, choose a "%s" device.')%Device.manufacturer)
     self.man_model = ManufacturerModel()
     self.manufacturer_view.setModel(self.man_model)
     previous = dynamic.get('welcome_wizard_device', False)
     if previous:
         previous = [x for x in get_devices() if x.id == previous]
         if not previous:
             previous = [Device]
         previous = previous[0]
     else:
         previous = Device
     idx = self.man_model.index_of(previous.manufacturer)
     if idx is None:
         idx = self.man_model.index_of(Device.manufacturer)
         previous = Device
     self.manufacturer_view.selectionModel().select(idx,
             QItemSelectionModel.Select)
     self.dev_model = DeviceModel(self.man_model.data(idx, Qt.UserRole))
     idx = self.dev_model.index_of(previous)
     self.device_view.setModel(self.dev_model)
     self.device_view.selectionModel().select(idx,
             QItemSelectionModel.Select)
     self.manufacturer_view.selectionModel().selectionChanged[(QItemSelection, QItemSelection)].connect(self.manufacturer_changed)
Exemple #7
0
def get_initial_folder(name, title, default_dir='~', no_save_dir=False):
    name = name or 'dialog_' + title
    if no_save_dir:
        initial_folder = expanduser(default_dir)
    else:
        initial_folder = dynamic.get(name, expanduser(default_dir))
    if not initial_folder or not os.path.isdir(initial_folder):
        initial_folder = select_initial_dir(initial_folder)
    return name, initial_folder
Exemple #8
0
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 get_initial_dir(name, title, default_dir, no_save_dir):
    if no_save_dir:
        return ensure_dir(process_path(default_dir))
    key = dialog_name(name, title)
    saved = dynamic.get(key)
    if not isinstance(saved, string_or_bytes):
        saved = None
    if saved and os.path.isdir(saved):
        return ensure_dir(process_path(saved))
    return ensure_dir(process_path(default_dir))
Exemple #10
0
def get_initial_dir(name, title, default_dir, no_save_dir):
    if no_save_dir:
        return ensure_dir(process_path(default_dir))
    key = dialog_name(name, title)
    saved = dynamic.get(key)
    if not isinstance(saved, basestring):
        saved = None
    if saved and os.path.isdir(saved):
        return ensure_dir(process_path(saved))
    return ensure_dir(process_path(default_dir))
Exemple #11
0
    def catalog_generated(self, job):
        if job.result:
            # Problems during catalog generation
            # jobs.results is a list - the first entry is the intended title for the dialog
            # Subsequent strings are error messages
            dialog_title = job.result.pop(0)
            if re.search('warning', job.result[0].lower()):
                msg = _("Catalog generation complete, with warnings.")
                warning_dialog(self.gui, dialog_title, msg, det_msg='\n'.join(job.result), show=True)
            else:
                job.result.append("Catalog generation terminated.")
                error_dialog(self.gui, dialog_title,'\n'.join(job.result),show=True)
                return

        if job.failed:
            return self.gui.job_exception(job)
        if dynamic.get('catalog_add_to_library', True):
            id = self.gui.library_view.model().add_catalog(job.catalog_file_path, job.catalog_title)
            self.gui.library_view.model().beginResetModel(), self.gui.library_view.model().endResetModel()
            if job.catalog_sync:
                sync = dynamic.get('catalogs_to_be_synced', set([]))
                sync.add(id)
                dynamic.set('catalogs_to_be_synced', sync)
        self.gui.status_bar.show_message(_('Catalog generated.'), 3000)
        self.gui.sync_catalogs()
        if not dynamic.get('catalog_add_to_library', True) or job.fmt not in {'EPUB','MOBI', 'AZW3'}:
            export_dir = choose_dir(self.gui, _('Export Catalog Directory'),
                    _('Select destination for %(title)s.%(fmt)s') % dict(
                        title=job.catalog_title, fmt=job.fmt.lower()))
            if export_dir:
                destination = os.path.join(export_dir, '%s.%s' % (
                    sanitize_file_name(job.catalog_title), job.fmt.lower()))
                try:
                    shutil.copyfile(job.catalog_file_path, destination)
                except EnvironmentError as err:
                    if getattr(err, 'errno', None) == errno.EACCES:  # Permission denied
                        import traceback
                        error_dialog(self.gui, _('Permission denied'),
                                _('Could not open %s. Is it being used by another'
                                ' program?')%destination, det_msg=traceback.format_exc(),
                                show=True)
                        return
                    raise
Exemple #12
0
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(sys.frameworks_dir))
                subprocess.Popen("sleep 3s; open " + 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]
        import subprocess

        creationflags = 0
        if iswindows:
            import win32process

            creationflags = win32process.CREATE_NO_WINDOW
        subprocess.Popen(
            [e, "--show-gui-debug", runner.main.gui_debug],
            creationflags=creationflags,
            stdout=open(os.devnull, "w"),
            stderr=subprocess.PIPE,
            stdin=open(os.devnull, "r"),
        )
    return ret
Exemple #13
0
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
Exemple #14
0
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
Exemple #15
0
 def export_key(self):
     if not self.listy.currentItem():
         errmsg = u"No keyfile selected to export. Highlight a keyfile first."
         r = error_dialog(None, "{0} {1}".format(PLUGIN_NAME, PLUGIN_VERSION),
                                 _(errmsg), show=True, show_copy_button=False)
         return
     filter = QString(u"{0} Files (*.{1})".format(self.key_type_name, self.keyfile_ext))
     keyname = unicode(self.listy.currentItem().text().toUtf8(), 'utf8')
     if dynamic.get(PLUGIN_NAME + 'save_dir'):
         defaultname = os.path.join(dynamic.get(PLUGIN_NAME + 'save_dir'), u"{0}.{1}".format(keyname , self.keyfile_ext))
     else:
         defaultname = os.path.join(os.path.expanduser('~'), u"{0}.{1}".format(keyname , self.keyfile_ext))
     filename = unicode(QtGui.QFileDialog.getSaveFileName(self, u"Save {0} File as...".format(self.key_type_name), defaultname,
                                         u"{0} Files (*.{1})".format(self.key_type_name,self.keyfile_ext), filter))
     if filename:
         dynamic[PLUGIN_NAME + 'save_dir'] = os.path.split(filename)[0]
         with file(filename, 'w') as fname:
             if self.binary_file:
                 fname.write(self.plugin_keys[keyname].decode('hex'))
             elif self.json_file:
                 fname.write(json.dumps(self.plugin_keys[keyname]))
             else:
                 fname.write(self.plugin_keys[keyname])
Exemple #16
0
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(sys.frameworks_dir))
                subprocess.Popen('sleep 3s; open ' + 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]
        import subprocess
        creationflags = 0
        if iswindows:
            import win32process
            creationflags = win32process.CREATE_NO_WINDOW
        subprocess.Popen([e, '--show-gui-debug', runner.main.gui_debug],
                         creationflags=creationflags,
                         stdout=open(os.devnull, 'w'),
                         stderr=subprocess.PIPE,
                         stdin=open(os.devnull, 'r'))
    return ret
Exemple #17
0
    def catalog_generated(self, job):
        if job.result:
            # Problems during catalog generation
            # jobs.results is a list - the first entry is the intended title for the dialog
            # Subsequent strings are error messages
            dialog_title = job.result.pop(0)
            if re.match('warning:', job.result[0].lower()):
                msg = _("Catalog generation complete, with warnings.")
                warning_dialog(self.gui,
                               dialog_title,
                               msg,
                               det_msg='\n'.join(job.result),
                               show=True)
            else:
                job.result.append("Catalog generation terminated.")
                error_dialog(self.gui,
                             dialog_title,
                             '\n'.join(job.result),
                             show=True)
                return

        if job.failed:
            return self.gui.job_exception(job)
        id = self.gui.library_view.model().add_catalog(job.catalog_file_path,
                                                       job.catalog_title)
        self.gui.library_view.model().reset()
        if job.catalog_sync:
            sync = dynamic.get('catalogs_to_be_synced', set([]))
            sync.add(id)
            dynamic.set('catalogs_to_be_synced', sync)
        self.gui.status_bar.show_message(_('Catalog generated.'), 3000)
        self.gui.sync_catalogs()
        if job.fmt not in ['EPUB', 'MOBI']:
            export_dir = choose_dir(
                self.gui, _('Export Catalog Directory'),
                _('Select destination for %(title)s.%(fmt)s') %
                dict(title=job.catalog_title, fmt=job.fmt.lower()))
            if export_dir:
                destination = os.path.join(
                    export_dir, '%s.%s' % (sanitize_file_name_unicode(
                        job.catalog_title), job.fmt.lower()))
                shutil.copyfile(job.catalog_file_path, destination)
Exemple #18
0
def run_gui(opts, args, actions, 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)
    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(sys.frameworks_dir))
                subprocess.Popen('sleep 3s; open '+app, shell=True)
            else:
                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]
        import subprocess
        creationflags = 0
        if iswindows:
            import win32process
            creationflags = win32process.CREATE_NO_WINDOW
        subprocess.Popen([e, '--show-gui-debug', runner.main.gui_debug],
            creationflags=creationflags, stdout=open(os.devnull, 'w'),
            stderr=subprocess.PIPE, stdin=open(os.devnull, 'r'))
    return ret
Exemple #19
0
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
        after_quit_actions['no_plugins_on_restart'] = getattr(
            runner.main, 'no_plugins_on_restart', False)
    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
Exemple #20
0
    def __init__(
        self,
        title=_("Choose Files"),
        filters=[],
        add_all_files_filter=True,
        parent=None,
        modal=True,
        name="",
        mode=QFileDialog.ExistingFiles,
        default_dir="~",
        no_save_dir=False,
    ):
        QObject.__init__(self)
        ftext = ""
        if filters:
            for filter in filters:
                text, extensions = filter
                extensions = ["*" + (i if i.startswith(".") else "." + i) for i in extensions]
                ftext += "%s (%s);;" % (text, " ".join(extensions))
        if add_all_files_filter or not ftext:
            ftext += "All files (*)"
        if ftext.endswith(";;"):
            ftext = ftext[:-2]

        self.dialog_name = name if name else "dialog_" + title
        self.selected_files = None
        self.fd = None

        if no_save_dir:
            initial_dir = os.path.expanduser(default_dir)
        else:
            initial_dir = dynamic.get(self.dialog_name, os.path.expanduser(default_dir))
        if not isinstance(initial_dir, basestring):
            initial_dir = os.path.expanduser(default_dir)
        self.selected_files = []
        use_native_dialog = "CALIBRE_NO_NATIVE_FILEDIALOGS" not in os.environ
        with SanitizeLibraryPath():
            opts = QFileDialog.Option()
            if not use_native_dialog:
                opts |= QFileDialog.DontUseNativeDialog
            if mode == QFileDialog.AnyFile:
                f = unicode(QFileDialog.getSaveFileName(parent, title, initial_dir, ftext, "", opts))
                if f:
                    self.selected_files.append(f)
            elif mode == QFileDialog.ExistingFile:
                f = unicode(QFileDialog.getOpenFileName(parent, title, initial_dir, ftext, "", opts))
                if f and os.path.exists(f):
                    self.selected_files.append(f)
            elif mode == QFileDialog.ExistingFiles:
                fs = QFileDialog.getOpenFileNames(parent, title, initial_dir, ftext, "", opts)
                for f in fs:
                    f = unicode(f)
                    if not f:
                        continue
                    if not os.path.exists(f):
                        # QFileDialog for some reason quotes spaces
                        # on linux if there is more than one space in a row
                        f = unquote(f)
                    if f and os.path.exists(f):
                        self.selected_files.append(f)
            else:
                if mode == QFileDialog.Directory:
                    opts |= QFileDialog.ShowDirsOnly
                f = unicode(QFileDialog.getExistingDirectory(parent, title, initial_dir, opts))
                if os.path.exists(f):
                    self.selected_files.append(f)
        if self.selected_files:
            self.selected_files = [unicode(q) for q in self.selected_files]
            saved_loc = self.selected_files[0]
            if os.path.isfile(saved_loc):
                saved_loc = os.path.dirname(saved_loc)
            if not no_save_dir:
                dynamic[self.dialog_name] = saved_loc
        self.accepted = bool(self.selected_files)
Exemple #21
0
    def __init__(self,
                 title=_('Choose Files'),
                 filters=[],
                 add_all_files_filter=True,
                 parent=None,
                 modal=True,
                 name='',
                 mode=QFileDialog.ExistingFiles,
                 default_dir='~'):
        QObject.__init__(self)
        ftext = ''
        if filters:
            for filter in filters:
                text, extensions = filter
                extensions = [
                    '*' + (i if i.startswith('.') else '.' + i)
                    for i in extensions
                ]
                ftext += '%s (%s);;' % (text, ' '.join(extensions))
        if add_all_files_filter or not ftext:
            ftext += 'All files (*)'
        if ftext.endswith(';;'):
            ftext = ftext[:-2]

        self.dialog_name = name if name else 'dialog_' + title
        self.selected_files = None
        self.fd = None

        initial_dir = dynamic.get(self.dialog_name,
                                  os.path.expanduser(default_dir))
        if not isinstance(initial_dir, basestring):
            initial_dir = os.path.expanduser(default_dir)
        self.selected_files = []
        with SanitizeLibraryPath():
            if mode == QFileDialog.AnyFile:
                f = unicode(
                    QFileDialog.getSaveFileName(parent, title, initial_dir,
                                                ftext, ""))
                if f:
                    self.selected_files.append(f)
            elif mode == QFileDialog.ExistingFile:
                f = unicode(
                    QFileDialog.getOpenFileName(parent, title, initial_dir,
                                                ftext, ""))
                if f and os.path.exists(f):
                    self.selected_files.append(f)
            elif mode == QFileDialog.ExistingFiles:
                fs = QFileDialog.getOpenFileNames(parent, title, initial_dir,
                                                  ftext, "")
                for f in fs:
                    f = unicode(f)
                    if not f: continue
                    if not os.path.exists(f):
                        # QFileDialog for some reason quotes spaces
                        # on linux if there is more than one space in a row
                        f = unquote(f)
                    if f and os.path.exists(f):
                        self.selected_files.append(f)
            else:
                opts = QFileDialog.ShowDirsOnly if mode == QFileDialog.Directory else QFileDialog.Option(
                )
                f = unicode(
                    QFileDialog.getExistingDirectory(parent, title,
                                                     initial_dir, opts))
                if os.path.exists(f):
                    self.selected_files.append(f)
        if self.selected_files:
            self.selected_files = [unicode(q) for q in self.selected_files]
            saved_loc = self.selected_files[0]
            if os.path.isfile(saved_loc):
                saved_loc = os.path.dirname(saved_loc)
            dynamic[self.dialog_name] = saved_loc
        self.accepted = bool(self.selected_files)
Exemple #22
0
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
Exemple #23
0
    def prepare_search_and_replace(self):
        self.search_for.initialize('bulk_edit_search_for')
        self.replace_with.initialize('bulk_edit_replace_with')
        self.s_r_template.initialize('bulk_edit_template')
        self.test_text.initialize('bulk_edit_test_test')
        self.all_fields = ['']
        self.writable_fields = ['']
        fm = self.db.field_metadata
        for f in fm:
            if (f in ['author_sort'] or
                    (fm[f]['datatype'] in ['text', 'series', 'enumeration', 'comments']
                     and fm[f].get('search_terms', None)
                     and f not in ['formats', 'ondevice', 'series_sort']) or
                    (fm[f]['datatype'] in ['int', 'float', 'bool', 'datetime'] and
                     f not in ['id', 'timestamp'])):
                self.all_fields.append(f)
                self.writable_fields.append(f)
            if fm[f]['datatype'] == 'composite':
                self.all_fields.append(f)
        self.all_fields.sort()
        self.all_fields.insert(1, '{template}')
        self.writable_fields.sort()
        self.search_field.setMaxVisibleItems(25)
        self.destination_field.setMaxVisibleItems(25)
        self.testgrid.setColumnStretch(1, 1)
        self.testgrid.setColumnStretch(2, 1)
        offset = 10
        self.s_r_number_of_books = min(10, len(self.ids))
        for i in range(1,self.s_r_number_of_books+1):
            w = QLabel(self.tabWidgetPage3)
            w.setText(_('Book %d:')%i)
            self.testgrid.addWidget(w, i+offset, 0, 1, 1)
            w = QLineEdit(self.tabWidgetPage3)
            w.setReadOnly(True)
            name = 'book_%d_text'%i
            setattr(self, name, w)
            self.book_1_text.setObjectName(name)
            self.testgrid.addWidget(w, i+offset, 1, 1, 1)
            w = QLineEdit(self.tabWidgetPage3)
            w.setReadOnly(True)
            name = 'book_%d_result'%i
            setattr(self, name, w)
            self.book_1_text.setObjectName(name)
            self.testgrid.addWidget(w, i+offset, 2, 1, 1)

        ident_types = sorted(self.db.get_all_identifier_types(), key=sort_key)
        self.s_r_dst_ident.setCompleter(QCompleter(ident_types))
        try:
            self.s_r_dst_ident.setPlaceholderText(_('Enter an identifier type'))
        except:
            pass
        self.s_r_src_ident.addItems(ident_types)

        self.main_heading = _(
                 '<b>You can destroy your library using this feature.</b> '
                 'Changes are permanent. There is no undo function. '
                 'You are strongly encouraged to back up your library '
                 'before proceeding.<p>'
                 'Search and replace in text fields using character matching '
                 'or regular expressions. ')

        self.character_heading = _(
                 'In character mode, the field is searched for the entered '
                 'search text. The text is replaced by the specified replacement '
                 'text everywhere it is found in the specified field. After '
                 'replacement is finished, the text can be changed to '
                 'upper-case, lower-case, or title-case. If the case-sensitive '
                 'check box is checked, the search text must match exactly. If '
                 'it is unchecked, the search text will match both upper- and '
                 'lower-case letters'
                 )

        self.regexp_heading = _(
                 'In regular expression mode, the search text is an '
                 'arbitrary python-compatible regular expression. The '
                 'replacement text can contain backreferences to parenthesized '
                 'expressions in the pattern. The search is not anchored, '
                 'and can match and replace multiple times on the same string. '
                 'The modification functions (lower-case etc) are applied to the '
                 'matched text, not to the field as a whole. '
                 'The destination box specifies the field where the result after '
                 'matching and replacement is to be assigned. You can replace '
                 'the text in the field, or prepend or append the matched text. '
                 'See <a href="http://docs.python.org/library/re.html"> '
                 'this reference</a> for more information on python\'s regular '
                 'expressions, and in particular the \'sub\' function.'
                 )

        self.search_mode.addItems(self.s_r_match_modes)
        self.search_mode.setCurrentIndex(dynamic.get('s_r_search_mode', 0))
        self.replace_mode.addItems(self.s_r_replace_modes)
        self.replace_mode.setCurrentIndex(0)

        self.s_r_search_mode = 0
        self.s_r_error = None
        self.s_r_obj = None

        self.replace_func.addItems(sorted(self.s_r_functions.keys()))
        self.search_mode.currentIndexChanged[int].connect(self.s_r_search_mode_changed)
        self.search_field.currentIndexChanged[int].connect(self.s_r_search_field_changed)
        self.destination_field.currentIndexChanged[int].connect(self.s_r_destination_field_changed)

        self.replace_mode.currentIndexChanged[int].connect(self.s_r_paint_results)
        self.replace_func.currentIndexChanged[str].connect(self.s_r_paint_results)
        self.search_for.editTextChanged[str].connect(self.s_r_paint_results)
        self.replace_with.editTextChanged[str].connect(self.s_r_paint_results)
        self.test_text.editTextChanged[str].connect(self.s_r_paint_results)
        self.comma_separated.stateChanged.connect(self.s_r_paint_results)
        self.case_sensitive.stateChanged.connect(self.s_r_paint_results)
        self.s_r_src_ident.currentIndexChanged[int].connect(self.s_r_identifier_type_changed)
        self.s_r_dst_ident.textChanged.connect(self.s_r_paint_results)
        self.s_r_template.lost_focus.connect(self.s_r_template_changed)
        self.central_widget.setCurrentIndex(0)

        self.search_for.completer().setCaseSensitivity(Qt.CaseSensitive)
        self.replace_with.completer().setCaseSensitivity(Qt.CaseSensitive)
        self.s_r_template.completer().setCaseSensitivity(Qt.CaseSensitive)

        self.s_r_search_mode_changed(self.search_mode.currentIndex())
        self.multiple_separator.setFixedWidth(30)
        self.multiple_separator.setText(' ::: ')
        self.multiple_separator.textChanged.connect(self.s_r_separator_changed)
        self.results_count.valueChanged[int].connect(self.s_r_display_bounds_changed)
        self.starting_from.valueChanged[int].connect(self.s_r_display_bounds_changed)

        self.save_button.clicked.connect(self.s_r_save_query)
        self.remove_button.clicked.connect(self.s_r_remove_query)

        self.queries = JSONConfig("search_replace_queries")
        self.saved_search_name = ''
        self.query_field.addItem("")
        self.query_field_values = sorted([q for q in self.queries], key=sort_key)
        self.query_field.addItems(self.query_field_values)
        self.query_field.currentIndexChanged[str].connect(self.s_r_query_change)
        self.query_field.setCurrentIndex(0)
        self.search_field.setCurrentIndex(0)
        self.s_r_search_field_changed(0)
Exemple #24
0
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
Exemple #25
0
    def __init__(self, title=_('Choose Files'),
                       filters=[],
                       add_all_files_filter=True,
                       parent=None,
                       modal=True,
                       name='',
                       mode=QFileDialog.ExistingFiles,
                       default_dir=u'~',
                       no_save_dir=False,
                       combine_file_and_saved_dir=False
                       ):
        QObject.__init__(self)
        ftext = ''
        if filters:
            for filter in filters:
                text, extensions = filter
                extensions = ['*'+(i if i.startswith('.') else '.'+i) for i in
                        extensions]
                ftext += '%s (%s);;'%(text, ' '.join(extensions))
        if add_all_files_filter or not ftext:
            ftext += 'All files (*)'
        if ftext.endswith(';;'):
            ftext = ftext[:-2]

        self.dialog_name = name if name else 'dialog_' + title
        self.selected_files = None
        self.fd = None

        if combine_file_and_saved_dir:
            bn = os.path.basename(default_dir)
            prev = dynamic.get(self.dialog_name,
                    expanduser(u'~'))
            if os.path.exists(prev):
                if os.path.isfile(prev):
                    prev = os.path.dirname(prev)
            else:
                prev = expanduser(u'~')
            initial_dir = os.path.join(prev, bn)
        elif no_save_dir:
            initial_dir = expanduser(default_dir)
        else:
            initial_dir = dynamic.get(self.dialog_name,
                    expanduser(default_dir))
        if not isinstance(initial_dir, basestring):
            initial_dir = expanduser(default_dir)
        if not initial_dir or (not os.path.exists(initial_dir) and not (
                mode == QFileDialog.AnyFile and (no_save_dir or combine_file_and_saved_dir))):
            initial_dir = select_initial_dir(initial_dir)
        self.selected_files = []
        use_native_dialog = 'CALIBRE_NO_NATIVE_FILEDIALOGS' not in os.environ
        with SanitizeLibraryPath():
            opts = QFileDialog.Option()
            if not use_native_dialog:
                opts |= QFileDialog.DontUseNativeDialog
            if mode == QFileDialog.AnyFile:
                f = unicode(QFileDialog.getSaveFileName(parent, title,
                    initial_dir, ftext, "", opts))
                if f:
                    self.selected_files.append(f)
            elif mode == QFileDialog.ExistingFile:
                f = unicode(QFileDialog.getOpenFileName(parent, title,
                    initial_dir, ftext, "", opts))
                if f and os.path.exists(f):
                    self.selected_files.append(f)
            elif mode == QFileDialog.ExistingFiles:
                fs = QFileDialog.getOpenFileNames(parent, title, initial_dir,
                        ftext, "", opts)
                for f in fs:
                    f = unicode(f)
                    if not f:
                        continue
                    if not os.path.exists(f):
                        # QFileDialog for some reason quotes spaces
                        # on linux if there is more than one space in a row
                        f = unquote(f)
                    if f and os.path.exists(f):
                        self.selected_files.append(f)
            else:
                if mode == QFileDialog.Directory:
                    opts |= QFileDialog.ShowDirsOnly
                f = unicode(QFileDialog.getExistingDirectory(parent, title, initial_dir, opts))
                if os.path.exists(f):
                    self.selected_files.append(f)
        if self.selected_files:
            self.selected_files = [unicode(q) for q in self.selected_files]
            saved_loc = self.selected_files[0]
            if os.path.isfile(saved_loc):
                saved_loc = os.path.dirname(saved_loc)
            if not no_save_dir:
                dynamic[self.dialog_name] = saved_loc
        self.accepted = bool(self.selected_files)
Exemple #26
0
    def __init__(self, title=_('Choose Files'),
                       filters=[],
                       add_all_files_filter=True,
                       parent=None,
                       modal=True,
                       name='',
                       mode=QFileDialog.ExistingFiles,
                       default_dir=u'~',
                       no_save_dir=False,
                       combine_file_and_saved_dir=False
                       ):
        QObject.__init__(self)
        ftext = ''
        if filters:
            for filter in filters:
                text, extensions = filter
                extensions = ['*'+(i if i.startswith('.') else '.'+i) for i in
                        extensions]
                ftext += '%s (%s);;'%(text, ' '.join(extensions))
        if add_all_files_filter or not ftext:
            ftext += 'All files (*)'
        if ftext.endswith(';;'):
            ftext = ftext[:-2]

        self.dialog_name = name if name else 'dialog_' + title
        self.selected_files = None
        self.fd = None

        if combine_file_and_saved_dir:
            bn = os.path.basename(default_dir)
            prev = dynamic.get(self.dialog_name,
                    expanduser(u'~'))
            if os.path.exists(prev):
                if os.path.isfile(prev):
                    prev = os.path.dirname(prev)
            else:
                prev = expanduser(u'~')
            initial_dir = os.path.join(prev, bn)
        elif no_save_dir:
            initial_dir = expanduser(default_dir)
        else:
            initial_dir = dynamic.get(self.dialog_name,
                    expanduser(default_dir))
        if not isinstance(initial_dir, basestring):
            initial_dir = expanduser(default_dir)
        if not initial_dir or (not os.path.exists(initial_dir) and not (
                mode == QFileDialog.AnyFile and (no_save_dir or combine_file_and_saved_dir))):
            initial_dir = select_initial_dir(initial_dir)
        self.selected_files = []
        use_native_dialog = 'CALIBRE_NO_NATIVE_FILEDIALOGS' not in os.environ
        with sanitize_env_vars():
            opts = QFileDialog.Option()
            if not use_native_dialog:
                opts |= QFileDialog.DontUseNativeDialog
            if mode == QFileDialog.AnyFile:
                f = QFileDialog.getSaveFileName(parent, title,
                    initial_dir, ftext, "", opts)
                if f and f[0]:
                    self.selected_files.append(f[0])
            elif mode == QFileDialog.ExistingFile:
                f = QFileDialog.getOpenFileName(parent, title,
                    initial_dir, ftext, "", opts)
                if f and f[0] and os.path.exists(f[0]):
                    self.selected_files.append(f[0])
            elif mode == QFileDialog.ExistingFiles:
                fs = QFileDialog.getOpenFileNames(parent, title, initial_dir,
                        ftext, "", opts)
                if fs and fs[0]:
                    for f in fs[0]:
                        f = unicode(f)
                        if not f:
                            continue
                        if not os.path.exists(f):
                            # QFileDialog for some reason quotes spaces
                            # on linux if there is more than one space in a row
                            f = unquote(f)
                        if f and os.path.exists(f):
                            self.selected_files.append(f)
            else:
                if mode == QFileDialog.Directory:
                    opts |= QFileDialog.ShowDirsOnly
                f = unicode(QFileDialog.getExistingDirectory(parent, title, initial_dir, opts))
                if os.path.exists(f):
                    self.selected_files.append(f)
        if self.selected_files:
            self.selected_files = [unicode(q) for q in self.selected_files]
            saved_loc = self.selected_files[0]
            if os.path.isfile(saved_loc):
                saved_loc = os.path.dirname(saved_loc)
            if not no_save_dir:
                dynamic[self.dialog_name] = saved_loc
        self.accepted = bool(self.selected_files)