def word_dialog(self, msg): response = QInputDialog.getText(self.top_level_window(), "Ledger Wallet Authentication", msg, QLineEdit.Password) if not response[1]: self.word = None else: self.word = str(response[0]) self.done.set()
def edit_prefix_list(self): prefixes, ok = QInputDialog.getMultiLineText( self, _('Edit prefixes'), _('Enter prefixes, one on a line. The first prefix becomes the default.'), '\n'.join(list(map(type(u''), gprefs['paste_isbn_prefixes'])))) if ok: gprefs['paste_isbn_prefixes'] = list(filter(None, (x.strip() for x in prefixes.splitlines()))) or gprefs.defaults['paste_isbn_prefixes'] self.update_paste_identifiers_menu()
def addImages(self): self.tweets = [] for tweet in self.listTweets: # Ignore empty tweets if tweet != "": # Ask if add add image message = 'Add an image to the tweet: "' + tweet + '"?' yesNo = QMessageBox.question(self, "Do you want to add an image?", message, QMessageBox.Yes | QMessageBox.No) # Ask the link of the image if yesNo == QMessageBox.Yes: url, ok = QInputDialog.getText(self, "Image URL", "Image URL: ", QLineEdit.Normal, "") self.tweets.append({"tweet": tweet, "image": url}) else: self.tweets.append({"tweet": tweet, "image": ""}) self.publish()
def anchor_clicked(self, qurl): url = qurl.toString() if url.startswith('err:'): errnum = int(url[4:]) err = self.errors[errnum] newurl, ok = QInputDialog.getText(self, _('Fix URL'), _('Enter the corrected URL:') + '\xa0' * 40, text=err[2]) if not ok: return nmap = defaultdict(set) for name, href in {(l[0], l[1]) for l in err[0]}: nmap[name].add(href) for name, hrefs in iteritems(nmap): raw = oraw = get_data(name) for href in hrefs: raw = raw.replace(href, newurl) if raw != oraw: set_data(name, raw) self.fixed_errors.add(errnum) self.populate_results() elif url.startswith('loc:'): lnum, name = url[4:].partition(',')[::2] lnum = int(lnum or 1) editor = get_boss().edit_file(name) if lnum and editor is not None and editor.has_line_numbers: editor.current_line = lnum
def save_ruleset(self): if not self.rules: error_dialog(self, _('No rules'), _('Cannot save as no rules have been created'), show=True) return text, ok = QInputDialog.getText(self, _('Save ruleset as'), _('Enter a name for this ruleset:'), text=self.loaded_ruleset or '') if ok and text: if self.loaded_ruleset and text == self.loaded_ruleset: if not question_dialog( self, _('Are you sure?'), _('A ruleset with the name "%s" already exists, do you want to replace it?' ) % text): return self.loaded_ruleset = text rules = self.rules if rules: self.PREFS_OBJECT[text] = self.rules elif text in self.PREFS_OBJECT: del self.PREFS_OBJECT[text] self.build_load_menu()
def getNome(self): msg, ok = QInputDialog.getText(self, 'Bem Vindo!', 'Olá, qual é seu nome?') if ok: script = ( "Meu nome é Judite, e eu irei lhe auxiliar em sua viagem analisando seu estado físico e mental" + "para evitar qualquer desatenção durante o percurso...") if (self.horario.currentTime() > QTime(5, 59) and self.horario.currentTime() < QTime(12, 0)): tts = gTTS(text='Olá, bom dia ' + msg + "." + script, lang='pt') tts.save("Mensagens Faladas\\boas-vindas.mp3") return msg elif (self.horario.currentTime() > QTime(11, 59) and self.horario.currentTime() < QTime(18, 0)): tts = gTTS(text='Olá, boa tarde ' + msg + "." + script, lang='pt') tts.save("Mensagens Faladas\\boas-vindas.mp3") return msg else: tts = gTTS(text='Olá, boa noite ' + msg + "." + script, lang='pt') tts.save("Mensagens Faladas\\boas-vindas.mp3") return msg
def rename_genre(self): selected_genre = self.edit_table.get_selected_genre() if not selected_genre: return new_genre_name, ok = QInputDialog.getText( self, 'Add new mapping', 'Enter a Goodreads genre name to create a mapping for:', text=selected_genre) if not ok: # Operation cancelled return new_genre_name = unicode(new_genre_name).strip() if not new_genre_name or new_genre_name == selected_genre: return data = self.edit_table.get_data() if new_genre_name.lower() != selected_genre.lower(): # Verify it does not clash with any other mappings in the list for genre_name in data.keys(): if genre_name.lower() == new_genre_name.lower(): return error_dialog( self, 'Rename Failed', 'A genre with the same name already exists', show=True) data[new_genre_name] = data[selected_genre] del data[selected_genre] self.edit_table.populate_table(data) self.edit_table.select_genre(new_genre_name)
def __init__(self,game): super().__init__() self.setCentralWidget(QtWidgets.QWidget()) # QMainWindown must have a centralWidget to be able to add layouts self.horizontal = QtWidgets.QHBoxLayout() # Horizontal main layout self.centralWidget().setLayout(self.horizontal) self.btn1 = QPushButton("New wave",self) self.btn1.move(660,600) self.btn1.clicked.connect(self.activateWave) items = ("level1", "level2", "level3", "level4","level5") item, ok = QInputDialog.getItem(self, "Select level","levels", items, 0, False) self.game = game self.game.loadMap(item) #self.start.addButton(QAbstractButton, QMessageBox_ButtonRole) self.map = game.map.map self.initWindow() self.loadTextures() self.drawMap() self.drawHp() self.squares() self.placeButtons() self.drawPlayerStats() self.drawTowerPrices() self.updateGame() self.placeTower = 0 # 0 for not active, 1 for arrow, 2 for gun and 3 for laser self.timer = QtCore.QTimer() self.timer.start(50) # Milliseconds self.timer.timeout.connect(self.updateGame)
def create_new_bookmark(self, pos_data): base_default_title = _('Bookmark') all_titles = {bm['title'] for bm in self.get_bookmarks()} c = 0 while True: c += 1 default_title = '{} #{}'.format(base_default_title, c) if default_title not in all_titles: break title, ok = QInputDialog.getText(self, _('Add bookmark'), _('Enter title for bookmark:'), text=pos_data.get('selected_text') or default_title) title = unicode_type(title).strip() if not ok or not title: return title = self.uniqify_bookmark_title(title) bm = { 'title': title, 'pos_type': 'epubcfi', 'pos': pos_data['cfi'], 'timestamp': utcnow() } bookmarks = self.get_bookmarks() bookmarks.append(bm) self.set_bookmarks(bookmarks) self.set_current_bookmark(bm) self.edited.emit(bookmarks)
def anchor_clicked(self, qurl): url = qurl.toString() if url.startswith('err:'): errnum = int(url[4:]) err = self.errors[errnum] newurl, ok = QInputDialog.getText(self, _('Fix URL'), _('Enter the corrected URL:') + '\xa0'*40, text=err[2]) if not ok: return nmap = defaultdict(set) for name, href in {(l[0], l[1]) for l in err[0]}: nmap[name].add(href) for name, hrefs in nmap.iteritems(): raw = oraw = get_data(name) for href in hrefs: raw = raw.replace(href, newurl) if raw != oraw: set_data(name, raw) self.fixed_errors.add(errnum) self.populate_results() elif url.startswith('loc:'): lnum, name = url[4:].partition(',')[::2] lnum = int(lnum or 1) editor = get_boss().edit_file(name) if lnum and editor is not None and editor.has_line_numbers: editor.current_line = lnum
def ask_user(self): # Ask the user for a factor by which to multiply all font sizes factor, ok = QInputDialog.getDouble( self.gui, 'Enter a magnification factor', 'Allow font sizes in the book will be multiplied by the specified factor', value=2, min=0.1, max=4 ) if ok: # Ensure any in progress editing the user is doing is present in the container self.boss.commit_all_editors_to_container() try: self.magnify_fonts(factor) except Exception: # Something bad happened report the error to the user import traceback error_dialog(self.gui, _('Failed to magnify fonts'), _( 'Failed to magnify fonts, click "Show details" for more info'), det_msg=traceback.format_exc(), show=True) # Revert to the saved restore point self.boss.revert_requested(self.boss.global_undo.previous_container) else: # Show the user what changes we have made, allowing her to # revert them if necessary self.boss.show_current_diff() # Update the editor UI to take into account all the changes we # have made self.boss.apply_container_update_to_gui()
def getNome(self): msg, ok = QInputDialog.getText(self, 'Bem Vindo!', 'Ola, qual eh seu nome?') if ok: script = ( "Meu nome eh Judite, e eu irei lhe auxiliar em sua viagem analisando seu estado fisico e mental" + "para evitar qualquer desatenção durante o percurso...")
def add_insert_tag(self): name, ok = QInputDialog.getText(self, _('Name of tag to add'), _('Enter the name of the tag')) if ok: mru = tprefs['insert_tag_mru'] mru.insert(0, name) tprefs['insert_tag_mru'] = mru self._build_insert_tag_button_menu()
def change_dictionary_website(self): idx = self.dictionary_list.currentIndex() if idx.isValid(): lc, url = idx.data(Qt.UserRole) url, ok = QInputDialog.getText(self, _('Enter new website'), 'URL:', text=url) if ok: wl = self.word_lookups wl[lc] = url self.word_lookups = wl
def change(self): while True: newpas, ok = QInputDialog.getText(self, "输入新密码", "输入新密码\n\n请输入:", QLineEdit.Password) newpas1, ok = QInputDialog.getText(self, "重复输入", "重复输入\n\n请输入:", QLineEdit.Password) if newpas == newpas1: bool = ch.change(self.acc, newpas) break pass else: QMessageBox.information(self, "错误", "密码不同", QMessageBox.Yes) if (bool): QMessageBox.information(self, '提示', '修改成功', QMessageBox.Yes) pass else: QMessageBox.information(self, '提示', '错误,请重试', QMessageBox.Yes) pass
def create_folder(self, item): text, ok = QInputDialog.getText(self, _('Folder name'), _('Enter a name for the new folder')) if ok and unicode_type(text): c = QTreeWidgetItem(item, (unicode_type(text),)) c.setIcon(0, QIcon(I('mimetypes/dir.png'))) for item in self.folders.selectedItems(): item.setSelected(False) c.setSelected(True) self.folders.setCurrentItem(c)
def rename_requested(self, name, location): LibraryDatabase = db_class() loc = location.replace('/', os.sep) base = os.path.dirname(loc) old_name = name.replace('&&', '&') newname, ok = QInputDialog.getText( self.gui, _('Rename') + ' ' + old_name, '<p>' + _('Choose a new name for the library <b>%s</b>. ') % name + '<p>' + _('Note that the actual library folder will be renamed.'), text=old_name) newname = sanitize_file_name(unicode_type(newname)) if not ok or not newname or newname == old_name: return newloc = os.path.join(base, newname) if os.path.exists(newloc): return error_dialog( self.gui, _('Already exists'), _('The folder %s already exists. Delete it first.') % newloc, show=True) if (iswindows and len(newloc) > LibraryDatabase.WINDOWS_LIBRARY_PATH_LIMIT): return error_dialog(self.gui, _('Too long'), _('Path to library too long. Must be less than' ' %d characters.') % LibraryDatabase.WINDOWS_LIBRARY_PATH_LIMIT, show=True) if not os.path.exists(loc): error_dialog( self.gui, _('Not found'), _('Cannot rename as no library was found at %s. ' 'Try switching to this library first, then switch back ' 'and retry the renaming.') % loc, show=True) return self.gui.library_broker.remove_library(loc) try: os.rename(loc, newloc) except: import traceback det_msg = 'Location: %r New Location: %r\n%s' % ( loc, newloc, traceback.format_exc()) error_dialog( self.gui, _('Rename failed'), _('Failed to rename the library at %s. ' 'The most common cause for this is if one of the files' ' in the library is open in another program.') % loc, det_msg=det_msg, show=True) return self.stats.rename(location, newloc) self.build_menus() self.gui.iactions['Copy To Library'].build_menus()
def change_dictionary_website(self): idx = self.dictionary_list.currentIndex() if idx.isValid(): lc, url = idx.data(Qt.UserRole) url, ok = QInputDialog.getText(self, _("Enter new website"), "URL:", text=url) if ok: wl = self.word_lookups wl[lc] = url self.word_lookups = wl
def add_view(self): # Display a prompt allowing user to specify a new view new_view_name, ok = QInputDialog.getText( self, 'Add new view', 'Enter a unique display name for this view:', text='Default') if not ok: # Operation cancelled return new_view_name = unicode(new_view_name).strip() # Verify it does not clash with any other views in the list for view_name in self.views.keys(): if view_name.lower() == new_view_name.lower(): return error_dialog(self, 'Add Failed', 'A view with the same name already exists', show=True) self.persist_view_config() view_info = get_empty_view() if self.view_name != None: # We will copy values from the currently selected view old_view_info = self.views[self.view_name] view_info[KEY_COLUMNS] = copy.deepcopy(old_view_info[KEY_COLUMNS]) view_info[KEY_APPLY_PIN_COLUMNS] = copy.deepcopy( old_view_info.get(KEY_APPLY_PIN_COLUMNS, False)) view_info[KEY_PIN_COLUMNS] = copy.deepcopy( old_view_info.get(KEY_PIN_COLUMNS, {})) view_info[KEY_SORT] = copy.deepcopy(old_view_info[KEY_SORT]) view_info[KEY_APPLY_RESTRICTION] = copy.deepcopy( old_view_info[KEY_APPLY_RESTRICTION]) view_info[KEY_RESTRICTION] = copy.deepcopy( old_view_info[KEY_RESTRICTION]) view_info[KEY_APPLY_SEARCH] = copy.deepcopy( old_view_info[KEY_APPLY_SEARCH]) view_info[KEY_SEARCH] = copy.deepcopy(old_view_info[KEY_SEARCH]) view_info[KEY_APPLY_VIRTLIB] = copy.deepcopy( old_view_info.get(KEY_APPLY_VIRTLIB, False)) view_info[KEY_VIRTLIB] = copy.deepcopy( old_view_info.get(KEY_VIRTLIB, '')) view_info[KEY_JUMP_TO_TOP] = copy.deepcopy( old_view_info[KEY_JUMP_TO_TOP]) else: # We will copy values from the current library view view_info[KEY_COLUMNS] = self.get_current_columns( visible_only=True) self.view_name = new_view_name self.views[new_view_name] = view_info # Now update the views combobox self.select_view_combo.populate_combo(self.views, new_view_name) self.select_view_combo_index_changed(save_previous=False) self.auto_view_combo.populate_combo( self.views, unicode(self.auto_view_combo.currentText()))
def create_master(self): name, ok_pressed = QInputDialog.getText(self, 'Новая мастер-вкладка', 'Название новой вкладки:') if ok_pressed: new_id = int( self.cur.execute("SELECT id FROM max_master").fetchall()[0] [0]) + 1 new_tag_id = int( self.cur.execute("SELECT id FROM max_id").fetchall()[0][0]) + 1 self.cur.execute("UPDATE max_master SET id=?", (new_id, )) self.cur.execute("UPDATE max_id SET id=?", (new_tag_id, )) self.con.commit() new_tag = Tag('google.com', new_tag_id) self.master_tags.append(Master_Tag(name, [new_tag], new_id)) self.gridLayout.addWidget(new_tag, 1, 0, 1, 2) new_tag.hide() not_deleted_num = sum( [0 if i.is_deleted else 1 for i in self.master_tags]) # print(self.master_tags[-1]) self.gridLayout.addWidget(self.master_tags[-1], 0, 2 * (not_deleted_num - 1), 1, 2) # self.master_tags[len(self.master_tags) - 1].show() self.master_tags[len(self.master_tags) - 1].tag_body.pressed.connect(self.change_master) self.master_tags[len(self.master_tags) - 1].del_btn.pressed.connect(self.delete_master) self.master_tags[len(self.master_tags) - 1].tag_body.index = len(self.master_tags) - 1 self.master_tags[len(self.master_tags) - 1].del_btn.index = len(self.master_tags) - 1 # print('hello') # print(new_tag_id, new_id) # print(self.cur.execute("SELECT * FROM Tags WHERE id=?", (new_tag_id, )).fetchall()) self.cur.execute("INSERT INTO Tags VALUES (?, 'google.com', 0)", (new_tag_id, )) # print('tags ready') self.cur.execute("INSERT INTO Masters VALUES (?, ?, 0, ?)", (new_id, name, str(new_tag_id))) self.current_master_index = not_deleted_num - 1 self.current_tag_index = 0 self.add_master_btn.hide() if not_deleted_num < self.max_tag_count: self.add_master_btn = QPushButton('+') self.add_master_btn.pressed.connect(self.create_master) self.gridLayout.addWidget(self.add_master_btn, 0, (not_deleted_num - 1) * 2, 1, 1) self.add_master_btn.show() self.con.commit() self.hide_all_master() self.show_current_master_tags() self.hide_all_tags() self.show_current_tags() self.update_web()
def add_list(self): # 新增右侧数据 text, okPressed = QInputDialog.getText(self, "新增", "请输入内容", QLineEdit.Normal, "") if okPressed and text != '': r = self.listWidget.currentRow() if r == -1: # 如果没有选中右侧的条目,则在第一行新增 self.listWidget.insertItem(0, text) self.listWidget.setCurrentRow(0) else: # 如果选中了右侧的条目,则在选中的条目下方新增 self.listWidget.insertItem(r + 1, text) self.listWidget.setCurrentRow(r + 1) # 选中新增的行
def s_r_save_query(self, *args): names = [''] names.extend(self.query_field_values) try: dex = names.index(self.saved_search_name) except: dex = 0 name = '' while not name: name, ok = QInputDialog.getItem(self, _('Save search/replace'), _('Search/replace name:'), names, dex, True) if not ok: return if not name: error_dialog(self, _("Save search/replace"), _("You must provide a name."), show=True) new = True name = unicode(name) if name in self.queries.keys(): if not question_dialog(self, _("Save search/replace"), _("That saved search/replace already exists and will be overwritten. " "Are you sure?")): return new = False query = {} query['name'] = name query['search_field'] = unicode(self.search_field.currentText()) query['search_mode'] = unicode(self.search_mode.currentText()) query['s_r_template'] = unicode(self.s_r_template.text()) query['s_r_src_ident'] = unicode(self.s_r_src_ident.currentText()) query['search_for'] = unicode(self.search_for.text()) query['case_sensitive'] = self.case_sensitive.isChecked() query['replace_with'] = unicode(self.replace_with.text()) query['replace_func'] = unicode(self.replace_func.currentText()) query['destination_field'] = unicode(self.destination_field.currentText()) query['s_r_dst_ident'] = unicode(self.s_r_dst_ident.text()) query['replace_mode'] = unicode(self.replace_mode.currentText()) query['comma_separated'] = self.comma_separated.isChecked() query['results_count'] = self.results_count.value() query['starting_from'] = self.starting_from.value() query['multiple_separator'] = unicode(self.multiple_separator.text()) self.queries[name] = query self.queries.commit() if new: self.query_field.blockSignals(True) self.query_field.clear() 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.blockSignals(False) self.query_field.setCurrentIndex(self.query_field.findText(name))
def sharpen_image(self): val, ok = QInputDialog.getInt( self, _('Sharpen image'), _('The standard deviation for the Gaussian sharpen operation (higher means more sharpening)' ), value=3, min=1, max=20) if ok: self.canvas.sharpen_image(sigma=val)
def blur_image(self): val, ok = QInputDialog.getInt( self, _('Blur image'), _('The standard deviation for the Gaussian blur operation (higher means more blurring)' ), value=3, min=1, max=20) if ok: self.canvas.blur_image(sigma=val)
def oilify_image(self): val, ok = QInputDialog.getDouble( self, _('Oilify image'), _('The strength of the operation (higher numbers have larger effects)' ), value=4, min=0.1, max=20) if ok: self.canvas.oilify_image(radius=val)
def on_createConfig_clicked(self): current_text, _ = QInputDialog.getText( self, "Config Name", "Please input config name:", QLineEdit.Normal, self.ui.configList.currentItem().text()) if len(current_text) == 0: return current_text = self.update_config_name(current_text) self.create_data_generator(current_text) self.generator_name_to_inputs = self._update_generator_name_to_inputs( self.generator_name_to_inputs) self.update_item_status()
def init_logic(self): logger.info(f"初始化逻辑数据") self.loop_index = 1 self.invalid_cell_count = 0 # 先手为蓝 self.step_cell = cell_blue # ai托管,默认不托管 self.ai_cells = {} self.ai_to_avg_stat = {} # type: Dict[int, AvgStat] self.ai_moving = False self.game_start_time = datetime.now() self.game_restarted = False self.ai_dfs_max_depth = 4 self.ai_min_decision_seconds = 0.5 self.ai_max_decision_time = timedelta(seconds=26) blue_set_ai = True red_set_ai = True self.ai_dfs_max_depth, _ = QInputDialog.getInt(self, "ai参数设置", f"ai最大搜索层数(越大越强,速度越慢,默认为{self.ai_dfs_max_depth})", self.ai_dfs_max_depth) self.ai_min_decision_seconds, _ = QInputDialog.getDouble(self, "ai参数设置", f"ai每步最小等待时间(秒)(太小可能会看不清手动方的落子位置-。-)", self.ai_min_decision_seconds) ai_max_decision_time, _ = QInputDialog.getDouble(self, "ai参数设置", f"ai每步最大等待时间(秒)(避免超出30秒)", self.ai_max_decision_time.total_seconds()) self.ai_max_decision_time = timedelta(seconds=ai_max_decision_time) blue_set_ai = QMessageBox.question(self, "AI配置", "蓝方是否启用AI?") == QMessageBox.Yes red_set_ai = QMessageBox.question(self, "AI配置", "红方是否启用AI?") == QMessageBox.Yes if blue_set_ai: self.set_ai(cell_blue, self.ai_min_max) if red_set_ai: self.set_ai(cell_red, self.ai_min_max) logger.info(f"ai最大迭代次数为{self.ai_dfs_max_depth},每次操作至少{self.ai_min_decision_seconds}秒,最大等待时间为{self.ai_max_decision_time}秒") self.last_step = (1, 1) self.init_board_without_invalid_cells()
def request_change_ext(self): names = self.request_rename_common() if names is not None: text, ok = QInputDialog.getText(self, _('Rename files'), _('New file extension:')) if ok and text: ext = text.lstrip('.') def change_name(name): base = posixpath.splitext(name)[0] return base + '.' + ext name_map = {n:change_name(n) for n in names} self.bulk_rename_requested.emit(name_map)
def change_name(self): ci = self.plist.currentItem() if ci is None: return error_dialog(self, _('No selection'), _( 'No application selected'), show=True) name, ok = QInputDialog.getText(self, _('Enter new name'), _('New name for {}').format(ci.data(Qt.DisplayRole))) if ok and name: entry = ci.data(ENTRY_ROLE) change_name_in_entry(entry, name) ci.setData(ENTRY_ROLE, entry) self.update_stored_config() ci.setData(Qt.DisplayRole, name)
def changeKeys(self): # Consumer key ok = False while not ok: consumerKey, ok = QInputDialog.getText(self, "CONSUMER KEY", "Consumer key: ", QLineEdit.Normal, "") # Consumer secret ok = False while not ok: consumerSecret, ok = QInputDialog.getText(self, "CONSUMER SECRET", "Consumer secret: ", QLineEdit.Normal, "") # Access token ok = False while not ok: accessToken, ok = QInputDialog.getText(self, "ACCESS TOKEN", "Access token: ", QLineEdit.Normal, "") # Access token secret ok = False while not ok: accessTokenSecret, ok = QInputDialog.getText(self, "ACCESS TOKEN SECRET", "Access token secret: ", QLineEdit.Normal, "") keys = { "consumer_key": consumerKey, "consumer_secret": consumerSecret, "access_token": accessToken, "access_token_secret": accessTokenSecret } json.dump(keys, open("keys.json", "w")) return keys
def editar_tratamientos(self): item_editar = self.ui.lst_tratamientos.currentRow( ) #selecciona el elemento de la fila seleccionada #da 2 variables, una para el texo que se ponga y otra para crear un input texto, resultado = QInputDialog.getText(self, "Ingresar", "Ingresar nuevo tratamiento ") if resultado == True and (len(texto) != 0): self.ui.lst_tratamientos.takeItem(item_editar) #quita ese item self.ui.lst_tratamientos.insertItem( item_editar, QListWidgetItem(texto)) #añade nuevo item en esa fila
def save_theme(self): themename, ok = QInputDialog.getText(self, _("Theme name"), _("Choose a name for this theme")) if not ok: return themename = unicode(themename).strip() if not themename: return c = config("") c.add_opt("theme_name_xxx", default=themename) self.save_options(c) self.themes["theme_" + themename] = c.src self.init_load_themes() self.theming_message.setText(_("Saved settings as the theme named: %s") % themename)
def save_theme(self): themename, ok = QInputDialog.getText(self, _('Theme name'), _('Choose a name for this theme')) if not ok: return themename = unicode(themename).strip() if not themename: return c = config('') c.add_opt('theme_name_xxx', default=themename) self.save_options(c) self.themes['theme_'+themename] = c.src self.init_load_themes() self.theming_message.setText(_('Saved settings as the theme named: %s')% themename)
def show_dialog(self): # Ask the user for a URL url, ok = QInputDialog.getText(self.gui, 'Enter a URL', 'Enter a URL to browse below', text='https://calibre-ebook.com') if not ok or not url: return # Launch a separate process to view the URL in WebEngine self.gui.job_manager.launch_gui_app( 'webengine-dialog', kwargs={ 'module': 'calibre_plugins.webengine_demo.main', 'url': url })
def save_settings(self): if not self.something_selected: return error_dialog(self, _('No actions selected'), _('You must select at least one action before saving'), show=True) name, ok = QInputDialog.getText(self, _('Choose name'), _('Choose a name for these settings')) if ok: name = unicode_type(name).strip() if name: settings = {ac:getattr(self, 'opt_'+ac).isChecked() for ac in self.all_actions} saved = gprefs.get('polish_settings', {}) saved[name] = settings gprefs.set('polish_settings', saved) self.setup_load_button()
def save_settings(self): xpaths = self.xpaths if not xpaths: return error_dialog(self, _('No XPaths'), _('No XPaths have been entered'), show=True) if not self.check(): return name, ok = QInputDialog.getText(self, _('Choose name'), _('Choose a name for these settings')) if ok: name = unicode(name).strip() if name: saved = gprefs.get('xpath_toc_settings', {}) saved[name] = {i:x for i, x in enumerate(xpaths)} gprefs.set('xpath_toc_settings', saved) self.setup_load_button()
def add_mapping(self): new_genre_name, ok = QInputDialog.getText(self, 'Add new mapping', 'Enter a Goodreads genre name to create a mapping for:', text='') if not ok: # Operation cancelled return new_genre_name = unicode(new_genre_name).strip() if not new_genre_name: return # Verify it does not clash with any other mappings in the list data = self.edit_table.get_data() for genre_name in data.keys(): if genre_name.lower() == new_genre_name.lower(): return error_dialog(self, 'Add Failed', 'A genre with the same name already exists', show=True) data[new_genre_name] = [] self.edit_table.populate_table(data) self.edit_table.select_genre(new_genre_name)
def bookmark(self, *args): num = 1 bm = None while True: bm = _("Bookmark #%d") % num if bm not in self.existing_bookmarks: break num += 1 title, ok = QInputDialog.getText(self, _("Add bookmark"), _("Enter title for bookmark:"), text=bm) title = unicode(title).strip() if ok and title: bm = self.view.bookmark() bm["spine"] = self.current_index bm["title"] = title self.iterator.add_bookmark(bm) self.set_bookmarks(self.iterator.bookmarks) self.bookmarks.set_current_bookmark(bm)
def rename_requested(self, name, location): LibraryDatabase = db_class() loc = location.replace('/', os.sep) base = os.path.dirname(loc) old_name = name.replace('&&', '&') newname, ok = QInputDialog.getText(self.gui, _('Rename') + ' ' + old_name, '<p>'+_( 'Choose a new name for the library <b>%s</b>. ')%name + '<p>'+_( 'Note that the actual library folder will be renamed.'), text=old_name) newname = sanitize_file_name(unicode_type(newname)) if not ok or not newname or newname == old_name: return newloc = os.path.join(base, newname) if os.path.exists(newloc): return error_dialog(self.gui, _('Already exists'), _('The folder %s already exists. Delete it first.') % newloc, show=True) if (iswindows and len(newloc) > LibraryDatabase.WINDOWS_LIBRARY_PATH_LIMIT): return error_dialog(self.gui, _('Too long'), _('Path to library too long. Must be less than' ' %d characters.')%LibraryDatabase.WINDOWS_LIBRARY_PATH_LIMIT, show=True) if not os.path.exists(loc): error_dialog(self.gui, _('Not found'), _('Cannot rename as no library was found at %s. ' 'Try switching to this library first, then switch back ' 'and retry the renaming.')%loc, show=True) return self.gui.library_broker.remove_library(loc) try: os.rename(loc, newloc) except: import traceback det_msg = 'Location: %r New Location: %r\n%s'%(loc, newloc, traceback.format_exc()) error_dialog(self.gui, _('Rename failed'), _('Failed to rename the library at %s. ' 'The most common cause for this is if one of the files' ' in the library is open in another program.') % loc, det_msg=det_msg, show=True) return self.stats.rename(location, newloc) self.build_menus() self.gui.iactions['Copy To Library'].build_menus()
def save_ruleset(self): if not self.rules: error_dialog(self, _('No rules'), _( 'Cannot save as no rules have been created'), show=True) return text, ok = QInputDialog.getText(self, _('Save ruleset as'), _( 'Enter a name for this ruleset:'), text=self.loaded_ruleset or '') if ok and text: if self.loaded_ruleset and text == self.loaded_ruleset: if not question_dialog(self, _('Are you sure?'), _( 'A ruleset with the name "%s" already exists, do you want to replace it?') % text): return self.loaded_ruleset = text rules = self.rules if rules: tag_maps[text] = self.rules elif text in tag_maps: del tag_maps[text] self.build_load_menu()
def oilify_image(self): val, ok = QInputDialog.getDouble(self, _('Oilify image'), _( 'The strength of the operation (higher numbers have larger effects)'), value=4, min=0.1, max=20) if ok: self.canvas.oilify_image(radius=val)
def rename_requested(self, name, location): LibraryDatabase = db_class() loc = location.replace("/", os.sep) base = os.path.dirname(loc) newname, ok = QInputDialog.getText( self.gui, _("Rename") + " " + name, "<p>" + _("Choose a new name for the library <b>%s</b>. ") % name + "<p>" + _("Note that the actual library folder will be renamed."), text=name, ) newname = sanitize_file_name_unicode(unicode(newname)) if not ok or not newname or newname == name: return newloc = os.path.join(base, newname) if os.path.exists(newloc): return error_dialog( self.gui, _("Already exists"), _("The folder %s already exists. Delete it first.") % newloc, show=True ) if iswindows and len(newloc) > LibraryDatabase.WINDOWS_LIBRARY_PATH_LIMIT: return error_dialog( self.gui, _("Too long"), _("Path to library too long. Must be less than" " %d characters.") % LibraryDatabase.WINDOWS_LIBRARY_PATH_LIMIT, show=True, ) if not os.path.exists(loc): error_dialog( self.gui, _("Not found"), _( "Cannot rename as no library was found at %s. " "Try switching to this library first, then switch back " "and retry the renaming." ) % loc, show=True, ) return try: os.rename(loc, newloc) except: import traceback det_msg = "Location: %r New Location: %r\n%s" % (loc, newloc, traceback.format_exc()) error_dialog( self.gui, _("Rename failed"), _( "Failed to rename the library at %s. " "The most common cause for this is if one of the files" " in the library is open in another program." ) % loc, det_msg=det_msg, show=True, ) return self.stats.rename(location, newloc) self.build_menus() self.gui.iactions["Copy To Library"].build_menus()
def delete_sample(self, sample, nr, project, status): """delete a sample from the database & file system """ self.log.debug("Attempting to delete sample '{}' allele {} of project '{}' from database...".format(sample, nr, project)) if self.settings["login"] == "admin": pass else: pwd, ok = QInputDialog.getText(self, "Enter Password", "Please provide password:"******"ichdarfdas": pass else: return else: return self.log.debug("Asking for confirmation before deleting allele...") reply = QMessageBox.question(self, 'Message', "Are you really sure you want to delete sample {} allele #{} from project {}?".format(sample, nr, project), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: # delete from database: delete_q_alleles = "delete from alleles where sample_id_int = '{}' and allele_nr = {} and project_name = '{}'".format(sample, nr, project) success, _ = db_internal.execute_query(delete_q_alleles, 0, self.log, "Deleting sample {} allele #{} from ALLELES table".format(sample, nr), "Sample Deletion Error", self) if success: self.log.debug("\t=> Successfully deleted sample from table ALLELES") more_projects_query = "select project_name from alleles where sample_id_int = '{}'".format(sample) success, data = db_internal.execute_query(more_projects_query, 1, self.log, "Finding more rows with sample {} in ALLELES table".format(sample), "Sample Deletion Error", self) single_allele = False if success: if not data: # sample was only contained in this project and only had one allele single_allele = True delete_q_samples = "delete from SAMPLES where sample_id_int = '{}'".format(sample) success, _ = db_internal.execute_query(delete_q_samples, 0, self.log, "Deleting sample {} from SAMPLES table".format(sample), "Sample Deletion Error", self) if success: self.log.debug("\t=> Successfully deleted sample from table SAMPLES") files_q = "select raw_file, fasta, blast_xml, ena_file, ena_response_file, ipd_submission_file from FILES where sample_id_int = '{}' and allele_nr = {}".format(sample, nr) success, files = db_internal.execute_query(files_q, 6, self.log, "Getting files of sample {} #{} from FILES table".format(sample, nr), "Sample Deletion Error", self) if success: delete_q_files = "delete from FILES where sample_id_int = '{}' and allele_nr = {}".format(sample, nr) success, _ = db_internal.execute_query(delete_q_files, 0, self.log, "Deleting sample {} from FILES table".format(sample), "Sample Deletion Error", self) if success: self.log.debug("\t=> Successfully deleted sample from table FILES") # delete from disk space: self.log.debug("Attempting to delete sample {} allele #{} of project '{}' from file system...".format(sample, nr, project)) sample_dir = os.path.join(self.settings["projects_dir"], project, sample) if files: for myfile in files[0]: if myfile: self.log.debug("\tDeleting {}...".format(myfile)) try: os.remove(os.path.join(sample_dir, myfile)) except Exception: self.log.debug("\t\t=> Could not delete") if single_allele: self.log.debug("\tDeleting sample dir {}...".format(sample_dir)) os.removedirs(sample_dir) self.log.debug("=> Sample {} #{} of project {} successfully deleted from database and file system".format(sample, nr, project)) self.refresh.emit(project) self.changed_projects.emit(project, status)
def blur_image(self): val, ok = QInputDialog.getInt(self, _('Blur image'), _( 'The standard deviation for the Gaussian blur operation (higher means more blurring)'), value=3, min=1, max=20) if ok: self.canvas.blur_image(sigma=val)
def sharpen_image(self): val, ok = QInputDialog.getInt(self, _('Sharpen image'), _( 'The standard deviation for the Gaussian sharpen operation (higher means more sharpening)'), value=3, min=1, max=20) if ok: self.canvas.sharpen_image(sigma=val)