def __initGeneralSettings(self): " Sets some generic look and feel " skin = GlobalData().skin self.setEolVisibility(Settings().ioconsoleshoweol) if Settings().ioconsolelinewrap: self.setWrapMode(QsciScintilla.WrapWord) else: self.setWrapMode(QsciScintilla.WrapNone) if Settings().ioconsoleshowspaces: self.setWhitespaceVisibility(QsciScintilla.WsVisible) else: self.setWhitespaceVisibility(QsciScintilla.WsInvisible) self.setPaper(skin.ioconsolePaper) self.setColor(skin.ioconsoleColor) self.setModified(False) self.setReadOnly(True) # If a lexer id bind then unnecessery visual effects appear like # disappearing assingned text style. As the lexer actually not required # at all I prefer not to struggle with styling but just not to use any # lexers # self.bindLexer( "", TexFileType ) self.setCurrentLineHighlight(False, None) self.setEdgeMode(QsciScintilla.EdgeNone) self.setCursorStyle() self.setAutoIndent(False) return
def __onShowHide(self, startup=False): " Triggered when show/hide button is clicked " if startup or self.__wpointsList.isVisible(): self.__wpointsList.setVisible(False) self.__enableButton.setVisible(False) self.__jumpToCodeButton.setVisible(False) self.__showHideButton.setIcon(PixmapCache().getIcon('more.png')) self.__showHideButton.setToolTip("Show watchpoints list") self.__minH = self.minimumHeight() self.__maxH = self.maximumHeight() self.setMinimumHeight(self.headerFrame.height()) self.setMaximumHeight(self.headerFrame.height()) Settings().showWatchPointViewer = False else: self.__wpointsList.setVisible(True) self.__enableButton.setVisible(True) self.__jumpToCodeButton.setVisible(True) self.__showHideButton.setIcon(PixmapCache().getIcon('less.png')) self.__showHideButton.setToolTip("Hide watchpoints list") self.setMinimumHeight(self.__minH) self.setMaximumHeight(self.__maxH) Settings().showWatchPointViewer = True return
def __onShowHide(self, startup=False): " Triggered when show/hide button is clicked " if startup or self.exceptionsList.isVisible(): self.exceptionsList.setVisible(False) self.__excTypeEdit.setVisible(False) self.__addButton.setVisible(False) self.__removeButton.setVisible(False) self.__removeAllButton.setVisible(False) self.__showHideButton.setIcon(PixmapCache().getIcon('more.png')) self.__showHideButton.setToolTip("Show ignored exceptions list") self.__minH = self.minimumHeight() self.__maxH = self.maximumHeight() self.setMinimumHeight(self.headerFrame.height()) self.setMaximumHeight(self.headerFrame.height()) Settings().showIgnoredExcViewer = False else: self.exceptionsList.setVisible(True) self.__excTypeEdit.setVisible(True) self.__addButton.setVisible(True) self.__removeButton.setVisible(True) self.__removeAllButton.setVisible(True) self.__showHideButton.setIcon(PixmapCache().getIcon('less.png')) self.__showHideButton.setToolTip("Hide ignored exceptions list") self.setMinimumHeight(self.__minH) self.setMaximumHeight(self.__maxH) Settings().showIgnoredExcViewer = True return
def __init__(self, parent): TextViewer.__init__(self, parent) self.setViewportMargins(10, 10, 10, 10) Settings().webResourceCache.sigResourceSaved.connect( self.onResourceSaved) Settings().plantUMLCache.sigRenderReady.connect(self.onPlantUMLRender)
def __settingsAboutToShow(self): " Settings menu is about to show " self.__wrapLongLinesAct.setChecked(Settings().ioconsolelinewrap) self.__showEOLAct.setChecked(Settings().ioconsoleshoweol) self.__showWhitespacesAct.setChecked(Settings().ioconsoleshowspaces) self.__autoscrollAct.setChecked(Settings().ioconsoleautoscroll) self.__showMarginAct.setChecked(Settings().ioconsoleshowmargin) return
def copySkin(): """Copies the new system-wide skins to the user settings dir. Also tests if the configured skin is in place. Sets the default if not. """ systemWideSkinsDir = srcDir + os.path.sep + "skins" + os.path.sep userSkinsDir = os.path.normpath(QDir.homePath()) + \ os.path.sep + CONFIG_DIR + os.path.sep + "skins" + os.path.sep for item in os.listdir(systemWideSkinsDir): candidate = systemWideSkinsDir + item if os.path.isdir(candidate): userCandidate = userSkinsDir + item if not os.path.exists(userCandidate): try: shutil.copytree(candidate, userCandidate) except Exception as exc: logging.error("Could not copy system wide skin from " + candidate + " to the user skin to " + userCandidate + ". Continue without copying skin.") logging.error(str(exc)) # Check that the configured skin is in place userSkinDir = userSkinsDir + Settings()['skin'] if os.path.exists(userSkinDir) and os.path.isdir(userSkinDir): # That's just fine return # Here: the configured skin is not found in the user dir. # Try to set the default. if os.path.exists(userSkinsDir + 'default'): if os.path.isdir(userSkinsDir + 'default'): logging.warning("The configured skin '" + Settings()['skin'] + "' has not been found. " "Fallback to the 'default' skin.") Settings()['skin'] = 'default' return # Default is not there. Try to pick any. anySkinName = None for item in os.listdir(userSkinsDir): if os.path.isdir(userSkinsDir + item): anySkinName = item break if anySkinName is None: # Really bad situation. No system wide skins, no local skins. logging.error("Cannot find the any Codimension skin. " "Please check Codimension installation.") return # Here: last resort - fallback to the first found skin logging.warning("The configured skin '" + Settings()['skin'] + "' has not been found. Fallback to the '" + anySkinName + "' skin.") Settings()['skin'] = anySkinName
def hiddenMessage(self, msg): " Returns True if the message should not be shown " if msg.msgType == IOConsoleMsg.STDERR_MESSAGE and \ not Settings().ioconsoleshowstderr: return True if msg.msgType == IOConsoleMsg.STDOUT_MESSAGE and \ not Settings().ioconsoleshowstdout: return True return False
def updateSettings(self): """Updates the IO console settings""" if Settings()['ioconsolelinewrap']: self.setWordWrapMode(QTextOption.WrapAnywhere) else: self.setWordWrapMode(QTextOption.NoWrap) self.drawAnyWhitespace = Settings()['ioconsoleshowspaces'] self.drawIncorrectIndentation = Settings()['ioconsoleshowspaces']
def __filterMenuTriggered(self, act): """A filter has been changed""" name = act.data() if name == 'showall': for _, settingName, _ in VARIABLE_FILTERS: Settings()[settingName] = True else: Settings()[name] = not Settings()[name] self.__updateFilter()
def terminate(self): """Called when a tab is closed""" if self.__updateTimer.isActive(): self.__updateTimer.stop() self.__updateTimer.deleteLater() self.__disconnectEditorSignals() self.__mainWindow = GlobalData().mainWindow editorsManager = self.__mainWindow.editorsManagerWidget.editorsManager editorsManager.sigFileTypeChanged.disconnect(self.__onFileTypeChanged) Settings().sigHideDocstringsChanged.disconnect( self.__onHideDocstringsChanged) Settings().sigHideCommentsChanged.disconnect( self.__onHideCommentsChanged) Settings().sigHideExceptsChanged.disconnect( self.__onHideExceptsChanged) Settings().sigSmartZoomChanged.disconnect(self.__onSmartZoomChanged) # Helps GC to collect more self.__cleanupCanvas() for index in range(self.smartViews.count()): self.smartViews.widget(index).terminate() self.smartViews.widget(index).deleteLater() self.smartViews.deleteLater() self.__navBar.deleteLater() self.__cf = None self.__saveAsButton.menu().deleteLater() self.__saveAsButton.deleteLater() self.__levelUpButton.clicked.disconnect(self.onSmartZoomLevelUp) self.__levelUpButton.deleteLater() self.__levelDownButton.clicked.disconnect(self.onSmartZoomLevelDown) self.__levelDownButton.deleteLater() self.__hideDocstrings.clicked.disconnect(self.__onHideDocstrings) self.__hideDocstrings.deleteLater() self.__hideComments.clicked.disconnect(self.__onHideComments) self.__hideComments.deleteLater() self.__hideExcepts.clicked.disconnect(self.__onHideExcepts) self.__hideExcepts.deleteLater() self.__toolbar.deleteLater() self.__editor = None self.__parentWidget = None self.cflowSettings = None self.__displayProps = None
def append(self, msg): """Appends the message to the list. Returns True if it was trimmed""" self.msgs.append(msg) self.size += 1 if self.size <= Settings()['ioconsolemaxmsgs']: return False removeCount = Settings()['ioconsoledelchunk'] self.msgs = self.msgs[removeCount:] self.size -= removeCount return True
def __init__(self, parent): TextViewer.__init__(self, parent) self.__parentWidget = parent self.setViewportMargins(10, 10, 10, 10) self.setOpenExternalLinks(True) self.setOpenLinks(False) self.anchorClicked.connect(self._onAnchorClicked) Settings().webResourceCache.sigResourceSaved.connect( self.onResourceSaved) Settings().plantUMLCache.sigRenderReady.connect(self.onPlantUMLRender)
def wheelEvent(self, event): """Mouse wheel event""" if QApplication.keyboardModifiers() == Qt.ControlModifier: angleDelta = event.angleDelta() if not angleDelta.isNull(): if angleDelta.y() > 0: Settings().onTextZoomIn() else: Settings().onTextZoomOut() event.accept() else: QutepartWrapper.wheelEvent(self, event)
def consoleSettingsUpdated(self): " Triggered when one of the consoles updated a common setting " if Settings().ioconsolelinewrap: self.__viewer.setWrapMode(QsciScintilla.WrapWord) else: self.__viewer.setWrapMode(QsciScintilla.WrapNone) self.__viewer.setEolVisibility(Settings().ioconsoleshoweol) if Settings().ioconsoleshowspaces: self.__viewer.setWhitespaceVisibility(QsciScintilla.WsVisible) else: self.__viewer.setWhitespaceVisibility(QsciScintilla.WsInvisible) self.__viewer.setTimestampMarginWidth() return
def newBreakpointWithProperties(self, bpoint): """Sets a new breakpoint and its properties""" if len(self.__breakpoints) >= Settings()['maxBreakpoints']: logging.error('The max number of breakpoints per file (' + str(Settings()['maxBreakpoints']) + ') is exceeded') return line = bpoint.getLineNumber() bpointHandle = self.__getAvailableHandle() self.__breakpoints[bpointHandle] = bpoint self.setBlockValue(self._qpart.document().findBlockByNumber(line - 1), bpointHandle) self.update()
def append( self, msg ): """ Appends the given message to the list. Returns True if there was trimming """ self.msgs.append( msg ) self.size += 1 if self.size <= Settings().ioconsolemaxmsgs: return False removeCount = Settings().ioconsoledelchunk self.msgs = self.msgs[ removeCount : ] self.size -= removeCount return True
class Login_page(Page): username_loc = (By.XPATH, '//input[@name="username"]') #用户名 password_loc = (By.XPATH, '//input[@name="password"]') #密码 loginsubmit_loc = (By.XPATH, '//input[@type="submit"]') #提交 login_valid = (By.XPATH, '//p[contains(.,"实现更便捷")]') #验证登录是否成功 username = Settings().get('user', index=0) password = Settings().get('pwd', index=0) def login(self): self.find_element(*self.username_loc).send_keys(self.username) self.find_element(*self.password_loc).send_keys(self.password) self.click(*self.loginsubmit_loc) assert '实现更便捷、更准确的沟通' in self.find_element( *self.login_valid).text, '登录失败'
def __getDiagramLayout(self): " Runs external tools to get the diagram layout " # Preparation: build a map of func ID -> fileName + line funcMap = {} index = 0 for func, props in self.__stats.stats.items(): funcMap[index] = (func[0], func[1]) index += 1 # First step is to run grpof2dot gprof2dot = thirdpartyDir + "gprof2dot" + os.path.sep + "gprof2dot.py" outputFile = self.__dataFile + ".dot" nodeLimit = Settings().profileNodeLimit edgeLimit = Settings().profileEdgeLimit dotSpec = safeRun([ gprof2dot, '-n', str(nodeLimit), '-e', str(edgeLimit), '-f', 'pstats', '-o', outputFile, self.__dataFile ]) graphDescr = safeRun(["dot", "-Tplain", outputFile]) graph = getGraphFromPlainDotData(graphDescr) graph.normalize(self.physicalDpiX(), self.physicalDpiY()) self.__scene.clear() self.__scene.setSceneRect(0, 0, graph.width, graph.height) for edge in graph.edges: self.__scene.addItem(FuncConnection(edge)) if edge.label != "": self.__scene.addItem(FuncConnectionLabel(edge)) for node in graph.nodes: fileName = "" lineNumber = 0 isOutside = True nodeID, newLabel = extractNodeID(node.label) if nodeID != -1: node.label = newLabel # Now, detect the file name/line number and # if it belongs to the project (fileName, lineNumber) = funcMap[nodeID] self.__scene.addItem( Function(node, fileName, lineNumber, self.__isOutsideItem(fileName))) return
def __init__(self, parent=None): QDialog.__init__(self, parent) self.__filesBrowser = None self.findCombo = None self.__projectLoaded = GlobalData().project.fileName != "" QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.__createLayout() self.findCombo.setFocus() QApplication.restoreOverrideCursor() # Set the window title and restore the previous searches if self.__projectLoaded: self.__findFileHistory = GlobalData().project.findFileHistory else: self.__findFileHistory = Settings().findFileHistory self.findCombo.addItems(self.__findFileHistory) self.findCombo.setEditText("") self.findCombo.editTextChanged.connect(self.__filterChanged) self.__highlightFirst() self.__updateTitle() return
def __init__(self, editorsManager, parent=None): QWidget.__init__(self, parent) self.__maxEntries = Settings()['maxSearchEntries'] self.editorsManager = editorsManager self.__editor = None self.__subscribedToCursor = False self.__createLayout() self.__changesConnected = False self.__connectOnChanges() self.__history = getFindHistory() self.__populateHistory() # Incremental search support self.__startPoint = None # {'absPos': int, 'firstVisible': int} GlobalData().project.sigProjectChanged.connect(self.__onProjectChanged) lineEdit = self.findtextCombo.lineEdit() self.__stateColors = { self.BG_IDLE: lineEdit.palette().color(lineEdit.backgroundRole()), self.BG_NOMATCH: GlobalData().skin['findNoMatchPaper'], self.BG_MATCH: GlobalData().skin['findMatchPaper'], self.BG_BROKEN: GlobalData().skin['findInvalidPaper'] }
def __onProjectChanged(self, what): """Triggered when a project is changed""" if what != CodimensionProject.CompleteProject: return self.clear() model = self.bpointsList.model().sourceModel() project = GlobalData().project if project.isLoaded(): bpoints = project.breakpoints else: bpoints = Settings().breakpoints for bpoint in bpoints: newBpoint = Breakpoint() try: if not newBpoint.deserialize(bpoint): # Non valid continue except: continue # Need to check if it still points to a breakable line line = newBpoint.getLineNumber() fileName = newBpoint.getAbsoluteFileName() breakableLines = getBreakpointLines(fileName, None, True) if breakableLines is not None and line in breakableLines: model.addBreakpoint(newBpoint) else: logging.warning("Breakpoint at " + fileName + ":" + str(line) + " does not point to a breakable " "line anymore (the file is invalid or was " "modified outside of the " "IDE etc.). The breakpoint is deleted.")
def __languageChanged(self, _=None): """Language changed""" isPython = self.__editor.isPythonBuffer() isMarkdown = self.__editor.isMarkdownBuffer() self.disasmScriptButton.setEnabled(isPython) self.__renderWidget.setVisible(not Settings()['floatingRenderer'] and (isPython or isMarkdown))
def dirty(self): """True if some other tab has switched display settings""" settings = Settings() return self.__displayProps[0] != settings['hidedocstrings'] or \ self.__displayProps[1] != settings['hidecomments'] or \ self.__displayProps[2] != settings['hideexcepts'] or \ self.__displayProps[3] != settings['smartZoom']
def updateTooltip(self): """Updates the item tooltip""" fileName = self.getFilename() # Check that the file exists if not os.path.exists(fileName): self.__isValid = False self.setToolTip(0, 'Project file does not exist') self.setToolTip(1, 'Project file does not exist') self.__markBroken() else: # Get the project properties try: tooltip = getProjectFileTooltip(fileName) if Settings()['recentTooltips']: self.setToolTip(1, tooltip) else: self.setToolTip(1, "") self.setText(0, "") if fileName == GlobalData().project.fileName: self.__markCurrent() except: # Cannot get project properties. Mark broken. self.__isValid = False self.setToolTip(0, 'Broken project file') self.setToolTip(1, 'Broken project file') self.__markBroken() self.setToolTip(2, self.getFilename())
def populateDisassembly(self, source, encoding, filename): """Populates the disassembly tree""" self.__navBar.clearWarnings() self.serializeScrollAndSelection() try: optLevel = Settings()['disasmLevel'] if source is None: props, disassembly = getFileDisassembled(filename, optLevel, stringify=False) else: props, disassembly = getBufferDisassembled(source, encoding, filename, optLevel, stringify=False) self.__table.clear() self.__setupLabel(props) self.__populate(disassembly) self.__table.header().resizeSections(QHeaderView.ResizeToContents) self.__navBar.updateInfoIcon(self.__navBar.STATE_OK_UTD) self.restoreScrollAndSelection() except Exception as exc: self.__navBar.updateInfoIcon(self.__navBar.STATE_BROKEN_UTD) self.__navBar.setErrors('Disassembling error:\n' + str(exc))
def __init__(self) -> None: # Load the settings. self.settings = Settings() # Initiate PRAW and the custom strapi wrapper. self.reddit = RedditInstance(core=self) self.strapi = StrapiInstance(core=self) # Load the RPAN subreddit list module. self.rpan_subreddits = RPANSubreddits() # Load the Sentry error tracking module. self.sentry = None if self.settings.links.sentry: self.sentry = start_sentry(link=self.settings.links.sentry) # Load the database handler. self.db_handler = DatabaseHandler(settings=self.settings) # Initiate the web and bot instances. self.web = create_app(core=self) self.bot = RPANBot(core=self) # Calculate the lines of code. self.calculate_loc() # Start the bot. self.bot.start_bot()
def __init__(self): """initialisation of the game and ressources""" # Game settings self.settings = Settings() # Pygame initializing pygame.init() # Game window self.window = pygame.display.set_mode( (self.settings.window_width, self.settings.window_height)) pygame.display.set_caption('Sudoku') # Window field self.screen = pygame.Rect(self.settings.game_left, self.settings.game_top, self.settings.game_width, self.settings.game_height) # Setting the clock self.clock = pygame.time.Clock() # Game modules # Game buttons # Game flags self.game_over = False self.pause = False self.play = True self.run = False
def writeFile(self, fileName): """Writes the text to a file""" QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) if Settings()['removeTrailingOnSave']: self.removeTrailingWhitespaces() try: encoding = detectWriteEncoding(self, fileName) if encoding is None: QApplication.restoreOverrideCursor() logging.error('Could not detect write encoding for ' + fileName) return False writeEncodedFile(fileName, self.textForSaving(), encoding) except Exception as exc: logging.error(str(exc)) QApplication.restoreOverrideCursor() return False self.encoding = encoding if self.explicitUserEncoding: userEncoding = getFileEncoding(fileName) if userEncoding != self.explicitUserEncoding: setFileEncoding(fileName, self.explicitUserEncoding) self.explicitUserEncoding = None self._parent.updateModificationTime(fileName) self._parent.setReloadDialogShown(False) QApplication.restoreOverrideCursor() return True
def __createGraphicsView(self): """ Creates the graphics view """ self.scene = CFGraphicsScene(self.__navBar, self) self.view = CFGraphicsView(self) self.view.setScene(self.scene) self.view.zoomTo(Settings().flowScale) return self.view
def updateSettings(self): " Updates settings " s = Settings() self.__needPathUpdate = s.showCFNavigationBar self.__navBar.setPathVisible(self.__needPathUpdate) self.__navBar.setPath("") return