def import_rules(self): paths = choose_files(self, 'export-style-transform-rules', _('Choose file to import rules from'), select_only_single_file=True) if paths: with open(paths[0], 'rb') as f: rules = import_rules(f.read()) self.rules_widget.rules = list(rules) + list(self.rules_widget.rules) self.changed.emit()
def filename_button_clicked(self): try: path = choose_files(self, 'choose_category_icon', _('Select Icon'), filters=[ ('Images', ['png', 'gif', 'jpg', 'jpeg'])], all_files=False, select_only_single_file=True) if path: icon_path = path[0] icon_name = sanitize_file_name_unicode( os.path.splitext( os.path.basename(icon_path))[0]+'.png') if icon_name not in self.icon_file_names: self.icon_file_names.append(icon_name) self.update_filename_box() try: p = QIcon(icon_path).pixmap(QSize(128, 128)) d = os.path.join(config_dir, 'cc_icons') if not os.path.exists(os.path.join(d, icon_name)): if not os.path.exists(d): os.makedirs(d) with open(os.path.join(d, icon_name), 'wb') as f: f.write(pixmap_to_data(p, format='PNG')) except: traceback.print_exc() self.icon_files.setCurrentIndex(self.icon_files.findText(icon_name)) self.icon_files.adjustSize() except: traceback.print_exc() return
def open_book(self, path=None, edit_file=None, clear_notify_data=True): if not self._check_before_open(): return if not hasattr(path, 'rpartition'): path = choose_files(self.gui, 'open-book-for-tweaking', _('Choose book'), [(_('Books'), [x.lower() for x in SUPPORTED])], all_files=False, select_only_single_file=True) if not path: return path = path[0] ext = path.rpartition('.')[-1].upper() if ext not in SUPPORTED: return error_dialog(self.gui, _('Unsupported format'), _('Tweaking is only supported for books in the %s formats.' ' Convert your book to one of these formats first.') % _(' and ').join(sorted(SUPPORTED)), show=True) if not os.path.exists(path): return error_dialog(self.gui, _('File not found'), _( 'The file %s does not exist.') % path, show=True) for name in tuple(editors): self.close_editor(name) self.gui.preview.clear() self.container_count = -1 if self.tdir: shutil.rmtree(self.tdir, ignore_errors=True) self.tdir = PersistentTemporaryDirectory() self._edit_file_on_open = edit_file self._clear_notify_data = clear_notify_data self.gui.blocking_job('open_book', _('Opening book, please wait...'), self.book_opened, get_container, path, tdir=self.mkdtemp())
def import_searches(self): path = choose_files(self, 'import_saved_searches', _('Choose file'), filters=[ (_('Saved Searches'), ['json'])], all_files=False, select_only_single_file=True) if path: with open(path[0], 'rb') as f: obj = json.loads(f.read()) needed_keys = {'name', 'find', 'replace', 'case_sensitive', 'dot_all', 'mode'} def err(): error_dialog(self, _('Invalid data'), _( 'The file %s does not contain valid saved searches') % path, show=True) if not isinstance(obj, dict) or 'version' not in obj or 'searches' not in obj or obj['version'] not in (1,): return err() searches = [] for item in obj['searches']: if not isinstance(item, dict) or not set(item.iterkeys()).issuperset(needed_keys): return err searches.append({k:item[k] for k in needed_keys}) if searches: tprefs['saved_searches'] = tprefs['saved_searches'] + searches count = len(searches) self.model.add_searches(count=count) sm = self.searches.selectionModel() top, bottom = self.model.index(self.model.rowCount() - count), self.model.index(self.model.rowCount() - 1) sm.select(QItemSelection(top, bottom), sm.ClearAndSelect) self.searches.scrollTo(bottom)
def load(self): files = choose_files( self, "recipe loader dialog", _("Choose a recipe file"), filters=[(_("Recipes"), [".py", ".recipe"])], all_files=False, select_only_single_file=True, ) if files: file = files[0] try: profile = open(file, "rb").read().decode("utf-8") title = compile_recipe(profile).title except Exception as err: error_dialog(self, _("Invalid input"), _("<p>Could not create recipe. Error:<br>%s") % str(err)).exec_() return if self._model.has_title(title): if question_dialog( self, _("Replace recipe?"), _("A custom recipe named %s already exists. Do you want to " "replace it?") % title, ): self._model.replace_by_title(title, profile) else: return else: self.model.add(title, profile) self.clear()
def add_formats(self, *args): if self.gui.stack.currentIndex() != 0: return view = self.gui.library_view rows = view.selectionModel().selectedRows() if not rows: return error_dialog(self.gui, _('No books selected'), _('Cannot add files as no books are selected'), show=True) ids = [view.model().id(r) for r in rows] if len(ids) > 1 and not question_dialog(self.gui, _('Are you sure'), _('Are you sure you want to add the same' ' files to all %d books? If the format' ' already exists for a book, it will be replaced.')%len(ids)): return books = choose_files(self.gui, 'add formats dialog dir', _('Select book files'), filters=get_filters()) if not books: return db = view.model().db for id_ in ids: for fpath in books: fmt = os.path.splitext(fpath)[1][1:].upper() if fmt: db.add_format_with_hooks(id_, fmt, fpath, index_is_id=True, notify=True) current_idx = self.gui.library_view.currentIndex() if current_idx.isValid(): view.model().current_changed(current_idx, current_idx)
def add_texture(self): path = choose_files( self, "choose-texture-image", _("Choose Image"), filters=[(_("Images"), ["jpeg", "jpg", "png"])], all_files=False, select_only_single_file=True, ) if not path: return path = path[0] fname = os.path.basename(path) name = fname.rpartition(".")[0] existing = { unicode(i.data(Qt.UserRole).toString()): i for i in (self.images.item(c) for c in xrange(self.images.count())) } dest = os.path.join(self.tdir, fname) with open(path, "rb") as s, open(dest, "wb") as f: shutil.copyfileobj(s, f) if fname in existing: self.takeItem(existing[fname]) data = {"fname": fname, "path": dest, "name": name} i = self.create_item(data) i.setSelected(True) self.images.scrollToItem(i)
def import_template(self): paths = choose_files(self, 'custom-list-template', _('Choose template file'), filters=[(_('Template files'), ['json'])], all_files=False, select_only_single_file=True) if paths: with lopen(paths[0], 'rb') as f: raw = f.read() self.current_template = self.deserialize(raw)
def add_fonts(parent): from calibre.utils.fonts.metadata import FontMetadata files = choose_files(parent, 'add fonts to calibre', _('Select font files'), filters=[(_('TrueType/OpenType Fonts'), ['ttf', 'otf'])], all_files=False) if not files: return families = set() for f in files: try: with open(f, 'rb') as stream: fm = FontMetadata(stream) except: import traceback error_dialog(parent, _('Corrupt font'), _('Failed to read metadata from the font file: %s')% f, det_msg=traceback.format_exc(), show=True) return families.add(fm.font_family) families = sorted(families) dest = os.path.join(config_dir, 'fonts') for f in files: shutil.copyfile(f, os.path.join(dest, os.path.basename(f))) return families
def add_files(self): if current_container() is None: return error_dialog(self.gui, _('No open book'), _( 'You must first open a book to tweak, before trying to create new files' ' in it.'), show=True) files = choose_files(self.gui, 'tweak-book-bulk-import-files', _('Choose files')) if files: folder_map = get_recommended_folders(current_container(), files) files = {x:('/'.join((folder, os.path.basename(x))) if folder else os.path.basename(x)) for x, folder in folder_map.iteritems()} self.commit_dirty_opf() self.add_savepoint(_('Add files')) c = current_container() for path, name in files.iteritems(): i = 0 while c.exists(name): i += 1 name, ext = name.rpartition('.')[0::2] name = '%s_%d.%s' % (name, i, ext) try: with open(path, 'rb') as f: c.add_file(name, f.read()) except: self.rewind_savepoint() raise self.gui.file_list.build(c) if c.opf_name in editors: editors[c.opf_name].replace_data(c.raw_data(c.opf_name)) self.set_modified()
def open_book(self, path=None): if not self.check_dirtied(): return if self.save_manager.has_tasks: return info_dialog(self.gui, _('Cannot open'), _('The current book is being saved, you cannot open a new book until' ' the saving is completed'), show=True) if not hasattr(path, 'rpartition'): path = choose_files(self.gui, 'open-book-for-tweaking', _('Choose book'), [(_('Books'), [x.lower() for x in SUPPORTED])], all_files=False, select_only_single_file=True) if not path: return path = path[0] ext = path.rpartition('.')[-1].upper() if ext not in SUPPORTED: return error_dialog(self.gui, _('Unsupported format'), _('Tweaking is only supported for books in the %s formats.' ' Convert your book to one of these formats first.') % _(' and ').join(sorted(SUPPORTED)), show=True) for name in tuple(editors): self.close_editor(name) self.gui.preview.clear() self.container_count = -1 if self.tdir: shutil.rmtree(self.tdir, ignore_errors=True) self.tdir = PersistentTemporaryDirectory() self.gui.blocking_job('open_book', _('Opening book, please wait...'), self.book_opened, get_container, path, tdir=self.mkdtemp())
def replace(self, name): c = current_container() mt = c.mime_map[name] oext = name.rpartition(".")[-1].lower() filters = [oext] fname = _("Files") if mt in OEB_DOCS: fname = _("HTML Files") filters = "html htm xhtm xhtml shtml".split() elif is_raster_image(mt): fname = _("Images") filters = "jpeg jpg gif png".split() path = choose_files( self, "tweak_book_import_file", _("Choose file"), filters=[(fname, filters)], select_only_single_file=True ) if not path: return path = path[0] ext = path.rpartition(".")[-1].lower() force_mt = None if mt in OEB_DOCS: force_mt = c.guess_type("a.html") nname = os.path.basename(path) nname, ext = nname.rpartition(".")[0::2] nname = nname + "." + ext.lower() self.replace_requested.emit(name, path, nname, force_mt)
def import_bookmarks(self): files = choose_files(self, 'export-viewer-bookmarks', _('Import Bookmarks'), filters=[(_('Saved Bookmarks'), ['pickle'])], all_files=False, select_only_single_file=True) if not files: return filename = files[0] imported = None with open(filename, 'rb') as fileobj: imported = cPickle.load(fileobj) if imported is not None: bad = False try: for bm in imported: if 'title' not in bm: bad = True break except Exception: pass if not bad: bookmarks = self.get_bookmarks() for bm in imported: if bm not in bookmarks: bookmarks.append(bm) self.set_bookmarks([bm for bm in bookmarks if bm['title'] != 'calibre_current_page_bookmark']) self.edited.emit(self.get_bookmarks())
def filename_button_clicked(self): try: path = choose_files(self, 'choose_category_icon', _('Select Icon'), filters=[ (_('Images'), ['png', 'gif', 'jpg', 'jpeg'])], all_files=False, select_only_single_file=True) if path: icon_path = path[0] icon_name = self.sanitize_icon_file_name(icon_path) if icon_name not in self.icon_file_names: self.icon_file_names.append(icon_name) try: p = QIcon(icon_path).pixmap(QSize(128, 128)) d = self.icon_folder if not os.path.exists(os.path.join(d, icon_name)): if not os.path.exists(d): os.makedirs(d) with open(os.path.join(d, icon_name), 'wb') as f: f.write(pixmap_to_data(p, format='PNG')) except: import traceback traceback.print_exc() self.update_filename_box() self.update_remove_button() if self.doing_multiple: if icon_name not in self.rule_icon_files: self.rule_icon_files.append(icon_name) self.update_icon_filenames_in_box() else: self.filename_box.setCurrentIndex(self.filename_box.findText(icon_name)) self.filename_box.adjustSize() except: import traceback traceback.print_exc() return
def import_file(self): path = choose_files(self, "tweak-book-new-resource-file", _("Choose file"), select_only_single_file=True) if path: path = path[0] with open(path, "rb") as f: self.file_data = f.read() name = os.path.basename(path) self.name.setText(name)
def choose_manually(filetype, parent): ans = choose_files(parent, 'choose-open-with-program-manually', _('Choose a program to open %s files') % filetype.upper(), select_only_single_file=True) if ans: ans = ans[0] if not os.access(ans, os.X_OK): return error_dialog(parent, _('Cannot execute'), _( 'The program %s is not an executable file') % ans, show=True) return {'Exec':[ans, '%f'], 'Name':os.path.basename(ans)}
def open_ebook(self, triggered): files = choose_files(self, 'open ebook dialog', 'Choose ebook', [('Ebooks', ['lrf'])], all_files=False, select_only_single_file=True) if files: file = files[0] self.set_ebook(open(file, 'rb')) self.render()
def choose_file(self): path = choose_files(self, 'choose-dict-for-import', _('Choose OXT Dictionary'), filters=[ (_('Dictionaries'), ['oxt'])], all_files=False, select_only_single_file=True) if path is not None: self.path.setText(path[0]) if not self.nickname: n = os.path.basename(path[0]) self.nick.setText(n.rpartition('.')[0])
def add_formats(self, *args): ids = self._check_add_formats_ok() if not ids: return books = choose_files(self.gui, 'add formats dialog dir', _('Select book files'), filters=get_filters()) if books: self._add_formats(books, ids)
def open_ebook(self, checked): files = choose_files(self, 'ebook viewer open dialog', _('Choose ebook'), [(_('Ebooks'), available_input_formats())], all_files=False, select_only_single_file=True) if files: self.load_ebook(files[0])
def import_urls(self): paths = choose_files(self, 'search-net-urls', _('Choose URLs file'), filters=[(_('URL files'), ['json'])], all_files=False, select_only_single_file=True) if paths: with lopen(paths[0], 'rb') as f: items = json.loads(f.read()) [self.append_item(x) for x in items] self.changed_signal.emit()
def migrate_files(self): unique_dlg_name = PLUGIN_NAME + u"import {0} keys".format(self.key_type_name).replace(' ', '_') #takes care of automatically remembering last directory caption = u"Select {0} files to import".format(self.key_type_name) filters = [(u"{0} files".format(self.key_type_name), [self.keyfile_ext])] files = choose_files(self, unique_dlg_name, caption, filters, all_files=False) counter = 0 skipped = 0 if files: for filename in files: fpath = os.path.join(config_dir, filename) filename = os.path.basename(filename) if type(self.plugin_keys) != dict: # must be the new Kindle for Android section print u"Getting keys from "+fpath new_keys = get_serials(fpath) for key in new_keys: if key in self.plugin_keys: skipped += 1 else: counter += 1 self.plugin_keys.append(key) else: new_key_name = os.path.splitext(os.path.basename(filename))[0] with open(fpath,'rb') as keyfile: new_key_value = keyfile.read() if self.binary_file: new_key_value = new_key_value.encode('hex') elif self.json_file: new_key_value = json.loads(new_key_value) match = False for key in self.plugin_keys.keys(): if uStrCmp(new_key_name, key, True): skipped += 1 msg = u"A key with the name <strong>{0}</strong> already exists!\nSkipping key file <strong>{1}</strong>.\nRename the existing key and import again".format(new_key_name,filename) inf = info_dialog(None, "{0} {1}".format(PLUGIN_NAME, PLUGIN_VERSION), _(msg), show_copy_button=False, show=True) match = True break if not match: if new_key_value in self.plugin_keys.values(): old_key_name = [name for name, value in self.plugin_keys.iteritems() if value == new_key_value][0] skipped += 1 info_dialog(None, "{0} {1}".format(PLUGIN_NAME, PLUGIN_VERSION), u"The key in file {0} is the same as the existing key <strong>{1}</strong> and has been skipped.".format(filename,old_key_name), show_copy_button=False, show=True) else: counter += 1 self.plugin_keys[new_key_name] = new_key_value msg = u"" if counter+skipped > 1: if counter > 0: msg += u"Imported <strong>{0:d}</strong> key {1}. ".format(counter, u"file" if counter == 1 else u"files") if skipped > 0: msg += u"Skipped <strong>{0:d}</strong> key {1}.".format(skipped, u"file" if counter == 1 else u"files") inf = info_dialog(None, "{0} {1}".format(PLUGIN_NAME, PLUGIN_VERSION), _(msg), show_copy_button=False, show=True) return counter > 0
def import_file(self): path = choose_files(self, 'tweak-book-new-resource-file', _('Choose file'), select_only_single_file=True) if path: path = path[0] with open(path, 'rb') as f: self.file_data = f.read() name = os.path.basename(path) self.name.setText(name) self.la.setText(_('Choose a name for the imported file'))
def cf(): files = choose_files(d, 'select link file', _('Choose file'), select_only_single_file=True) if files: path = files[0] d.url.setText(path) if path and os.path.exists(path): with lopen(path, 'rb') as f: q = what(f) is_image = q in {'jpeg', 'png', 'gif'} d.treat_as_image.setChecked(is_image)
def add_plugin(self): info = "" if iswindows else " [.zip %s]" % _("files") path = choose_files( self, "add a plugin dialog", _("Add plugin"), filters=[(_("Plugins") + info, ["zip"])], all_files=False, select_only_single_file=True, ) if not path: return path = path[0] if path and os.access(path, os.R_OK) and path.lower().endswith(".zip"): if not question_dialog( self, _("Are you sure?"), "<p>" + _( "Installing plugins is a <b>security risk</b>. " "Plugins can contain a virus/malware. " "Only install it if you got it from a trusted source." " Are you sure you want to proceed?" ), show_copy_button=False, ): return from calibre.customize.ui import config installed_plugins = frozenset(config["plugins"]) try: plugin = add_plugin(path) except NameConflict as e: return error_dialog(self, _("Already exists"), unicode(e), show=True) self._plugin_model.populate() self._plugin_model.reset() self.changed_signal.emit() self.check_for_add_to_toolbars(plugin, previously_installed=plugin.name in installed_plugins) info_dialog( self, _("Success"), _( "Plugin <b>{0}</b> successfully installed under <b>" " {1} plugins</b>. You may have to restart calibre " "for the plugin to take effect." ).format(plugin.name, plugin.type), show=True, show_copy_button=False, ) idx = self._plugin_model.plugin_to_index_by_properties(plugin) if idx.isValid(): self.highlight_index(idx) else: error_dialog(self, _("No valid plugin path"), _("%s is not a valid plugin path") % path).exec_()
def open_ebook(self, checked): files = choose_files( self, "ebook viewer open dialog", _("Choose ebook"), [(_("Ebooks"), available_input_formats())], all_files=False, select_only_single_file=True, ) if files: self.load_ebook(files[0])
def import_image(self): path = choose_files(self, 'tweak-book-choose-image-for-import', _('Choose image'), filters=[(_('Images'), ('jpg', 'jpeg', 'png', 'gif', 'svg'))], all_files=True, select_only_single_file=True) if path: path = path[0] basename = os.path.basename(path) n, e = basename.rpartition('.')[0::2] basename = n + '.' + e.lower() d = ChooseName(basename, self) if d.exec_() == d.Accepted and d.filename: self.accept() self.chosen_image_is_external = (d.filename, path)
def choose_source(self): from calibre.ebooks.oeb.polish.import_book import IMPORTABLE path = choose_files( self, "edit-book-choose-file-to-import", _("Choose file"), filters=[(_("Importable files"), list(IMPORTABLE))], select_only_single_file=True, ) if path: self.set_src(path[0])
def import_file(self): path = choose_files(self, 'tweak-book-new-resource-file', _('Choose file'), select_only_single_file=True) if path: path = path[0] with open(path, 'rb') as f: self.file_data = f.read() name = os.path.basename(path) fmap = get_recommended_folders(current_container(), (name,)) if fmap[name]: name = '/'.join((fmap[name], name)) self.name.setText(name) self.la.setText(_('Choose a name for the imported file'))
def choose_manually(filetype, parent): ans = choose_files( parent, 'choose-open-with-program-manually-win', _('Choose a program to open %s files') % filetype.upper(), filters=[(_('Executable files'), ['exe', 'bat', 'com'])], select_only_single_file=True) if ans: ans = os.path.abspath(ans[0]) if not os.access(ans, os.X_OK): return error_dialog(parent, _('Cannot execute'), _( 'The program %s is not an executable file') % ans, show=True) qans = ans.replace('"', r'\"') name = friendly_app_name(exe=ans) or os.path.splitext(os.path.basename(ans))[0] return {'cmdline':'"%s" "%%1"' % qans, 'name':name, 'icon_resource':ans + ',0'}
def choose_manually(filetype, parent): ans = choose_files( parent, 'choose-open-with-program-manually-win', _('Choose a program to open %s files') % filetype.upper(), filters=[(_('Executable files'), ['exe', 'bat', 'com', 'cmd'])], select_only_single_file=True) if ans: ans = os.path.abspath(ans[0]) if not os.access(ans, os.X_OK): error_dialog(parent, _('Cannot execute'), _('The program %s is not an executable file') % ans, show=True) return qans = ans.replace('"', r'\"') name = friendly_app_name(exe=ans) or os.path.splitext( os.path.basename(ans))[0] return { 'cmdline': '"%s" "%%1"' % qans, 'name': name, 'icon_resource': ans + ',0' }
def migrate_files(self): dynamic[PLUGIN_NAME + u"config_dir"] = config_dir files = choose_files( self, PLUGIN_NAME + u"config_dir", u"Select {0} files to import".format(self.key_type_name), [(u"{0} files".format(self.key_type_name), [self.keyfile_ext])], False) counter = 0 skipped = 0 if files: for filename in files: fpath = os.path.join(config_dir, filename) filename = os.path.basename(filename) new_key_name = os.path.splitext(os.path.basename(filename))[0] with open(fpath, 'rb') as keyfile: new_key_value = keyfile.read() if self.binary_file: new_key_value = new_key_value.encode('hex') elif self.json_file: new_key_value = json.loads(new_key_value) match = False for key in self.plugin_keys.keys(): if uStrCmp(new_key_name, key, True): skipped += 1 msg = u"A key with the name <strong>{0}</strong> already exists!\nSkipping key file <strong>{1}</strong>.\nRename the existing key and import again".format( new_key_name, filename) inf = info_dialog(None, "{0} {1}".format( PLUGIN_NAME, PLUGIN_VERSION), _(msg), show_copy_button=False, show=True) match = True break if not match: if new_key_value in self.plugin_keys.values(): old_key_name = [ name for name, value in self.plugin_keys.iteritems() if value == new_key_value ][0] skipped += 1 info_dialog( None, "{0} {1}".format(PLUGIN_NAME, PLUGIN_VERSION), u"The key in file {0} is the same as the existing key <strong>{1}</strong> and has been skipped." .format(filename, old_key_name), show_copy_button=False, show=True) else: counter += 1 self.plugin_keys[new_key_name] = new_key_value msg = u"" if counter + skipped > 1: if counter > 0: msg += u"Imported <strong>{0:d}</strong> key {1}. ".format( counter, u"file" if counter == 1 else u"files") if skipped > 0: msg += u"Skipped <strong>{0:d}</strong> key {1}.".format( skipped, u"file" if counter == 1 else u"files") inf = info_dialog(None, "{0} {1}".format(PLUGIN_NAME, PLUGIN_VERSION), _(msg), show_copy_button=False, show=True) return counter > 0
def add_format(self, *args): files = choose_files( self, 'add formats dialog', _("Choose formats for ") + self.dialog.title.current_val, [(_('Books'), BOOK_EXTENSIONS)]) self._add_formats(files)
def filebrowse_button_clicked(self): filenames = choose_files(self, 'Exec Macro: load macro', _('Load macro'), select_only_single_file=True, default_dir=self.macrofile.text()) if filenames: self.macrofile.setText(filenames[0]) return filenames[0]
def cf(): files = choose_files(d, 'select link file', _('Choose file'), select_only_single_file=True) if files: d.url.setText(files[0])
def context_menu_handler(self, action=None, category=None, key=None, index=None, search_state=None, use_vl=None, is_first_letter=False): if not action: return try: if action == 'set_icon': try: path = choose_files(self, 'choose_category_icon', _('Change icon for: %s')%key, filters=[ ('Images', ['png', 'gif', 'jpg', 'jpeg'])], all_files=False, select_only_single_file=True) if path: path = path[0] p = QIcon(path).pixmap(QSize(128, 128)) d = os.path.join(config_dir, 'tb_icons') if not os.path.exists(d): os.makedirs(d) with open(os.path.join(d, 'icon_' + sanitize_file_name(key)+'.png'), 'wb') as f: f.write(pixmap_to_data(p, format='PNG')) path = os.path.basename(f.name) self._model.set_custom_category_icon(key, unicode_type(path)) self.recount() except: import traceback traceback.print_exc() return if action == 'clear_icon': self._model.set_custom_category_icon(key, None) self.recount() return def set_completion_data(category): try: completion_data = self.db.new_api.all_field_names(category) except: completion_data = None self.itemDelegate().set_completion_data(completion_data) if action == 'edit_item_no_vl': item = self.model().get_node(index) item.use_vl = False set_completion_data(category) self.edit(index) return if action == 'edit_item_in_vl': item = self.model().get_node(index) item.use_vl = True set_completion_data(category) self.edit(index) return if action == 'delete_item_in_vl': tag = index.tag children = index.child_tags() self.tag_item_delete.emit(key, tag.id, tag.original_name, self.model().get_book_ids_to_use(), children) return if action == 'delete_item_no_vl': tag = index.tag children = index.child_tags() self.tag_item_delete.emit(key, tag.id, tag.original_name, None, children) return if action == 'open_editor': self.tags_list_edit.emit(category, key, is_first_letter) return if action == 'manage_categories': self.edit_user_category.emit(category) return if action == 'search': self._toggle(index, set_to=search_state) return if action == "raw_search": from calibre.gui2.ui import get_gui get_gui().get_saved_search_text(search_name='search:' + key) return if action == 'add_to_category': tag = index.tag if len(index.children) > 0: for c in index.all_children(): self.add_item_to_user_cat.emit(category, c.tag.original_name, c.tag.category) self.add_item_to_user_cat.emit(category, tag.original_name, tag.category) return if action == 'add_subcategory': self.add_subcategory.emit(key) return if action == 'search_category': self._toggle(index, set_to=search_state) return if action == 'delete_user_category': self.delete_user_category.emit(key) return if action == 'delete_search': self.model().db.saved_search_delete(key) self.rebuild_saved_searches.emit() return if action == 'delete_item_from_user_category': tag = index.tag if len(index.children) > 0: for c in index.children: self.del_item_from_user_cat.emit(key, c.tag.original_name, c.tag.category) self.del_item_from_user_cat.emit(key, tag.original_name, tag.category) return if action == 'manage_searches': self.saved_search_edit.emit(category) return if action == 'edit_authors': self.author_sort_edit.emit(self, index, False, False, is_first_letter) return if action == 'edit_author_sort': self.author_sort_edit.emit(self, index, True, False, is_first_letter) return if action == 'edit_author_link': self.author_sort_edit.emit(self, index, False, True, False) return reset_filter_categories = True if action == 'hide': self.hidden_categories.add(category) elif action == 'show': self.hidden_categories.discard(category) elif action == 'categorization': changed = self.collapse_model != category self._model.collapse_model = category if changed: reset_filter_categories = False gprefs['tags_browser_partition_method'] = category elif action == 'defaults': self.hidden_categories.clear() elif action == 'add_tag': item = self.model().get_node(index) if item is not None: self.apply_to_selected_books(item) return elif action == 'remove_tag': item = self.model().get_node(index) if item is not None: self.apply_to_selected_books(item, True) return self.db.new_api.set_pref('tag_browser_hidden_categories', list(self.hidden_categories)) if reset_filter_categories: self._model.set_categories_filter(None) self._model.rebuild_node_tree() except Exception: import traceback traceback.print_exc() return
def open_clicked(self): files = choose_files(self, 'regexp tester dialog', _('Open book'), select_only_single_file=True) if files: self.open_book(files[0])
def context_menu_handler(self, action=None, category=None, key=None, index=None, search_state=None): if not action: return try: if action == 'set_icon': try: path = choose_files(self, 'choose_category_icon', _('Change Icon for: %s') % key, filters=[ ('Images', ['png', 'gif', 'jpg', 'jpeg']) ], all_files=False, select_only_single_file=True) if path: path = path[0] p = QIcon(path).pixmap(QSize(128, 128)) d = os.path.join(config_dir, 'tb_icons') if not os.path.exists(d): os.makedirs(d) with open( os.path.join( d, 'icon_' + sanitize_file_name_unicode(key) + '.png'), 'wb') as f: f.write(pixmap_to_data(p, format='PNG')) path = os.path.basename(f.name) self._model.set_custom_category_icon( key, unicode(path)) self.recount() except: import traceback traceback.print_exc() return if action == 'clear_icon': self._model.set_custom_category_icon(key, None) self.recount() return if action == 'edit_item': self.edit(index) return if action == 'delete_item': self.tag_item_delete.emit(key, index.id, index.original_name) return if action == 'open_editor': self.tags_list_edit.emit(category, key) return if action == 'manage_categories': self.edit_user_category.emit(category) return if action == 'search': self._toggle(index, set_to=search_state) return if action == 'add_to_category': tag = index.tag if len(index.children) > 0: for c in index.all_children(): self.add_item_to_user_cat.emit(category, c.tag.original_name, c.tag.category) self.add_item_to_user_cat.emit(category, tag.original_name, tag.category) return if action == 'add_subcategory': self.add_subcategory.emit(key) return if action == 'search_category': self._toggle(index, set_to=search_state) return if action == 'delete_user_category': self.delete_user_category.emit(key) return if action == 'delete_search': saved_searches().delete(key) self.rebuild_saved_searches.emit() return if action == 'delete_item_from_user_category': tag = index.tag if len(index.children) > 0: for c in index.children: self.del_item_from_user_cat.emit( key, c.tag.original_name, c.tag.category) self.del_item_from_user_cat.emit(key, tag.original_name, tag.category) return if action == 'manage_searches': self.saved_search_edit.emit(category) return if action == 'edit_author_sort': self.author_sort_edit.emit(self, index, True, False) return if action == 'edit_author_link': self.author_sort_edit.emit(self, index, False, True) return reset_filter_categories = True if action == 'hide': self.hidden_categories.add(category) elif action == 'show': self.hidden_categories.discard(category) elif action == 'categorization': changed = self.collapse_model != category self._model.collapse_model = category if changed: reset_filter_categories = False gprefs['tags_browser_partition_method'] = category elif action == 'defaults': self.hidden_categories.clear() self.db.prefs.set('tag_browser_hidden_categories', list(self.hidden_categories)) if reset_filter_categories: self._model.set_categories_filter(None) self._model.rebuild_node_tree() except: return
def choose(self): ans = choose_files(self, 'choose_path_srv_opts_' + self.dname, _('Choose a file'), select_only_single_file=True) if ans: self.set(ans[0]) self.text.save_history()
def add_archive(self, single): paths = choose_files( self.gui, 'recursive-archive-add', _('Choose archive file'), filters=[(_('Archives'), ('zip', 'rar'))], all_files=False, select_only_single_file=False) if paths: self.do_add_recursive(paths, single, list_of_archives=True)
def add_formats(self, *args): if self.gui.stack.currentIndex() != 0: return view = self.gui.library_view rows = view.selectionModel().selectedRows() if not rows: return error_dialog(self.gui, _('No books selected'), _('Cannot add files as no books are selected'), show=True) ids = [view.model().id(r) for r in rows] if len(ids) > 1 and not question_dialog( self.gui, _('Are you sure?'), _('Are you sure you want to add the same' ' files to all %d books? If the format' ' already exists for a book, it will be replaced.') % len(ids)): return books = choose_files(self.gui, 'add formats dialog dir', _('Select book files'), filters=get_filters()) if not books: return db = view.model().db if len(ids) == 1: formats = db.formats(ids[0], index_is_id=True) if formats: formats = {x.upper() for x in formats.split(',')} nformats = {f.rpartition('.')[-1].upper() for f in books} override = formats.intersection(nformats) if override: title = db.title(ids[0], index_is_id=True) msg = _( 'The {0} format(s) will be replaced in the book {1}. Are you sure?' ).format(', '.join(override), title) if not confirm(msg, 'confirm_format_override_on_add', title=_('Are you sure?'), parent=self.gui): return fmt_map = { os.path.splitext(fpath)[1][1:].upper(): fpath for fpath in books } for id_ in ids: for fmt, fpath in fmt_map.iteritems(): if fmt: db.add_format_with_hooks(id_, fmt, fpath, index_is_id=True, notify=True) current_idx = self.gui.library_view.currentIndex() if current_idx.isValid(): view.model().current_changed(current_idx, current_idx)
def import_file(self): path = choose_files(self, 'tweak-book-new-resource-file', _('Choose file'), select_only_single_file=True) if path: self.do_import_file(path[0])
def choose_source(self): from calibre.ebooks.oeb.polish.import_book import IMPORTABLE path = choose_files(self, 'edit-book-choose-file-to-import', _('Choose file'), filters=[ (_('Importable files'), list(IMPORTABLE))], select_only_single_file=True) if path: self.set_src(path[0])
def choose_file(self): opml_files = choose_files( self, 'opml-select-dialog', _('Select OPML file'), filters=[(_('OPML files'), ['opml'])], all_files=False, select_only_single_file=True) if opml_files: self.path.setText(opml_files[0])