class ThemeChooser(QWidget): """docstring for ThemeChooser.""" themeChanged = pyqtSignal(str) def __init__(self, parent): super(ThemeChooser, self).__init__(parent) self.currentIconTheme = QIcon.themeName() self.label = QLabel(self) self.comboBox = QComboBox(self) self.setLayout(QVBoxLayout(self)) self.label.setText('Available themes :') self.layout().addWidget(self.label) self.layout().addWidget(self.comboBox) self.comboBox.currentTextChanged.connect(self.onThemeChanged) self.populateComboBox() def populateComboBox(self): self.comboBox.clear() for path in QIcon.themeSearchPaths(): for subdir in helpers.listing_subdir(path): if subdir.name != self.currentIconTheme: self.comboBox.addItem(subdir.name) self.comboBox.insertItem(0, self.currentIconTheme) self.comboBox.setCurrentIndex(0) def onThemeChanged(self, themeName): QIcon.setThemeName(themeName) self.themeChanged.emit(themeName) def rollback(self): self.onThemeChanged(self.currentIconTheme) def commit(self): self.currentIconTheme = QIcon.themeName()
def clear_history(self, *args): QComboBox.clear(self)
class App(QWidget): USs = [] # { F# , name , description , Acceptance Criteria } USNames = [] # user stories names TCs = [] # { TC name , TC description } def __init__(self): super().__init__() self.title = 'NLP project.' self.left = 50 self.top = 50 self.width = 1500 self.height = 800 self.initUI() def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) app.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True) # Create Label label = QLabel('Select User Story by name:', self) label.move(50, 0) # Create Label label2 = QLabel('US Description + Acceptance Criteria:', self) label2.move(50, 125) # Create Label label3 = QLabel('Choose Algorithm:', self) label3.move(50, 600) # Create Label label4 = QLabel('Results:', self) label4.move(1000, 50) # Create textbox user story self.textbox = QPlainTextEdit(self) self.textbox.move(50, 175) self.textbox.resize(500, 300) """ # Create textbox results self.textbox3 = QLineEdit(self) self.textbox3.move(1000, 75) self.textbox3.resize(400,600) self.textbox3.setDisabled(True) """ self.tableWidget = QTableWidget() #self.tableWidget.resize(400,600) # Create textbox tokenize self.textbox4 = QLineEdit(self) self.textbox4.move(50, 700) self.textbox4.resize(280, 40) #self.textbox4.setDisabled(True) """ self.scrollArea = QScrollArea(self) self.scrollArea.setWidgetResizable(True) self.scrollArea.move(50,400) self.scrollArea.resize(280,40) self.scrollArea.setWidget(self.textbox4) """ button = QPushButton('Start', self) button.move(150, 750) button.clicked.connect(self.on_click_start) button2 = QPushButton('Tokenize', self) button2.move(50, 625) button2.clicked.connect(self.on_click_tokenize) button3 = QPushButton('Load excel', self) button3.move(50, 750) button3.clicked.connect(self.on_click_load) button4 = QPushButton('Choose US', self) button4.move(550, 29) button4.clicked.connect(self.on_click_choose_US) button5 = QPushButton('Choose AC', self) button5.move(550, 149) button5.clicked.connect(self.on_click_choose_AC) button6 = QPushButton('Clear', self) button6.move(250, 750) button6.clicked.connect(self.on_click_clear) # algorithm combobox self.comboBox = QComboBox(self) algorithms = ['cosine', 'other'] self.comboBox.addItems(algorithms) self.comboBox.move(150, 625) # US combobox self.comboBox2 = QComboBox(self) self.comboBox2.move(50, 25) self.comboBox2.resize(500, 20) #action_relect = lambda: self.on_click_reselect_us(self) self.comboBox2.currentIndexChanged.connect(self.on_click_reselect_us) # AC combobox self.comboBox3 = QComboBox(self) self.comboBox3.move(50, 150) self.comboBox3.resize(500, 20) self.show() @pyqtSlot() def on_click_reselect_us(self): self.textbox.clear() self.comboBox3.clear() @pyqtSlot() def on_click_clear(self): self.textbox.clear() self.textbox3.clear() self.textbox4.clear() self.comboBox.clear() self.comboBox2.clear() self.comboBox3.clear() @pyqtSlot() def on_click_start(self): us = self.textbox2.text() results = [] for tc in self.TCs: tmp = tc[0] + tc[1] results.append({ 'match_sentence': tmp, 'score': compare_sens(us, tmp) }) i = 0 self.tableWidget.setSortingEnabled(True) self.tableWidget.setRowCount(100) self.tableWidget.setColumnCount(2) results = sorted(results, key=itemgetter('score'), reverse=True) for res in results: #self.tableWidget.insertRow(str(res)+str1) #self.tableWidget.setItem(i,0, QTableWidgetItem(str(res[1]))) self.tableWidget.setItem(i, 0, QTableWidgetItem(str(res))) i += 1 #self.textbox3.insert(str(res)+str1 self.tableWidget.move(1000, 75) self.tableWidget.show() @pyqtSlot() def on_click_choose_US(self): # set User Story over textbox so we can edit if needed text = self.comboBox2.currentText() self.textbox.setPlainText(text) self.textbox.show() # fill AC combobox descriptions = [] ACs = [] tmp = [] us = self.comboBox2.currentText() for a, b, c, d in self.USs: if b == us: descriptions.append(c) ACs.append(d) tmp.append(c + d) self.comboBox3.addItems(tmp) @pyqtSlot() def on_click_choose_AC(self): # set AC over textbox so we can edit if needed text = self.comboBox3.currentText() self.textbox.paste() self.textbox.show() @pyqtSlot() def on_click_tokenize(self): text = self.textbox.text() tok = str(tokenize(text)) self.textbox4.setText(tok) @pyqtSlot() def on_click_load(self): # Assign spreadsheet filename to `file` file = self.openFileNameDialog() # Load in the workbook wb = load_workbook(file) # Get sheet names data_sheets_names = wb.sheetnames print(wb.sheetnames) # Get all the sheet names that hold User stories and Test Cases USs_sheets_names = [] TCs_Sheets_names = [] for sheet_name in data_sheets_names: if sheet_name.find("TCs") != -1: TCs_Sheets_names.append(sheet_name) if sheet_name.find(" F") != -1: USs_sheets_names.append(sheet_name) # get NLP data sheets for name in USs_sheets_names: sheet = wb[name] for i in range(2, sheet.max_row + 1): self.USs.append( ((sheet.cell(i, 1).value), (sheet.cell(i, 2).value), (sheet.cell(i, 3).value), (sheet.cell(i, 4).value))) self.USNames.append((sheet.cell(2, 2).value)) for name in TCs_Sheets_names: sheet = wb[name] for i in range(2, sheet.max_row + 1): self.TCs.append( (name, (sheet.cell(i, 1).value), (sheet.cell(i, 2).value))) #remove doubles self.USNames = list(set(self.USNames)) self.comboBox2.addItems(self.USNames) print(self.USNames) def openFileNameDialog(self): options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog fileName, _ = QFileDialog.getOpenFileName( self, "QFileDialog.getOpenFileName()", "", "All Files (*);;Excel Files (*.xlsx)", options=options) if fileName: print(fileName) return fileName
class SourceSelectorDialog(QDialog): def __init__(self, parent, flags=Qt.WindowFlags()): QDialog.__init__(self, parent, flags) self.setModal(False) self.setWindowTitle("Select sources by...") lo = QVBoxLayout(self) lo.setContentsMargins(10, 10, 10, 10) lo.setSpacing(5) # select by lo1 = QHBoxLayout() lo.addLayout(lo1) lo1.setContentsMargins(0, 0, 0, 0) # lab = QLabel("Select:") # lo1.addWidget(lab) self.wselby = QComboBox(self) lo1.addWidget(self.wselby, 0) self.wselby.activated[str].connect(self._setup_selection_by) # under/over self.wgele = QComboBox(self) lo1.addWidget(self.wgele, 0) self.wgele.addItems([">", ">=", "<=", "<", "sum<=", "sum>", "=="]) self.wgele.activated[str].connect(self._select_threshold) # threshold value self.wthreshold = QLineEdit(self) self.wthreshold.editingFinished.connect(self._select_threshold) lo1.addWidget(self.wthreshold, 1) # min and max label self.wminmax = QLabel(self) lo.addWidget(self.wminmax) # selection slider lo1 = QHBoxLayout() lo.addLayout(lo1) self.wpercent = QSlider(self) self.wpercent.setTracking(False) self.wpercent.valueChanged[int].connect(self._select_percentile) self.wpercent.sliderMoved[int].connect( self._select_percentile_threshold) self.wpercent.setRange(0, 100) self.wpercent.setOrientation(Qt.Horizontal) lo1.addWidget(self.wpercent) self.wpercent_lbl = QLabel("0%", self) self.wpercent_lbl.setMinimumWidth(64) lo1.addWidget(self.wpercent_lbl) # # hide button # lo.addSpacing(10) # lo2 = QHBoxLayout() # lo.addLayout(lo2) # lo2.setContentsMargins(0,0,0,0) # hidebtn = QPushButton("Close",self) # hidebtn.setMinimumWidth(128) # QObject.connect(hidebtn,pyqtSignal("clicked()"),self.hide) # lo2.addStretch(1) # lo2.addWidget(hidebtn) # lo2.addStretch(1) # self.setMinimumWidth(384) self._in_select_threshold = False self._sort_index = None self.qerrmsg = QErrorMessage(self) def resetModel(self): """Resets dialog based on current model.""" if not self.model: return # getset of model tags, and remove the non-sorting tags alltags = set(self.model.tagnames) alltags -= NonSortingTags # make list of tags from StandardTags that are present in model self.sorttags = [ tag for tag in StandardTags if tag in alltags or tag in TagAccessors ] # append model tags that were not in StandardTags self.sorttags += list(alltags - set(self.sorttags)) # set selector self.wselby.clear() self.wselby.addItems(self.sorttags) for tag in "Iapp", "I": if tag in self.sorttags: self.wselby.setCurrentIndex(self.sorttags.index(tag)) break self._setup_selection_by(self.wselby.currentText()) def _reset_percentile(self): self.wthreshold.setText("") self.wpercent.setValue(50) self.wpercent_lbl.setText("--%") def _setup_selection_by(self, tag): tag = str(tag) # may be QString # clear threshold value and percentiles self._reset_percentile() # get min/max values, and sort indices # _sort_index will be an array of (value,src,cumsum) tuples, sorted by tag value (high to low), # where src is the source, and cumsum is the sum of all values in the list from 0 up to and including the current one self._sort_index = [] minval = maxval = value = None for isrc, src in enumerate(self.model.sources): try: if hasattr(src, tag): # test if item can be cast to float try: float(getattr(src, tag)) except: continue else: value = float(getattr(src, tag)) elif tag in TagAccessors: value = float(TagAccessors[tag](src)) else: # not existant for this source (maybe a tag or something??) value = np.nan # skip source if failed to access this tag as a float except: traceback.print_exc() continue if value is not None: self._sort_index.append( [value if not np.isnan(value) else -np.inf, src, 0.]) minval = min(minval, value if not np.isnan(value) else np.inf) if minval is not None else value maxval = max(maxval, value if not np.isnan(value) else -np.inf) if maxval is not None else value # add label if minval is None: self._range = None self.wminmax.setText( "<font color=red>'%s' is not a numeric attribute</font>" % tag) for w in self.wgele, self.wthreshold, self.wpercent, self.wpercent_lbl: w.setEnabled(False) else: self._range = (minval, maxval) self.wminmax.setText("min: %g max: %g" % self._range) for w in self.wgele, self.wthreshold, self.wpercent, self.wpercent_lbl: w.setEnabled(True) # sort index by descending values self._sort_index.sort(reverse=True, key=operator.itemgetter(0)) # generate cumulative sums cumsum = 0. for entry in self._sort_index: if not np.isneginf(entry[0]): cumsum += entry[0] entry[2] = cumsum # Maps comparison operators to callables. Used in _select_threshold. # Each callable takes two arguments: e is a tuple of (value,src,cumsum) (see _sort_index above), and x is a threshold # Second argument is a flag: if False, selection is inverted w.r.t. operator Operators = { "<": ((lambda e, x: e[0] >= x), False), "<=": ((lambda e, x: e[0] > x), False), ">": ((lambda e, x: e[0] > x), True), ">=": ((lambda e, x: e[0] >= x), True), "sum<=": ((lambda e, x: e[2] <= x), True), "sum>": ((lambda e, x: e[2] <= x), False), "==": ((lambda e, x: np.abs(e[0] - x) < 1.0e-8), True), } def _select_threshold(self, *dum): dprint(1, "select_threshold", dum) self._in_select_threshold = True busy = BusyIndicator() try: # get threshold, ignore if not set threshold = str(self.wthreshold.text()) if not threshold: self._reset_percentile() return # try to parse threshold, ignore if invalid try: threshold = float(threshold) except: self._reset_percentile() return # get comparison operator op, select = self.Operators[str(self.wgele.currentText())] # apply to initial segment (that matches operator) for num, entry in enumerate(self._sort_index): if not op(entry, threshold): break entry[1].selected = select else: num = len(self._sort_index) # apply to remaining segment for val, src, cumsum in self._sort_index[num:]: src.selected = not select # set percentile percent = round(float(num * 100) / len(self._sort_index)) if not select: percent = 100 - percent self.wpercent.setValue(percent) self.wpercent_lbl.setText("%3d%%" % percent) # emit signal self.model.emitSelection(self) finally: self._in_select_threshold = False busy.reset_cursor() def _select_percentile(self, percent): self._select_percentile_threshold(percent, do_select=True) def _select_percentile_threshold(self, percent, do_select=False): # ignore if no sort index set up, or if _select_threshold() is being called if self._sort_index is None or self._in_select_threshold: return dprint(1, "select_precentile_threshold", percent) busy = BusyIndicator() # number of objects to select nsrc = len(self._sort_index) nsel = int(math.ceil(nsrc * float(percent) / 100)) # get comparison operator opstr = str(self.wgele.currentText()) op, select = self.Operators[opstr] # select head or tail of list, depending on direction of operator if select: thr = self._sort_index[min(nsel, nsrc - 1)] slc1 = slice(0, nsel) slc2 = slice(nsel, None) else: thr = self._sort_index[-min(nsel + 1, nsrc)] slc1 = slice(nsrc - nsel, None) slc2 = slice(0, nsrc - nsel) if do_select: for val, src, cumsum in self._sort_index[slc1]: src.selected = True for val, src, cumsum in self._sort_index[slc2]: src.selected = False self.model.emitSelection(self) self.wpercent_lbl.setText("%3d%%" % percent) self.wthreshold.setText( "%g" % (thr[2] if opstr.startswith("sum") else thr[0])) busy.reset_cursor() return nsel def setModel(self, model): """Sets the current model. If dialog is visible, applies the changes""" self.model = model if self.isVisible(): self.resetModel() if not model: self.hide() def show(self): """Shows dialog, resetting the model if it was invisible.""" if not self.isVisible(): self.resetModel() QDialog.show(self)
class Prime(QWidget): """ Main GUI window """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._crawler = Crawler() self._producer = Producer() self._config = get_config() self._path = get_path() self._selected_playlist_index = 0 self._crawl_button = QLabel(self) self._playlist_combo = QComboBox(self) self._build_gui() def _build_gui(self): main_layout = QVBoxLayout() main_layout.addLayout(self._build_playlist_layout()) main_layout.addLayout(self._build_button_layout()) self.setLayout(main_layout) self.setWindowTitle("FlukeBox") self.show() def _build_playlist_layout(self) -> QHBoxLayout: playlist_label = QLabel(self) playlist_label.setText("Playlist") self._playlist_combo.currentIndexChanged.connect( self._playlist_selected) self._fill_playlist_combo() playlist_layout = QHBoxLayout() playlist_layout.addWidget(playlist_label) playlist_layout.addWidget(self._playlist_combo) return playlist_layout def _fill_playlist_combo(self): self._playlist_combo.clear() for playlist in self._config["playlists"]: self._playlist_combo.addItem(playlist["name"]) def _build_button_layout(self) -> QVBoxLayout: edit_button = QLabel(self) edit_button.setText("Edit") edit_button.mousePressEvent = self._edit_clicked reload_button = QLabel(self) reload_button.setText("Reload") reload_button.mousePressEvent = self._reload_clicked crawl_text = "Crawl" if NewFileDetector().are_there_new_files(): crawl_text += "!" self._crawl_button.setText(crawl_text) self._crawl_button.mousePressEvent = self._crawl_clicked gen_button = QLabel(self) gen_button.setText("Play") gen_button.mousePressEvent = self._generate_clicked btn_layout = QHBoxLayout() btn_layout.addWidget(edit_button) btn_layout.addWidget(reload_button) btn_layout.addWidget(self._crawl_button) btn_layout.addWidget(gen_button) return btn_layout def _playlist_selected(self, i): self._selected_playlist_index = i def _edit_clicked(self, event): # pylint: disable=W0613, R0201 data_path = path.join(self._path["data_path"], self._path["config_file"]) subprocess.call(["open", data_path]) def _reload_clicked(self, event): # pylint: disable=W0613, R0201 self._config = reload_config() self._fill_playlist_combo() def _crawl_clicked(self, event): # pylint: disable=W0613, R0201 self._crawl_button.setText("...") self._crawler.crawl() self._crawl_button.setText("Crawl") def _generate_clicked(self, event): # pylint: disable=W0613 selected_playlist = self._config["playlists"][ self._selected_playlist_index]["name"] self._producer.produce_with_playlist(selected_playlist) self.close()
class WebVttConvertDialog(QDialog): def __init__(self, gui, icon, do_user_config): QDialog.__init__(self, gui) self.outputFmt = 'epub' self.gui = gui self.do_user_config = do_user_config # The current database shown in the GUI # db is an instance of the class LibraryDatabase from db/legacy.py # This class has many, many methods that allow you to do a lot of # things. For most purposes you should use db.new_api, which has # a much nicer interface from db/cache.py self.db = gui.current_db self.l = QVBoxLayout() self.setLayout(self.l) label = QLabel( '1. Choose subtitle directory or choose a zip file, \n2. Setup main language and sub language when they appear.\n3. Click Convert button' ) self.l.addWidget(label) self.setWindowTitle('WebVtt Converter') self.setWindowIcon(icon) #self.about_button = QPushButton('About', self) #self.about_button.clicked.connect(self.about) #self.l.addWidget(self.about_button) self.setup_dir_button = QPushButton('subtitle directory', self) self.setup_dir_button.clicked.connect(self.setup_vtt_dir) self.choose_zip_button = QPushButton('subtitle zip file', self) self.choose_zip_button.clicked.connect(self.setup_vtt_zip_file) hbox = QHBoxLayout() hbox.addWidget(self.setup_dir_button) hbox.addWidget(self.choose_zip_button) self.l.addLayout(hbox) self.setup_cover_file_button = QPushButton( 'Choose Cover image (Optional)', self) self.setup_cover_file_button.clicked.connect(self.setup_cover) self.l.addWidget(self.setup_cover_file_button) self.main_lang_combo = QComboBox(self) self.main_lang_combo.addItem('-', '-') hbox = QHBoxLayout() hbox.addWidget(QLabel('Main language:'), alignment=Qt.AlignLeft) hbox.addWidget(self.main_lang_combo) self.l.addLayout(hbox) self.sub_lang_combo = QComboBox(self) self.sub_lang_combo.addItem('-', '-') hbox = QHBoxLayout() hbox.addWidget(QLabel('Second language:'), alignment=Qt.AlignLeft) hbox.addWidget(self.sub_lang_combo) self.l.addLayout(hbox) self.convert_button = QPushButton('Convert', self) self.convert_button.clicked.connect(self.convert_vtt_files) self.l.addWidget(self.convert_button) self.convert_button.setEnabled(False) self.resize(self.sizeHint()) self.temp_dir = PersistentTemporaryDirectory() #print(self.temp_dir) def about(self): text = get_resources('about.txt') QMessageBox.about(self, 'About the Interface Plugin Demo', text.decode('utf-8')) def setup_vtt_zip_file(self): vtt_zip_file, _ = QFileDialog.getOpenFileName( self, '', 'Select subtitle zip file', 'Zip Files(*.zip)') if vtt_zip_file == "": return # extract vtt files inside zip to temp directory with zipfile.ZipFile(vtt_zip_file, 'r') as zip_ref: for zip_info in zip_ref.infolist(): if zip_info.filename[-1] == '/': continue zip_info.filename = os.path.basename(zip_info.filename) zip_ref.extract(zip_info, self.temp_dir) self.vtt_dir = self.temp_dir self.update_language_combobox() def setup_vtt_dir(self): self.vtt_dir = str( QFileDialog.getExistingDirectory(self, "Select Directory", expanduser("~"), QFileDialog.ShowDirsOnly)) if self.vtt_dir == "": return self.update_language_combobox() def update_language_combobox(self): langs = convert.get_lang_list(self.vtt_dir) if len(langs) > 0: self.main_lang_combo.clear() self.sub_lang_combo.clear() self.sub_lang_combo.addItem('-', '-') for lang in langs: if lang.endswith('-forced'): continue self.main_lang_combo.addItem(self.get_long_language_name(lang), lang) self.sub_lang_combo.addItem(self.get_long_language_name(lang), lang) self.convert_button.setEnabled(True) def setup_cover(self): self.cover_file_path, _ = QFileDialog.getOpenFileName( self, 'Select Cover Image', 'Image Files(*.png *.jpg *.jpeg)') def convert_vtt_files(self): main_lang = self.main_lang_combo.currentData() if main_lang == '-': QMessageBox.about(self, 'Information', 'Select the main language before conversion.') return sub_lang = str(self.sub_lang_combo.currentData()) # if user does not select sub_lang, set it to main_lang, so that when converting, it won't generate sub language. if sub_lang == '-': sub_lang = main_lang # convert to html if hasattr(self, 'cover_file_path'): cover_file_path = self.cover_file_path else: cover_file_path = None self.book_id = self.convert_to_html_add_to_library( self.vtt_dir, main_lang, sub_lang, cover_file_path) # add html to epub conversion job self.jobs, changed, bad = convert_single_ebook( self.gui, self.gui.library_view.model().db, [self.book_id], True, self.outputFmt) func, args, desc, fmt, id, temp_files = self.jobs[0] core_usage = 1 plugin = plugin_for_input_format('html') if plugin is not None: core_usage = plugin.core_usage self.gui.job_manager.run_job(Dispatcher(self.converted_func), func, args=args, description=desc, core_usage=core_usage) self.close() def convert_to_html_add_to_library(self, vtt_dir, main_lang, sub_lang, cover_file_path): ''' return book_id when the html is added to library ''' html_file = PersistentTemporaryFile('.html', dir=self.temp_dir) convert.convert_webvtt_to_html(vtt_dir, main_lang, sub_lang, html_file.name) # add to library new_api = self.db.new_api from calibre.ebooks.metadata.meta import get_metadata with lopen(html_file.name, 'rb') as stream: mi = get_metadata(stream, stream_type='html', use_libprs_metadata=True) mi.tags = ['subtitles'] if cover_file_path != None: ext = cover_file_path.rpartition('.')[-1].lower().strip() if ext not in ('png', 'jpg', 'jpeg'): ext = 'jpg' with lopen(cover_file_path, 'rb') as stream: mi.cover_data = (ext, stream.read()) # add book in html format book_ids, duplicates = new_api.add_books([(mi, { 'HTML': html_file.name })], run_hooks=False) self.db.data.books_added(book_ids) self.gui.library_view.model().books_added(1) # remove temp directory #shutil.rmtree(self.temp_dir) return book_ids[0] def converted_func(self, job): temp_file = self.jobs[0][-1][-1].name self.db.new_api.add_format(self.book_id, self.outputFmt, temp_file, run_hooks=False) self.gui.library_view.model().refresh_ids((self.book_id, )) os.remove(temp_file) QMessageBox.about(self, 'Conversion', "Conversion is done.") def config(self): self.do_user_config(parent=self) # Apply the changes self.label.setText(prefs['hello_world_msg']) def get_long_language_name(self, short_name): if short_name.endswith('[cc]'): name = short_name[:-4] return language_map.get(name, name) + '[cc]' else: return language_map.get(short_name, short_name)
def clear(self): QComboBox.clear(self) self.initialize_saved_search_names() self.setEditText('') self.line_edit.home(False)
class ConditionEditor(QWidget): # {{{ ACTION_MAP = { 'bool' : ( (_('is true'), 'is true',), (_('is false'), 'is false'), (_('is undefined'), 'is undefined') ), 'ondevice' : ( (_('is true'), 'is set',), (_('is false'), 'is not set'), ), 'identifiers' : ( (_('has id'), 'has id'), (_('does not have id'), 'does not have id'), ), 'int' : ( (_('is equal to'), 'eq'), (_('is less than'), 'lt'), (_('is greater than'), 'gt') ), 'datetime' : ( (_('is equal to'), 'eq'), (_('is less than'), 'lt'), (_('is greater than'), 'gt'), (_('is set'), 'is set'), (_('is not set'), 'is not set'), (_('is more days ago than'), 'older count days'), (_('is fewer days ago than'), 'count_days'), (_('is more days from now than'), 'newer future days'), (_('is fewer days from now than'), 'older future days') ), 'multiple' : ( (_('has'), 'has'), (_('does not have'), 'does not have'), (_('has pattern'), 'has pattern'), (_('does not have pattern'), 'does not have pattern'), (_('is set'), 'is set'), (_('is not set'), 'is not set'), ), 'single' : ( (_('is'), 'is'), (_('is not'), 'is not'), (_('matches pattern'), 'matches pattern'), (_('does not match pattern'), 'does not match pattern'), (_('is set'), 'is set'), (_('is not set'), 'is not set'), ), } for x in ('float', 'rating'): ACTION_MAP[x] = ACTION_MAP['int'] def __init__(self, fm, parent=None): QWidget.__init__(self, parent) self.fm = fm self.action_map = self.ACTION_MAP self.l = l = QGridLayout(self) self.setLayout(l) texts = _('If the ___ column ___ values') try: one, two, three = texts.split('___') except: one, two, three = 'If the ', ' column ', ' value ' self.l1 = l1 = QLabel(one) l.addWidget(l1, 0, 0) self.column_box = QComboBox(self) l.addWidget(self.column_box, 0, 1) self.l2 = l2 = QLabel(two) l.addWidget(l2, 0, 2) self.action_box = QComboBox(self) l.addWidget(self.action_box, 0, 3) self.l3 = l3 = QLabel(three) l.addWidget(l3, 0, 4) self.value_box = QLineEdit(self) l.addWidget(self.value_box, 0, 5) self.column_box.addItem('', '') for key in sorted( conditionable_columns(fm), key=lambda(key): sort_key(fm[key]['name'])): self.column_box.addItem(fm[key]['name'], key) self.column_box.setCurrentIndex(0) self.column_box.currentIndexChanged.connect(self.init_action_box) self.action_box.currentIndexChanged.connect(self.init_value_box) for b in (self.column_box, self.action_box): b.setSizeAdjustPolicy(b.AdjustToMinimumContentsLengthWithIcon) b.setMinimumContentsLength(20) @dynamic_property def current_col(self): def fget(self): idx = self.column_box.currentIndex() return unicode(self.column_box.itemData(idx) or '') def fset(self, val): for idx in range(self.column_box.count()): c = unicode(self.column_box.itemData(idx) or '') if c == val: self.column_box.setCurrentIndex(idx) return raise ValueError('Column %r not found'%val) return property(fget=fget, fset=fset) @dynamic_property def current_action(self): def fget(self): idx = self.action_box.currentIndex() return unicode(self.action_box.itemData(idx) or '') def fset(self, val): for idx in range(self.action_box.count()): c = unicode(self.action_box.itemData(idx) or '') if c == val: self.action_box.setCurrentIndex(idx) return raise ValueError('Action %r not valid for current column'%val) return property(fget=fget, fset=fset) @property def current_val(self): ans = unicode(self.value_box.text()).strip() if self.current_col == 'languages': rmap = {lower(v):k for k, v in lang_map().iteritems()} ans = rmap.get(lower(ans), ans) return ans @dynamic_property def condition(self): def fget(self): c, a, v = (self.current_col, self.current_action, self.current_val) if not c or not a: return None return (c, a, v) def fset(self, condition): c, a, v = condition if not v: v = '' v = v.strip() self.current_col = c self.current_action = a self.value_box.setText(v) return property(fget=fget, fset=fset) def init_action_box(self): self.action_box.blockSignals(True) self.action_box.clear() self.action_box.addItem('', '') col = self.current_col if col: m = self.fm[col] dt = m['datatype'] if dt in self.action_map: actions = self.action_map[dt] else: if col == 'ondevice': k = 'ondevice' elif col == 'identifiers': k = 'identifiers' else: k = 'multiple' if m['is_multiple'] else 'single' actions = self.action_map[k] for text, key in actions: self.action_box.addItem(text, key) self.action_box.setCurrentIndex(0) self.action_box.blockSignals(False) self.init_value_box() def init_value_box(self): self.value_box.setEnabled(True) self.value_box.setText('') self.value_box.setInputMask('') self.value_box.setValidator(None) col = self.current_col if not col: return action = self.current_action if not action: return m = self.fm[col] dt = m['datatype'] tt = '' if col == 'identifiers': tt = _('Enter either an identifier type or an ' 'identifier type and value of the form identifier:value') elif col == 'languages': tt = _('Enter a 3 letter ISO language code, like fra for French' ' or deu for German or eng for English. You can also use' ' the full language name, in which case calibre will try to' ' automatically convert it to the language code.') elif dt in ('int', 'float', 'rating'): tt = _('Enter a number') v = QIntValidator if dt == 'int' else QDoubleValidator self.value_box.setValidator(v(self.value_box)) elif dt == 'datetime': if action == 'count_days': self.value_box.setValidator(QIntValidator(self.value_box)) tt = _('Enter the maximum days old the item can be. Zero is today. ' 'Dates in the future always match') elif action == 'older count days': self.value_box.setValidator(QIntValidator(self.value_box)) tt = _('Enter the minimum days old the item can be. Zero is today. ' 'Dates in the future never match') elif action == 'older future days': self.value_box.setValidator(QIntValidator(self.value_box)) tt = _('Enter the maximum days in the future the item can be. ' 'Zero is today. Dates in the past always match') elif action == 'newer future days': self.value_box.setValidator(QIntValidator(self.value_box)) tt = _('Enter the minimum days in the future the item can be. ' 'Zero is today. Dates in the past never match') else: self.value_box.setInputMask('9999-99-99') tt = _('Enter a date in the format YYYY-MM-DD') else: tt = _('Enter a string.') if 'pattern' in action: tt = _('Enter a regular expression') elif m.get('is_multiple', False): tt += '\n' + _('You can match multiple values by separating' ' them with %s')%m['is_multiple']['ui_to_list'] self.value_box.setToolTip(tt) if action in ('is set', 'is not set', 'is true', 'is false', 'is undefined'): self.value_box.setEnabled(False)
class ParameterMeshGroupView(ParameterView): """Top-level table editor item.""" meshFileChanged = pyqtSignal(str, str, float, bool) meshGroupCheck = pyqtSignal(str, str, str) meshGroupUnCheck = pyqtSignal(str, str, str) meshChanged = pyqtSignal() """Signal: emitted when mesh is changed in the combo box.""" def __init__(self, panel, **kwargs): """ Create view. Arguments: **kwargs: Arbitrary keyword arguments. """ super(ParameterMeshGroupView, self).__init__(panel, **kwargs) self.setStretchable(True) self._mesh = QComboBox(self) self._mesh.setObjectName("MESH") self._msg = QLabel(self) self._list = QTreeWidget(self) self._list.setAllColumnsShowFocus(True) self._list.setSelectionMode(QTreeWidget.SingleSelection) self._list.setColumnCount(2) titles = [] titles.append(translate("AsterStudy", "Name")) titles.append(translate("AsterStudy", "Size")) self._list.setHeaderLabels(titles) self._list.header().setSectionResizeMode(QHeaderView.ResizeToContents) self._list.header().setStretchLastSection(True) manlabel = QLabel(translate("ParameterPanel", "Manual selection"), self) manlabel.setToolTip( translate( "ParameterPanel", "Enter manually the wanted groups if " "not present in the list")) self._manual = QLineEdit(self) self._manual.setObjectName("MANUAL_INPUT") base = self.grid() base.addWidget(self._mesh, 0, 0, 1, -1) base.addWidget(self._msg, 1, 0, 1, -1) base.addWidget(self._list, 2, 0, 1, -1) base.addWidget(manlabel, 3, 0, 1, -1) base.addWidget(self._manual, 4, 0, 1, -1) self._mesh.activated[int].connect(self._meshActivated) self._updateMeshList() self.meshFileChanged.connect(self.meshview().displayMEDFileName) self.meshGroupCheck.connect(self.meshview().displayMeshGroup) self.meshGroupUnCheck.connect(self.meshview().undisplayMeshGroup) self._list.itemChanged.connect(self.meshGroupToChange) def meshList(self): """ Gets the mesh commands list Returns: list (Command): List of commands with meshes. """ mlist = [] for i in xrange(self._mesh.count()): mlist.append(self._mesh.itemData(i).name) return mlist def setMeshList(self, meshlist): """ Sets the mesh commands list Arguments: meshlist: List of commands with meshes. """ self._mesh.clear() show_title = behavior().show_catalogue_name_in_selectors title_mask = '{n} ({t})' if show_title else '{n}' for meshcmd in meshlist: title = title_mask.format(n=meshcmd.name, t=meshcmd.title) self._mesh.addItem(title, meshcmd) def mesh(self): """ Gets the currently selected mesh command object or None in error case. Returns: Command: Current mesh command object. """ idx = self._mesh.currentIndex() return self._mesh.itemData(idx) if idx >= 0 else None def setMesh(self, mesh): """ Sets the current mesh command object if it exists in the list. Arguments: mesh: Current mesh command object. """ self._mesh.setCurrentIndex(self._mesh.findData(mesh)) def message(self): """ Gets the info message text. Returns: str: info message text. """ return self._msg.text() def setMessage(self, msg): """ Sets the info message text. Arguments: msg (str): info message text. """ self._msg.setText(msg) self._msg.setVisible(len(msg) > 0) def setMeshGroups(self, groups): """ Sets the mesh group list Arguments: groups (dict[int, list[tuple[str, int]]]): Mesh groups info. """ self._list.clear() grp_types = sorted(groups.keys()) for typ in grp_types: names = groups[typ] if not names: continue title = MeshElemType.value2str(typ) item = QTreeWidgetItem(self._list, [title]) for name, size in names: sub_item = QTreeWidgetItem(item, [name, str(size)]) sub_item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) sub_item.setCheckState(0, Qt.Unchecked) sub_item.setTextAlignment(1, Qt.AlignRight) self._list.expandAll() def inputMeshGroups(self): """ Gets the mesh group names list entered manually Returns: list (str): List of group names. """ text = self._manual.text().strip() return [i.strip() for i in text.split(",")] if len(text) > 0 else [] def setInputMeshGroups(self, groups): """ Sets the mesh group list entered manually Arguments: groups: List of mesh group names. """ self._manual.setText(",".join(groups)) def selectedMeshGroups(self): """ Gets the names of selected (checked) mesh groups. Returns: list (str): List of selected group names. """ groups = [] for i in range(self._list.topLevelItemCount()): item = self._list.topLevelItem(i) for j in xrange(item.childCount()): sub_item = item.child(j) if sub_item.checkState(0) == Qt.Checked: groups.append(sub_item.text(0)) return list(set(groups)) def setSelectedMeshGroups(self, groups): """ Sets the specified group names are selected (checked) and unchecked all other. Arguments: groups: List of selected mesh group names. """ for i in range(self._list.topLevelItemCount()): item = self._list.topLevelItem(i) for j in xrange(item.childCount()): sub_item = item.child(j) state = Qt.Checked if sub_item.text(0) in groups \ else Qt.Unchecked sub_item.setCheckState(0, state) @pyqtSlot(QTreeWidgetItem, int) def meshGroupToChange(self, item, column): """ Emits display signal whenever the user clicks a check box """ meshcmd = self._meshcmd(self._mesh.currentIndex()) if meshcmd is not None: file_name, nom_med = get_cmd_mesh(meshcmd) if file_name is not None and nom_med is not None: if item.checkState(column) == Qt.Checked: self.meshGroupCheck.emit(file_name, nom_med, item.text(0)) else: self.meshGroupUnCheck.emit(file_name, nom_med, item.text(0)) def _meshcmd(self, index): """ Returns the *Command* instance associated with the panel """ meshcmd = None if 0 <= index < self._mesh.count(): meshcmd = self._mesh.itemData(index) return meshcmd def itemValue(self, **kwargs): """ Get selected values. Returns: tuple: List with all selected mesh groups """ res = tuple(self.selectedMeshGroups() + self.inputMeshGroups()) return res if len(res) > 0 else None def setItemValue(self, values): """ Set values of child items. Arguments: values: Tuple with item values (see `childValues()`). """ grplist = [] if values is not None: if isinstance(values, (tuple, list)): grplist = list(values) else: grplist = [values] self.setSelectedMeshGroups(grplist) check = dict.fromkeys(self.selectedMeshGroups()) grplist = [grp for grp in grplist if grp not in check] self.setInputMeshGroups(grplist) self._cache = self.itemValue() def filterItem(self, text): """ Filter out the item. Arguments: text (str): Regular expression. """ regex = QRegExp(text, Qt.CaseInsensitive) for i in range(self._list.topLevelItemCount()): item = self._list.topLevelItem(i) cnt_visible = 0 for j in xrange(item.childCount()): sub_item = item.child(j) item_text = sub_item.text(0) hidden = text != "" and regex.indexIn(item_text) == -1 sub_item.setHidden(hidden) if not hidden: cnt_visible += 1 item.setHidden(cnt_visible == 0) def _updateMeshList(self): """ Updates the mesh list in the combobox """ meshlist = avail_meshes(parameterPanel(self).pendingStorage()) meshlist.reverse() self.setMeshList(meshlist) msg = "" if len(meshlist) > 1: msg = translate("ParameterPanel", "More than one mesh found") elif len(meshlist) == 0: msg = translate("ParameterPanel", "No mesh found") self.setMessage(msg) self._meshActivated(self._mesh.currentIndex()) def _meshActivated(self, index): """ Updates the mesh groups in checkable list. Invoked after mesh changing in mesh combobox. """ meshcmd = None if 0 <= index < self._mesh.count(): meshcmd = self._mesh.itemData(index) groups = {} if meshcmd is not None: group_type = self._meshGroupType() file_name, nom_med = get_cmd_mesh(meshcmd) if is_medfile(file_name) or is_reference(file_name): self.meshFileChanged.emit(file_name, nom_med, 0.1, False) try: groups = get_cmd_groups(meshcmd, group_type, with_size=True) except TypeError: pass self.setMeshGroups(groups) self.meshChanged.emit() def _meshGroupType(self): """ Get the type of the mesh group Returns: str: Mesh group type (see `MeshGroupType`). """ mgtype = -1 name = self.itemName() if name.endswith("_MA") or is_contains_word(name, "MA"): mgtype = MeshGroupType.GElement elif name.endswith("_NO") or is_contains_word(name, "NO"): mgtype = MeshGroupType.GNode return mgtype
class ConfigDialog(QDialog): """Allow user to modify some persistent configuration settings.""" def __init__(self, parent=None): super().__init__(parent) self.lineEditPPScannos = QLineEdit() self.lineEditPPScannos.setReadOnly(True) self.comboScannoFiles = QComboBox() labelPPScannosLoc = QLabel('PPScannos File') labelPPScannosLoc.setBuddy(self.lineEditPPScannos) labelScannoLoc = QLabel('Default Scanno File') labelScannoLoc.setBuddy(self.comboScannoFiles) self.buttonPPScannos = QPushButton('Change') self.buttonPPScannos.pressed.connect(self.openFileDlg) hbox = QHBoxLayout() hbox.addWidget(labelPPScannosLoc) hbox.addWidget(self.lineEditPPScannos) hbox.addWidget(self.buttonPPScannos) self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) mainLayout = QGridLayout() mainLayout.addLayout(hbox, 0, 0, 2, 0) mainLayout.addWidget(labelScannoLoc, 1, 0) mainLayout.addWidget(self.comboScannoFiles, 1, 1) mainLayout.addWidget(self.buttonBox, 5, 0, 1, 2) self.setLayout(mainLayout) self.populate() self.lineEditPPScannos.textChanged.connect(self.ppscannosChanged) self.setWindowTitle("Configure Gui Scannos") self.resize(650, 400) def populate(self): """Fill the dialog.""" settings = QSettings(self) ppscannos = settings.value('ppscannos', type=str) if not ppscannos: #ppscannos = os.environ['HOME'] ppscannos = os.path.expanduser('~') ppscannos = ppscannos + '/ppscannos1/ppscannos1.py' self.lineEditPPScannos.setText(ppscannos) self.ppscannosChanged() defaultScanno = settings.value('defaultScannoFile', type=str) if defaultScanno: idx = self.comboScannoFiles.findText(defaultScanno) self.comboScannoFiles.setCurrentIndex(idx) #print('settings:', settings.allKeys()) #print('\tdefault:', settings.value('defaultScannoFile')) def ppscannosChanged(self): self.comboScannoFiles.clear() ppscannos = self.lineEditPPScannos.text() if not ppscannos: return scannoFiles = getRCFilesForDir(os.path.dirname(ppscannos)) if scannoFiles: for f in scannoFiles: (base, ext) = os.path.splitext(f) if ext == '.rc': self.comboScannoFiles.addItem(f) idx = self.comboScannoFiles.findText('regex.rc') if idx != -1: self.comboScannoFiles.setCurrentIndex(idx) def openFileDlg(self): """Open file picker for ppscannos.py file""" d = self.lineEditPPScannos.text() if d: d = os.path.dirname(d) dlg = QFileDialog(self, "Select PPScannos File...", None, "Python Files (*.py);;All Files (*)") dlg.setFileMode(QFileDialog.ExistingFile) if dlg.exec(): flist = dlg.selectedFiles() # returns a list if len(flist): self.lineEditPPScannos.setText(flist[0]) def ppscannosPath(self): return self.lineEditPPScannos.text() def scannoFileNames(self): lst = [] for i in range(self.comboScannoFiles.count()): lst.append(self.comboScannoFiles.itemText(i)) return lst
class AddTagDialog(QDialog): def __init__(self, parent, modal=True, flags=Qt.WindowFlags()): QDialog.__init__(self, parent, flags) self.setModal(modal) self.setWindowTitle("Add Tag") lo = QVBoxLayout(self) lo.setContentsMargins(10, 10, 10, 10) lo.setSpacing(5) # tag selector lo1 = QHBoxLayout() lo.addLayout(lo1) lo1.setSpacing(5) self.wtagsel = QComboBox(self) self.wtagsel.setEditable(True) wtagsel_lbl = QLabel("&Tag:", self) wtagsel_lbl.setBuddy(self.wtagsel) lo1.addWidget(wtagsel_lbl, 0) lo1.addWidget(self.wtagsel, 1) self.wtagsel.activated[int].connect(self._check_tag) self.wtagsel.editTextChanged['QString'].connect(self._check_tag_text) # value editor self.valedit = ValueTypeEditor(self) lo.addWidget(self.valedit) # buttons lo.addSpacing(10) lo2 = QHBoxLayout() lo.addLayout(lo2) lo2.setContentsMargins(0, 0, 0, 0) lo2.setContentsMargins(5, 5, 5, 5) self.wokbtn = QPushButton("OK", self) self.wokbtn.setMinimumWidth(128) self.wokbtn.clicked.connect(self.accept) self.wokbtn.setEnabled(False) cancelbtn = QPushButton("Cancel", self) cancelbtn.setMinimumWidth(128) cancelbtn.clicked.connect(self.reject) lo2.addWidget(self.wokbtn) lo2.addStretch(1) lo2.addWidget(cancelbtn) self.setMinimumWidth(384) def setTags(self, tagnames): self.wtagsel.clear() self.wtagsel.addItems(list(tagnames)) self.wtagsel.addItem("") self.wtagsel.setCurrentIndex(len(tagnames)) def setValue(self, value): self.valedit.setValue(value) def _check_tag(self, tag): self.wokbtn.setEnabled(True) def _check_tag_text(self, text): self.wokbtn.setEnabled(bool(str(text) != "")) def accept(self): """When dialog is accepted with a default (bool) tag type, check if the user hasn't entered a name=value entry in the tag name field. This is a common mistake, and should be treated as a shortcut for setting string tags.""" if isinstance(self.valedit.getValue(), bool): tagval = str(self.wtagsel.currentText()).split("=", 1) if len(tagval) > 1: # print tagval if QMessageBox.warning(self, "Set a string tag instead?", """<P>You have included an "=" sign in the tag name. Perhaps you actually mean to set tag "%s" to the string value "%s"?</P>""" % tuple(tagval), QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) == QMessageBox.No: return self.wtagsel.setEditText(tagval[0]) self.valedit.setValue(tagval[1]) return QDialog.accept(self) def getTag(self): return str(self.wtagsel.currentText()), self.valedit.getValue()
class ConfigWidget(QWidget): # GUI definition def __init__(self): QWidget.__init__(self) self.l = QVBoxLayout() self.setLayout(self.l) self.ll = QHBoxLayout() self.l.addLayout(self.ll) self.label_exe = QLabel(_('&Prince executable:')) self.ll.addWidget(self.label_exe) self.exe = QLineEdit(self) self.exe.setText(prefs['prince_exe']) self.exe.setToolTip( _('<qt>Executable for the Prince program (command-line interface)</qt>' )) self.ll.addWidget(self.exe) self.label_exe.setBuddy(self.exe) self.browse = QPushButton(_('&Browse') + '...', self) self.browse.setToolTip( _('<qt>Search the Prince executable in your computer</qt>')) self.browse.clicked.connect(self.select_exe) self.ll.addWidget(self.browse) self.lll = QHBoxLayout() self.l.addLayout(self.lll) self.label_fmts = QLabel(_('Preferred &formats:')) self.lll.addWidget(self.label_fmts) self.fmts = QLineEdit(self) self.fmts.setText(','.join(prefs['formats'])) self.fmts.setToolTip( _('<qt>Comma-separated list of preferred formats to use as source, the first that matches will be used</qt>' )) self.lll.addWidget(self.fmts) self.label_fmts.setBuddy(self.fmts) self.add_book = QCheckBox(_('&Add PDF to the book record')) self.add_book.setToolTip( _('<qt>Add the converted PDF to the selected book record</qt>')) self.add_book.setChecked(prefs['add_book']) self.l.addWidget(self.add_book) self.show_css = QCheckBox(_('&Show CSS in the Convert dialog')) self.show_css.setToolTip( _('<qt>Show by default the styles in the Convert dialog</qt>')) self.show_css.setChecked(prefs['show_CSS']) self.l.addWidget(self.show_css) self.css_layout = QVBoxLayout() self.llll = QHBoxLayout() self.css_layout.addLayout(self.llll) self.css_list = QComboBox() self.css_list.setToolTip( _('<qt>List of custom styles defined. Select one to edit</qt>')) self.css_list.setSizeAdjustPolicy(QComboBox.AdjustToContents) self.CSS_list = prefs['custom_CSS_list'].copy() self.default_CSS = prefs['default_CSS'] if 'custom_CSS' in prefs: self.CSS_list[_('old')] = prefs['custom_CSS'] self.default_CSS = _('old') if self.default_CSS not in self.CSS_list: self.default_CSS = sorted(self.CSS_list, key=lambda x: x.lower())[0] for key in sorted(self.CSS_list, key=lambda x: x.lower()): self.css_list.addItem(key, key) self.css_list.setCurrentIndex(self.css_list.findText(self.default_CSS)) self.css_list.currentIndexChanged.connect(self.set_css) self.llll.addWidget(self.css_list) self.css_rename = QPushButton(_('Re&name')) self.css_rename.setToolTip( _('<qt>Rename the current style to the name on the right</qt>')) self.css_rename.clicked.connect(self.rename_css) self.css_rename.setEnabled(False) self.llll.addWidget(self.css_rename) self.css_name = QLineEdit(self) self.css_name.setToolTip( _('<qt>Name for the new or renamed style</qt>')) self.css_name.setText(self.css_list.currentText()) self.css_name.textChanged.connect(self.check_names) self.llll.addWidget(self.css_name) self.css_add = QPushButton(_('A&dd')) self.css_add.setToolTip( _('<qt>Add a new empty style with the name on the left</qt>')) self.css_add.clicked.connect(self.add_css) self.css_add.setEnabled(False) self.llll.addWidget(self.css_add) self.css_remove = QPushButton(_('Re&move')) self.css_remove.setToolTip(_('<qt>Remove the current style</qt>')) self.css_remove.clicked.connect(self.remove_css) self.llll.addWidget(self.css_remove) self.llll_ = QHBoxLayout() self.css_layout.addLayout(self.llll_) self.label_args = QLabel(_('Addi&tional command-line arguments:')) self.llll_.addWidget(self.label_args) self.args = QLineEdit(self) # Make sure custom_CSS_list and custom_args_list have the same keys if 'custom_args_list' in prefs: self.args_list = prefs['custom_args_list'].copy() else: self.args_list = {} for key in self.CSS_list: if not key in self.args_list: self.args_list[key] = '' for key in self.args_list: if not key in self.CSS_list: del self.args_list[key] self.args.setText(self.args_list[unicode(self.css_list.currentText())]) self.args.setToolTip( _('<qt>Additional command-line arguments used in conversions with this style</qt>' )) self.llll_.addWidget(self.args) self.label_args.setBuddy(self.args) self.css = TextEditWithTooltip(self, expected_geometry=(80, 20)) self.css.setLineWrapMode(TextEditWithTooltip.NoWrap) self.css.load_text(self.CSS_list[unicode(self.css_list.currentText())], 'css') self.css.setToolTip( _('<qt>Custom stylesheet that will be applied, if selected, to all Prince PDF conversions</qt>' )) self.css_layout.addWidget(self.css) self.css_templates = QLabel(_('Book metadata can be used in the stylesheet. Anything between %(s1)s and %(s2)s will be processed as a calibre template. For instance, %(s3)s in the stylesheet will be replaced with the book title in the conversion.') % \ {'s1':'<span style="font-family:monospace ; font-weight:bold">@{@</span>', \ 's2':'<span style="font-family:monospace ; font-weight:bold">@}@</span>', \ 's3':'<span style="font-family:monospace ; font-weight:bold">@{@{title}@}@</span>'}) self.css_templates.setWordWrap(True) self.css_layout.addWidget(self.css_templates) self.css_box = QGroupBox(_('&Custom styles:')) self.css_box.setLayout(self.css_layout) self.l.addWidget(self.css_box) self.lllll = QHBoxLayout() self.lllll.setAlignment(Qt.AlignLeft) self.l.addLayout(self.lllll) self.defaults = QPushButton(_('&Restore defaults')) self.defaults.setToolTip(_('<qt>Restore the default settings</qt>')) self.defaults.clicked.connect(self.restore_defaults) self.lllll.addWidget(self.defaults, alignment=Qt.AlignLeft) self.warning = QLabel(_('<b>Warning</b>: Deletes modified styles')) self.lllll.addWidget(self.warning) self.adjustSize() def select_exe(self): ''' Create a dialog to select the Prince executable ''' dialog = QFileDialog() dialog.setFileMode(QFileDialog.ExistingFile) filename = dialog.getOpenFileName(self, _('Select Prince executable'), '', '') if filename: try: self.exe.setText(filename) except (TypeError): self.exe.setText(filename[0]) def restore_defaults(self): ''' Restore the default settings ''' self.exe.setText(prefs.defaults['prince_exe']) self.fmts.setText(','.join(prefs.defaults['formats']).lower()) self.show_css.setChecked(prefs.defaults['show_CSS']) self.add_book.setChecked(prefs.defaults['add_book']) self.css_list.currentIndexChanged.disconnect() self.css_list.clear() self.CSS_list = prefs.defaults['custom_CSS_list'].copy() self.args_list = prefs.defaults['custom_args_list'].copy() self.default_CSS = prefs.defaults['default_CSS'] for key in sorted(self.CSS_list, key=lambda x: x.lower()): self.css_list.addItem(key, key) self.css_list.setCurrentIndex(self.css_list.findText(self.default_CSS)) self.css_name.setText(self.default_CSS) self.css.load_text(self.CSS_list[unicode(self.css_list.currentText())], 'css') self.args.setText(self.args_list[unicode(self.css_list.currentText())]) self.css_list.currentIndexChanged.connect(self.set_css) def save_settings(self): ''' Save the current settings ''' prefs['prince_exe'] = unicode(self.exe.text()) prefs['formats'] = unicode(self.fmts.text().lower()).split(',') prefs['show_CSS'] = self.show_css.isChecked() prefs['add_book'] = self.add_book.isChecked() self.set_css() prefs['default_CSS'] = self.default_CSS prefs['custom_CSS_list'] = self.CSS_list.copy() prefs['custom_args_list'] = self.args_list.copy() if 'custom_CSS' in prefs: del prefs['custom_CSS'] def set_css(self): ''' Fill the CSS text box with the selected stylesheet, and similarly for command-line arguments ''' self.CSS_list[self.default_CSS] = unicode(self.css.toPlainText()) self.args_list[self.default_CSS] = unicode(self.args.text()) self.default_CSS = unicode(self.css_list.currentText()) self.css.load_text(self.CSS_list[self.default_CSS], 'css') self.args.setText(self.args_list[self.default_CSS]) self.css_name.setText(self.css_list.currentText()) def add_css(self): ''' Add a new style ''' from calibre.gui2 import error_dialog name = unicode(self.css_name.text()) if name in self.CSS_list: error_dialog( self, _('Cannot add style'), _('A style with the name "%s" is already defined, use a different name.' ) % name, show=True) else: self.CSS_list[name] = '' self.args_list[name] = '' self.css_list.addItem(name, name) self.css_list.setCurrentIndex(self.css_list.findText(name)) self.css_add.setEnabled(False) self.css_rename.setEnabled(False) def remove_css(self): ''' Remove an existing style ''' from calibre.gui2 import error_dialog if (self.css_list.count() > 1): self.css_list.currentIndexChanged.disconnect() self.css_list.removeItem(self.css_list.currentIndex()) del self.CSS_list[self.default_CSS] del self.args_list[self.default_CSS] self.default_CSS = unicode(self.css_list.currentText()) self.css.load_text(self.CSS_list[self.default_CSS], 'css') self.args.setText(self.args_list[self.default_CSS]) self.css_list.currentIndexChanged.connect(self.set_css) self.css_name.setText(self.css_list.currentText()) else: error_dialog( self, _('Cannot delete the last style'), _('The last style cannot be removed. You can rename it and/or remove its contents.' ), show=True) def rename_css(self): ''' Rename a style ''' from calibre.gui2 import error_dialog name = unicode(self.css_name.text()) if name in self.CSS_list: error_dialog( self, _('Cannot rename style'), _('A style with the name "%s" is already defined, use a different name.' ) % name, show=True) else: self.CSS_list[name] = self.CSS_list.pop(self.default_CSS) self.args_list[name] = self.args_list.pop(self.default_CSS) self.css_list.setItemText(self.css_list.currentIndex(), name) self.default_CSS = name def check_names(self, text): name = unicode(text) if name in self.CSS_list: self.css_add.setEnabled(False) self.css_rename.setEnabled(False) else: self.css_add.setEnabled(True) self.css_rename.setEnabled(True)
def clear(self): QComboBox.clear(self) self.initialize_saved_search_names() self.setEditText("") self.setToolTip(self.tool_tip_text) self.line_edit.home(False)
class RemoveDialog(Dialog): def __init__(self, parent): from calibre_plugins.diaps_toolbag.span_div_config import plugin_prefs as prefs self.criteria = None self.prefs = prefs self.parent = parent self.help_file_name = '{0}_span_div_help.html'.format(PLUGIN_SAFE_NAME) self.taglist = TAGLIST Dialog.__init__(self, _('Edit Spans & Divs'), 'toolbag_spans_divs_dialog', parent) def setup_ui(self): DELETE_STR = _('Delete') MODIFY_STR = _('Modify') NO_ATTRIB_STR = _('No attributes ("naked" tag)') self.NO_CHANGE_STR = _('No change') layout = QVBoxLayout(self) self.setLayout(layout) help_layout = QHBoxLayout() layout.addLayout(help_layout) # Add hyperlink to a help file at the right. We will replace the correct name when it is clicked. help_label = QLabel('<a href="http://www.foo.com/">Plugin Help</a>', self) help_label.setTextInteractionFlags(Qt.LinksAccessibleByMouse | Qt.LinksAccessibleByKeyboard) help_label.setAlignment(Qt.AlignRight) help_label.linkActivated.connect(self.help_link_activated) help_layout.addWidget(help_label) action_layout = QHBoxLayout() layout.addLayout(action_layout) label = QLabel(_('Action type:'), self) action_layout.addWidget(label) self.action_combo = QComboBox() action_layout.addWidget(self.action_combo) self.action_combo.addItems([DELETE_STR, MODIFY_STR]) self.action_combo.currentIndexChanged.connect(self.update_gui) tag_layout = QHBoxLayout() layout.addLayout(tag_layout) label = QLabel(_('Tag name:'), self) tag_layout.addWidget(label) self.tag_combo = QComboBox() tag_layout.addWidget(self.tag_combo) self.tag_combo.addItems(self.taglist) self.tag_combo.currentIndexChanged.connect(self.update_gui) attr_layout = QHBoxLayout() layout.addLayout(attr_layout) label = QLabel(_('Having the attribute:'), self) attr_layout.addWidget(label) self.attr_combo = QComboBox() attr_layout.addWidget(self.attr_combo) self.attr_combo.addItems(self.prefs['attrs']) self.attr_combo.addItem(NO_ATTRIB_STR) self.attr_combo.currentIndexChanged.connect(self.update_gui) srch_layout = QHBoxLayout() layout.addLayout(srch_layout) label = QLabel(_("Whose value is (no quotes):"), self) srch_layout.addWidget(label) self.srch_txt = QLineEdit('', self) srch_layout.addWidget(self.srch_txt) self.srch_method = QCheckBox(_('Regex'), self) srch_layout.addWidget(self.srch_method) newtag_layout = QHBoxLayout() layout.addLayout(newtag_layout) label = QLabel(_('Change tag to:'), self) newtag_layout.addWidget(label) self.newtag_combo = QComboBox() newtag_layout.addWidget(self.newtag_combo) self.newtag_combo.addItem(self.NO_CHANGE_STR) self.newtag_combo.addItems(self.prefs['{}_changes'.format(unicode(self.tag_combo.currentText()))]) if self.action_combo.currentIndex() == 0: self.newtag_combo.setDisabled(True) newattr_layout = QVBoxLayout() layout.addLayout(newattr_layout) label = QLabel(_('New attribute string to insert (entire):'), self) newattr_layout.addWidget(label) self.newattr_txt = QLineEdit('', self) newattr_layout.addWidget(self.newattr_txt) self.copy_attr = QCheckBox(_('Copy existing attribute string'), self) self.copy_attr.stateChanged.connect(self.update_txt_box) newattr_layout.addWidget(self.copy_attr) if self.action_combo.currentIndex() == 0: self.copy_attr.setDisabled(True) self.newattr_txt.setDisabled(True) layout.addSpacing(10) button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) button_box.accepted.connect(self._ok_clicked) button_box.rejected.connect(self.reject) layout.addWidget(button_box) def update_gui(self): if self.attr_combo.currentIndex() == self.attr_combo.count()-1: self.srch_txt.clear() self.srch_txt.setDisabled(True) self.srch_method.setChecked(False) self.srch_method.setDisabled(True) else: self.srch_txt.setDisabled(False) self.srch_method.setDisabled(False) self.newtag_combo.clear() self.newtag_combo.addItem(self.NO_CHANGE_STR) self.newtag_combo.addItems(self.prefs['{}_changes'.format(unicode(self.tag_combo.currentText()))]) if self.action_combo.currentIndex() == 0: self.newtag_combo.setCurrentIndex(0) self.newtag_combo.setDisabled(True) self.newattr_txt.clear() self.newattr_txt.setDisabled(True) self.copy_attr.setChecked(False) self.copy_attr.setDisabled(True) else: self.newtag_combo.setDisabled(False) self.newattr_txt.setDisabled(False) self.copy_attr.setDisabled(False) def update_txt_box(self): if self.copy_attr.isChecked(): self.newattr_txt.clear() self.newattr_txt.setDisabled(True) else: self.newattr_txt.setDisabled(False) def _ok_clicked(self): if self.action_combo.currentIndex() == 0: action = 'delete' else: action = 'modify' if self.attr_combo.currentIndex() == self.attr_combo.count()-1: attribute = None else: attribute = unicode(self.attr_combo.currentText()) srch_str = unicode(self.srch_txt.displayText()) if not len(srch_str): srch_str = None if srch_str is None and attribute is not None: return error_dialog(self.parent, _('Error'), '<p>{0}'.format( _('Must enter a value for the attribute selected')), det_msg='', show=True) srch_method = 'normal' if self.srch_method.isChecked(): srch_method = 'regex' if self.newtag_combo.currentIndex() == 0: newtag = None else: newtag = unicode(self.newtag_combo.currentText()) if action == 'modify' and newtag is None and self.copy_attr.isChecked(): return error_dialog(self.parent, _('Error'), '<p>{0}'.format( _('What--exactly--would that achieve?')), det_msg='', show=True) new_str = unicode(self.newattr_txt.displayText()) copy_attr = False if self.copy_attr.isChecked(): copy_attr = True if not len(new_str): new_str = '' self.criteria = (srch_str, srch_method, unicode(self.tag_combo.currentText()), attribute, action, newtag, new_str, copy_attr) self.accept() def getCriteria(self): return self.criteria def help_link_activated(self, url): def get_help_file_resource(): # Copy the HTML helpfile to the plugin directory each time the # link is clicked in case the helpfile is updated in newer plugins. file_path = os.path.join(config_dir, 'plugins', self.help_file_name) with open(file_path,'w') as f: f.write(load_resource('resources/{}'.format(self.help_file_name))) return file_path url = 'file:///' + get_help_file_resource() open_url(QUrl(url))
class ConfigWidget(QWidget): # GUI definition def __init__(self): QWidget.__init__(self) self.l = QVBoxLayout() self.setLayout(self.l) self.ll = QHBoxLayout() self.l.addLayout(self.ll) self.label_exe = QLabel(_('&Prince executable:')) self.ll.addWidget(self.label_exe) self.exe = QLineEdit(self) self.exe.setText(prefs['prince_exe']) self.exe.setToolTip(_('<qt>Executable for the Prince program (command-line interface)</qt>')) self.ll.addWidget(self.exe) self.label_exe.setBuddy(self.exe) self.browse = QPushButton(_('&Browse') + '...', self) self.browse.setToolTip(_('<qt>Search the Prince executable in your computer</qt>')) self.browse.clicked.connect(self.select_exe) self.ll.addWidget(self.browse) self.lll = QHBoxLayout() self.l.addLayout(self.lll) self.label_fmts = QLabel(_('Preferred &formats:')) self.lll.addWidget(self.label_fmts) self.fmts = QLineEdit(self) self.fmts.setText(','.join(prefs['formats'])) self.fmts.setToolTip(_('<qt>Comma-separated list of preferred formats to use as source, the first that matches will be used</qt>')) self.lll.addWidget(self.fmts) self.label_fmts.setBuddy(self.fmts) self.add_book = QCheckBox(_('&Add PDF to the book record')) self.add_book.setToolTip(_('<qt>Add the converted PDF to the selected book record</qt>')) self.add_book.setChecked(prefs['add_book']) self.l.addWidget(self.add_book) self.show_css = QCheckBox(_('&Show CSS in the Convert dialog')) self.show_css.setToolTip(_('<qt>Show by default the stylesheets in the Convert dialog</qt>')) self.show_css.setChecked(prefs['show_CSS']) self.l.addWidget(self.show_css) self.css_layout = QVBoxLayout() self.llll = QHBoxLayout() self.css_layout.addLayout(self.llll) self.css_list = QComboBox() self.css_list.setToolTip(_('<qt>List of custom stylesheets defined. Select one to edit</qt>')) self.css_list.setSizeAdjustPolicy(QComboBox.AdjustToContents) self.CSS_list = prefs['custom_CSS_list'].copy() self.default_CSS = prefs['default_CSS'] if 'custom_CSS' in prefs: self.CSS_list[_('old')] = prefs['custom_CSS'] self.default_CSS = _('old') if self.default_CSS not in self.CSS_list: self.default_CSS = sorted(self.CSS_list, key=lambda x: x.lower())[0] for key in sorted(self.CSS_list, key=lambda x: x.lower()): self.css_list.addItem(key, key) self.css_list.setCurrentIndex(self.css_list.findText(self.default_CSS)) self.css_list.currentIndexChanged.connect(self.set_css) self.llll.addWidget(self.css_list) self.css_rename = QPushButton(_('Re&name')) self.css_rename.setToolTip(_('<qt>Rename the current stylesheet to the name on the right</qt>')) self.css_rename.clicked.connect(self.rename_css) self.css_rename.setEnabled(False) self.llll.addWidget(self.css_rename) self.css_name = QLineEdit(self) self.css_name.setToolTip(_('<qt>Name for the new or renamed stylesheet</qt>')) self.css_name.setText(self.css_list.currentText()) self.css_name.textChanged.connect(self.check_names) self.llll.addWidget(self.css_name) self.css_add = QPushButton(_('A&dd')) self.css_add.setToolTip(_('<qt>Add a new empty stylesheet with the name on the left</qt>')) self.css_add.clicked.connect(self.add_css) self.css_add.setEnabled(False) self.llll.addWidget(self.css_add) self.css_remove = QPushButton(_('Re&move')) self.css_remove.setToolTip(_('<qt>Remove the current stylesheet</qt>')) self.css_remove.clicked.connect(self.remove_css) self.llll.addWidget(self.css_remove) self.css = TextEditWithTooltip() self.css.setLineWrapMode(TextEditWithTooltip.NoWrap) self.css.load_text(self.CSS_list[unicode(self.css_list.currentText())],'css') self.css.setToolTip(_('<qt>Custom stylesheet that will be applied, if selected, to all Prince PDF conversions</qt>')) self.css_layout.addWidget(self.css) self.css_templates = QLabel(_('Book metadata can be used in the stylesheet. Anything between %(s1)s and %(s2)s will be processed as a calibre template. For instance, %(s3)s in the stylesheet will be replaced with the book title in the conversion.') % \ {'s1':'<span style="font-family:monospace ; font-weight:bold">@{@</span>', \ 's2':'<span style="font-family:monospace ; font-weight:bold">@}@</span>', \ 's3':'<span style="font-family:monospace ; font-weight:bold">@{@{title}@}@</span>'}) self.css_templates.setWordWrap(True) self.css_layout.addWidget(self.css_templates) self.css_box = QGroupBox(_('&Custom CSS:')) self.css_box.setLayout(self.css_layout) self.l.addWidget(self.css_box) self.lllll = QHBoxLayout() self.lllll.setAlignment(Qt.AlignLeft) self.l.addLayout(self.lllll) self.defaults = QPushButton(_('&Restore defaults')) self.defaults.setToolTip(_('<qt>Restore the default settings</qt>')) self.defaults.clicked.connect(self.restore_defaults) self.lllll.addWidget(self.defaults, alignment=Qt.AlignLeft) self.warning = QLabel(_('<b>Warning</b>: Deletes modified stylesheets')) self.lllll.addWidget(self.warning) self.adjustSize() def select_exe(self): ''' Create a dialog to select the Prince executable ''' dialog = QFileDialog() dialog.setFileMode(QFileDialog.ExistingFile) filename = dialog.getOpenFileName(self, _('Select Prince executable'), '', '') if filename: try: self.exe.setText(filename) except(TypeError): self.exe.setText(filename[0]) def restore_defaults(self): ''' Restore the default settings ''' self.exe.setText(prefs.defaults['prince_exe']) self.fmts.setText(','.join(prefs.defaults['formats']).lower()) self.show_css.setChecked(prefs.defaults['show_CSS']) self.add_book.setChecked(prefs.defaults['add_book']) self.css_list.currentIndexChanged.disconnect() self.css_list.clear() self.CSS_list = prefs.defaults['custom_CSS_list'].copy() self.default_CSS = prefs.defaults['default_CSS'] for key in sorted(self.CSS_list, key=lambda x: x.lower()): self.css_list.addItem(key, key) self.css_list.setCurrentIndex(self.css_list.findText(self.default_CSS)) self.css_name.setText(self.default_CSS) self.css.load_text(self.CSS_list[unicode(self.css_list.currentText())],'css') self.css_list.currentIndexChanged.connect(self.set_css) def save_settings(self): ''' Save the current settings ''' prefs['prince_exe'] = unicode(self.exe.text()) prefs['formats'] = unicode(self.fmts.text().lower()).split(',') prefs['show_CSS'] = self.show_css.isChecked() prefs['add_book'] = self.add_book.isChecked() self.set_css() prefs['default_CSS'] = self.default_CSS prefs['custom_CSS_list'] = self.CSS_list.copy() if 'custom_CSS' in prefs: del prefs['custom_CSS'] def set_css(self): ''' Fill the CSS text box with the selected stylesheet ''' self.CSS_list[self.default_CSS] = unicode(self.css.toPlainText()) self.default_CSS = unicode(self.css_list.currentText()) self.css.load_text(self.CSS_list[self.default_CSS],'css') self.css_name.setText(self.css_list.currentText()) def add_css(self): ''' Add a new stylesheet ''' from calibre.gui2 import error_dialog name = unicode(self.css_name.text()) if name in self.CSS_list: error_dialog(self, _('Cannot add stylesheet'), _('A stylesheet with the name "%s" is already defined, use a different name.') % name, show=True) else: self.CSS_list[name] = '' self.css_list.addItem(name, name) self.css_list.setCurrentIndex(self.css_list.findText(name)) self.css_add.setEnabled(False) self.css_rename.setEnabled(False) def remove_css(self): ''' Remove an existing stylesheet ''' from calibre.gui2 import error_dialog if (self.css_list.count() > 1): self.css_list.currentIndexChanged.disconnect() self.css_list.removeItem(self.css_list.currentIndex()) del self.CSS_list[self.default_CSS] self.default_CSS = unicode(self.css_list.currentText()) self.css.load_text(self.CSS_list[self.default_CSS],'css') self.css_list.currentIndexChanged.connect(self.set_css) self.css_name.setText(self.css_list.currentText()) else: error_dialog(self, _('Cannot delete the last stylesheet'), _('The last stylesheet cannot be removed. You can rename it and/or remove its contents.'), show=True) def rename_css(self): ''' Rename a stylesheet ''' from calibre.gui2 import error_dialog name = unicode(self.css_name.text()) if name in self.CSS_list: error_dialog(self, _('Cannot rename stylesheet'), _('A stylesheet with the name "%s" is already defined, use a different name.') % name, show=True) else: self.CSS_list[name] = self.CSS_list.pop(self.default_CSS) self.css_list.setItemText(self.css_list.currentIndex(),name) self.default_CSS = name def check_names(self, text): name = unicode(text) if name in self.CSS_list: self.css_add.setEnabled(False) self.css_rename.setEnabled(False) else: self.css_add.setEnabled(True) self.css_rename.setEnabled(True)
class StartMenu(QWidget): def __init__(self, parent): super(StartMenu, self).__init__(parent) self.tophbox = QHBoxLayout() self.hbox = QHBoxLayout() self.vbox = QVBoxLayout() self.label = QLabel() self.label.setPixmap(QPixmap('img/new-game.png')) self.label.setScaledContents(True) self.label.setFixedSize(600, 200) self.tophbox.addWidget(self.label) self.startbutton = Button(self, 'Start') self.startbutton.setEnabled(False) self.startbutton.setFixedHeight(100) self.tophbox.addWidget(self.startbutton) self.playeramt_label = QLabel('Number of players:') self.playeramt_label.setFixedWidth(125) self.playeramount = QComboBox() self.playeramount.setStyleSheet('color: rgb(0, 0, 0)') self.playeramount.setFixedWidth(50) self.playeramount.addItems([str(i) for i in range(2, 13)]) self.playeramount.setCurrentIndex(2) self.playeramount.setMaxVisibleItems(11) self.playeramount.currentTextChanged.connect(self.form_player_entries) self.score_label = QLabel('Score limit:') self.score_label.setFixedWidth(65) self.score_limit = QLineEdit() self.score_limit.setMaximumWidth(40) self.score_limit.setPalette(QPalette(Qt.white)) self.score_limit.setText('16') self.mode_label = QLabel('Game Mode:') self.mode_label.setFixedWidth(85) self.mode_select = QComboBox() self.mode_select.addItems(['Deal-1', 'Deal-4']) self.mode_select.setPalette(QPalette(Qt.white)) self.mode_select.setFixedWidth(100) self.mode_select.currentTextChanged.connect(self.update_playeramount) self.autofill_button = Button(self, 'Auto Fill') self.autofill_button.clicked.connect(self.auto_fill) self.clear_button = Button(self, 'Clear All') self.clear_button.clicked.connect(self.clear_all) self.player_entries = QVBoxLayout() self.spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.hbox.addWidget(self.playeramt_label) self.hbox.addWidget(self.playeramount) self.hbox.addWidget(self.score_label) self.hbox.addWidget(self.score_limit) self.hbox.addWidget(self.mode_label) self.hbox.addWidget(self.mode_select) self.hbox.addWidget(self.autofill_button) self.hbox.addWidget(self.clear_button) self.vbox.addLayout(self.tophbox) self.vbox.addLayout(self.hbox) self.vbox.addLayout(self.player_entries) self.vbox.addItem(self.spacer) self.setLayout(self.vbox) self.form_player_entries() def form_player_entries(self): amt = self.playeramount.currentIndex() + 2 #desired amount of player entries curr = self.player_entries.count() #current amount of player entries dif = amt - self.player_entries.count() #difference between desired and current entries if dif < 0: #if too many entries currently for i in range(curr-1, amt-1, -1): #remove starting from last entry rm = self.player_entries.itemAt(i).widget() self.player_entries.removeWidget(rm) rm.setParent(None) else: #if too few entries, add until desired amount reached for i in range(dif): new_entry = PlayerInfoField(self, self.player_entries.count()) new_entry.name_field.textChanged.connect(self.check_filled) self.player_entries.addWidget(new_entry) self.check_filled() def check_filled(self): #Enables start button when player fields are correctly filled ready = True for i in range(self.player_entries.count()): entry = self.player_entries.itemAt(i).widget() if entry.name_field.text() == '': ready = False break if ready: self.startbutton.setEnabled(True) else: self.startbutton.setEnabled(False) def auto_fill(self): #Generates fills the rest of the form automatically for i in range(self.player_entries.count()): entry = self.player_entries.itemAt(i).widget() if entry.name_field.text() == '': entry.generate_name() entry.AItoggle.setChecked(True) def clear_all(self): for i in range(self.player_entries.count()): entry = self.player_entries.itemAt(i).widget() entry.name_field.clear() entry.AItoggle.setChecked(False) def update_playeramount(self, mode): ind = self.playeramount.currentIndex() if mode == 'Deal-1': #Limit max players to 12 self.playeramount.clear() self.playeramount.addItems([str(i) for i in range(2, 13)]) self.playeramount.setCurrentIndex(ind) if mode == 'Deal-4': #Limit max players to 4 self.playeramount.clear() self.playeramount.addItems([str(i) for i in range(2, 5)]) self.playeramount.setCurrentIndex(min(2, ind)) self.check_filled() def extract_info_and_init_game(self): #Creates a game object based on the info pointlimit = int(self.score_limit.text()) dealmode = self.mode_select.currentIndex() game = Game(pointlimit, dealmode) for i in range(self.player_entries.count()): entry = self.player_entries.itemAt(i).widget() name = entry.name_field.text() if entry.AItoggle.isChecked(): difficulty = entry.AIdifficulty.currentIndex() game.add_player(name, difficulty) else: game.add_player(name, 5) return game
class EKWindow(QDialog): """ Class which is responisble for running this entire application """ def __init__(self): """ Constructor for this class """ super(EKWindow, self).__init__() self.engine = Engine("tables/Tamil-bamini.txt.in") # Settings file initialization self.settingsFilePath = os.getenv("APPDATA") + "\\" + qApp.applicationName() + "\eksettings.ini" self.init_settings() # Function to check whether the settings file is or not. self.iniSettings = QSettings(self.settingsFilePath, QSettings.IniFormat) # Variable Initialization self.registrySettings = QSettings("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run", QSettings.NativeFormat) self.shortcutModifierKey = self.iniSettings.value("shortcut_modifier") self.shortcutKey = self.iniSettings.value("shortcut") self.selectedKeyboard = self.iniSettings.value("selected_keyboard") self.keyboardStatus = False self.fileName = "" # Ui variable Initialization self.iconGroupBox = QGroupBox("Keyboards") self.iconLabel = QLabel("Keyboard:") self.iconComboBox = QComboBox(self) self.shortcutGroupBox = QGroupBox("Shortcut Setting") self.shortcutComboBox1 = QComboBox(self) self.shortcutComboBox2 = QComboBox(self) self.otherSettingsGroupBox = QGroupBox("Other Settings") self.checkboxStartWithWindows = QCheckBox() self.minimizeAction = QAction("Minimize", self) self.maximizeAction = QAction("Maximize", self) self.settingsAction = QAction("Settings", self) self.aboutAction = QAction("About", self) self.quitAction = QAction("Quit", self) self.trayIconMenu = QMenu(self) self.trayIcon = QSystemTrayIcon(self) self.mainLayout = QVBoxLayout() self.mainLayout.addWidget(self.iconGroupBox) self.mainLayout.addWidget(self.shortcutGroupBox) self.mainLayout.addWidget(self.otherSettingsGroupBox) self.setLayout(self.mainLayout) # UI constructor and connectors self.create_settings_group_boxes() self.create_actions() self.create_tray_icon() # Signal connectors self.iconComboBox.currentIndexChanged.connect(self.change_keyboard) self.shortcutComboBox1.currentIndexChanged.connect(self.set_shortcut_modifier) self.shortcutComboBox2.currentIndexChanged.connect(self.set_shortcut_key) self.trayIcon.activated.connect(self.icon_activated) self.checkboxStartWithWindows.stateChanged.connect(self.checkbox_start_with_windows_ticked) if self.keyboardStatus: self.iconComboBox.setCurrentIndex(self.selectedKeyBoard) else: self.change_keyboard(0) self.iconComboBox.setCurrentIndex(0) self.trayIcon.show() self.set_shortcut_key() self.setWindowTitle(qApp.applicationName() + " " + qApp.applicationVersion()) def init_settings(self): """ Function to check whether the settings file is there or not. If there is no file, then it will create with default settings. """ if not os.path.exists(self.settingsFilePath): settings_dir = os.getenv("APPDATA") + "\\" + qApp.applicationName() if not os.path.exists(settings_dir): os.makedirs(settings_dir) setting_path = "" if getattr(sys, 'frozen', False): setting_path = os.path.dirname(sys.executable) elif __file__: setting_path = os.path.dirname(__file__) shutil.copyfile(os.path.join(setting_path, "resources\eksettings.ini"), self.settingsFilePath) return def create_settings_group_boxes(self): """ UI generator function. """ self.iconComboBox.addItem("No Keyboard") self.iconComboBox.addItem("Tamil99") self.iconComboBox.addItem("Phonetic") self.iconComboBox.addItem("Typewriter") self.iconComboBox.addItem("Bamini") self.iconComboBox.addItem("Inscript") icon_layout = QHBoxLayout(self) icon_layout.addWidget(self.iconLabel) icon_layout.addWidget(self.iconComboBox) icon_layout.addStretch() self.iconGroupBox.setLayout(icon_layout) shortcut_label_1 = QLabel("Modifier Key:") shortcut_label_2 = QLabel("Shortcut Key:") self.shortcutComboBox1.addItem("NONE") self.shortcutComboBox1.addItem("CTRL") self.shortcutComboBox1.addItem("ALT") modifier_index = self.shortcutComboBox1.findText(self.shortcutModifierKey) self.shortcutComboBox1.setCurrentIndex(modifier_index) self.shortcutComboBox2.setMinimumContentsLength(3) if modifier_index == 0: self.shortcutComboBox2.addItem("F1") self.shortcutComboBox2.addItem("ESC") self.shortcutComboBox2.addItem("F2") self.shortcutComboBox2.addItem("F3") self.shortcutComboBox2.addItem("F4") self.shortcutComboBox2.addItem("F5") self.shortcutComboBox2.addItem("F6") self.shortcutComboBox2.addItem("F7") self.shortcutComboBox2.addItem("F8") self.shortcutComboBox2.addItem("F9") self.shortcutComboBox2.addItem("F10") else: self.shortcutComboBox2.addItem("1") self.shortcutComboBox2.addItem("2") self.shortcutComboBox2.addItem("3") self.shortcutComboBox2.addItem("4") self.shortcutComboBox2.addItem("5") self.shortcutComboBox2.addItem("6") self.shortcutComboBox2.addItem("7") self.shortcutComboBox2.addItem("8") self.shortcutComboBox2.addItem("9") self.shortcutComboBox2.addItem("0") key_index = self.shortcutComboBox2.findText(self.shortcutKey) self.shortcutComboBox2.setCurrentIndex(key_index) shortcut_layout = QHBoxLayout(self) shortcut_layout.addWidget(shortcut_label_1) shortcut_layout.addWidget(self.shortcutComboBox1) shortcut_layout.addWidget(shortcut_label_2) shortcut_layout.addWidget(self.shortcutComboBox2) shortcut_layout.addStretch() self.shortcutGroupBox.setLayout(shortcut_layout) checkbox_start_with_windows_label = QLabel("Start eKalappai whenever windows starts") # if registry entry for auto start with windows for the current user exists, then check the checkbox if self.registrySettings.contains(qApp.applicationName()): self.checkboxStartWithWindows.setChecked(True) else: self.checkboxStartWithWindows.setChecked(False) other_settings_layout = QHBoxLayout(self) other_settings_layout.addWidget(checkbox_start_with_windows_label) other_settings_layout.addWidget(self.checkboxStartWithWindows) other_settings_layout.addStretch() self.otherSettingsGroupBox.setLayout(other_settings_layout) def set_shortcut_key(self): """ Function to change the shortcut key when its changed. """ self.shortcutKey = self.shortcutComboBox2.currentText() self.iniSettings.setValue("shortcut", self.shortcutKey) self.register_shortcut_listener() if self.shortcutKey == "ESC": self.shortcutKeyHex = 0x1B elif self.shortcutKey == "F1": self.shortcutKeyHex = 0x70 elif self.shortcutKey == "F2": self.shortcutKeyHex = 0x71 elif self.shortcutKey == "F3": self.shortcutKeyHex = 0x72 elif self.shortcutKey == "F4": self.shortcutKeyHex = 0x73 elif self.shortcutKey == "F5": self.shortcutKeyHex = 0x74 elif self.shortcutKey == "F6": self.shortcutKeyHex = 0x75 elif self.shortcutKey == "F7": self.shortcutKeyHex = 0x76 elif self.shortcutKey == "F8": self.shortcutKeyHex = 0x77 elif self.shortcutKey == "F9": self.shortcutKeyHex = 0x78 elif self.shortcutKey == "F10": self.shortcutKeyHex = 0x79 elif self.shortcutKey == "1": self.shortcutKeyHex = 0x31 elif self.shortcutKey == "2": self.shortcutKeyHex = 0x32 elif self.shortcutKey == "3": self.shortcutKeyHex = 0x33 elif self.shortcutKey == "4": self.shortcutKeyHex = 0x34 elif self.shortcutKey == "5": self.shortcutKeyHex = 0x35 elif self.shortcutKey == "6": self.shortcutKeyHex = 0x36 elif self.shortcutKey == "7": self.shortcutKeyHex = 0x37 elif self.shortcutKey == "8": self.shortcutKeyHex = 0x38 elif self.shortcutKey == "9": self.shortcutKeyHex = 0x39 elif self.shortcutKey == "0": self.shortcutKeyHex = 0x30 def create_actions(self): """ Slot connectors for all right clicking and other actions. """ self.minimizeAction.triggered.connect(self.hide) self.maximizeAction.triggered.connect(self.showMaximized) self.settingsAction.triggered.connect(self.showNormal) self.aboutAction.triggered.connect(self.show_about) self.quitAction.triggered.connect(self.quit) def quit(self): self.engine.un_hook() exit(0) def create_tray_icon(self): """ Tray icon creator and corresponding connectors """ self.trayIconMenu.addAction(self.settingsAction) self.trayIconMenu.addSeparator() self.trayIconMenu.addAction(self.aboutAction) self.trayIconMenu.addSeparator() self.trayIconMenu.addAction(self.quitAction) self.trayIcon.setContextMenu(self.trayIconMenu) def setVisible(self, visible): self.settingsAction.setEnabled(self.isMaximized() or not visible) super(EKWindow, self).setVisible(visible) def closeEvent(self, event): if self.trayIcon.isVisible(): self.hide() event.ignore() def load_keyboard(self): """ Mapping file loading function """ if self.selectedKeyboard == 1: self.fileName = "tables/Tamil-tamil99.txt.in" elif self.selectedKeyboard == 2: self.fileName = "tables/Tamil-phonetic.txt.in" elif self.selectedKeyboard == 3: self.fileName = "tables/Tamil-typewriter.txt.in" elif self.selectedKeyboard == 4: self.fileName = "tables/Tamil-bamini.txt.in" elif self.selectedKeyboard == 5: self.fileName = "tables/Tamil-inscript.txt.in" else: pass def getPath(self, index): if index == 1: self.path = "tables/Tamil-tamil99.txt.in" elif index == 2: self.path = "tables/Tamil-phonetic.txt.in" elif index == 3: self.path = "tables/Tamil-typewriter.txt.in" elif index == 4: self.path = "tables/Tamil-bamini.txt.in" elif index == 5: self.path = "tables/Tamil-inscript.txt.in" else: pass def change_keyboard(self, index): """ Function to change the keyboard based on the index which was sent as a param """ if int(index) != 0: self.iniSettings.setValue("selected_keyboard", index) self.selectedKeyboard = index self.iconComboBox.setCurrentIndex(int(index)) icon = self.iconComboBox.itemIcon(int(index)) self.trayIcon.setIcon(icon) self.setWindowIcon(icon) self.trayIcon.setToolTip(self.iconComboBox.itemText(int(index))) self.show_tray_message(index) self.load_keyboard() if int(index) != 0: self.getPath(int(index)) self.engine.file_name = self.path self.engine.initialize() self.engine.conv_state = True else: try: self.engine.conv_state = False except: pass def icon_activated(self, reason): """ Function to toggle the state when the icon is clicked or shortcut key is pressed """ if reason == QSystemTrayIcon.DoubleClick: pass elif reason == QSystemTrayIcon.Trigger: if self.keyboardStatus: self.keyboardStatus = False else: self.keyboardStatus = True if self.keyboardStatus: self.change_keyboard(self.selectedKeyboard) else: self.change_keyboard(0) elif reason == QSystemTrayIcon.MiddleClick: pass else: pass def show_tray_message(self, index): """ Tray message generator when there is change in keyboard state """ icon = QSystemTrayIcon.MessageIcon(0) message = self.iconComboBox.itemText(int(index)) + " set" self.trayIcon.showMessage(qApp.applicationName() + " " + qApp.applicationVersion(), message, icon, 100) def checkbox_start_with_windows_ticked(self): """ Function to add or disable registry entry to auto start ekalappai with windows for the current users """ if self.checkboxStartWithWindows.isChecked(): self.registrySettings.setValue(qApp.applicationName(), qApp.applicationFilePath()) else: self.registrySettings.remove(qApp.applicationName()) def show_about(self): pass def set_shortcut_modifier(self, index): """ Function to set the shortcut modifier when its changed. """ self.iniSettings.setValue("shortcut_modifier", self.shortcutComboBox1.currentText()) self.shortcutModifierKey = self.iniSettings.value("shortcut_modifier") # if none is selected, the allowed single key shortcuts should change if index == 0: self.shortcutComboBox2.clear() self.shortcutComboBox2.addItem("ESC") self.shortcutComboBox2.addItem("F1") self.shortcutComboBox2.addItem("F2") self.shortcutComboBox2.addItem("F3") self.shortcutComboBox2.addItem("F4") self.shortcutComboBox2.addItem("F5") self.shortcutComboBox2.addItem("F6") self.shortcutComboBox2.addItem("F7") self.shortcutComboBox2.addItem("F8") self.shortcutComboBox2.addItem("F9") self.shortcutComboBox2.addItem("F10") else: self.shortcutComboBox2.clear() self.shortcutComboBox2.addItem("1") self.shortcutComboBox2.addItem("2") self.shortcutComboBox2.addItem("3") self.shortcutComboBox2.addItem("4") self.shortcutComboBox2.addItem("5") self.shortcutComboBox2.addItem("6") self.shortcutComboBox2.addItem("7") self.shortcutComboBox2.addItem("8") self.shortcutComboBox2.addItem("9") self.shortcutComboBox2.addItem("0") self.register_shortcut_listener() def register_shortcut_listener(self): self.engine.event_queue.remove_all() if self.iniSettings.value("shortcut_modifier") == "NONE": self.engine.event_queue.register_event([[self.shortcutKey], self.icon_activated, QSystemTrayIcon.Trigger]) elif self.iniSettings.value("shortcut_modifier") == "CTRL": self.engine.event_queue.register_event([['Lcontrol', self.shortcutKey], self.icon_activated, QSystemTrayIcon.Trigger]) self.engine.event_queue.register_event([['Rcontrol', self.shortcutKey], self.icon_activated, QSystemTrayIcon.Trigger]) elif self.iniSettings.value("shortcut_modifier") == "ALT": self.engine.event_queue.register_event([['LMenu', self.shortcutKey], self.icon_activated, QSystemTrayIcon.Trigger]) self.engine.event_queue.register_event([['RMenu', self.shortcutKey], self.icon_activated, QSystemTrayIcon.Trigger]) return True
class ConditionEditor(QWidget): # {{{ ACTION_MAP = { 'bool' : ( (_('is true'), 'is true',), (_('is false'), 'is false'), (_('is undefined'), 'is undefined') ), 'ondevice' : ( (_('is true'), 'is set',), (_('is false'), 'is not set'), ), 'identifiers' : ( (_('has id'), 'has id'), (_('does not have id'), 'does not have id'), ), 'int' : ( (_('is equal to'), 'eq'), (_('is less than'), 'lt'), (_('is greater than'), 'gt') ), 'datetime' : ( (_('is equal to'), 'eq'), (_('is less than'), 'lt'), (_('is greater than'), 'gt'), (_('is set'), 'is set'), (_('is not set'), 'is not set'), (_('is more days ago than'), 'older count days'), (_('is fewer days ago than'), 'count_days'), (_('is more days from now than'), 'newer future days'), (_('is fewer days from now than'), 'older future days') ), 'multiple' : ( (_('has'), 'has'), (_('does not have'), 'does not have'), (_('has pattern'), 'has pattern'), (_('does not have pattern'), 'does not have pattern'), (_('is set'), 'is set'), (_('is not set'), 'is not set'), ), 'single' : ( (_('is'), 'is'), (_('is not'), 'is not'), (_('contains'), 'contains'), (_('does not contain'), 'does not contain'), (_('matches pattern'), 'matches pattern'), (_('does not match pattern'), 'does not match pattern'), (_('is set'), 'is set'), (_('is not set'), 'is not set'), ), } for x in ('float', 'rating'): ACTION_MAP[x] = ACTION_MAP['int'] def __init__(self, fm, parent=None): QWidget.__init__(self, parent) self.fm = fm self.action_map = self.ACTION_MAP self.l = l = QGridLayout(self) self.setLayout(l) texts = _('If the ___ column ___ values') try: one, two, three = texts.split('___') except: one, two, three = 'If the ', ' column ', ' value ' self.l1 = l1 = QLabel(one) l.addWidget(l1, 0, 0) self.column_box = QComboBox(self) l.addWidget(self.column_box, 0, 1) self.l2 = l2 = QLabel(two) l.addWidget(l2, 0, 2) self.action_box = QComboBox(self) l.addWidget(self.action_box, 0, 3) self.l3 = l3 = QLabel(three) l.addWidget(l3, 0, 4) self.value_box = QLineEdit(self) l.addWidget(self.value_box, 0, 5) self.column_box.addItem('', '') for key in sorted( conditionable_columns(fm), key=lambda key: sort_key(fm[key]['name'])): self.column_box.addItem(fm[key]['name'], key) self.column_box.setCurrentIndex(0) self.column_box.currentIndexChanged.connect(self.init_action_box) self.action_box.currentIndexChanged.connect(self.init_value_box) for b in (self.column_box, self.action_box): b.setSizeAdjustPolicy(b.AdjustToMinimumContentsLengthWithIcon) b.setMinimumContentsLength(20) @dynamic_property def current_col(self): def fget(self): idx = self.column_box.currentIndex() return unicode_type(self.column_box.itemData(idx) or '') def fset(self, val): for idx in range(self.column_box.count()): c = unicode_type(self.column_box.itemData(idx) or '') if c == val: self.column_box.setCurrentIndex(idx) return raise ValueError('Column %r not found'%val) return property(fget=fget, fset=fset) @dynamic_property def current_action(self): def fget(self): idx = self.action_box.currentIndex() return unicode_type(self.action_box.itemData(idx) or '') def fset(self, val): for idx in range(self.action_box.count()): c = unicode_type(self.action_box.itemData(idx) or '') if c == val: self.action_box.setCurrentIndex(idx) return raise ValueError('Action %r not valid for current column'%val) return property(fget=fget, fset=fset) @property def current_val(self): ans = unicode_type(self.value_box.text()).strip() if self.current_col == 'languages': rmap = {lower(v):k for k, v in lang_map().iteritems()} ans = rmap.get(lower(ans), ans) return ans @dynamic_property def condition(self): def fget(self): c, a, v = (self.current_col, self.current_action, self.current_val) if not c or not a: return None return (c, a, v) def fset(self, condition): c, a, v = condition if not v: v = '' v = v.strip() self.current_col = c self.current_action = a self.value_box.setText(v) return property(fget=fget, fset=fset) def init_action_box(self): self.action_box.blockSignals(True) self.action_box.clear() self.action_box.addItem('', '') col = self.current_col if col: m = self.fm[col] dt = m['datatype'] if dt in self.action_map: actions = self.action_map[dt] else: if col == 'ondevice': k = 'ondevice' elif col == 'identifiers': k = 'identifiers' else: k = 'multiple' if m['is_multiple'] else 'single' actions = self.action_map[k] for text, key in actions: self.action_box.addItem(text, key) self.action_box.setCurrentIndex(0) self.action_box.blockSignals(False) self.init_value_box() def init_value_box(self): self.value_box.setEnabled(True) self.value_box.setText('') self.value_box.setInputMask('') self.value_box.setValidator(None) col = self.current_col if not col: return action = self.current_action if not action: return m = self.fm[col] dt = m['datatype'] tt = '' if col == 'identifiers': tt = _('Enter either an identifier type or an ' 'identifier type and value of the form identifier:value') elif col == 'languages': tt = _('Enter a 3 letter ISO language code, like fra for French' ' or deu for German or eng for English. You can also use' ' the full language name, in which case calibre will try to' ' automatically convert it to the language code.') elif dt in ('int', 'float', 'rating'): tt = _('Enter a number') v = QIntValidator if dt == 'int' else QDoubleValidator self.value_box.setValidator(v(self.value_box)) elif dt == 'datetime': if action == 'count_days': self.value_box.setValidator(QIntValidator(self.value_box)) tt = _('Enter the maximum days old the item can be. Zero is today. ' 'Dates in the future always match') elif action == 'older count days': self.value_box.setValidator(QIntValidator(self.value_box)) tt = _('Enter the minimum days old the item can be. Zero is today. ' 'Dates in the future never match') elif action == 'older future days': self.value_box.setValidator(QIntValidator(self.value_box)) tt = _('Enter the maximum days in the future the item can be. ' 'Zero is today. Dates in the past always match') elif action == 'newer future days': self.value_box.setValidator(QIntValidator(self.value_box)) tt = _('Enter the minimum days in the future the item can be. ' 'Zero is today. Dates in the past never match') else: self.value_box.setInputMask('9999-99-99') tt = _('Enter a date in the format YYYY-MM-DD') else: tt = _('Enter a string.') if 'pattern' in action: tt = _('Enter a regular expression') elif m.get('is_multiple', False): tt += '\n' + _('You can match multiple values by separating' ' them with %s')%m['is_multiple']['ui_to_list'] self.value_box.setToolTip(tt) if action in ('is set', 'is not set', 'is true', 'is false', 'is undefined'): self.value_box.setEnabled(False)
class MainWin(QMainWindow): def __init__(self, fileName=None, logName=None, parent=None): super(MainWin, self).__init__(parent) #self.setWindowIcon(QIcon(':/images/logo.png')) self.setToolButtonStyle(Qt.ToolButtonFollowStyle) self.setupFileActions() self.setupEditActions() self.setupTextActions() self.setupRunActions() self.initializeSettings() self.populateRunSettings() # FIXME put in initializeSettings()? settingsMenu = QMenu('Settings', self) self.menuBar().addMenu(settingsMenu) settingsMenu.addAction('Configure...', self.configure) helpMenu = QMenu("Help", self) self.menuBar().addMenu(helpMenu) helpMenu.addAction("About", self.about) helpMenu.addAction("About &Qt", QApplication.instance().aboutQt) self.splitter = QSplitter(self) self.splitter.setOrientation(Qt.Vertical) self.textPane = TextPane() self.logPane = LogPane() self.logBox = QGroupBox() self.logBox.setFlat(True) vbox = QVBoxLayout() vbox.addWidget(self.logPane) self.logBox.setLayout(vbox) self.splitter.addWidget(self.textPane) self.splitter.addWidget(QLabel()) # spacer self.splitter.addWidget(self.logBox) self.setCentralWidget(self.splitter) self.loadSrc(fileName) self.loadLog(logName) #if logName and (-1 == self.comboLogFile.findText(logName)): #self.comboLogFile.addItem(logName) self.logPane.setFocus() self.fontChanged(self.textPane.font()) self.textPane.document().modificationChanged.connect(self.actionSave.setEnabled) self.textPane.document().modificationChanged.connect(self.setWindowModified) self.textPane.document().undoAvailable.connect(self.actionUndo.setEnabled) self.textPane.document().redoAvailable.connect( self.actionRedo.setEnabled) self.setWindowModified(self.textPane.document().isModified()) self.actionSave.setEnabled(self.textPane.document().isModified()) self.actionUndo.setEnabled(self.textPane.document().isUndoAvailable()) self.actionRedo.setEnabled(self.textPane.document().isRedoAvailable()) self.actionUndo.triggered.connect(self.textPane.undo) self.actionRedo.triggered.connect(self.textPane.redo) self.actionCut.setEnabled(False) self.actionCopy.setEnabled(False) self.actionCut.triggered.connect(self.textPane.cut) self.actionCopy.triggered.connect(self.textPane.copy) self.actionPaste.triggered.connect(self.textPane.paste) self.textPane.copyAvailable.connect(self.actionCut.setEnabled) self.textPane.copyAvailable.connect(self.actionCopy.setEnabled) QApplication.clipboard().dataChanged.connect(self.clipboardDataChanged) self.actionRun.triggered.connect(self.scannoCheck) self.logPane.lineMatchChanged.connect(self.logLineMatchChanged) def closeEvent(self, e): if self.maybeSave(): e.accept() else: e.ignore() def setupFileActions(self): tb = QToolBar(self) tb.setWindowTitle("File Actions") self.addToolBar(tb) menu = QMenu("&File", self) self.menuBar().addMenu(menu) self.actionNew = QAction("&New", self, priority=QAction.LowPriority, shortcut=QKeySequence.New, triggered=self.fileNew) tb.addAction(self.actionNew) menu.addAction(self.actionNew) self.actionOpen = QAction("&Open...", self, shortcut=QKeySequence.Open, triggered=self.fileOpen) tb.addAction(self.actionOpen) menu.addAction(self.actionOpen) menu.addSeparator() self.actionSave = QAction("&Save", self, shortcut=QKeySequence.Save, triggered=self.fileSave, enabled=False) tb.addAction(self.actionSave) menu.addAction(self.actionSave) self.actionSaveAs = QAction("Save &As...", self, priority=QAction.LowPriority, shortcut=Qt.CTRL + Qt.SHIFT + Qt.Key_S, triggered=self.fileSaveAs) menu.addAction(self.actionSaveAs) menu.addSeparator() self.actionQuit = QAction("&Quit", self, shortcut=QKeySequence.Quit, triggered=self.close) menu.addAction(self.actionQuit) def setupEditActions(self): tb = QToolBar(self) tb.setWindowTitle("Edit Actions") self.addToolBar(tb) menu = QMenu("&Edit", self) self.menuBar().addMenu(menu) self.actionUndo = QAction("&Undo", self, shortcut=QKeySequence.Undo) tb.addAction(self.actionUndo) menu.addAction(self.actionUndo) self.actionRedo = QAction("&Redo", self, priority=QAction.LowPriority, shortcut=QKeySequence.Redo) tb.addAction(self.actionRedo) menu.addAction(self.actionRedo) menu.addSeparator() self.actionCut = QAction("Cu&t", self, priority=QAction.LowPriority, shortcut=QKeySequence.Cut) tb.addAction(self.actionCut) menu.addAction(self.actionCut) self.actionCopy = QAction("&Copy", self, priority=QAction.LowPriority, shortcut=QKeySequence.Copy) tb.addAction(self.actionCopy) menu.addAction(self.actionCopy) self.actionPaste = QAction("&Paste", self, priority=QAction.LowPriority, shortcut=QKeySequence.Paste, enabled=(len(QApplication.clipboard().text()) != 0)) tb.addAction(self.actionPaste) menu.addAction(self.actionPaste) def setupTextActions(self): tb = QToolBar(self) tb.setWindowTitle("Format Actions") self.addToolBar(tb) tb = QToolBar(self) tb.setAllowedAreas(Qt.TopToolBarArea | Qt.BottomToolBarArea) tb.setWindowTitle("Format Actions") self.addToolBarBreak(Qt.TopToolBarArea) self.addToolBar(tb) self.comboFont = QFontComboBox(tb) tb.addWidget(self.comboFont) self.comboFont.activated[str].connect(self.textFamily) self.comboSize = QComboBox(tb) self.comboSize.setObjectName("comboSize") tb.addWidget(self.comboSize) self.comboSize.setEditable(True) db = QFontDatabase() for size in db.standardSizes(): self.comboSize.addItem('{}'.format(size)) self.comboSize.activated[str].connect(self.textSize) self.comboSize.setCurrentIndex(self.comboSize.findText('{}'.format(QApplication.font().pointSize()))) def setupRunActions(self): tb = QToolBar(self) tb.setWindowTitle("Run Actions") self.addToolBar(tb) menu = QMenu("Run", self) self.menuBar().addMenu(menu) self.actionRun = QAction( "&Run", self, shortcut=Qt.CTRL + Qt.Key_R) tb.addAction(self.actionRun) menu.addAction(self.actionRun) self.comboScannoFile = QComboBox(tb) self.comboScannoFile.setObjectName("comboScannoFile") tb.addWidget(self.comboScannoFile) self.comboScannoFile.setEditable(True) self.comboLogFile= QComboBox(tb) self.comboLogFile.setObjectName("comboLogFile") self.comboLogFile.setEditable(True) tb.addWidget(self.comboLogFile) def populateRunSettings(self): for f in self.scannoFiles(): self.comboScannoFile.addItem(f) if self.defaultScannoFile: idx = self.comboScannoFile.findText(self.defaultScannoFile) self.comboScannoFile.setCurrentIndex(idx) self.comboLogFile.addItem('plog.txt') def loadSrc(self, src): if src: if not self.textPane.load(src): return False self.setCurrentFileName(src) return True def loadLog(self, log): if log: if not self.logPane.load(log): return False self.comboLogFile.clear() self.comboLogFile.addItem(log) else: self.logPane.clear() self.logPane.setEnabled(False) self.logBox.setTitle(self.tr('No log file loaded.')) return True def maybeSave(self): if not self.textPane.document().isModified(): return True ret = QMessageBox.warning(self, 'GuiScannos', 'The document has been modified.\n' 'Do you want to save your changes?', QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel) if ret == QMessageBox.Save: return self.fileSave() if ret == QMessageBox.Cancel: return False return True def setCurrentFileName(self, fileName=''): self.fileName = fileName self.textPane.document().setModified(False) if not fileName: shownName = 'untitled.txt' self.actionRun.setEnabled(False) else: shownName = QFileInfo(fileName).fileName() self.actionRun.setEnabled(True) self.setWindowTitle(self.tr('{}[*] - {}'.format(shownName, 'GUI Scannos'))) self.setWindowModified(False) def fileNew(self): if self.maybeSave(): self.textPane.clear() self.loadLog(None) # clears logPane, logBox title, etc self.setCurrentFileName() def fileOpen(self): fn, _ = QFileDialog.getOpenFileName(self, 'Open File...', None, 'Text Files (*.txt);;All Files (*)') if fn: self.loadSrc(fn) self.loadLog(None) # clears logPane, logBox title, etc def fileSave(self): if not self.fileName: return self.fileSaveAs() return self.textpane.save(self.fileName) def fileSaveAs(self): fn, _ = QFileDialog.getSaveFileName(self, "Save as...", None, "text files (*.txt);;All Files (*)") if not fn: return False self.setCurrentFileName(fn) return self.fileSave() def logLineMatchChanged(self): linenum = self.logPane.srcLineNum() col = self.logPane.srcColNum() s = self.logPane.srcScanno() self.textPane.setSelection(linenum, col, len(s)) def textFamily(self, family): """Set font family for text and log panes.""" self.textPane.setFontFamily(family) self.logPane.setFontFamily(family) def textSize(self, pointSize): """Set font size for text and log panes.""" self.textPane.setFontPointSize(pointSize) self.logPane.setFontPointSize(pointSize) def clipboardDataChanged(self): self.actionPaste.setEnabled(len(QApplication.clipboard().text()) != 0) def about(self): QMessageBox.about(self, 'About', 'GUI for ppscannos.') def fontChanged(self, font): self.comboFont.setCurrentIndex(self.comboFont.findText(QFontInfo(font).family())) self.comboSize.setCurrentIndex(self.comboSize.findText('{}'.format(font.pointSize()))) def scannoCheck(self): """Run ppscannos.""" scannodir = os.path.dirname(self.ppscannos) cmd = sys.executable assert(cmd) scannoFile = self.comboScannoFile.currentText() if not scannoFile: scannoFile = self.defaultScannoFile scannoFile = scannodir + '/' + scannoFile src = self.fileName log = self.comboLogFile.currentText() if not log: log = './plog.txt' subprocess.call([cmd, self.ppscannos, '-s' + scannoFile, '-o' + log, '-i' + src]) self.loadLog(log) self.logPane.setEnabled(True) def configure(self): """Configure application settings by way of a dialog.""" dlg = ConfigDialog() if dlg.exec(): self.setPPScannos(dlg.lineEditPPScannos.text()) self.setDefaultScannoFile(dlg.comboScannoFiles.currentText()) settings = QSettings(QApplication.organizationName(), QApplication.applicationName()) settings.setValue('ppscannos', self.ppscannos) settings.setValue('defaultScannoFile', self.defaultScannoFile) def setPPScannos(self, s): self.ppscannos = s self.actionRun.setEnabled(self.ppscannos and os.path.exists(self.ppscannos)) def scannoFiles(self): """Return list of .rc filenames (without path) that are in ppscannos directory.""" if not self.ppscannos: return [] return getRCFilesForDir(os.path.dirname(self.ppscannos)) def setDefaultScannoFile(self, s): self.defaultScannoFile = s valid = False if self.defaultScannoFile and self.ppscannos and os.path.exists(self.ppscannos): if os.path.exists(os.path.dirname(self.ppscannos) + '/' + self.defaultScannoFile): valid = True self.actionRun.setEnabled(valid) def initializeSettings(self): """Load persistent config settings.""" settings = QSettings() s = settings.value('ppscannos', type=str) if not s: # try the default s = os.path.expanduser('~') + '/ppscannos1/ppscannos1.py' #s = os.environ['HOME'] + '/ppscannos1/ppscannos1.py' self.setPPScannos(s) s = settings.value('defaultScannoFile', type=str) if (not s) and self.ppscannos: # try the default lst = getRCFilesForDir(os.path.dirname(self.ppscannos)) if len(lst): # prefer 'regex.rc'; otherwise use the first one s = lst[0] for f in lst: if f == 'regex.rc': s = f break self.setDefaultScannoFile(s)