def go_to_definition(self): self.dirty = True self.results = [] locations = self.get_locations() if self._isVariable: preResults = [ [file_manager.get_basename(x.path), x.path, x.lineno, ''] for x in locations if (x.type == FILTERS['attribs']) and (x.name == self._search)] else: preResults = [ [file_manager.get_basename(x.path), x.path, x.lineno, ''] for x in locations if ((x.type == FILTERS['functions']) or (x.type == FILTERS['classes'])) and (x.name.startswith(self._search))] for data in preResults: file_object = QFile(data[1]) if not file_object.open(QFile.ReadOnly): return stream = QTextStream(file_object) line_index = 0 line = stream.readLine() while not self._cancel and not stream.atEnd(): if line_index == data[2]: data[3] = line self.results.append(data) break #take the next line! line = stream.readLine() line_index += 1
def findFiles(self, files, text): progressDialog = QProgressDialog(self) progressDialog.setCancelButtonText("&Cancel") progressDialog.setRange(0, files.count()) progressDialog.setWindowTitle("Find Files") foundFiles = [] for i in range(files.count()): progressDialog.setValue(i) progressDialog.setLabelText("Searching file number %d of %d..." % (i, files.count())) QApplication.processEvents() if progressDialog.wasCanceled(): break inFile = QFile(self.currentDir.absoluteFilePath(files[i])) if inFile.open(QIODevice.ReadOnly): stream = QTextStream(inFile) while not stream.atEnd(): if progressDialog.wasCanceled(): break line = stream.readLine() if text in line: foundFiles.append(files[i]) break progressDialog.close() return foundFiles
def save(self): if "Unnamed" in self.filename: filename = QFileDialog.getSaveFileName(self, "G.R.O.M. Editor -- Save File As", self.filename, "MD files (*.mdp *.itp *.top *.*)") print('filename is ', filename) if len(filename[0]) == 0: return self.filename = filename[0] self.setWindowTitle(QFileInfo(self.filename).fileName()) exception = None fh = None try: fh = QFile(self.filename) if not fh.open(QIODevice.WriteOnly): raise IOError(str(fh.errorString())) stream = QTextStream(fh) stream.setCodec("UTF-8") stream << self.toPlainText() self.document().setModified(False) except EnvironmentError as e: exception = e finally: if fh is not None: fh.close() if exception is not None: raise exception
def load_stylesheet_pyqt5(): """ Loads the stylesheet for use in a pyqt5 application. :param pyside: True to load the pyside rc file, False to load the PyQt rc file :return the stylesheet string """ # Smart import of the rc file import theme.pyqt5_style_rc # Load the stylesheet content from resources from PyQt5.QtCore import QFile, QTextStream f = QFile(":qdarkstyle/style.qss") if not f.exists(): _logger().error("Unable to load stylesheet, file not found in " "resources") return "" else: f.open(QFile.ReadOnly | QFile.Text) ts = QTextStream(f) stylesheet = ts.readAll() if platform.system().lower() == 'darwin': # see issue #12 on github mac_fix = ''' QDockWidget::title { background-color: #353434; text-align: center; height: 12px; } ''' stylesheet += mac_fix return stylesheet
def _grep_file(self, file_path, file_name): """Search for each line inside the file.""" if not self.by_phrase: with open(file_path, 'r') as f: content = f.read() words = [word for word in self.search_pattern.pattern().split('|')] words.insert(0, True) def check_whole_words(result, word): return result and content.find(word) != -1 if not reduce(check_whole_words, words): return file_object = QFile(file_path) if not file_object.open(QFile.ReadOnly): return stream = QTextStream(file_object) lines = [] line_index = 0 line = stream.readLine() while not self._cancel and not (stream.atEnd() and not line): column = self.search_pattern.indexIn(line) if column != -1: lines.append((line_index, line)) #take the next line! line = stream.readLine() line_index += 1 #emit a signal! relative_file_name = file_manager.convert_to_relative( self.root_dir, file_path) self.found_pattern.emit((relative_file_name, lines))
def openFile(self, path=None): if not path: path, _ = QFileDialog.getOpenFileName(self, "Choose a data file", '', '*.cht') if path: f = QFile(path) if f.open(QFile.ReadOnly | QFile.Text): stream = QTextStream(f) self.model.removeRows(0, self.model.rowCount(QModelIndex()), QModelIndex()) row = 0 line = stream.readLine() while line: self.model.insertRows(row, 1, QModelIndex()) pieces = line.split(',') self.model.setData(self.model.index(row, 0, QModelIndex()), pieces[0]) self.model.setData(self.model.index(row, 1, QModelIndex()), float(pieces[1])) self.model.setData(self.model.index(row, 0, QModelIndex()), QColor(pieces[2]), Qt.DecorationRole) row += 1 line = stream.readLine() f.close() self.statusBar().showMessage("Loaded %s" % path, 2000)
def readTextFromFile(self, fileName=None, encoding=None): previousFileName = self._fileName if fileName: self._fileName = fileName # Only try to detect encoding if it is not specified if encoding is None and globalSettings.detectEncoding: encoding = self.detectFileEncoding(self._fileName) # TODO: why do we open the file twice: for detecting encoding # and for actual read? Can we open it just once? openfile = QFile(self._fileName) openfile.open(QFile.ReadOnly) stream = QTextStream(openfile) encoding = encoding or globalSettings.defaultCodec if encoding: stream.setCodec(encoding) # If encoding is specified or detected, we should save the file with # the same encoding self.editBox.document().setProperty("encoding", encoding) text = stream.readAll() openfile.close() self.editBox.setPlainText(text) self.editBox.document().setModified(False) if previousFileName != self._fileName: self.updateActiveMarkupClass() self.fileNameChanged.emit()
def openFile(self): if settings.get("file_dialog_dir"): self.curDir = '~/' else: self.curDir = settings.get("file_dialog_dir") fn = QFileDialog.getOpenFileName(self, self.tr("Open File..."), self.curDir, self.tr("HTML-Files (*.htm *.html);;All Files (*)")) QApplication.setOverrideCursor(Qt.WaitCursor) if fn: self.lastFolder = os.path.dirname(fn) if os.path.exists(fn): if os.path.isfile(fn): f = QFile(fn) if not f.open(QIODevice.ReadOnly | QIODevice.Text): QtGui.QMessageBox.information(self.parent(), self.tr("Error - Lector"), self.tr("Can't open '%s.'" % fn)) else: stream = QTextStream(f) text = stream.readAll() self.setText(text) else: QMessageBox.information(self.parent(), self.tr("Error - Lector"), self.tr("'%s' is not a file." % fn)) QApplication.restoreOverrideCursor()
def __init__(self, ui_file, bus, devices=[], parent=None): QtWidgets.QMainWindow.__init__(self, parent=parent) self.bus = bus # TODO: CAMPid 980567566238416124867857834291346779 ico_file = os.path.join(QFileInfo.absolutePath(QFileInfo(__file__)), "icon.ico") ico = QtGui.QIcon(ico_file) self.setWindowIcon(ico) ui = ui_file # TODO: CAMPid 9549757292917394095482739548437597676742 if not QFileInfo(ui).isAbsolute(): ui_file = os.path.join(QFileInfo.absolutePath(QFileInfo(__file__)), ui) else: ui_file = ui ui_file = QFile(ui_file) ui_file.open(QFile.ReadOnly | QFile.Text) ts = QTextStream(ui_file) sio = io.StringIO(ts.readAll()) self.ui = uic.loadUi(sio, self) self.ui.action_About.triggered.connect(self.about) device_tree = epyqlib.devicetree.Tree() device_tree_model = epyqlib.devicetree.Model(root=device_tree) device_tree_model.device_removed.connect(self._remove_device) self.ui.device_tree.setModel(device_tree_model) self.ui.device_tree.device_selected.connect(self.set_current_device)
def write(self, tileset, fileName): file = QSaveFile(fileName) if (not file.open(QIODevice.WriteOnly | QIODevice.Text)): self.mError = self.tr("Could not open file for writing.") return False converter = MapToVariantConverter() variant = converter.toVariant(tileset, QFileInfo(fileName).dir()) writer = json try: result = writer.dumps(variant, indent=4) except: # This can only happen due to coding error self.mError = self.tr('Unknow error.') return False out = QTextStream(file) out << result out.flush() if (file.error() != QFile.NoError): self.mError = self.tr("Error while writing file:\n%1").arg(file.errorString()) return False if (not file.commit()): self.mError = file.errorString() return False return True
def set_window_style(window): """ :return the stylesheet string """ # Smart import of the rc file f = QFile(":dark_style.qss") if not f.exists(): print('Custom stylesheet not present') Lumberjack.error("Unable to load stylesheet, file not found in " "resources") return "" else: f.open(QFile.ReadOnly | QFile.Text) ts = QTextStream(f) stylesheet = ts.readAll() if platform.system().lower() == 'darwin': # see issue #12 on github mac_fix = ''' QDockWidget::title { background-color: #31363b; text-align: center; height: 12px; } ''' stylesheet += mac_fix window.setWindowIcon(QIcon(':/app_icons/rc/PAT_icon.png')) window.setStyleSheet(stylesheet)
def save(self, content, path=None): """ Write a temporary file with .tnj extension and copy it over the original one. .nsf = Ninja Swap File # FIXME: Where to locate addExtension, does not fit here """ new_path = False if path: self.attach_to_path(path) new_path = True save_path = self._file_path if not save_path: raise NinjaNoFileNameException("I am asked to write a " "file but no one told me where") swap_save_path = "%s.nsp" % save_path # If we have a file system watcher, remove the file path # from its watch list until we are done making changes. if self.__watcher is not None: self.__watcher.removePath(save_path) flags = QIODevice.WriteOnly | QIODevice.Truncate f = QFile(swap_save_path) if settings.use_platform_specific_eol(): flags |= QIODevice.Text if not f.open(flags): raise NinjaIOException(f.errorString()) stream = QTextStream(f) encoding = get_file_encoding(content) if encoding: stream.setCodec(encoding) encoded_stream = stream.codec().fromUnicode(content) f.write(encoded_stream) f.flush() f.close() # SIGNAL: Will save (temp, definitive) to warn folder to do something self.willSave.emit(swap_save_path, save_path) self.__mtime = os.path.getmtime(swap_save_path) shutil.move(swap_save_path, save_path) self.reset_state() # If we have a file system watcher, add the saved path back # to its watch list, otherwise create a watcher and start # watching if self.__watcher is not None: if new_path: # self.__watcher.removePath(self.__watcher.files()[0]) self.__watcher.addPath(self._file_path) else: self.__watcher.addPath(save_path) else: self.start_watching() return self
def ReadTextFile(filePath): file = QFile(filePath) file.open(QFile.ReadOnly | QFile.Text) textStream = QTextStream(file) data = textStream.readAll() file.close() return data
def readFile(self, path, coding = "UTF-8"): """读取文件""" file = QFile(path) file.open(QIODevice.ReadOnly | QIODevice.Text) fin = QTextStream(file) fin.setCodec(coding) data = fin.readAll() file.close() return data
def loadStyle(stylesheet): if stylesheet not in StyleSheets.keys(): raise RuntimeError('Invalid stylesheet (%s)' %stylesheet) f = QFile(StyleSheets[stylesheet]) f.open(QFile.ReadOnly | QFile.Text) ts = QTextStream(f) return ts.readAll()
def ReadResourceTextFile(resFile): res = QResource(resFile) file = QFile(res.absoluteFilePath()) file.open(QFile.ReadOnly | QFile.Text) textStream = QTextStream(file) data = textStream.readAll() file.close() return data
def ouvrirtexte(self): filename, _ = QFileDialog.getOpenFileName(self) if filename: file = QFile(filename) if not file.open(QFile.ReadOnly | QFile.Text): QMessageBox.critical(self, appname + version + "Open File", "Reading Error %s:\n%s." % (filename, file.errorString())) return instr = QTextStream(file) self.ui.plainTextEdit.setPlainText(instr.readAll())
def loadFile(self): fh = QFile(self.filename) print("fh is ", fh) if not fh.open(QIODevice.ReadOnly): raise IOError(str(fh.errorString())) stream = QTextStream(fh) stream.setCodec("UTF-8") # self.setPlainText("Hello World") self.preParse = (stream.readAll()) # Here lies the problem how to fix it? PyQt 3.4.2 Works Fine print(self.preParse) self.parseOutputData(self.preParse)
def __init__(self, parent): QThread.__init__(self, parent) self.fCloseNow = False self.fPurgeLogs = False self.fRealParent = parent # ------------------------------------------------------------- # Take some values from Logs Window self.LOG_FILE_JACK = LogsW.LOG_FILE_JACK self.LOG_FILE_A2J = LogsW.LOG_FILE_A2J self.LOG_FILE_LASH = LogsW.LOG_FILE_LASH self.LOG_FILE_LADISH = LogsW.LOG_FILE_LADISH # ------------------------------------------------------------- # Init logs if self.LOG_FILE_JACK is not None: self.fLogFileJACK = QFile(self.LOG_FILE_JACK) self.fLogFileJACK.open(QIODevice.ReadOnly) self.fLogStreamJACK = QTextStream(self.fLogFileJACK) self.fLogStreamJACK.setCodec("UTF-8") if self.fLogFileJACK.size() > self.MAX_INITIAL_SIZE: self.fLogStreamJACK.seek(self.fLogFileJACK.size() - self.MAX_INITIAL_SIZE) if self.LOG_FILE_A2J is not None: self.fLogFileA2J = QFile(self.LOG_FILE_A2J) self.fLogFileA2J.open(QIODevice.ReadOnly) self.fLogStreamA2J = QTextStream(self.fLogFileA2J) self.fLogStreamA2J.setCodec("UTF-8") if self.fLogFileA2J.size() > self.MAX_INITIAL_SIZE: self.fLogStreamA2J.seek(self.fLogFileA2J.size() - self.MAX_INITIAL_SIZE) if self.LOG_FILE_LASH is not None: self.fLogFileLASH = QFile(self.LOG_FILE_LASH) self.fLogFileLASH.open(QIODevice.ReadOnly) self.fLogStreamLASH = QTextStream(self.fLogFileLASH) self.fLogStreamLASH.setCodec("UTF-8") if self.fLogFileLASH.size() > self.MAX_INITIAL_SIZE: self.fLogStreamLASH.seek(self.fLogFileLASH.size() - self.MAX_INITIAL_SIZE) if self.LOG_FILE_LADISH is not None: self.fLogFileLADISH = QFile(self.LOG_FILE_LADISH) self.fLogFileLADISH.open(QIODevice.ReadOnly) self.fLogStreamLADISH = QTextStream(self.fLogFileLADISH) self.fLogStreamLADISH.setCodec("UTF-8") if self.fLogFileLADISH.size() > self.MAX_INITIAL_SIZE: self.fLogStreamLADISH.seek(self.fLogFileLADISH.size() - self.MAX_INITIAL_SIZE)
def readExtension(self, fileName): extFile = QFile(fileName) extFile.open(QIODevice.ReadOnly) extension = {} stream = QTextStream(extFile) while not stream.atEnd(): line = stream.readLine() if '=' in line: index = line.index('=') extension[line[:index].rstrip()] = line[index+1:].lstrip() extFile.close() return extension
def _autosave(self): if self._neditable.editor.is_modified: flags = QIODevice.WriteOnly f = QFile(self.filename()) if not f.open(flags): raise IOError(f.errorString()) content = self._neditable.editor.text stream = QTextStream(f) encoded_stream = stream.codec().fromUnicode(content) f.write(encoded_stream) f.flush() f.close()
def writeTextToFile(self, fileName=None): # Just writes the text to file, without any changes to tab object # Used directly for i.e. export extensions savefile = QFile(fileName or self._fileName) result = savefile.open(QFile.WriteOnly) if result: savestream = QTextStream(savefile) if globalSettings.defaultCodec: savestream.setCodec(globalSettings.defaultCodec) savestream << self.editBox.toPlainText() savefile.close() return result
def saveFileCore(self, fn): self.fileSystemWatcher.removePath(fn) savefile = QFile(fn) result = savefile.open(QIODevice.WriteOnly) if result: savestream = QTextStream(savefile) if globalSettings.defaultCodec: savestream.setCodec(globalSettings.defaultCodec) savestream << self.editBoxes[self.ind].toPlainText() savefile.close() self.fileSystemWatcher.addPath(fn) return result
def read(self): """ Reads the file and returns the content """ _file = QFile(self.filename) if not _file.open(QIODevice.ReadOnly | QIODevice.Text): raise Exception(_file.errorString()) # Codec codec = QTextCodec.codecForLocale() stream = QTextStream(_file) stream.setCodec(codec) return stream.readAll()
def readTextFromFile(self, encoding=None): openfile = QFile(self.fileName) openfile.open(QFile.ReadOnly) stream = QTextStream(openfile) encoding = encoding or globalSettings.defaultCodec if encoding: stream.setCodec(encoding) text = stream.readAll() openfile.close() markupClass = get_markup_for_file_name(self.fileName, return_class=True) self.setMarkupClass(markupClass) modified = bool(encoding) and (self.editBox.toPlainText() != text) self.editBox.setPlainText(text) self.editBox.document().setModified(modified)
def loadFile(self, fileName): file = QFile(fileName) if not file.open(QFile.ReadOnly | QFile.Text): QMessageBox.warning(self, "Application", "Cannot read file %s:\n%s." % (fileName, file.errorString())) return inf = QTextStream(file) QApplication.setOverrideCursor(Qt.WaitCursor) self.textEdit.setPlainText(inf.readAll()) QApplication.restoreOverrideCursor() self.setCurrentFile(fileName) self.statusBar().showMessage("File loaded", 2000)
def loadFile(self, filePath): ret = True absPath = QFileInfo(filePath).path() rulesFile = QFile(filePath) if (not rulesFile.exists()): self.mError += self.tr("No rules file found at:\n%s\n"%filePath) return False if (not rulesFile.open(QIODevice.ReadOnly | QIODevice.Text)): self.mError += self.tr("Error opening rules file:\n%s\n"%filePath) return False i = QTextStream(rulesFile) line = ' ' while line != '': line = i.readLine() rulePath = line.strip() if (rulePath=='' or rulePath.startswith('#') or rulePath.startswith("//")): continue if (QFileInfo(rulePath).isRelative()): rulePath = absPath + '/' + rulePath if (not QFileInfo(rulePath).exists()): self.mError += self.tr("File not found:\n%s"%rulePath) + '\n' ret = False continue if (rulePath.lower().endswith(".tmx")): tmxFormat = TmxMapFormat() rules = tmxFormat.read(rulePath) if (not rules): self.mError += self.tr("Opening rules map failed:\n%s"%tmxFormat.errorString()) + '\n' ret = False continue tilesetManager = TilesetManager.instance() tilesetManager.addReferences(rules.tilesets()) autoMapper = None autoMapper = AutoMapper(self.mMapDocument, rules, rulePath) self.mWarning += autoMapper.warningString() error = autoMapper.errorString() if error != '': self.mAutoMappers.append(autoMapper) else: self.mError += error del autoMapper if (rulePath.lower().endswith(".txt")): if (not self.loadFile(rulePath)): ret = False return ret
def saveHtml(self, fileName): if not QFileInfo(fileName).suffix(): fileName += ".html" try: htmltext = self.currentTab.getHtml(includeStyleSheet=False, webenv=True) except Exception: return self.printError() htmlFile = QFile(fileName) htmlFile.open(QIODevice.WriteOnly) html = QTextStream(htmlFile) if globalSettings.defaultCodec: html.setCodec(globalSettings.defaultCodec) html << htmltext htmlFile.close()
def save(self): fileName, _ = QFileDialog.getSaveFileName(self) if fileName: outFile = QFile(fileName) if not outFile.open(QFile.WriteOnly|QFile.Text): QMessageBox.warning(self, "Codecs", "Cannot write file %s:\n%s" % (fileName, outFile.errorString())) return action = self.sender() codecName = action.data() out = QTextStream(outFile) out.setCodec(codecName) out << self.textEdit.toPlainText()
def saveTextToFile(self, fileName=None, addToWatcher=True): if fileName is None: fileName = self.fileName self.p.fileSystemWatcher.removePath(fileName) savefile = QFile(fileName) result = savefile.open(QFile.WriteOnly) if result: savestream = QTextStream(savefile) if globalSettings.defaultCodec: savestream.setCodec(globalSettings.defaultCodec) savestream << self.editBox.toPlainText() savefile.close() if result and addToWatcher: self.p.fileSystemWatcher.addPath(fileName) return result
def __saveByStream(self, fileName): fileDevice = QFile(fileName) if not fileDevice.exists(): return False if not fileDevice.open(QIODevice.ReadOnly | QIODevice.Text): return False try: fileStream = QTextStream(fileDevice) fileStream.setAutoDetectUnicode(True) fileStream.setCodec("utf-8") text = self.ui.textEdit.toPlainText() fileStream << text finally: fileDevice.close() return True
def set_theme(self): if not self.flag: # self.palette.setColor(QPalette.Window, QColor('lavenderblush')) # self.palette.setColor(QPalette.Button, QColor('lightsalmon')) file = QFile(":/light.qss") file.open(QFile.ReadOnly | QFile.Text) stream = QTextStream(file) self.setStyleSheet(stream.readAll()) self.tmBtn.setText("Dark") else: # self.palette.setColor(QPalette.Window, QColor('gray')) # self.palette.setColor(QPalette.Button, QColor('darkgray')) file = QFile(":/dark.qss") file.open(QFile.ReadOnly | QFile.Text) stream = QTextStream(file) self.setStyleSheet(stream.readAll()) self.tmBtn.setText("Light") # self.setPalette(self.palette) self.flag = not self.flag
def setPersepolisColorScheme(self, color_scheme): self.persepolis_color_scheme = color_scheme if color_scheme == 'Persepolis Old Dark Red': persepolis_dark_red = DarkRedPallete() self.setPalette(persepolis_dark_red) self.setStyleSheet("QMenu::item:selected {background-color : #d64937 ;color : white} QToolTip { color: #ffffff; background-color: #353535; border: 1px solid white; }") elif color_scheme == 'Persepolis Old Dark Blue': persepolis_dark_blue = DarkBluePallete() self.setPalette(persepolis_dark_blue) self.setStyleSheet("QMenu::item:selected { background-color : #2a82da ;color : white } QToolTip { color: #ffffff; background-color: #353535; border: 1px solid white; }") elif color_scheme == 'Persepolis ArcDark Red': persepolis_arcdark_red = ArcDarkRedPallete() self.setPalette(persepolis_arcdark_red) self.setStyleSheet("QMenu::item:selected {background-color : #bf474d ; color : white} QToolTip { color: #ffffff; background-color: #353945; border: 1px solid white; } QPushButton {background-color: #353945 } QTabWidget {background-color : #353945;} QMenu {background-color: #353945 }") elif color_scheme == 'Persepolis ArcDark Blue': persepolis_arcdark_blue = ArcDarkBluePallete() self.setPalette(persepolis_arcdark_blue) self.setStyleSheet("QMenu::item:selected {background-color : #5294e2 ; color : white } QToolTip { color: #ffffff; background-color: #353945; border: 1px solid white; } QPushButton {background-color: #353945 } QTabWidget {background-color : #353945;} QMenu {background-color: #353945 }") elif color_scheme == 'Persepolis Old Light Red': persepolis_light_red = LightRedPallete() self.setPalette(persepolis_light_red) self.setStyleSheet("QMenu::item:selected {background-color : #d64937 ;color : white} QToolTip { color: #ffffff; background-color: #353535; border: 1px solid white; }") elif color_scheme == 'Persepolis Old Light Blue': persepolis_light_blue = LightBluePallete() self.setPalette(persepolis_light_blue) self.setStyleSheet("QMenu::item:selected { background-color : #2a82da ;color : white } QToolTip { color: #ffffff; background-color: #353535; border: 1px solid white; }") elif color_scheme == 'Persepolis Dark Blue': file = QFile(":/dark_style.qss") file.open(QFile.ReadOnly | QFile.Text) stream = QTextStream(file) self.setStyleSheet(stream.readAll()) elif color_scheme == 'Persepolis Light Blue': file = QFile(":/light_style.qss") file.open(QFile.ReadOnly | QFile.Text) stream = QTextStream(file) self.setStyleSheet(stream.readAll())
def overseek(self): outdatar = "" CONFIGPATH = os.path.join(sys.path[0],"plugins\\ResolutionExtension\\Resolution.txt") if QFile(CONFIGPATH).exists() == False:#Default outdatar = outdatar + self.overread(QSize(70,70)) outdatar = outdatar + self.overread(QSize(95,80)) outdatar = outdatar + self.overread(QSize(95,95)) outdatar = outdatar + self.overread(QSize(160,140)) else: fh = QFile(CONFIGPATH) fh.open(QIODevice.ReadOnly) stream = QTextStream(fh) stream.setCodec(CODEC) while stream.atEnd() == False: tem = stream.readLine() if tem[0] == '#': continue tems = tem.split(",") if len(tems) == 2 and tems[0].isdigit() and tems[1].isdigit(): outdatar = outdatar + self.overread(QSize(int(tems[0]),int(tems[1]))) fh.close() return outdatar
def addData(self): dataArray = [] stream = QTextStream() dataFile = QFile(QFileInfo(__file__).absolutePath() + '/data.txt') if dataFile.open(QIODevice.ReadOnly | QIODevice.Text): stream.setDevice(dataFile) while not stream.atEnd(): line = stream.readLine() if line.startswith('#'): continue strList = line.split(',') # Each line has three data items: xPos, yPos and zPos values. if len(strList) < 3: continue position = QVector3D(float(strList[0]), float(strList[1]), float(strList[2])) dataArray.append(QScatterDataItem(position)) self.m_graph.seriesList()[0].dataProxy().resetArray(dataArray)
def set_dark_theme_if_needed(self): use_dark_theme = self.config.get('qt_gui_color_theme', 'light') == 'dark' if use_dark_theme: try: file = QFile(":/dark.qss") file.open(QFile.ReadOnly | QFile.Text) stream = QTextStream(file) self.app.setStyleSheet(stream.readAll()) except BaseException as e: use_dark_theme = False print_error('Error setting dark theme: {}'.format(e)) else: try: file = QFile(":/light.qss") file.open(QFile.ReadOnly | QFile.Text) stream = QTextStream(file) self.app.setStyleSheet(stream.readAll()) except BaseException as e: print_error('Error setting light theme: {}'.format(e)) # Even if we ourselves don't set the dark theme, # the OS/window manager/etc might set *a dark theme*. # Hence, try to choose colors accordingly: ColorScheme.update_from_widget(QWidget(), force_dark=use_dark_theme)
def run(self): settings = QSettings() style = settings.value(SETTINGS_STYLE, "default", type=str) if style == "dark": stylesheet = QFile(":/dark.qss") stylesheet.open(QFile.ReadOnly | QFile.Text) stream = QTextStream(stylesheet) self.app.setStyleSheet(stream.readAll()) elif style == "light": stylesheet = QFile(":/light.qss") stylesheet.open(QFile.ReadOnly | QFile.Text) stream = QTextStream(stylesheet) self.app.setStyleSheet(stream.readAll()) elif style == "dark2": self.app.setStyleSheet(qdarkstyle.load_stylesheet(qt_api='pyqt5')) elif style == "darkgray": self.app.setStyleSheet(qdarkgraystyle.load_stylesheet()) else: stylesheet = self.get_resource('styles.qss') self.app.setStyleSheet(open(stylesheet).read()) self.window.show() return self.app.exec_()
def write(self, map, fileName): file = QSaveFile(fileName) if (not file.open(QIODevice.WriteOnly | QIODevice.Text)): self.mError = self.tr("Could not open file for writing.") return False out = QTextStream(file) # Write the header header = map.property("header") for line in header.split("\\n"): out << line << '\n' width = map.width() height = map.height() asciiMap = QList() cachedTiles = QHash() propertyOrder = QList() propertyOrder.append("terrain") propertyOrder.append("object") propertyOrder.append("actor") propertyOrder.append("trap") propertyOrder.append("status") propertyOrder.append("spot") # Ability to handle overflow and strings for display outputLists = False asciiDisplay = ASCII_MIN overflowDisplay = 1 # Add the empty tile numEmptyTiles = 0 emptyTile = Properties() emptyTile["display"] = "?" cachedTiles["?"] = emptyTile # Process the map, collecting used display strings as we go for y in range(0, height): for x in range(0, width): currentTile = cachedTiles["?"] for layer in map.layers(): # If the layer name does not start with one of the tile properties, skip it layerKey = '' for currentProperty in propertyOrder: if (layer.name().lower().startswith( currentProperty.lower())): layerKey = currentProperty break if layerKey == '': continue tileLayer = layer.asTileLayer() objectLayer = layer.asObjectGroup() # Process the Tile Layer if (tileLayer): tile = tileLayer.cellAt(x, y).tile if (tile): currentTile["display"] = tile.property("display") currentTile[layerKey] = tile.property("value") # Process the Object Layer elif (objectLayer): for obj in objectLayer.objects(): if (math.floor(obj.y()) <= y and y <= math.floor(obj.y() + obj.height())): if (math.floor(obj.x()) <= x and x <= math.floor(obj.x() + obj.width())): # Check the Object Layer properties if either display or value was missing if (not obj.property("display").isEmpty()): currentTile["display"] = obj.property( "display") elif (not objectLayer.property( "display").isEmpty()): currentTile[ "display"] = objectLayer.property( "display") if (not obj.property("value").isEmpty()): currentTile[layerKey] = obj.property( "value") elif (not objectLayer.property( "value").isEmpty()): currentTile[ layerKey] = objectLayer.property( "value") # If the currentTile does not exist in the cache, add it if (not cachedTiles.contains(currentTile["display"])): cachedTiles[currentTile["display"]] = currentTile # Otherwise check that it EXACTLY matches the cached one # and if not... elif (currentTile != cachedTiles[currentTile["display"]]): # Search the cached tiles for a match foundInCache = False displayString = QString() for i in cachedTiles.items(): displayString = i[0] currentTile["display"] = displayString if (currentTile == i[1]): foundInCache = True break # If we haven't found a match then find a random display string # and cache it if (not foundInCache): while (True): # First try to use the ASCII characters if (asciiDisplay < ASCII_MAX): displayString = asciiDisplay asciiDisplay += 1 # Then fall back onto integers else: displayString = QString.number(overflowDisplay) overflowDisplay += 1 currentTile["display"] = displayString if (not cachedTiles.contains(displayString)): cachedTiles[displayString] = currentTile break elif (currentTile == cachedTiles[ currentTile["display"]]): break # Check the output type if len(currentTile["display"]) > 1: outputLists = True # Check if we are still the emptyTile if (currentTile == emptyTile): numEmptyTiles += 1 # Finally add the character to the asciiMap asciiMap.append(currentTile["display"]) # Write the definitions to the file out << "-- defineTile section\n" for i in cachedTiles.items(): displayString = i[0] # Only print the emptyTile definition if there were empty tiles if (displayString == "?" and numEmptyTiles == 0): continue # Need to escape " and \ characters displayString.replace('\\', "\\\\") displayString.replace('"', "\\\"") args = self.constructArgs(i[1], propertyOrder) if (not args.isEmpty()): args = QString(", %1").arg(args) out << "defineTile(\"%s\"%s)\n" % (displayString, args) # Check for an ObjectGroup named AddSpot out << "\n-- addSpot section\n" for layer in map.layers(): objectLayer = layer.asObjectGroup() if (objectLayer and objectLayer.name().lower().startsWith("addspot")): for obj in objectLayer.objects(): propertyOrder = QList() propertyOrder.append("type") propertyOrder.append("subtype") propertyOrder.append("additional") args = self.constructArgs(obj.properties(), propertyOrder) if (not args.isEmpty()): args = QString(", %1").arg(args) for y in range(math.floor(obj.y()), math.floor(obj.y() + obj.height())): for y in range(math.floor(obj.x()), math.floor(obj.x() + obj.width())): out << "addSpot({%s, %s}%s)\n" % (x, y, args) # Check for an ObjectGroup named AddZone out << "\n-- addZone section\n" for layer in map.layers(): objectLayer = layer.asObjectGroup() if (objectLayer and objectLayer.name().lower().startsWith("addzone")): for obj in objectLayer.objects(): propertyOrder = QList() propertyOrder.append("type") propertyOrder.append("subtype") propertyOrder.append("additional") args = self.constructArgs(obj.properties(), propertyOrder) if (not args.isEmpty()): args = QString(", %1").arg(args) top_left_x = math.floor(obj.x()) top_left_y = math.floor(obj.y()) bottom_right_x = math.floor(obj.x() + obj.width()) bottom_right_y = math.floor(obj.y() + obj.height()) out << "addZone({%s, %s, %s, %s}%s)" % ( top_left_x, top_left_y, bottom_right_x, bottom_right_y, args) # Write the map returnStart = QString() returnStop = QString() lineStart = QString() lineStop = QString() itemStart = QString() itemStop = QString() seperator = QString() if (outputLists): returnStart = "{" returnStop = "}" lineStart = "{" lineStop = "}," itemStart = "[[" itemStop = "]]" seperator = "," else: returnStart = "[[" returnStop = "]]" lineStart = "" lineStop = "" itemStart = "" itemStop = "" seperator = "" out << "\n-- ASCII map section\n" out << "return " << returnStart << '\n' for y in range(0, height): out << lineStart for x in range(0, width): out << itemStart << asciiMap[x + (y * width)] << itemStop << seperator if (y == height - 1): out << lineStop << returnStop else: out << lineStop << '\n' if not file.commit(): self.mError = file.errorString() return False return True
def read_qss(style): file = QFile(style) file.open(QFile.ReadOnly) return QTextStream(file).readAll()
def main(): # Initialise. defaultContext = "@default" fetchedTor = MetaTranslator() codecForTr = '' codecForSource = '' tsFileNames = [] uiFileNames = [] verbose = False noObsolete = False metSomething = False numFiles = 0 standardSyntax = True metTsFlag = False tr_func = None translate_func = None # Parse the command line. for arg in sys.argv[1:]: if arg == "-ts": standardSyntax = False argc = len(sys.argv) i = 1 while i < argc: arg = sys.argv[i] i += 1 if arg == "-help": printUsage() sys.exit(0) if arg == "-version": sys.stderr.write("pylupdate5 v%s\n" % PYQT_VERSION_STR) sys.exit(0) if arg == "-noobsolete": noObsolete = True continue if arg == "-verbose": verbose = True continue if arg == "-ts": metTsFlag = True continue if arg == "-tr-function": if i >= argc: sys.stderr.write( "pylupdate5 error: missing -tr-function name\n") sys.exit(2) tr_func = sys.argv[i] i += 1 continue if arg == "-translate-function": if i >= argc: sys.stderr.write( "pylupdate5 error: missing -translate-function name\n") sys.exit(2) translate_func = sys.argv[i] i += 1 continue numFiles += 1 fullText = "" if not metTsFlag: f = QFile(arg) if not f.open(QIODevice.ReadOnly): sys.stderr.write("pylupdate5 error: Cannot open file '%s'\n" % arg) sys.exit(1) t = QTextStream(f) fullText = t.readAll() f.close() if standardSyntax: oldDir = QDir.currentPath() QDir.setCurrent(QFileInfo(arg).path()) fetchedTor = MetaTranslator() codecForTr = '' codecForSource = '' tsFileNames = [] uiFileNames = [] for key, value in proFileTagMap(fullText).items(): for t in value.split(' '): if key == "SOURCES": fetchtr_py(QDir.current().absoluteFilePath(t), fetchedTor, defaultContext, True, codecForSource, tr_func, translate_func) metSomething = True elif key == "TRANSLATIONS": tsFileNames.append(QDir.current().absoluteFilePath(t)) metSomething = True elif key in ("CODEC", "DEFAULTCODEC", "CODECFORTR"): codecForTr = t fetchedTor.setCodec(codecForTr) elif key == "CODECFORSRC": codecForSource = t elif key == "FORMS": fetchtr_ui(QDir.current().absoluteFilePath(t), fetchedTor, defaultContext, True) updateTsFiles(fetchedTor, tsFileNames, codecForTr, noObsolete, verbose) if not metSomething: sys.stderr.write( "pylupdate5 warning: File '%s' does not look like a " "project file\n" % arg) elif len(tsFileNames) == 0: sys.stderr.write( "pylupdate5 warning: Met no 'TRANSLATIONS' entry in " "project file '%s'\n" % arg) QDir.setCurrent(oldDir) else: if metTsFlag: if arg.lower().endswith(".ts"): fi = QFileInfo(arg) if not fi.exists() or fi.isWritable(): tsFileNames.append(arg) else: sys.stderr.write( "pylupdate5 warning: For some reason, I " "cannot save '%s'\n" % arg) else: sys.stderr.write( "pylupdate5 error: File '%s' lacks .ts extension\n" % arg) else: fi = QFileInfo(arg) if fi.suffix() in ("py", "pyw"): fetchtr_py(fi.absoluteFilePath(), fetchedTor, defaultContext, True, codecForSource, tr_func, translate_func) else: fetchtr_ui(fi.absoluteFilePath(), fetchedTor, defaultContext, True) if not standardSyntax: updateTsFiles(fetchedTor, tsFileNames, codecForTr, noObsolete, verbose) if numFiles == 0: printUsage() sys.exit(1)
def load_style_from_file(file_path): file = QFile(file_path) file.open(QFile.ReadOnly | QFile.Text) stream = QTextStream(file) return stream.readAll()
self.file_writer_group.root_dir_entry.setText( p['Writer']['Data dir']) self.file_writer_group.ctset_fmt_entry.setText( p['Writer']['CT scan name']) self.file_writer_group.dsetname_entry.setText( p['Writer']['Filename']) self.file_writer_group.bigtiff_checkbox.setChecked( p['Writer']['Big tiffs']) self.file_writer_group.separate_scans_checkbox.setChecked( p['Writer']['Separate scans']) except: warning_message('Cannot enter file-writer settings correctly') if __name__ == '__main__': parsed_args, unparsed_args = process_cl_args() if parsed_args.debug: log.log_to_console(level=logging.DEBUG) # QApplication expects the first argument to be the program name. qt_args = sys.argv[:1] + unparsed_args app = QApplication(qt_args) loop = QEventLoop(app) root_dir = os.path.dirname(os.path.abspath(__file__)) style_file = QFile(os.path.join(root_dir, "styles/breeze/dark.qss")) style_file.open(QFile.ReadOnly | QFile.Text) stream = QTextStream(style_file) # Set application style to dark; Comment following line to unset # app.setStyleSheet(stream.readAll()) ex = GUI() sys.exit(app.exec_())
class QtSingleApplication(QApplication): """ This class makes sure that we can only start one Tribler application. When a user tries to open a second Tribler instance, the current active one will be brought to front. """ messageReceived = pyqtSignal(str) def __init__(self, win_id, *argv): logfunc = logging.info logfunc(sys._getframe().f_code.co_name + '()') QApplication.__init__(self, *argv) self._id = win_id self._activation_window = None self._activate_on_message = False # Is there another instance running? self._outSocket = QLocalSocket() self._outSocket.connectToServer(self._id) self._isRunning = self._outSocket.waitForConnected() self._outStream = None self._inSocket = None self._inStream = None self._server = None if self._isRunning: # Yes, there is. self._outStream = QTextStream(self._outSocket) self._outStream.setCodec('UTF-8') else: # No, there isn't, at least not properly. # Cleanup any past, crashed server. error = self._outSocket.error() logfunc(LOGVARSTR % ('self._outSocket.error()', error)) if error == QLocalSocket.ConnectionRefusedError: logfunc('received QLocalSocket.ConnectionRefusedError; removing server.') self.close() QLocalServer.removeServer(self._id) self._outSocket = None self._server = QLocalServer() self._server.listen(self._id) self._server.newConnection.connect(self._on_new_connection) logfunc(sys._getframe().f_code.co_name + '(): returning') def close(self): logfunc = logging.info logfunc(sys._getframe().f_code.co_name + '()') if self._inSocket: self._inSocket.disconnectFromServer() if self._outSocket: self._outSocket.disconnectFromServer() if self._server: self._server.close() logfunc(sys._getframe().f_code.co_name + '(): returning') def is_running(self): return self._isRunning def get_id(self): return self._id def activation_window(self): return self._activation_window def set_activation_window(self, activation_window, activate_on_message=True): self._activation_window = activation_window self._activate_on_message = activate_on_message def activate_window(self): if not self._activation_window: return self._activation_window.setWindowState(self._activation_window.windowState() & ~Qt.WindowMinimized) self._activation_window.raise_() def send_message(self, msg): if not self._outStream: return False self._outStream << msg << '\n' self._outStream.flush() return self._outSocket.waitForBytesWritten() def _on_new_connection(self): if self._inSocket: self._inSocket.readyRead.disconnect(self._on_ready_read) self._inSocket = self._server.nextPendingConnection() if not self._inSocket: return self._inStream = QTextStream(self._inSocket) self._inStream.setCodec('UTF-8') self._inSocket.readyRead.connect(self._on_ready_read) if self._activate_on_message: self.activate_window() def _on_ready_read(self): while True: msg = self._inStream.readLine() if not msg: break self.messageReceived.emit(msg)
class QSingleApplication(QApplication): messageReceived = pyqtSignal(str) def __init__(self, id, *argv): super(QSingleApplication, self).__init__(*argv) self._id = id self._activationWindow = None self._activateOnMessage = False self._server = None # Is there another instance running? self._outSocket = QLocalSocket() self._outSocket.connectToServer(self._id) self._outSocket.error.connect(self.handleError) self._isRunning = self._outSocket.waitForConnected() if self._isRunning: # Yes, there is. self._outStream = QTextStream(self._outSocket) self._outStream.setCodec('UTF-8') else: # No, there isn't. self._outSocket = None self._outStream = None self._inSocket = None self._inStream = None self._server = QLocalServer() self._server.listen(self._id) self._server.newConnection.connect(self._onNewConnection) self.aboutToQuit.connect(self.removeServer) def handleError(self, msg): print(msg) def server(self): return self._server def isRunning(self): return self._isRunning def id(self): return self._id def activationWindow(self): return self._activationWindow def setActivationWindow(self, activationWindow, activateOnMessage=True): self._activationWindow = activationWindow self._activateOnMessage = activateOnMessage def activateWindow(self): if not self._activationWindow: print("No registered ActivationWindow") return # Unfortunately this *doesn't* do much of any use, as it won't # bring the window to the foreground under KDE... sigh. self._activationWindow.setWindowState( self._activationWindow.windowState() & ~Qt.WindowMinimized) self._activationWindow.raise_() self._activationWindow.requestActivate() def sendMessage(self, msg, msecs=5000): if not self._outStream: return False self._outStream << msg << '' if not self._outSocket.waitForBytesWritten(msecs): raise RuntimeError("Bytes not written within %ss" % (msecs / 1000.)) def _onNewConnection(self): if self._inSocket: self._inSocket.readyRead.disconnect(self._onReadyRead) self._inSocket = self._server.nextPendingConnection() if not self._inSocket: return self._inStream = QTextStream(self._inSocket) self._inStream.setCodec('UTF-8') self._inSocket.readyRead.connect(self._onReadyRead) if self._activateOnMessage: self.activateWindow() def _onReadyRead(self): while True: msg = self._inStream.readLine() if not msg: break print("Message received") self.messageReceived.emit(msg) def removeServer(self): self._server.close() self._server.removeServer(self._id)
from PyQt5.QtGui import QPalette, QColor from PyQt5.QtGui import QFont, QIcon,QPixmap from PyQt5.QtCore import Qt, QMetaObject, pyqtSignal, pyqtSlot, QSize, QFile, QTextStream from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QLabel, QSizePolicy) import resources import sys QT_VERSION = (5, 15, 1) _raw_data = QFile(":/stylesheet/style.qss") _raw_data.open(QFile.ReadOnly | QFile.Text) _ts = QTextStream(_raw_data) app_stylesheet = _ts.readAll() def _apply_base_theme(app): if QT_VERSION < (5,): app.setStyle('plastique') else: app.setStyle('Fusion') app.setStyleSheet(app_stylesheet) def apply_palette(app): """ Apply Light Theme to the Qt application instance. Args:
def loadQTextStream(self): error = None fh = None try: fh = QFile(self.__fname) if not fh.open(QIODevice.ReadOnly): raise IOError(unicode(fh.errorString())) stream = QTextStream(fh) stream.setCodec(CODEC) self.clear(False) lino = 0 while not stream.atEnd(): title = year = minutes = acquired = notes = None line = stream.readLine() lino += 1 if not line.startsWith("{{MOVIE}}"): raise ValueError("no movie record found") else: title = line.mid(len("{{MOVIE}}")).trimmed() if stream.atEnd(): raise ValueError("premature end of file") line = stream.readLine() lino += 1 parts = line.split(" ") if parts.count() != 3: raise ValueError("invalid numeric data") year = intFromQStr(parts[0]) minutes = intFromQStr(parts[1]) ymd = parts[2].split("-") if ymd.count() != 3: raise ValueError("invalid acquired date") acquired = QDate(intFromQStr(ymd[0]), intFromQStr(ymd[1]), intFromQStr(ymd[2])) if stream.atEnd(): raise ValueError("premature end of file") line = stream.readLine() lino += 1 if line != "{NOTES}": raise ValueError("notes expected") notes = QString() while not stream.atEnd(): line = stream.readLine() lino += 1 if line == "{{ENDMOVIE}}": if (title is None or year is None or minutes is None or acquired is None or notes is None): raise ValueError("incomplete record") self.add( Movie(title, year, minutes, acquired, notes.trimmed())) break else: notes += line + "\n" else: raise ValueError("missing endmovie marker") except (IOError, OSError, ValueError) as e: error = "Failed to load: {0} on line {1}".format(e, lino) finally: if fh is not None: fh.close() if error is not None: return False, error self.__dirty = False return True, "Loaded {0} movie records from {1}".format( len(self.__movies), QFileInfo(self.__fname).fileName())
def main(): multiprocessing.set_start_method('spawn') if markups.__version_tuple__ < (2, ): sys.exit('Error: ReText needs PyMarkups 2.0 or newer to run.') # If we're running on Windows without a console, then discard stdout # and save stderr to a file to facilitate debugging in case of crashes. if sys.executable.endswith('pythonw.exe'): sys.stdout = open(devnull, 'w') sys.stderr = open('stderr.log', 'w') try: # See https://github.com/retext-project/retext/issues/399 # and https://launchpad.net/bugs/941826 ctypes.CDLL('libGL.so.1', ctypes.RTLD_GLOBAL) except OSError: pass # Needed for Qt WebEngine on Windows QApplication.setAttribute(Qt.AA_ShareOpenGLContexts) app = QApplication(sys.argv) app.setOrganizationName("ReText project") app.setApplicationName("ReText") app.setApplicationDisplayName("ReText") app.setApplicationVersion(app_version) app.setOrganizationDomain('mitya57.me') if hasattr(app, 'setDesktopFileName'): # available since Qt 5.7 app.setDesktopFileName('me.mitya57.ReText.desktop') QNetworkProxyFactory.setUseSystemConfiguration(True) initializeDataDirs() RtTranslator = QTranslator() for path in datadirs: if RtTranslator.load('retext_' + globalSettings.uiLanguage, join(path, 'locale')): break QtTranslator = QTranslator() QtTranslator.load("qtbase_" + globalSettings.uiLanguage, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(RtTranslator) app.installTranslator(QtTranslator) print('Using configuration file:', settings.fileName()) if globalSettings.appStyleSheet: sheetfile = QFile(globalSettings.appStyleSheet) sheetfile.open(QIODevice.ReadOnly) app.setStyleSheet(QTextStream(sheetfile).readAll()) sheetfile.close() window = ReTextWindow() window.show() # ReText can change directory when loading files, so we # need to have a list of canonical names before loading fileNames = list(map(canonicalize, sys.argv[1:])) previewMode = False readStdIn = False if globalSettings.openLastFilesOnStartup: window.restoreLastOpenedFiles() for fileName in fileNames: if QFile.exists(fileName): window.openFileWrapper(fileName) if previewMode: window.actionPreview.setChecked(True) window.preview(True) elif fileName == '--preview': previewMode = True elif fileName == '-': readStdIn = True inputData = '' if readStdIn and sys.stdin is not None: if sys.stdin.isatty(): print('Reading stdin, press ^D to end...') inputData = sys.stdin.read() if inputData or not window.tabWidget.count(): window.createNew(inputData) signal.signal(signal.SIGINT, lambda sig, frame: window.close()) sys.exit(app.exec())
class NSwapFile(QObject): """ In case Ninja-IDE crash, this can be used to recover the lost data. When the user begins to edit an existing file on the disk, this object creates a swap file and activates a timer that will execute a function, that will update that swap file as soon as the timeout ends (by default, is 15 seconds). The swap file is deleted when the original file is saved or closed. When system or Ninja crash, the swap file exists on disk and Ninja will used to recover the lost data. """ canBeRecovered = pyqtSignal() def __init__(self, neditable): QObject.__init__(self) self._neditable = neditable self.__swap_file = QFile() self.__stream = QTextStream() # Activate timer when user typing self.__timer = QTimer() self.__timer.setSingleShot(True) self.__timer.timeout.connect(self._finish_typing) self._neditable.fileLoaded.connect(self._file_loaded) self._neditable.fileSaved.connect(self._file_saved) self.init(tracking=True) def init(self, tracking): if tracking: self._neditable.editor.textChanged.connect(self._start_typing) self._neditable.fileClosing.connect(self._file_closed) else: self._neditable.editor.textChanged.disconnect(self._start_typing) self._neditable.fileClosing.disconnect(self._file_closed) def _file_closed(self): """Editor was closed normally, now remove swap file""" self.__remove() def _file_saved(self): """If file is saved, remove swap file""" # Remove old swap file and set the name for the new swap file self.__remove() self.__update_filename() def __remove(self): """Remove swap file""" if self.__swap_file.fileName() and self.__swap_file.exists(): self.__stream.setDevice(None) self.__swap_file.close() self.__swap_file.remove() def _file_loaded(self): """This slot is executed when a file is loaded on the editor and look for swap file, if exists then can be recover""" self.__update_filename() if self.__swap_file.exists(): # In recovery process can't edit self._neditable.editor.setReadOnly(True) # Ok, can be recover self.canBeRecovered.emit() def __update_filename(self): # First clear filename self.__swap_file.setFileName("") # Get new path filename = self.filename() self.__swap_file.setFileName(filename) def _start_typing(self): # Skip if editor is not modified if not self._neditable.editor.is_modified: return # No swap file, no work if not self.__swap_file.fileName(): return # Create the file if not self.__swap_file.exists(): self.__swap_file.open(QIODevice.WriteOnly) permissions = QFileDevice.ReadOwner | QFileDevice.WriteOwner self.__swap_file.setPermissions(permissions) self.__stream.setDevice(self.__swap_file) if self.__timer.isActive(): self.__timer.stop() # Write swap file to the disk every 10 seconds by default self.__timer.start(settings.SWAP_FILE_INTERVAL * 1000) def _finish_typing(self): if not self.__swap_file.isOpen(): return logger.debug("Now write the swap file...") text = self._neditable.editor.text self.__swap_file.write(text.encode()) self.__swap_file.flush() def filename(self): """Returns the filename for swap file""" path, name = os.path.split( os.path.join(SWAP_PATH, self._neditable.nfile.file_name)) filename = os.path.join(path, "%s.ninja-swap" % name) return filename def recover(self): self._neditable.editor.setReadOnly(False) # Disconnect signals self.init(tracking=False) self.__stream.setDevice(self.__swap_file) if not self.__swap_file.open(QIODevice.ReadOnly): logger.warning("Can't open swap file") return # Ok data = [] append = data.append while not self.__stream.atEnd(): line = self.__stream.readLine() append(line) # Set data in the editor self._neditable.editor.text = "\n".join(data) self._neditable.document.setModified(True) # Close swap file self.__stream.setDevice(None) self.__swap_file.close() # Reconnect signals self.init(tracking=True) def discard(self): self._neditable.editor.setReadOnly(False) # Remove swap file self.__remove()
def reload_style(self): style_file = QFile(':/style.css') style_file.open(QIODevice.ReadOnly) self.setStyleSheet(QTextStream(style_file).readAll()) style_file.close()
class SingleApplication(QApplication): messageReceived = pyqtSignal(str) def __init__(self, appid, *argv): super(SingleApplication, self).__init__(*argv) self._appid = appid self._activationWindow = None self._activateOnMessage = False self._outSocket = QLocalSocket() self._outSocket.connectToServer(self._appid) self._isRunning = self._outSocket.waitForConnected() self._outStream = None self._inSocket = None self._inStream = None self._server = None self.settings = QSettings(SingleApplication.getSettingsPath(), QSettings.IniFormat) self.singleInstance = self.settings.value('singleInstance', 'on', type=str) in {'on', 'true'} if self._isRunning and self.singleInstance: self._outStream = QTextStream(self._outSocket) for a in argv[0][1:]: a = os.path.join(os.getcwd(), a) if os.path.isfile(a): self.sendMessage(a) break sys.exit(0) else: error = self._outSocket.error() if error == QLocalSocket.ConnectionRefusedError: self.close() QLocalServer.removeServer(self._appid) self._outSocket = None self._server = QLocalServer() self._server.listen(self._appid) self._server.newConnection.connect(self._onNewConnection) def close(self): if self._inSocket: self._inSocket.disconnectFromServer() if self._outSocket: self._outSocket.disconnectFromServer() if self._server: self._server.close() @staticmethod def getSettingsPath() -> str: if sys.platform == 'win32': settings_path = os.path.join(QDir.homePath(), 'AppData', 'Local', 'vidcutter') elif sys.platform == 'darwin': settings_path = os.path.join(QDir.homePath(), 'Library', 'Preferences', 'vidcutter') else: if QFileInfo(__file__).absolutePath().startswith('/app/'): settings_path = QProcessEnvironment.systemEnvironment().value( 'XDG_CONFIG_HOME', '') if not len(settings_path): settings_path = os.path.join(QDir.homePath(), '.var', 'app', vidcutter.__desktopid__, 'config') else: settings_path = os.path.join(QDir.homePath(), '.config', 'vidcutter') return os.path.join(settings_path, 'vidcutter.ini') def isRunning(self): return self._isRunning def appid(self): return self._appid def activationWindow(self): return self._activationWindow def setActivationWindow(self, activationWindow, activateOnMessage=True): self._activationWindow = activationWindow self._activateOnMessage = activateOnMessage def activateWindow(self): if not self._activationWindow: return self._activationWindow.setWindowState( self._activationWindow.windowState() & ~Qt.WindowMinimized) self._activationWindow.raise_() self._activationWindow.activateWindow() def sendMessage(self, msg): if not self._outStream: return False # noinspection PyUnresolvedReferences self._outStream << msg << '\n' self._outStream.flush() return self._outSocket.waitForBytesWritten() def _onNewConnection(self): if self._inSocket: self._inSocket.readyRead.disconnect(self._onReadyRead) self._inSocket = self._server.nextPendingConnection() if not self._inSocket: return self._inStream = QTextStream(self._inSocket) self._inSocket.readyRead.connect(self._onReadyRead) if self._activateOnMessage: self.activateWindow() def _onReadyRead(self): while True: msg = self._inStream.readLine() if not msg: break self.messageReceived.emit(msg)
app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui_principal = VentanaTienda() ui_registro = RegistroMain() ui_listado1 = Listado1Main() ui_listado2 = Listado2Main() ui_table = TableWidget() ui_editar = EditarRegistro() ui_principal.setupUi(MainWindow) ui_principal.submenu_registrar_periferico.triggered.connect(mostrar_registro) ui_principal.submenu_listado_1.triggered.connect(mostrar_listado1) ui_principal.submenu_listado_2.triggered.connect(mostrar_listado2) ui_principal.submenu_listado_3.triggered.connect(mostrar_table) # Stylesheet QSS from file: file = QFile("style\style.qss") file.open(QFile.ReadOnly | QFile.Text) stream = QTextStream(file) app.setStyleSheet(stream.readAll()) MainWindow.show() sys.exit(app.exec_())
def getStyleSheet(self, path): f = QFile(path) f.open(QFile.ReadOnly | QFile.Text) stylesheet = QTextStream(f).readAll() f.close() return stylesheet
def readStyleSheet(self): f = QFile(self.appContext.get_resource(self.stylesheetPath)) f.open(QFile.ReadOnly | QFile.Text) stream = QTextStream(f) self.setStyleSheet(stream.readAll())
def set(self, name): self.active_theme = name self.config.update_config('General', 'theme', name) style = QFile(self.get_active()['location']) style.open(QFile.ReadOnly | QFile.Text) self.app.setStyleSheet(QTextStream(style).readAll())
def _perform_migrations(self): qry = self.getQuery() d = self.getDatabase() # check if we can query a version of # the schema_changes table, if not possible # we likely need to create a completly new db if qry.exec( "SELECT version FROM schema_changes ORDER BY version DESC LIMIT 1" ) and qry.next(): db_version = int(qry.value(0)) print(f"Found Database Version to be {db_version}") else: db_version = -1 print( "Could not determine database version, will create new schema from scratch..." ) # check to see if we can find any migration files # we will prefer the ones in sql/*.sql on disk over the ones # bundled with qrc for easier development, but the release version # will likely use the ones bundled with the applications ressources files = glob.glob("sql/*.sql") if len(files) == 0: # could not find any files on disk in sql subdir if QDir(":/sql").exists(): dir_ = QDir(":/sql") dir_.setNameFilters(["*.sql"]) # in QDir.entryList files will be stripped of path # and we also need to append : files = [ ":/sql/" + x for x in dir_.entryList(filters=QDir.Files) ] # if the number of files is still zero we could not find any migrations # this would be a bug and we can terminate if len(files) == 0: print( "Could not find any Schema Files in sql/*.sql - Please reinstall application." ) print("Exiting now ...") sys.exit(1) else: # next we sort the files in the correct order files = sorted(files, key=lambda x: float(re.findall(r"(\d+)", x)[0])) # next up, we check the highest migration file version number # this should be the last list entry # if thats higher than db version we migrate # otherwise we return early doing nothing highvers = self._get_migrationfile_version( os.path.basename(files[-1])) if highvers <= db_version: print( f"Found highest Version of migration files is {highvers}") print("Nothing needs to be migrated.") return print("Performing outstanding Database migrations...") qry.exec( "SELECT version, apply_date FROM schema_changes ORDER BY version ASC" ) all_migrations = dict() while qry.next(): all_migrations[qry.value(0)] = qry.value(1) d.transaction() for file in files: scriptname: str = os.path.basename(file) file_version = self._get_migrationfile_version(scriptname) # if the database version is already higher then the version in the filename # we may skip this sql file if db_version >= file_version: print( f"Skipping {scriptname}, because migration {file_version} was already applied on {all_migrations.get(file_version, 'NULL')}" ) else: # otherwise we will execute the sql code and apply the migration try: if file.startswith(":"): fd = QFile(file) fd.open(QFile.ReadOnly | QFile.Text) sql = QTextStream(fd).readAll() else: with open(file, 'rt', encoding='utf-8') as fd: sql = fd.read() except OSError: print(f"Could not open file for reading: {file}") sys.exit(1) finally: if file.startswith(":"): fd.close() # We will have to use sqlparser to split our migration files # into atomic statements since the sqlite qt driver does not # work with multiple stmts in one exec call and offers itself # no alternative like the sqlite3.executescript() that comes # with python3... :( for stmt in sqlparse.split(sql): if not qry.exec(stmt): print(f"Applying {scriptname} to schema failed") print( f"The error appeared with the following statement:" ) print(stmt) print(qry.lastError().text()) d.rollback() sys.exit(1) if not qry.exec(f""" INSERT INTO schema_changes (version, scriptname, apply_date) VALUES ({file_version}, '{scriptname}', DATETIME('now')) """): print(qry.lastError().text()) d.rollback() sys.exit(1) else: print(f"Successfully applied {scriptname} to schema") # if we come this far we've applied all outstanding migrations # and can commit all changes to disk d.commit() print(f"All outstanding db migrations were applied") print(f"Database schema is now at version: {file_version}")
class QtSingleApplication(QApplication): messageReceived = pyqtSignal(str) def __init__(self, _id, _viewer_id, *argv): super(QtSingleApplication, self).__init__(*argv) self._id = _id self._viewer_id = _viewer_id self._activationWindow = None self._activateOnMessage = False # Is there another instance running? self._outSocket = QLocalSocket() self._outSocket.connectToServer(self._id) self._isRunning = self._outSocket.waitForConnected(-1) if self._isRunning: # Yes, there is. self._outStream = QTextStream(self._outSocket) self._outStream.setCodec('UTF-8') # Is there another viewer runnging? self._outSocketViewer = QLocalSocket() self._outSocketViewer.connectToServer(self._viewer_id) self._isRunningViewer = self._outSocketViewer.waitForConnected(-1) if self._isRunningViewer: self._outStreamViewer = QTextStream(self._outSocketViewer) self._outStreamViewer.setCodec('UTF-8') else: # app is running, we announce us as viewer app # First we remove existing servers of that name that might not have been properly closed as the server died QLocalServer.removeServer(self._viewer_id) self._outSocketViewer = None self._outStreamViewer = None self._inSocket = None self._inStream = None self._server = QLocalServer() self._server.listen(self._viewer_id) self._server.newConnection.connect(self._onNewConnection) else: self._isRunningViewer = False # No, there isn't. # First we remove existing servers of that name that might not have been properly closed as the server died QLocalServer.removeServer(self._id) self._outSocket = None self._outStream = None self._inSocket = None self._inStream = None self._server = QLocalServer() self._server.listen(self._id) self._server.newConnection.connect(self._onNewConnection) def isRunning(self): return self._isRunning def isRunningViewer(self): return self._isRunningViewer def id(self): return self._id def activationWindow(self): return self._activationWindow def setActivationWindow(self, activationWindow, activateOnMessage=True): self._activationWindow = activationWindow self._activateOnMessage = activateOnMessage def activateWindow(self): if not self._activationWindow: return self._activationWindow.show() self._activationWindow.setWindowState( self._activationWindow.windowState() & ~Qt.WindowMinimized) self._activationWindow.raise_() self._activationWindow.activateWindow() def sendMessage(self, msg): if not self._outStream: return False self._outStream << msg << '\n' self._outStream.flush() return self._outSocket.waitForBytesWritten() @pyqtSlot() def _onNewConnection(self): if self._inSocket: self._inSocket.readyRead.disconnect(self._onReadyRead) self._inSocket = self._server.nextPendingConnection() if not self._inSocket: return self._inStream = QTextStream(self._inSocket) self._inStream.setCodec('UTF-8') self._inSocket.readyRead.connect(self._onReadyRead) if self._activateOnMessage and self._isRunning: self.activateWindow() @pyqtSlot() def _onReadyRead(self): while True: msg = self._inStream.readLine() if not msg: break self.messageReceived.emit(msg)
class QtSingleApplication(QApplication): """ Adapted from https://stackoverflow.com/a/12712362/11038610 Published by Johan Rade under 2-clause BSD license, opensource.org/licenses/BSD-2-Clause """ message_received_event = pyqtSignal(str) def __init__(self, id, *argv): super().__init__(*argv) self._id = id # Is there another instance running? self._outSocket = QLocalSocket() self._outSocket.connectToServer(self._id) self._isRunning = self._outSocket.waitForConnected() if self._isRunning: # Yes, there is. self._outStream = QTextStream(self._outSocket) self._outStream.setCodec('UTF-8') else: # No, there isn't. self._outSocket = None self._outStream = None self._inSocket = None self._inStream = None self._server = QLocalServer() self._server.removeServer(self._id) self._server.listen(self._id) self._server.newConnection.connect(self._onNewConnection) def isRunning(self): return self._isRunning def id(self): return self._id def sendMessage(self, msg): if not self._outStream: return False self._outStream << msg << '\n' self._outStream.flush() return self._outSocket.waitForBytesWritten() def _onNewConnection(self): if self._inSocket: self._inSocket.readyRead.disconnect(self._onReadyRead) self._inSocket = self._server.nextPendingConnection() if not self._inSocket: return self._inStream = QTextStream(self._inSocket) self._inStream.setCodec('UTF-8') self._inSocket.readyRead.connect(self._onReadyRead) def _onReadyRead(self): while True: msg = self._inStream.readLine() if not msg: break self.message_received_event.emit(msg)
def stream_stylesheet(stylesheet_url): stylesheet = QFile(stylesheet_url) stylesheet.open(QFile.ReadOnly | QFile.Text) stream = QTextStream(stylesheet) QtWidgets.qApp.setStyleSheet(stream.readAll())
def buttonClickedInfer(self): class inferProgressWindow(progressWindow): def __init__(self): super().__init__() # add compare button to hbox self.body_button_hbox = QHBoxLayout() self.compare_button = QPushButton('Compare') self.body_button_hbox.addStretch(1) self.body_button_hbox.addWidget(self.compare_button) self.body_vbox.addLayout(self.body_button_hbox) if any(len(os.listdir(save_folder_lineEdit.text())) > 0 for save_folder_lineEdit in self.save_folder_lineEdits.values()): QMessageBox.warning(self, 'Error Message', 'Each save folder must be empty, please check if there is anything in the folder.') return if self.status is Status.initial: self.switchFromIntialToInfering() elif self.status is Status.infered: ret = QMessageBox.question(self, "Re-Infer Dialog", "Are you sure you want to Re-Infer?") if ret == QMessageBox.Yes: self.switchFromInferedToInfering() else: return # add progress window self.infer_progress_window = inferProgressWindow() self.infer_progress_window.addMultipleProgress(len(self.model_path_buttons)) self.infer_progress_window.compare_button.clicked.connect(self.buttonClickedCompare) self.window_vbox.addWidget(self.infer_progress_window) for which_model, widget_id in enumerate(self.model_path_buttons): time_stamp = int(time.time()*10e6) config_file_name = 'config_' + str(time_stamp) + '.yml' current_directory = os.getcwd() if not os.path.isdir('configs'): os.mkdir('configs') config_file_path = os.path.join(current_directory, 'configs', config_file_name) error = None config_file = None try: config_file = QFile(config_file_path) if not config_file.open(QIODevice.WriteOnly): raise IOError(str(config_file.errorString())) config_stream = QTextStream(config_file) config_stream.setCodec('UTF-8') config_stream << 'infer_settings:\n' config_stream << ' save_dir: ' << self.save_folder_lineEdits[widget_id].text() << '\n' config_stream << ' restore_from: ' << self.model_path_lineEdits[widget_id].text() << '\n' config_stream << ' data_dir: ' << self.source_image_folder_lineEdit.text() << '\n' config_stream << ' depth_dir: ' << self.depth_image_folder_lineEdit.text() << '\n' config_stream << ' model_config: ' << self.model_config_lineEdit.text() << '\n' config_stream << ' #color_type candidates: \'instance\',\'class\' ' << '\n' config_stream << ' color_type: ' << self.color_type_combobox.currentText() << '\n' print("Saved config file as {0}".format(config_file_path)) except EnvironmentError as e: error = "Failed to save {0} because of {1}".format(config_file_name, e) finally: if config_file is not None: config_file.close() if error is not None: print(error) # start inference subprocess python_version = str(self.python_version_combobox.currentText()) subprocess_args = python_version + ' ' + self.infer_script_path_lineEdit.text() + ' ' + config_file_path p = subprocess.Popen(subprocess_args, shell=True) number_of_source_images = len(os.listdir(self.source_image_folder_lineEdit.text())) while p.poll() is None: number_of_saved_images = len(os.listdir(self.save_folder_lineEdits[widget_id].text())) self.infer_progress_window.progress_bars[which_model].setValue(number_of_saved_images/number_of_source_images*100) QApplication.processEvents() QMessageBox.warning(self, 'Success Message', 'The infer process has successfully finished!') self.switchFromInferingToInfered()
def getstylesheetfromQss(qss_path): file = QFile(qss_path) file.open(QFile.ReadOnly) ts = QTextStream(file) stylesheet = ts.readAll() return stylesheet