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 get_updated_settings(args): settings = Settings.load() u = User(user=args.user, password=args.password) s = XcodeServer(host=args.host, port=args.port) settings.update(s, u) settings.validate() return settings
def __init__(self, parent, debugger): QWidget.__init__(self, parent) extendInstance(self, MarginBase) MarginBase.__init__(self, parent, "cdm_bpoint_margin", getMarginBits()) self.setMouseTracking(True) self.__debugger = debugger self.__breakpoints = {} # block handle -> Breakpoint instance self.__breakableLines = None self.__maxBreakpoints = Settings()['maxBreakpoints'] self.__bgColor = GlobalData().skin['bpointsMarginPaper'] self.__marks = { self.BPOINT_MARK: [getPixmap('dbgbpointmarker.png'), 0], self.TMP_BPOINT_MARK: [getPixmap('dbgtmpbpointmarker.png'), 0], self.DISABLED_BPOINT_MARK: [getPixmap('dbgdisbpointmarker.png'), 0]} for item in self.__marks: self.__marks[item][1] = self.__marks[item][0].height() if self.__marks[item][0].height() != self.__marks[item][0].width(): logging.error('breakpoint margin pixmap needs to be square') self.myUUID = None if hasattr(self._qpart._parent, 'getUUID'): self.myUUID = self._qpart._parent.getUUID() mainWindow = GlobalData().mainWindow editorsManager = mainWindow.editorsManagerWidget.editorsManager editorsManager.sigFileTypeChanged.connect(self.__onFileTypeChanged) self.blockClicked.connect(self.__onBlockClicked) self._qpart.blockCountChanged.connect(self.__onBlockCountChanged) bpointModel = self.__debugger.getBreakPointModel() bpointModel.rowsAboutToBeRemoved.connect(self.__deleteBreakPoints) bpointModel.sigDataAboutToBeChanged.connect( self.__breakPointDataAboutToBeChanged) bpointModel.dataChanged.connect(self.__changeBreakPoints) bpointModel.rowsInserted.connect(self.__addBreakPoints)
def main(): pygame.init() clock_object = pygame.time.Clock() game_settings = Settings() lines = Borders(game_settings) # initialize screen size screen = pygame.display.set_mode((game_settings.screen_width, game_settings.screen_height)) pygame.display.set_caption("2048") # Create game instance and add three cells to it. game_board = Board(game_settings, screen) game_board.add_tile(game_settings, quantity=3) while True: # Limits screen refreshment speed. clock_object.tick(30) game_board.draw_board(game_settings) lines.draw_lines(screen, game_settings) for event in pygame.event.get(): if event.type == pygame.QUIT: # If game window is closed. sys.exit() elif event.type == pygame.KEYDOWN: # If keyboard keys are pressed. if event.key in game_board.movement_keys: # New tile is added only if key press initiated a change in game board. # If move() or calculate() returns True, then cell value was modified, and new tile is added. change_in_move_1 = game_board.move(event.key, game_settings) change_in_calculate = game_board.calculate(event.key, game_settings) change_in_move_2 = game_board.move(event.key, game_settings) if change_in_move_1 or change_in_move_2 or change_in_calculate: game_board.add_tile(game_settings, quantity=1) elif game_board.check_game_over(game_settings): game_board.game_over(game_settings) elif event.key == pygame.K_q: sys.exit() pygame.display.flip()
def __init__(self, paintDevice, params): self.__paintDevice = paintDevice self.__params = params # Used to generate each item unique sequential ID self.itemID = 0 self.__noZoomFontMetrics = QFontMetrics(self.__params['cfMonoFont'], self.__paintDevice) self.coefficient = 1.0 for key, value in params.items(): setattr(self, key, value) # Some display related settings are coming from the IDE wide settings settings = Settings() setattr(self, 'hidedocstrings', settings['hidedocstrings']) setattr(self, 'hidecomments', settings['hidecomments']) setattr(self, 'hideexcepts', settings['hideexcepts']) setattr(self, 'hidedecors', settings['hidedecors']) # Dynamic settings for the smart zoom feature setattr(self, 'noContent', False) setattr(self, 'noComment', False) setattr(self, 'noDocstring', False) setattr(self, 'noBlock', False) setattr(self, 'noImport', False) setattr(self, 'noBreak', False) setattr(self, 'noContinue', False) setattr(self, 'noReturn', False) setattr(self, 'noRaise', False) setattr(self, 'noAssert', False) setattr(self, 'noSysExit', False) setattr(self, 'noDecor', False) setattr(self, 'noFor', False) setattr(self, 'noWhile', False) setattr(self, 'noWith', False) setattr(self, 'noTry', False) setattr(self, 'noIf', False) setattr(self, 'noGroup', False) self.onFlowZoomChanged()
def __renderMessage(self, msg): """Adds a single message""" margin = self.getMargin('cdm_redirected_io_margin') timestamp = msg.getTimestamp() if msg.msgType == IOConsoleMsg.IDE_MESSAGE: line, pos = self.getEndPosition() txt = msg.msgText startMarkLine = line if pos != 0: txt = '\n' + txt startMarkLine += 1 self.append(txt) line, _ = self.getEndPosition() for lineNo in range(startMarkLine, line + 1): margin.addData(lineNo + 1, timestamp, timestamp, IOConsoleMsg.IDE_MESSAGE) else: line, pos = self.getEndPosition() txt = msg.msgText startTimestampLine = line if pos != 0: lastMsgType = margin.getLineMessageType(line + 1) if lastMsgType == IOConsoleMsg.IDE_MESSAGE: txt = '\n' + txt startTimestampLine = line + 1 self.append(txt) endTimestampLine, pos = self.getEndPosition() if pos == 0: endTimestampLine -= 1 for lineNo in range(startTimestampLine, endTimestampLine + 1): margin.addData(lineNo + 1, timestamp, timestamp, msg.msgType) self.clearUndoRedoHistory() if Settings()['ioconsoleautoscroll']: line, pos = self.getEndPosition() self.gotoLine(line + 1, pos + 1)
def onClose( self ): """ Called when an item has been selected and the cursor jumped where it should """ # Save the current filter if needed filterText = self.findCombo.currentText().strip() if filterText != "": if filterText in self.__findNameHistory: self.__findNameHistory.remove( filterText ) self.__findNameHistory.insert( 0, filterText ) if len( self.__findNameHistory ) > 32: self.__findNameHistory = self.__findNameHistory[ : 32 ] if GlobalData().project.fileName != "": GlobalData().project.setFindNameHistory( self.__findNameHistory ) else: Settings().findNameHistory = self.__findNameHistory self.close() return
def __createProjectPopupMenu(self): """Creates the recent project popup menu""" self.__projectMenu = QMenu(self.projectsView) self.__prjLoadMenuItem = self.__projectMenu.addAction( getIcon('load.png'), 'Load', self.__loadProject) self.__projectMenu.addSeparator() self.__propsMenuItem = self.__projectMenu.addAction( getIcon('smalli.png'), 'Properties', self.__viewProperties) self.__prjCopyPathMenuItem = self.__projectMenu.addAction( getIcon('copymenu.png'), 'Copy path to clipboard', self.__prjPathToClipboard) self.__projectMenu.addSeparator() self.__delPrjMenuItem = self.__projectMenu.addAction( getIcon('trash.png'), 'Delete from recent', self.__deleteProject) self.projectsView.setContextMenuPolicy(Qt.CustomContextMenu) self.projectsView.customContextMenuRequested.connect( self.__handleShowPrjContextMenu) Settings().sigRecentListChanged.connect(self.__populateProjects) GlobalData().project.sigProjectChanged.connect(self.__projectChanged)
def __init__(self, navBar, parent): QWidget.__init__(self, parent) self.__navBar = navBar self.__textEdit = BinViewTextEditor(self) self.__summary = HeaderLabel(parent=self) self.__summary.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Maximum) self.__summary.setMinimumWidth(10) self.__summary.setVisible(False) vLayout = QVBoxLayout() vLayout.setContentsMargins(0, 0, 0, 0) vLayout.setSpacing(0) vLayout.addWidget(self.__summary) vLayout.addWidget(self.__textEdit) self.setLayout(vLayout) Settings().sigTextZoomChanged.connect(self.onTextZoomChanged)
def __appendReplaceMessage(self): """Appends a proper message to the status bar after replace""" mainWindow = GlobalData().mainWindow currentMessage = mainWindow.getCurrentStatusBarMessage() currentIndex, totalMatches = self.__editor.getMatchesInfo() if totalMatches is None or totalMatches == 0: msg = currentMessage + '; no more matches' else: if currentIndex is not None: msg = currentMessage + '; match %d of %d' % (currentIndex, totalMatches) else: if totalMatches == 1: msg = currentMessage + '; 1 match left' else: msg = currentMessage + '; %d matches left' % totalMatches if totalMatches > Settings()['maxHighlightedMatches']: msg += ' (too many to highlight)' mainWindow.showStatusBarMessage(msg)
def addExceptionFilter(self, excType): " Adds a new item into the ignored exceptions list " if excType == "": return if " " in excType: return if excType in self.__ignored: return item = QTreeWidgetItem(self.exceptionsList) item.setText(0, excType) project = GlobalData().project if project.isLoaded(): project.addExceptionFilter(excType) else: Settings().addExceptionFilter(excType) self.__ignored.append(excType) self.__updateTitle() return
def redrawScene(self): """Redraws the scene""" smartZoomLevel = Settings()['smartZoom'] self.cflowSettings = getCflowSettings(self) if self.dirty(): self.__displayProps = (self.cflowSettings.hidedocstrings, self.cflowSettings.hidecomments, self.cflowSettings.hideexcepts, smartZoomLevel) self.cflowSettings.itemID = 0 self.cflowSettings = tweakSmartSettings(self.cflowSettings, smartZoomLevel) try: fileName = self.__parentWidget.getFileName() if not fileName: fileName = self.__parentWidget.getShortName() collapsedGroups = getCollapsedGroups(fileName) # Top level canvas has no adress and no parent canvas self.__cleanupCanvas() self.__canvas = VirtualCanvas(self.cflowSettings, None, None, self.__validGroups, collapsedGroups, None) lStart = timer() self.__canvas.layoutModule(self.__cf) lEnd = timer() self.__canvas.setEditor(self.__editor) width, height = self.__canvas.render() rEnd = timer() self.scene().setSceneRect(0, 0, width, height) self.__canvas.draw(self.scene(), 0, 0) dEnd = timer() if self.isDebugMode(): logging.info('Redrawing is done. Size: %d x %d', width, height) logging.info('Layout timing: %f', lEnd - lStart) logging.info('Render timing: %f', rEnd - lEnd) logging.info('Draw timing: %f', dEnd - rEnd) except Exception as exc: logging.error(str(exc)) raise
def loadResource(self, resourceType, resourceURL): """Overloaded; by default the remote pixmaps are not loaded""" if resourceType == QTextDocument.ImageResource: url = resourceURL.toString() currentFileName = self._parentWidget.getFileName() if currentFileName: currentDir = os.path.dirname(currentFileName) + os.path.sep if url.startswith(currentDir): url = url.replace(currentDir, '', 1) lowerUrl = url.lower() if url.startswith('plantuml:'): fName = url[9:] if os.path.exists(fName): return QPixmap(fName) # I cannot return my picture. If I do that then the resource # will not be reloaded when the generated diagram is ready return None if url.startswith('cdm-image:'): try: return getPixmap(url[10:]) except Exception as exc: logging.error('Unknown Codimension cache image: ' + url[10:]) return None if lowerUrl.startswith('http:/') or lowerUrl.startswith('https:/'): if not lowerUrl.startswith('http://') and \ not lowerUrl.startswith('https://'): url = url.replace(':/', '://', 1) fName = Settings().webResourceCache.getResource( url, self._parentWidget.getUUID()) if fName is not None: try: return QPixmap(fName) except Exception as exc: logging.error('Cannot use the image from ' + fName + ': ' + str(exc)) return None return TextViewer.loadResource(self, resourceType, resourceURL)
def __populateFromProject(self): """Populates find name dialog from the project files""" mainWindow = GlobalData().mainWindow showTooltips = Settings()['findFileTooltips'] for fname in GlobalData().project.filesList: if fname.endswith(os.path.sep): continue mime, icon, _ = getFileProperties(fname) tooltip = "" if showTooltips and isPythonMime(mime): widget = mainWindow.getWidgetForFileName(fname) if widget is None: info = GlobalData().briefModinfoCache.get(fname) else: content = widget.getEditor().text info = getBriefModuleInfoFromMemory(content) if info.docstring is not None: tooltip = info.docstring.text newItem = FileItem(self.rootItem, icon, fname, tooltip) self.rootItem.appendChild(newItem) self.count += 1
def run(self, path, needDialog): " Runs the given script with redirected IO " if needDialog: params = GlobalData().getRunParameters(path) termType = Settings().terminalType profilerParams = Settings().getProfilerSettings() debuggerParams = Settings().getDebuggerSettings() dlg = RunDialog(path, params, termType, profilerParams, debuggerParams, "Run", self.__mainWindow) if dlg.exec_() != QDialog.Accepted: return GlobalData().addRunParams(path, dlg.runParams) if dlg.termType != termType: Settings().terminalType = dlg.termType # The parameters for the run are ready. # Start the run business. remoteProc = RemoteProcess() remoteProc.isProfiling = False remoteProc.procWrapper = RemoteProcessWrapper( path, self.__tcpServer.serverPort()) if Settings().terminalType == TERM_REDIRECT: remoteProc.widget = RunConsoleTabWidget( remoteProc.procWrapper.procID()) self.connect(remoteProc.procWrapper, SIGNAL('ClientStdout'), remoteProc.widget.appendStdoutMessage) self.connect(remoteProc.procWrapper, SIGNAL('ClientStderr'), remoteProc.widget.appendStderrMessage) self.connect(remoteProc.procWrapper, SIGNAL('ClientRawInput'), remoteProc.widget.rawInput) self.connect(remoteProc.widget, SIGNAL('UserInput'), self.__onUserInput) else: remoteProc.widget = None self.connect(remoteProc.procWrapper, SIGNAL('Finished'), self.__onProcessFinished) self.__processes.append(remoteProc) if remoteProc.procWrapper.start() == False: # Failed to start - the fact is logged, just remove from the list procIndex = self.__getProcessIndex(remoteProc.procWrapper.procID()) if procIndex is not None: del self.__processes[procIndex] else: if Settings().terminalType != TERM_REDIRECT: if not self.__waitTimer.isActive(): self.__waitTimer.start(1000) return
def __init__(self): # Load the configurations. self.settings = Settings() # Initiate the Reddit instance. self.reddit = GTSReddit(settings=self.settings) # Initiate Sentry (if a URL is provided in the ENV file) self.sentry = None if self.settings.sentry_url: self.sentry = sentry_sdk self.sentry.init(self.settings.sentry_url) # Initiate sections of the bot. self.points = PointsHandler(bot=self) self.widgets = Widgets(bot=self) self.posts = PostsHandler(bot=self) self.schedular = Schedular(bot=self) # Update the widgets. self.widgets.update()
def __init__(self, parent): TextEditor.__init__(self, parent, None) self.zoomTo(Settings().zoom) # line number -> [ timestamps ] self.__marginTooltip = {} self.mode = self.MODE_OUTPUT self.lastOutputPos = None self.inputEcho = True self.inputBuffer = "" self.__messages = IOConsoleMessages() self.__initGeneralSettings() self.__initMargins() self.__timestampTooltipShown = False self.__initMessageMarkers() self._updateDwellingTime() self.installEventFilter(self) return
def __initHotKeys(self): """Initializes a map for the hot keys event filter""" self.autoIndentLineAction.setShortcut('Ctrl+Shift+I') self.invokeCompletionAction.setEnabled(False) self.__hotKeys = { CTRL_SHIFT: {Qt.Key_T: self.onJumpToTop, Qt.Key_M: self.onJumpToMiddle, Qt.Key_B: self.onJumpToBottom}, SHIFT: {Qt.Key_Delete: self.onShiftDel, Qt.Key_Backtab: self.dedentLine, Qt.Key_End: self.onShiftEnd, Qt.Key_Home: self.onShiftHome}, CTRL: {Qt.Key_X: self.onShiftDel, Qt.Key_C: self.onCtrlC, Qt.Key_Insert: self.onCtrlC, Qt.Key_Apostrophe: self.onHighlight, Qt.Key_Period: self.onNextHighlight, Qt.Key_Comma: self.onPrevHighlight, Qt.Key_M: self.onCommentUncomment, Qt.Key_Space: self.onAutoComplete, Qt.Key_F1: self.onTagHelp, Qt.Key_Backslash: self.onGotoDefinition, Qt.Key_BracketRight: self.onOccurences, Qt.Key_Slash: self.onShowCalltip, Qt.Key_Minus: Settings().onTextZoomOut, Qt.Key_Equal: Settings().onTextZoomIn, Qt.Key_0: Settings().onTextZoomReset, Qt.Key_Home: self.onFirstChar, Qt.Key_End: self.onLastChar, Qt.Key_B: self.highlightInOutline, Qt.Key_QuoteLeft: self.highlightInCFlow}, ALT: {Qt.Key_U: self.onScopeBegin}, CTRL_KEYPAD: {Qt.Key_Minus: Settings().onTextZoomOut, Qt.Key_Plus: Settings().onTextZoomIn, Qt.Key_0: Settings().onTextZoomReset}, NO_MODIFIER: {Qt.Key_Home: self.onHome, Qt.Key_End: self.moveToLineEnd, Qt.Key_F12: self.makeLineFirst}} # Not all the derived classes need certain tool functionality if hasattr(self._parent, "getType"): widgetType = self._parent.getType() if widgetType in [MainWindowTabWidgetBase.PlainTextEditor]: if hasattr(self._parent, "onOpenImport"): self.__hotKeys[CTRL][Qt.Key_I] = self._parent.onOpenImport if hasattr(self._parent, "onNavigationBar"): self.__hotKeys[NO_MODIFIER][Qt.Key_F2] = \ self._parent.onNavigationBar
def __applyDisabledPlugins(self, collectedPlugins): """Marks the disabled plugins in accordance to settings""" for disabledPlugin in Settings()['disabledPlugins']: # Parse the record try: conflictType, path, conflictMessage = \ CDMPluginInfo.parseDisabledLine(disabledPlugin) except Exception as excpt: logging.warning(str(excpt)) continue found = False for category in collectedPlugins: for plugin in collectedPlugins[category]: if plugin.getPath() == path: found = True plugin.conflictType = conflictType plugin.conflictMessage = conflictMessage if category in self.inactivePlugins: self.inactivePlugins[category].append(plugin) else: self.inactivePlugins[category] = [plugin] collectedPlugins[category].remove(plugin) break if found: break if not found: # Second try - search through the unknown plugins for plugin in self.unknownPlugins: if plugin.getPath() == path: found = True plugin.conflictType = conflictType plugin.conflictMessage = conflictMessage break if not found: logging.warning("The disabled plugin at " + path + " has not been found. The information that" " the plugin is disabled will be deleted.")
def __init__(self): """Initialize the game and create game's ressources""" # Game settings self.settings = Settings() # Pygame intiliazing pygame.init() # Game Window self.window = pygame.display.set_mode( (self.settings.window_width, self.settings.window_height) ) pygame.display.set_caption('SnAAke') # 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 self.snake = Snake(self) self.apple = Apple(self) self.scoreboard = Scoreboard(self) # Game button self.play_button = PlayButton(self, 'Play') self.exit_button = ExitButton(self, 'Exit') self.restart_button = RestartButton(self, 'Restart') # Game flags self.game_over = False self.pause = False self.play = True self.run = False
def __populateGlobalScope(self): """Repopulates the global scope combo box""" self.__globalScopeCombo.clear() self.__populateClassesAndFunctions(self.__currentInfo, self.__globalScopeCombo) if not Settings()['navbarglobalsimports']: return if len(self.__currentInfo.globals) == 0 and \ len(self.__currentInfo.imports) == 0: return if self.__globalScopeCombo.count() != 0: self.__globalScopeCombo.insertSeparator( self.__globalScopeCombo.count()) for glob in self.__currentInfo.globals: self.__globalScopeCombo.addItem('global ' + glob.name, glob.line) for imp in self.__currentInfo.imports: self.__globalScopeCombo.addItem('import ' + imp.name, imp.line)
def __onRemoveFromIgnore(self): """Removes an item from the ignored exception types list""" if self.__currentItem is None: return text = self.__currentItem.text(0) # Find the item index and remove it index = 0 while True: if self.exceptionsList.topLevelItem(index).text(0) == text: self.exceptionsList.takeTopLevelItem(index) break index += 1 project = GlobalData().project if project.isLoaded(): project.deleteExceptionFilter(text) else: Settings().deleteExceptionFilter(text) self.__ignored.remove(text) self.__updateTitle()
def launchUserInterface(): """UI launchpad""" globalData = GlobalData() if globalData.splash is not None: globalData.splash.finish(globalData.mainWindow) splashScreen = globalData.splash globalData.splash = None del splashScreen for message in __delayedWarnings: logging.warning(message) # Load the available plugins globalData.pluginManager.load() # Additional checks may come here globalData.mainWindow.getToolbar().setVisible( Settings()['showMainToolBar']) # Some startup time objects could be collected here. In my test runs # there were around 700 objects. gc.collect()
def __populateFromOpened(self): " Populates the name dialog from the opened files " mainWindow = GlobalData().mainWindow editorsManager = mainWindow.editorsManagerWidget.editorsManager showTooltips = Settings().findFileTooltips for record in editorsManager.getTextEditors(): # uuid = record[ 0 ] fname = record[1] widget = record[2] fileType = detectFileType(fname) tooltip = "" if showTooltips and fileType in [PythonFileType, Python3FileType]: content = widget.getEditor().text() info = getBriefModuleInfoFromMemory(content) if info.docstring is not None: tooltip = info.docstring.text newItem = FileItem(self.rootItem, getFileIcon(fileType), fname, tooltip) self.rootItem.appendChild(newItem) self.count += 1 return
def highlightRegexp(self, regExp, searchPos, forward, needMessage=True): """Highlights the matches, moves cursor, displays message""" highlighted = self.updateFoundItemsHighlighting(regExp) match = self.__searchInText(regExp, searchPos, forward) if match is not None: matchIndex = self.__matchesCache.index(match) + 1 totalMatches = len(self.__matchesCache) self.absCursorPosition = match.start() self.ensureCursorVisible() if needMessage: if highlighted: if self.__matchesCache: msg = 'match %d of %d' % (matchIndex, totalMatches) else: msg = 'no matches' else: msg = 'match %d of %d (too many to highlight, ' \ 'exceeds the limit of %d)' % \ (matchIndex, totalMatches, Settings()['maxHighlightedMatches']) self.__showStatusBarMessage(msg) return len(self.__matchesCache)
def updateSettings(self): """Updates the editor settings""" settings = Settings() if settings['verticalEdge']: self.lineLengthEdge = settings['editorEdge'] self.lineLengthEdgeColor = GlobalData().skin['edgeColor'] self.drawSolidEdge = True else: self.lineLengthEdge = None self.drawAnyWhitespace = settings['showSpaces'] self.drawIncorrectIndentation = settings['showSpaces'] if settings['lineWrap']: self.setWordWrapMode(QTextOption.WrapAnywhere) else: self.setWordWrapMode(QTextOption.NoWrap) if hasattr(self._parent, "getNavigationBar"): navBar = self._parent.getNavigationBar() if navBar: navBar.updateSettings()
def __populateFromProject(self): " Populates find name dialog from the project files " mainWindow = GlobalData().mainWindow showTooltips = Settings().findFileTooltips for fname in GlobalData().project.filesList: if fname.endswith(os.path.sep): continue fileType = detectFileType(fname) tooltip = "" if showTooltips and fileType in [PythonFileType, Python3FileType]: widget = mainWindow.getWidgetForFileName(fname) if widget is None: info = GlobalData().briefModinfoCache.get(fname) else: content = widget.getEditor().text() info = getBriefModuleInfoFromMemory(content) if info.docstring is not None: tooltip = info.docstring.text newItem = FileItem(self.rootItem, getFileIcon(fileType), fname, tooltip) self.rootItem.appendChild(newItem) self.count += 1 return
def __init__(self, view: BaseTFWindow): self.view: BaseTFWindow = view self.is_plotted: bool = False self.plot_ampl: bool = True self.tasks_completed: int = 0 self.signals: Signals = None self.selected_signal_name: str = None self.open_file: str = None self.freq: float = None self.mp_handler: MPHandler = None self.preproc_mp_handler: MPHandler = None self._logger: WindowLogger = stdout_redirect.WindowLogger(self.on_log) self._can_save_data: bool = False self.settings: Settings = Settings() errorhandling.subscribe(self.on_error) stdout_redirect.subscribe(self._logger) # Will be used to record the parameters passed to the algorithms. This is useful when saving data. self.params = None
def __activatePlugins(self, collectedPlugins): """Activating the plugins""" from utils.globals import GlobalData for category in collectedPlugins: for plugin in collectedPlugins[category]: try: plugin.getObject().activate(Settings(), GlobalData()) if category in self.activePlugins: self.activePlugins[category].append(plugin) else: self.activePlugins[category] = [plugin] self.sendPluginActivated(plugin) except Exception as excpt: logging.error("Error activating plugin at " + plugin.getPath() + ". The plugin disabled. Error message: \n" + str(excpt)) plugin.conflictType = CDMPluginManager.BAD_ACTIVATION plugin.conflictMessage = "Error activating the plugin" if category in self.inactivePlugins: self.inactivePlugins[category].append(plugin) else: self.inactivePlugins[category] = [plugin]
def populateBinary(self, source, encoding, filename): """Populates the disassembly tree""" self.__navBar.clearWarnings() self.serializeScrollAndSelection() try: optLevel = Settings()['disasmLevel'] if source is None: props, binContent = getFileBinary(filename, optLevel) else: props, binContent = getBufferBinary(source, encoding, filename, optLevel) self.__textEdit.clear() self.__populate(binContent, props) self.__setupLabel(props) self.__navBar.updateInfoIcon(self.__navBar.STATE_OK_UTD) QTimer.singleShot(0, self.restoreScrollAndSelection) except Exception as exc: self.__navBar.updateInfoIcon(self.__navBar.STATE_BROKEN_UTD) self.__navBar.setErrors('Binary view populating error:\n' + str(exc))
def __onFileTypeChanged(self, fileName, uuid, newFileType): " Triggered when a buffer content type has changed " if self.__parentWidget.getUUID() != uuid: return if newFileType not in [Python3FileType, PythonFileType]: self.__disconnectEditorSignals() self.__updateTimer.stop() self.__cf = None self.setVisible(False) self.__navBar.updateInfoIcon(self.__navBar.STATE_UNKNOWN) return # Update the bar and show it self.setVisible(True) self.process() # The buffer type change event comes when the content is loaded first # time. So this is a good point to restore the position _, _, _, cflowHPos, cflowVPos = Settings().filePositions.getPosition( fileName) self.setScrollbarPositions(cflowHPos, cflowVPos) return
def handle_init(args): settings = get_settings(args) settings.store(not args.local) path = Settings.storage_path(not args.local) success("Settings saved successfully to '%s'" % path)
#!/usr/bin/env python # encoding: utf-8 import requests, re, argparse, time, sys from utils.settings import Settings from utils.words import Words from utils.file import File reload(sys) sys.setdefaultencoding( "utf-8" ) ALPHABET = [chr(i) for i in range(97, 123)] def get_words(): all_words = {} for char in ALPHABET: try: if Settings.VERBOSE: print "\n>> Getting words starting with '%s'" %char.upper() words = Words.get( char ).with_variants() all_words.update( words ) except IndexError: continue return all_words if __name__ == '__main__': Settings.check() File.write( get_words() )
class FindFileDialog(QDialog): " Find file dialog implementation " 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 __highlightFirst(self): " Sets the selection to the first item in the files list " if self.__filesBrowser.getVisible() == 0: return self.__filesBrowser.clearSelection() first = self.__filesBrowser.model().index(0, 0, QModelIndex()) self.__filesBrowser.setCurrentIndex(first) self.__filesBrowser.scrollTo(first) return def __updateTitle(self): " Updates the window title " title = "Find file in the " if self.__projectLoaded: title += "project: " else: title += "opened files: " title += str( self.__filesBrowser.getVisible() ) + " of " + \ str( self.__filesBrowser.getTotal() ) self.setWindowTitle(title) return def __createLayout(self): """ Creates the dialog layout """ self.resize(600, 300) self.setSizeGripEnabled(True) verticalLayout = QVBoxLayout(self) self.__filesBrowser = FilesBrowser(self) verticalLayout.addWidget(self.__filesBrowser) self.findCombo = EnterSensitiveComboBox(self) self.__tuneCombo(self.findCombo) self.findCombo.lineEdit().setToolTip( "Regular expression to search for") verticalLayout.addWidget(self.findCombo) self.findCombo.enterClicked.connect(self.__enterInFilter) return @staticmethod def __tuneCombo(comboBox): " Sets the common settings for a combo box " sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(comboBox.sizePolicy().hasHeightForWidth()) comboBox.setSizePolicy(sizePolicy) comboBox.setEditable(True) comboBox.setInsertPolicy(QComboBox.InsertAtTop) comboBox.setAutoCompletion(False) comboBox.setDuplicatesEnabled(False) return def __filterChanged(self, text): " Triggers when the filter text changed " self.__filesBrowser.setFilter(text) self.__highlightFirst() self.__updateTitle() return def onClose(self): """ Called when an item has been selected and the cursor jumped where it should """ # Save the current filter if needed filterText = self.findCombo.currentText().strip() if filterText != "": if filterText in self.__findFileHistory: self.__findFileHistory.remove(filterText) self.__findFileHistory.insert(0, filterText) if len(self.__findFileHistory) > 32: self.__findFileHistory = self.__findFileHistory[:32] if GlobalData().project.fileName != "": GlobalData().project.setFindFileHistory(self.__findFileHistory) else: Settings().findFileHistory = self.__findFileHistory self.close() return def __enterInFilter(self): " Handles ENTER and RETURN keys in the find combo " if self.__filesBrowser.getVisible() == 0: return self.__filesBrowser.openCurrentItem() return
class FindFileDialog( QDialog ): " Find file dialog implementation " 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 __highlightFirst( self ): " Sets the selection to the first item in the files list " if self.__filesBrowser.getVisible() == 0: return self.__filesBrowser.clearSelection() first = self.__filesBrowser.model().index( 0, 0, QModelIndex() ) self.__filesBrowser.setCurrentIndex( first ) self.__filesBrowser.scrollTo( first ) return def __updateTitle( self ): " Updates the window title " title = "Find file in the " if self.__projectLoaded: title += "project: " else: title += "opened files: " title += str( self.__filesBrowser.getVisible() ) + " of " + \ str( self.__filesBrowser.getTotal() ) self.setWindowTitle( title ) return def __createLayout( self ): """ Creates the dialog layout """ self.resize( 600, 300 ) self.setSizeGripEnabled( True ) verticalLayout = QVBoxLayout( self ) self.__filesBrowser = FilesBrowser( self ) verticalLayout.addWidget( self.__filesBrowser ) self.findCombo = EnterSensitiveComboBox( self ) self.__tuneCombo( self.findCombo ) self.findCombo.lineEdit().setToolTip( "Regular expression to search for" ) verticalLayout.addWidget( self.findCombo ) self.findCombo.enterClicked.connect( self.__enterInFilter ) return @staticmethod def __tuneCombo( comboBox ): " Sets the common settings for a combo box " sizePolicy = QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Fixed ) sizePolicy.setHorizontalStretch( 0 ) sizePolicy.setVerticalStretch( 0 ) sizePolicy.setHeightForWidth( comboBox.sizePolicy().hasHeightForWidth() ) comboBox.setSizePolicy( sizePolicy ) comboBox.setEditable( True ) comboBox.setInsertPolicy( QComboBox.InsertAtTop ) comboBox.setAutoCompletion( False ) comboBox.setDuplicatesEnabled( False ) return def __filterChanged( self, text ): " Triggers when the filter text changed " self.__filesBrowser.setFilter( text ) self.__highlightFirst() self.__updateTitle() return def onClose( self ): """ Called when an item has been selected and the cursor jumped where it should """ # Save the current filter if needed filterText = self.findCombo.currentText().strip() if filterText != "": if filterText in self.__findFileHistory: self.__findFileHistory.remove( filterText ) self.__findFileHistory.insert( 0, filterText ) if len( self.__findFileHistory ) > 32: self.__findFileHistory = self.__findFileHistory[ : 32 ] if GlobalData().project.fileName != "": GlobalData().project.setFindFileHistory( self.__findFileHistory ) else: Settings().findFileHistory = self.__findFileHistory self.close() return def __enterInFilter( self ): " Handles ENTER and RETURN keys in the find combo " if self.__filesBrowser.getVisible() == 0: return self.__filesBrowser.openCurrentItem() return