def __init__(self, *args, **kwargs): super(MyThread, self).__init__(*args, **kwargs) self._isPause = False self._value = 0 self.cond = QWaitCondition() self.mutex = QMutex()
class SharedData: """ Provides access to shared data between Window and Classifier """ def __init__(self): self._mutex = QMutex() self._data = None self._data_available = QWaitCondition() def consume(self): self._mutex.lock() if self._data is None: self._data_available.wait(self._mutex) result = self._data self._data = None self._mutex.unlock() return result def provide(self, data): self._mutex.lock() self._data = data self._data_available.wakeAll() self._mutex.unlock()
def __init__(self, interval, project, vcs, parent=None): """ Constructor @param interval new interval in seconds (integer) @param project reference to the project object (Project) @param vcs reference to the version control object @param parent reference to the parent object (QObject) """ super(VcsStatusMonitorThread, self).__init__(parent) self.setObjectName("VcsStatusMonitorThread") self.setTerminationEnabled(True) self.projectDir = project.getProjectPath() self.project = project self.vcs = vcs self.interval = interval self.autoUpdate = False self.statusList = [] self.reportedStates = {} self.shouldUpdate = False self.monitorMutex = QMutex() self.monitorCondition = QWaitCondition() self.__stopIt = False
class Thread(QThread): signal_update = pyqtSignal() def __init__(self, window): QThread.__init__(self) self.cond = QWaitCondition() self.mutex = QMutex() self.cnt = 0 self._status = True self.window = window self.logger = Logger(window) def __del__(self): self.wait() def run(self): while True: self.mutex.lock() if not self._status: self.cond.wait(self.mutex) # self.logger.print_log("working auto bot") self.msleep(1000) # ※주의 QThread에서 제공하는 sleep을 사용 self.signal_update.emit() self.mutex.unlock() def toggle_status(self): self._status = not self._status if self._status: self.cond.wakeAll() @property def status(self): return self._status
def __init__(self): self.logger = logging.getLogger(constants.General.NAME) self.__mutex = QMutex() self.__condition = QWaitCondition() self.__data = None
def __init__(self, logger=None): QThread.__init__(self) self.cond = QWaitCondition() self.mutex = QMutex() if logger is None: exit(-1) self.logger = logger self.wakereason = self.REASON_NONE self.uievent = '' self.state = None self.statePhase = None self.timer = QTimer() self.timer.setSingleShot(False) self.timer.timeout.connect(self.__timerTick) self.timerStart.connect(self.timer.start) self.timerStop.connect(self.timer.stop) self.quit = False
def __init__(self, config, hku_config_file, market='SH'): super(self.__class__, self).__init__() self.working = True self._config = config self.hku_config_file = hku_config_file self.market = market.lower() self.marketid = None self._interval = TimeDelta(seconds=config.getint('collect', 'interval', fallback=60 * 60)) self._phase1_start_time = Datetime( datetime.datetime.combine( datetime.date.today(), datetime.time.fromisoformat( (config.get('collect', 'phase1_start', fallback='09:05')) ) ) ) self._phase1_end_time = Datetime( datetime.datetime.combine( datetime.date.today(), datetime.time.fromisoformat( (config.get('collect', 'phase1_end', fallback='09:05')) ) ) ) self._use_zhima_proxy = config.getboolean('collect', 'use_zhima_proxy', fallback=False) self.cond = QWaitCondition() self.mutex = QMutex()
class Thread(QThread): valueChange = pyqtSignal(int) def __init__(self, *args, **kwargs): super(Thread, self).__init__(*args, **kwargs) self._isPause = False self._value = 0 self.cond = QWaitCondition() self.mutex = QMutex() def pause(self): self._isPause = True def resume(self): self._isPause = False self.cond.wakeAll() def run(self): while 1: self.mutex.lock() if self._isPause: self.cond.wait(self.mutex) if self._value > 100: self._value = 0 self._value += 1 self.valueChange.emit(self._value) self.msleep(100) self.mutex.unlock()
def __init__(self, do_sync=True): self.sync_devices = set() self.do_sync = do_sync self.wc = QWaitCondition() self.mutex = QMutex() self.arrived = 0 self.buffer_maps = dict()
def __init__(self, parent, limit): QThread.__init__(self) self.cond = QWaitCondition() self.mutex = QMutex() self.is_running = True self.limit = limit self.parent = parent
class LoadingBarThread(QThread): change_value = pyqtSignal(int) def __init__(self, parent, limit): QThread.__init__(self) self.cond = QWaitCondition() self.mutex = QMutex() self.is_running = True self.limit = limit self.parent = parent def __del__(self): self.wait() def run(self): self.cnt = 0 while True: self.mutex.lock() if not self.is_running: self.cond.wait(self.mutex) if self.cnt == self.limit: self.toggle_status() self.cnt += 1 self.change_value.emit(self.cnt) self.msleep(10) self.mutex.unlock() def toggle_status(self): self.is_running = not self.is_running if self.is_running: self.cond.wakeAll()
def __init__(self): # QThread.__init__(self) super().__init__() self.cond = QWaitCondition() self.mutex = QMutex() self.cnt = 0 self._status = True
def __init__(self, recording_time=5): super().__init__() self._rec_time = recording_time # self._is_active = False self._mutex = QMutex() self._abort = False self._condition = QWaitCondition()
def shown(self): # Disable mouse handler ctx.mainScreen.dontAskCmbAgain = True ctx.mainScreen.theme_shortcut.setEnabled(False) ctx.mainScreen.ui.system_menu.setEnabled(False) # start installer thread ctx.logger.debug("PkgInstaller is creating...") self.mutex = QMutex() self.wait_condition = QWaitCondition() self.queue = Queue() self.pkg_installer = PkgInstaller(self.queue, self.mutex, self.wait_condition, self.retry_answer) self.poll_timer.start(500) # start installer polling ctx.logger.debug("Calling PkgInstaller.start...") self.pkg_installer.start() ctx.mainScreen.disableNext() ctx.mainScreen.disableBack() # start 30 seconds self.timer.start(1000 * 30) self.installProgress.showInstallProgress()
class WorkerThread(QThread): def __init__(self): QThread.__init__(self) self.cond = QWaitCondition() self.mutex = QMutex() self._status = False self.userID = "" def __del__(self): self.wait() def run(self): while True: self.mutex.lock() print("start thread") if not self._status: self.cond.wait(self.mutex) #print(userID) recordingSnd.recording(self.userID) print("going to another work") self.msleep(100) self.mutex.unlock() def toggle_status(self, userID): self.userID = userID self._status = not self._status if self._status: self.cond.wakeAll() @property def status(self): return self._status
class ConsoleInitThread(QObject): initialized = pyqtSignal(object, object) def __init__(self, *args, **kwargs): super(ConsoleInitThread, self).__init__(*args, **kwargs) self.mutex = QMutex() self.wait_condition = QWaitCondition() def run(self): self.mutex.lock() kernel_manager = QtKernelManager(kernel_name="""python3""") kernel_manager.start_kernel() kernel_client = kernel_manager.client() kernel_client.start_channels() # notify to update ui self.initialized.emit(kernel_manager, kernel_client) # wait for exit self.wait_condition.wait(self.mutex) self.mutex.unlock() # stop channels and kernel kernel_client.stop_channels() kernel_manager.shutdown_kernel() def stop(self): self.wait_condition.wakeAll()
def __init__(self, parent=None): super().__init__(parent) self._mutex = QMutex() self._condition = QWaitCondition() self.frame = None self.parameters = None self.abort = False
class SerialThread(QThread): # define a signal, when cam opens, emit this signal def __init__(self): super(SerialThread, self).__init__() # self.tnum = num self.isstop = True self.cond = QWaitCondition() self.mutex = QMutex() # self.sensor = ControlBoard() def __del__(self): # 线程状态改变与线程终止 self.isstop = True self.quit() def pause(self): # print("thread pause") self.isstop = True def resume(self): self.isstop = False self.cond.wakeAll() def run(self): pass
class DownloadManager(QThread): imagesLoaded = QtCore.pyqtSignal(list) downloadFailed = QtCore.pyqtSignal(list) allDownloaded = QtCore.pyqtSignal() downloadPaused = QtCore.pyqtSignal() downloadResumed = QtCore.pyqtSignal() exceptionRaised = QtCore.pyqtSignal(str) def __init__(self, app_state): super().__init__() self.mutex = QMutex() self.download_paused = False self.wait_condition = QWaitCondition() self.stateful_downloader = StatefulDownloader(app_state) self._has_started = False def run(self): try: self._has_started = True stateful_downloader = self.stateful_downloader for result in stateful_downloader: self.imagesLoaded.emit(result.succeeded_urls) self.downloadFailed.emit(result.failed_urls) if self.download_paused: self.downloadPaused.emit() self.mutex.lock() self.wait_condition.wait(self.mutex) self.mutex.unlock() self.allDownloaded.emit() except WordNetIdsUnavailableError: msg = 'Failed to fetch a list of WordNet ids. ' \ 'Check if ImageNet server can be reached' self.exceptionRaised.emit(msg) def pause_download(self): self.mutex.lock() self.download_paused = True self.mutex.unlock() def resume_download(self): if not self._has_started: self.start() return self.mutex.lock() self.download_paused = False self.mutex.unlock() self.wait_condition.wakeAll() self.downloadResumed.emit()
def __init__(self, window): QThread.__init__(self) self.cond = QWaitCondition() self.mutex = QMutex() self.cnt = 0 self._status = True self.window = window self.logger = Logger(window)
def __init__(self, results, *args, **kwargs): super(Thread, self).__init__(*args, **kwargs) # results 是从raw_datas查询的所有数据 一般以城市为条件查询 self.results = results self._isPause = True self._value = 1 self.cond = QWaitCondition() self.mutex = QMutex()
def __init__(self, multi=10): QThread.__init__(self) self.cond = QWaitCondition() self.mutex = QMutex() self.count = 0 self._status = True self.multi = multi print(multi)
def __init__(self, parent=None): super(FortuneThread, self).__init__(parent) self.quit = False self.hostName = "" self.cond = QWaitCondition() self.mutex = QMutex() self.port = 0
def __init__(self, max_alternatives=1): super().__init__() self.max_alter = max_alternatives self._mutex = QMutex() self._abort = False self._condition = QWaitCondition() self.client = speech.Client() self.file_path = None
def __init__(self, plugin_id, address, socket): QThread.__init__(self) self.plugin_id = plugin_id self.address = address self.udp_socket = socket self.finished.connect(self.quit) self.wait = QWaitCondition() self.mutex = QMutex()
def __init__(self): # Initialize variables(s) self.nArrived = 0 self.doSync = False self.syncSet = set() self.wc = QWaitCondition() self.imageBufferDict = dict() self.mutex = QMutex()
def __init__(self, drop_if_full=True, buffer_size=8): self.drop_if_full = drop_if_full self.buffer = Buffer(buffer_size) self.sync_devices = set() self.wc = QWaitCondition() self.mutex = QMutex() self.arrived = 0 self.current_frames = dict()
def __init__(self, app_state): super().__init__() self.mutex = QMutex() self.download_paused = False self.wait_condition = QWaitCondition() self.stateful_downloader = StatefulDownloader(app_state) self._has_started = False
def __init__(self, serial, write_queue: queue.Queue): QThread.__init__(self) self.cond = QWaitCondition() self.mutex = QMutex() self._status = False self.serial = serial self.write_queue = write_queue
def __init__(self, searcher, parent): QThread.__init__(self, parent) self._searcher = searcher self._quit = False self._mutex = QMutex() self._pending = QWaitCondition() self._collector = None self._query = None self._result = None
def __init__(self, parent=None): super(FetchPage, self).__init__(parent) print('thread initialized') self.mutex = QMutex() self.condition = QWaitCondition() self.restart = False self.abort = False
def __init__(self, parent=None): super(FortuneThread, self).__init__(parent) self.quit = False self.hostName = '' self.cond = QWaitCondition() self.mutex = QMutex() self.port = 0
def __init__(self, parent=None): super(SyncAllThread, self).__init__(parent) print("thread initialized") self.mutex = QMutex() self.condition = QWaitCondition() self.restart = False self.abort = False
def __init__(self, parent=None): super(RenderThread, self).__init__(parent) self.mutex = QMutex() self.condition = QWaitCondition() self.centerX = 0.0 self.centerY = 0.0 self.scaleFactor = 0.0 self.resultSize = QSize() self.colormap = [] self.restart = False self.abort = False for i in range(RenderThread.ColormapSize): self.colormap.append(self.rgbFromWaveLength(380.0 + (i * 400.0 / RenderThread.ColormapSize)))
class FetchPage(QThread): fetchSignal = pyqtSignal(str, name='fetchComplete') def __init__(self, parent=None): super(FetchPage, self).__init__(parent) print('thread initialized') self.mutex = QMutex() self.condition = QWaitCondition() self.restart = False self.abort = False def __del__(self): self.mutex.lock() self.abort = True self.condition.wakeOne() self.mutex.unlock() self.wait() def fetch(self, page): locker = QMutexLocker(self.mutex) self.page = page if page.content is not None: print('Returning old content') self.fetchSignal.emit(page.content) else: if not self.isRunning(): self.start(QThread.LowPriority) else: self.restart = True self.condition.wakeOne() def run(self): print("running page fetch for " + self.page.title) rest_api = RestAPI() self.page.content = (rest_api.get_page_content(self.page.content_url)) # print(self.page.content) self.fetchSignal.emit(self.page.content) # self.fetchSignal.emit() print('signal emitted') self.mutex.lock() if not self.restart: self.condition.wait(self.mutex) self.restart = False self.mutex.unlock()
class SyncAllThread(QThread): syncCompleteSignal = pyqtSignal(Dbm, name="syncComplete") def __init__(self, parent=None): super(SyncAllThread, self).__init__(parent) print("thread initialized") self.mutex = QMutex() self.condition = QWaitCondition() self.restart = False self.abort = False def __del__(self): self.mutex.lock() self.abort = True self.condition.wakeOne() self.mutex.unlock() self.wait() def sync(self): locker = QMutexLocker(self.mutex) self.dbm = Dbm() print("in sync thread") if not self.isRunning(): self.start(QThread.LowPriority) else: self.restart = True self.condition.wakeOne() def run(self): print("running sync thread") self.dbm.fetch() # print(self.page.content) self.syncCompleteSignal.emit(self.dbm) # self.fetchSignal.emit() print("signal emitted") self.mutex.lock() if not self.restart: self.condition.wait(self.mutex) self.restart = False self.mutex.unlock()
def __init__(self, parent): super(RequestHandler, self).__init__() self.parent = parent self.__terminated = False self.mutex = QMutex() self.waitForClick = QWaitCondition()
class SwitchRefreshThread(QThread): # Initialize class signals. data_signal = pyqtSignal(bool) """ This function is responsible for initializing any related objects for refresh thread. """ def __init__(self, plugin_id, address, socket): QThread.__init__(self) self.plugin_id = plugin_id self.address = address self.udp_socket = socket self.finished.connect(self.quit) self.wait = QWaitCondition() self.mutex = QMutex() """ This is the entry point for refresh thread. """ def run(self): # Run indefinately. while True: # Wait for trigger. self.mutex.lock() self.wait.wait(self.mutex) self.mutex.unlock() # Receive and discard any datagrams from this socket. self.udp_socket.setblocking(0) try: while True: _ = self.udp_socket.recv(65535) except: pass self.udp_socket.setblocking(1) self.udp_socket.settimeout(WV_REQ_TIMEOUT) try: rx_data = None if DEBUG: print("Sending an update request for", self.plugin_id, "to", self.address) # Send a request update for this plugin. self.udp_socket.sendto(bytes.fromhex(WV_UPDATE) + bytes([((self.plugin_id & 0xFF00) >> 8), (self.plugin_id & 0x00FF)]), self.address) # Receive data form the UDP port. rx_data = self.udp_socket.recv(65535) # If we did receive a vaild reply. if (rx_data[ : 4] == bytes.fromhex(WV_UPDATE_REPLY)): # Remove packet descriptor. rx_data = rx_data[4 : ] # If we did receive some data. if len(rx_data) == 1: if DEBUG: print("Got an update for", self.plugin_id, "from", self.address) # Check if we are now turned on. if (rx_data[0] == WV_PLUGIN_SWITCH_ON): # Signal the data to update the plugin display. self.data_signal.emit(True) # Check if we are now turned off. elif (rx_data[0] == WV_PLUGIN_SWITCH_OFF): # Signal the data to append the plugin display. self.data_signal.emit(False) else: if DEBUG: print("Invalid header for", self.plugin_id, "from", self.address) else: if DEBUG: print("No data received for", self.plugin_id, "from", self.address, "or invalid data was received") else: if DEBUG: print("Invalid header for", self.plugin_id, "from", self.address) except: # Nothing to do here. pass
class RenderThread(QThread): ColormapSize = 512 renderedImage = pyqtSignal(QImage, float) def __init__(self, parent=None): super(RenderThread, self).__init__(parent) self.mutex = QMutex() self.condition = QWaitCondition() self.centerX = 0.0 self.centerY = 0.0 self.scaleFactor = 0.0 self.resultSize = QSize() self.colormap = [] self.restart = False self.abort = False for i in range(RenderThread.ColormapSize): self.colormap.append(self.rgbFromWaveLength(380.0 + (i * 400.0 / RenderThread.ColormapSize))) def __del__(self): self.mutex.lock() self.abort = True self.condition.wakeOne() self.mutex.unlock() self.wait() def render(self, centerX, centerY, scaleFactor, resultSize): locker = QMutexLocker(self.mutex) self.centerX = centerX self.centerY = centerY self.scaleFactor = scaleFactor self.resultSize = resultSize if not self.isRunning(): self.start(QThread.LowPriority) else: self.restart = True self.condition.wakeOne() def run(self): while True: self.mutex.lock() resultSize = self.resultSize scaleFactor = self.scaleFactor centerX = self.centerX centerY = self.centerY self.mutex.unlock() halfWidth = resultSize.width() // 2 halfHeight = resultSize.height() // 2 image = QImage(resultSize, QImage.Format_RGB32) NumPasses = 8 curpass = 0 while curpass < NumPasses: MaxIterations = (1 << (2 * curpass + 6)) + 32 Limit = 4 allBlack = True for y in range(-halfHeight, halfHeight): if self.restart: break if self.abort: return ay = 1j * (centerY + (y * scaleFactor)) for x in range(-halfWidth, halfWidth): c0 = centerX + (x * scaleFactor) + ay c = c0 numIterations = 0 while numIterations < MaxIterations: numIterations += 1 c = c*c + c0 if abs(c) >= Limit: break numIterations += 1 c = c*c + c0 if abs(c) >= Limit: break numIterations += 1 c = c*c + c0 if abs(c) >= Limit: break numIterations += 1 c = c*c + c0 if abs(c) >= Limit: break if numIterations < MaxIterations: image.setPixel(x + halfWidth, y + halfHeight, self.colormap[numIterations % RenderThread.ColormapSize]) allBlack = False else: image.setPixel(x + halfWidth, y + halfHeight, qRgb(0, 0, 0)) if allBlack and curpass == 0: curpass = 4 else: if not self.restart: self.renderedImage.emit(image, scaleFactor) curpass += 1 self.mutex.lock() if not self.restart: self.condition.wait(self.mutex) self.restart = False self.mutex.unlock() def rgbFromWaveLength(self, wave): r = 0.0 g = 0.0 b = 0.0 if wave >= 380.0 and wave <= 440.0: r = -1.0 * (wave - 440.0) / (440.0 - 380.0) b = 1.0 elif wave >= 440.0 and wave <= 490.0: g = (wave - 440.0) / (490.0 - 440.0) b = 1.0 elif wave >= 490.0 and wave <= 510.0: g = 1.0 b = -1.0 * (wave - 510.0) / (510.0 - 490.0) elif wave >= 510.0 and wave <= 580.0: r = (wave - 510.0) / (580.0 - 510.0) g = 1.0 elif wave >= 580.0 and wave <= 645.0: r = 1.0 g = -1.0 * (wave - 645.0) / (645.0 - 580.0) elif wave >= 645.0 and wave <= 780.0: r = 1.0 s = 1.0 if wave > 700.0: s = 0.3 + 0.7 * (780.0 - wave) / (780.0 - 700.0) elif wave < 420.0: s = 0.3 + 0.7 * (wave - 380.0) / (420.0 - 380.0) r = pow(r * s, 0.8) g = pow(g * s, 0.8) b = pow(b * s, 0.8) return qRgb(r*255, g*255, b*255)
class MainWindow(QMainWindow): inputReceived = pyqtSignal(str) def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) # Left Browser tabs self.ui.tabWidgetBrowser.removeTab(1) self.ui.tabWidgetBrowser.removeTab(1) self.ui.tabWidgetBrowser.setTabsClosable(True) self.ui.tabWidgetBrowser.tabCloseRequested.connect(self.closeBrowserTab) self.ui.tabWidgetBrowser.tabBarDoubleClicked.connect(lambda: self.maximizeTabs(self.ui.tabWidgetBrowser)) # Left tree views self.fileTreeModel = QFileSystemModel(self) self.fileTreeModel.setRootPath(QDir.currentPath() + QDir.separator() + 'test') self.ui.treeViewFile.setModel(self.fileTreeModel) self.ui.treeViewFile.setRootIndex(self.fileTreeModel.index(QDir.currentPath() + QDir.separator() + 'test')) self.ui.treeViewFile.hideColumn(1) self.ui.treeViewFile.hideColumn(2) self.ui.treeViewFile.hideColumn(3) self.ui.treeViewFile.doubleClicked.connect(self.openFileFromTree) self.ui.treeViewFile.setAnimated(True) self.ui.treeViewSyntax.setAnimated(True) self.ui.treeViewToken.setAnimated(True) self.ui.treeViewFile.setHeaderHidden(True) self.ui.treeViewSyntax.setHeaderHidden(True) self.ui.treeViewToken.setHeaderHidden(True) # Editor tabs self.currentEditor = self.ui.codeEditor self.currentEditor.file = None self.currentEditorTab = self.ui.tabEditor self.openedEditors = [self.currentEditor] self.openedEditorTabs = [self.currentEditorTab] self.currentEditor.setFocus() # set focus self.ui.tabWidgetEditor.tabCloseRequested.connect(self.closeEditorTab) self.ui.tabWidgetEditor.tabBarClicked.connect(self.switchEditorTab) self.ui.tabWidgetEditor.tabBarDoubleClicked.connect(lambda: self.maximizeTabs(self.ui.tabWidgetEditor)) # Bottom console font = QFont() font.setFamily("Courier") font.setStyleHint(QFont.Monospace) font.setFixedPitch(True) font.setPointSize(10) self.ui.console.setFont(font) self.ui.console.setReadOnly(True) self.waitInputCond = QWaitCondition() self.oldConsoleText = None # Bottom output tabs self.ui.tabWidgetOutput.hide() self.ui.tabWidgetOutput.tabCloseRequested.connect(self.closeOutputTab) self.ui.tabWidgetOutput.tabBarDoubleClicked.connect(lambda: self.maximizeTabs(self.ui.tabWidgetOutput)) self.ui.tabWidgetOutput.setTabText(0, 'Console') # Previous opened tabs,for maximizing self.preOpenedTabs = None # Initial size of inner splitter self.ui.splitterInner.setSizes([180, 459 * 2 - 180]) # Menu "File" self.ui.actionOpen.triggered.connect(self.openFile) self.ui.actionNew.triggered.connect(self.newFile) self.ui.actionSave.triggered.connect(self.saveFile) self.ui.actionSaveAs.triggered.connect(self.saveFileAs) self.ui.actionQuit.triggered.connect(self.close) # Menu "Edit" self.connectMenuEditSlots() # Menu "View" self.ui.menuView.triggered.connect(self.manageMenuView) self.ui.actionAboutQt.triggered.connect(QApplication.aboutQt) # Menu "Run" self.ui.actionRun.triggered.connect(self.run) self.ui.actionBuild.triggered.connect(self.runCompile) self.ui.actionShowStable.triggered.connect(self.runSemantic) self.ui.actionRunParser.triggered.connect(self.runParser) self.ui.actionRunLexer.triggered.connect(self.runLexer) @pyqtSlot(bool) def runLexer(self, checked): """ Run lexer and present result on self.ui.tabToken Tree :return: """ p = self.genParser(Parser.mode_lexer) tokenNode = p.lexse() if p else None if not tokenNode: self.endEcho(False) return self.showBrowserTree(self.ui.tabToken, tokenNode) self.endEcho(True) @pyqtSlot(bool) def runParser(self, checked): """ Run parser and present result on self.ui.tabSyntax Tree :return: """ # Begin parse p = self.genParser(Parser.mode_parser) result = p.parse() if p else None if not result: self.endEcho(False) return syntaxNode, tokenNode = result # self.showBrowserTree(self.ui.tabToken, tokenNode) self.ui.treeViewToken.setModel(TreeModel(tokenNode)) self.showBrowserTree(self.ui.tabSyntax, syntaxNode) self.endEcho(True) @pyqtSlot(bool) def runSemantic(self, checked): """ run semantics analysing and print symbol table :return: """ p = self.genParser(Parser.mode_stable) result = p.semantic() if p else None if not result: self.endEcho(False) return stable, syntaxNode, tokenNode = result self.ui.treeViewToken.setModel(TreeModel(tokenNode)) self.ui.treeViewSyntax.setModel(TreeModel(syntaxNode)) self.endEcho(True) @pyqtSlot(bool) def runCompile(self, checked): """ Run compiler and print Intermediate code :return: """ p = self.genParser(Parser.mode_compile) result = p.compile() if p else None if not result: self.endEcho(False) return codes, stable, syntaxNode, tokenNode = result self.ui.treeViewToken.setModel(TreeModel(tokenNode)) self.ui.treeViewSyntax.setModel(TreeModel(syntaxNode)) self.endEcho(True) @pyqtSlot(bool) def run(self, checked): """ compile and run the source code compile in main thread and run in a worker thread """ p = self.genParser(Parser.mode_execute) result = p.compile() if p else None if not result: self.endEcho(False) return codes, stable, syntaxNode, tokenNode = result self.ui.treeViewToken.setModel(TreeModel(tokenNode)) self.ui.treeViewSyntax.setModel(TreeModel(syntaxNode)) console = Console(self.ui.console, parent=self, waitCond=self.waitInputCond) console.update.connect(self.updateOutput) self.inputReceived.connect(console.receivedInput) self.ui.console.blockCountChanged.connect(self.waitInput) self.ui.console.textChanged.connect(self.disableBack) interp = Interpreter(codes, stdin=console, stdout=console, stderr=console) thread = ExecuteThread(interp.inter, self) thread.start() def genParser(self, mode=Parser.mode_execute): """ Generate a parser instance :param mode: :return: """ if not self.saveFile(): return self.showOutputPanel() self.ui.actionViewConsole.setChecked(True) self.beginEcho() stdin = open(self.currentEditor.file, 'r') console = Console(self.ui.console, parent=self) console.update.connect(self.updateOutput) return Parser(stdin, stdout=console, stderr=console, mode=mode) def beginEcho(self): self.updateOutput('%s\n' % self.currentEditor.file) def endEcho(self, success=True): msg = 'successfully' if success else 'unsuccessfully' self.updateOutput('Process finished %s\n' % msg) @pyqtSlot(str) def updateOutput(self, content): """ Update bottom text browser when content is writen to it. :param content: :return: """ self.ui.console.moveCursor(QTextCursor.End) self.ui.console.insertPlainText('%s' % content) self.oldConsoleText = self.ui.console.toPlainText() @pyqtSlot(int) def waitInput(self, newBlockCount): """ :param newBlockCount: line count :return: """ if not self.ui.console.isReadOnly(): self.inputReceived.emit(self.ui.console.toPlainText() .replace(self.oldConsoleText, '')) self.waitInputCond.wakeAll() self.ui.console.setReadOnly(True) @pyqtSlot() def disableBack(self): """ disable backspace when waiting for input :return: """ if not self.ui.console.isReadOnly(): if len(self.oldConsoleText) > len(self.ui.console.toPlainText()): self.ui.console.setPlainText(self.oldConsoleText) self.ui.console.moveCursor(QTextCursor.End) def closeEvent(self, event): """ Override. When Close Event Triggered. Ask user for saving modified files :param event: :return: """ for i in range(len(self.openedEditors)): editor = self.openedEditors[i] editorTab = self.openedEditorTabs[i] if editor.document().isModified(): name = ntpath.basename(editor.file) if editor.file else 'New File' ret = QMessageBox.warning( self, name, 'The document has been modified.\nDo you want to save your changes?', QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel) if ret == QMessageBox.Save: event.accept() if self.saveFile() else event.ignore() elif ret == QMessageBox.Discard: index = self.ui.tabWidgetEditor.indexOf(editorTab) self.ui.tabWidgetEditor.removeTab(index) event.accept() else: event.ignore() def showOutputPanel(self): """ Clear previous output and show the ouput panel :return: """ self.ui.console.clear() self.ui.tabWidgetOutput.show() def showBrowserTree(self, tab, rootNode): """ Show treeView on tabWidgetBrowser :param tab: :param rootNode: """ model = TreeModel(rootNode) if tab == self.ui.tabSyntax: treeView = self.ui.treeViewSyntax name = 'Syntax' self.ui.actionViewSystaxTree.setChecked(True) else: treeView = self.ui.treeViewToken name = 'Token' self.ui.actionViewTokenTree.setChecked(True) treeView.setModel(model) # show the tab index = self.ui.tabWidgetBrowser.indexOf(tab) if index == -1: self.ui.tabWidgetBrowser.addTab(tab, name) index = self.ui.tabWidgetBrowser.indexOf(tab) self.ui.tabWidgetBrowser.setCurrentIndex(index) self.addjustBrowserWidth() def connectMenuEditSlots(self): """ set menu "Edit" signals connect to current editor slots :return: """ self.ui.actionCopy.triggered.connect(self.currentEditor.copy) self.ui.actionCut.triggered.connect(self.currentEditor.cut) self.ui.actionPaste.triggered.connect(self.currentEditor.paste) self.ui.actionUndo.triggered.connect(self.currentEditor.undo) self.ui.actionRedo.triggered.connect(self.currentEditor.redo) self.ui.actionSelectAll.triggered.connect(self.currentEditor.selectAll) def disconnectMenuEditSlots(self): """ disconnect menu "Edit" signals :return: """ self.ui.actionCopy.triggered.disconnect(self.currentEditor.copy) self.ui.actionCut.triggered.disconnect(self.currentEditor.cut) self.ui.actionPaste.triggered.disconnect(self.currentEditor.paste) self.ui.actionUndo.triggered.disconnect(self.currentEditor.undo) self.ui.actionRedo.triggered.disconnect(self.currentEditor.redo) self.ui.actionSelectAll.triggered.disconnect(self.currentEditor.selectAll) def createEditorTab(self): """ Create a new Editor tab and set as current editor Should reconnect the signal on menu 'Edit' actions :return: """ # add a new editor self.currentEditorTab = QtWidgets.QWidget() horizontalLayout = QtWidgets.QHBoxLayout(self.currentEditorTab) horizontalLayout.setContentsMargins(0, 0, 0, 0) horizontalLayout.setSpacing(6) codeEditor = CodeEditor(self.currentEditorTab) horizontalLayout.addWidget(codeEditor) self.ui.tabWidgetEditor.addTab(self.currentEditorTab, "") # disconnect signals self.disconnectMenuEditSlots() # change current tab and editors self.currentEditor = codeEditor self.currentEditor.file = None self.openedEditors.append(self.currentEditor) self.openedEditorTabs.append(self.currentEditorTab) # connect signals self.connectMenuEditSlots() # set tab closeable if len(self.openedEditorTabs) > 1: self.ui.tabWidgetEditor.setTabsClosable(True) @pyqtSlot(int) def switchEditorTab(self, index): """ Switch current active editor tab to index Should reconnect the signal on menu 'Edit' actions :param index: :return: """ self.disconnectMenuEditSlots() self.currentEditorTab = self.openedEditorTabs[index] self.currentEditor = self.openedEditors[index] self.connectMenuEditSlots() @pyqtSlot(int) def closeEditorTab(self, index): """ Triggered when closing the editor tab at index requested :param index: :return: """ self.ui.tabWidgetEditor.removeTab(index) self.openedEditorTabs.pop(index) self.openedEditors.pop(index) self.switchEditorTab(0) # choose the beginning tab as current active if len(self.openedEditorTabs) == 1: self.ui.tabWidgetEditor.setTabsClosable(False) @pyqtSlot(int) def closeBrowserTab(self, index): """ Close Left Browser Tab at index :param index: :return: """ # make menu "View" corresponding w = self.ui.tabWidgetBrowser.widget(index) if w == self.ui.tabFile: self.ui.actionViewFiles.setChecked(False) elif w == self.ui.tabToken: self.ui.actionViewTokenTree.setChecked(False) else: self.ui.actionViewSystaxTree.setChecked(False) # remove tab self.ui.tabWidgetBrowser.removeTab(index) if self.ui.tabWidgetBrowser.count() == 0: self.ui.tabWidgetBrowser.hide() @pyqtSlot(int) def closeOutputTab(self, index): """ Close(hide) the output tab widget :param index: """ # make menu "View" corresponding self.ui.actionViewConsole.setChecked(False) self.ui.tabWidgetOutput.hide() def recoverTabWidgets(self): """ recover tabs when cancel maximizing :return: """ for tab in self.preOpenedTabs: tab.show() self.preOpenedTabs = None def storeOpenedTabs(self): """ store tabs opened before maximize :return: """ self.preOpenedTabs = [] if not self.ui.tabWidgetOutput.isHidden(): self.preOpenedTabs.append(self.ui.tabWidgetOutput) if not self.ui.tabWidgetEditor.isHidden(): self.preOpenedTabs.append(self.ui.tabWidgetEditor) if not self.ui.tabWidgetBrowser.isHidden(): self.preOpenedTabs.append(self.ui.tabWidgetBrowser) def maximizeTabs(self, widget): if self.preOpenedTabs: self.recoverTabWidgets() else: self.storeOpenedTabs() for w in [self.ui.tabWidgetBrowser, self.ui.tabWidgetOutput, self.ui.tabWidgetEditor]: if w != widget: w.hide() @pyqtSlot(QAction) def manageMenuView(self, action): """ Handle the action on menu "View" :param action: :return: """ if action == self.ui.actionViewToolbar: self.ui.toolBar.show() if action.isChecked() else self.ui.toolBar.hide() return pair = { self.ui.actionViewFiles: (self.ui.tabWidgetBrowser, self.ui.tabFile, 'File'), self.ui.actionViewTokenTree: (self.ui.tabWidgetBrowser, self.ui.tabToken, 'Token'), self.ui.actionViewSystaxTree: (self.ui.tabWidgetBrowser, self.ui.tabSyntax, 'Syntax'), self.ui.actionViewConsole: (self.ui.tabWidgetOutput, self.ui.tabConsole, 'Console'), } p = pair[action] widget = p[0] tab = p[1] name = p[2] if action.isChecked(): widget.addTab(tab, name) widget.setCurrentWidget(tab) if widget == self.ui.tabWidgetBrowser: # reset tab inner splitter size self.addjustBrowserWidth() if widget.isHidden(): widget.show() else: widget.removeTab( widget.indexOf(tab)) if widget.count() == 0: widget.hide() def addjustBrowserWidth(self): w = self.ui.tabWidgetBrowser.count() * 80 self.ui.splitterInner.setSizes([w, self.ui.splitterInner.width() - w]) @pyqtSlot(bool) def openFile(self, checked=True, path=None): """ Open a new file. If current editor is associated with a file or its content is not null, Then create a new editor tab :return: """ path = QFileDialog.getOpenFileName()[0] if not path else path if len(path) != 0: qfile = QFile(path) if not qfile.open(QFile.ReadOnly or QFile.Text): QMessageBox.warning(self, 'Application', 'Cannot read file %s:\n%s.' % (path, qfile.errorString())) return with open(path, 'r') as _file: content = _file.read() if self.currentEditor.file or len(self.currentEditor.document().toPlainText()) > 0: self.createEditorTab() # associate file on disk with editor self.currentEditor.file = path # update tab name index = self.ui.tabWidgetEditor.indexOf(self.currentEditorTab) _translate = QCoreApplication.translate self.ui.tabWidgetEditor.setTabText( index, _translate("MainWindow", ntpath.basename(path))) self.ui.tabWidgetEditor.setCurrentIndex(index) self.currentEditor.setPlainText(content) @pyqtSlot(int) def openFileFromTree(self, index): f = self.fileTreeModel.fileInfo(index) if f.isFile(): self.openFile(path=f.filePath()) @pyqtSlot(bool) def newFile(self, checked): """ create a new editor tab :param action: :return: """ self.createEditorTab() index = self.ui.tabWidgetEditor.indexOf(self.currentEditorTab) _translate = QCoreApplication.translate self.ui.tabWidgetEditor.setTabText( index, _translate("MainWindow", 'New File')) self.ui.tabWidgetEditor.setCurrentIndex(index) @pyqtSlot(bool) def saveFile(self, checked=None): """ Save file. If current editor is associated with a file on the disk, then save it. Or save file as... :param checked: :return: Saved or canceled """ if self.currentEditor.file: if self.currentEditor.document().isModified(): with open(self.currentEditor.file, 'w') as f: f.write(self.currentEditor.document().toPlainText()) self.currentEditor.document().setModified(False) return True else: return self.saveFileAs() @pyqtSlot(bool) def saveFileAs(self, checked=None): """ Save File As... :param checked: :return: If saved or canceled """ dialog = QFileDialog() dialog.setWindowModality(Qt.WindowModal) dialog.setAcceptMode(QFileDialog.AcceptSave) if dialog.exec_(): filepath = dialog.selectedFiles()[0] with open(filepath, 'w') as f: f.write(self.currentEditor.document().toPlainText()) self.currentEditor.document().setModified(False) self.currentEditor.file = filepath return True else: return False
def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) # Left Browser tabs self.ui.tabWidgetBrowser.removeTab(1) self.ui.tabWidgetBrowser.removeTab(1) self.ui.tabWidgetBrowser.setTabsClosable(True) self.ui.tabWidgetBrowser.tabCloseRequested.connect(self.closeBrowserTab) self.ui.tabWidgetBrowser.tabBarDoubleClicked.connect(lambda: self.maximizeTabs(self.ui.tabWidgetBrowser)) # Left tree views self.fileTreeModel = QFileSystemModel(self) self.fileTreeModel.setRootPath(QDir.currentPath() + QDir.separator() + 'test') self.ui.treeViewFile.setModel(self.fileTreeModel) self.ui.treeViewFile.setRootIndex(self.fileTreeModel.index(QDir.currentPath() + QDir.separator() + 'test')) self.ui.treeViewFile.hideColumn(1) self.ui.treeViewFile.hideColumn(2) self.ui.treeViewFile.hideColumn(3) self.ui.treeViewFile.doubleClicked.connect(self.openFileFromTree) self.ui.treeViewFile.setAnimated(True) self.ui.treeViewSyntax.setAnimated(True) self.ui.treeViewToken.setAnimated(True) self.ui.treeViewFile.setHeaderHidden(True) self.ui.treeViewSyntax.setHeaderHidden(True) self.ui.treeViewToken.setHeaderHidden(True) # Editor tabs self.currentEditor = self.ui.codeEditor self.currentEditor.file = None self.currentEditorTab = self.ui.tabEditor self.openedEditors = [self.currentEditor] self.openedEditorTabs = [self.currentEditorTab] self.currentEditor.setFocus() # set focus self.ui.tabWidgetEditor.tabCloseRequested.connect(self.closeEditorTab) self.ui.tabWidgetEditor.tabBarClicked.connect(self.switchEditorTab) self.ui.tabWidgetEditor.tabBarDoubleClicked.connect(lambda: self.maximizeTabs(self.ui.tabWidgetEditor)) # Bottom console font = QFont() font.setFamily("Courier") font.setStyleHint(QFont.Monospace) font.setFixedPitch(True) font.setPointSize(10) self.ui.console.setFont(font) self.ui.console.setReadOnly(True) self.waitInputCond = QWaitCondition() self.oldConsoleText = None # Bottom output tabs self.ui.tabWidgetOutput.hide() self.ui.tabWidgetOutput.tabCloseRequested.connect(self.closeOutputTab) self.ui.tabWidgetOutput.tabBarDoubleClicked.connect(lambda: self.maximizeTabs(self.ui.tabWidgetOutput)) self.ui.tabWidgetOutput.setTabText(0, 'Console') # Previous opened tabs,for maximizing self.preOpenedTabs = None # Initial size of inner splitter self.ui.splitterInner.setSizes([180, 459 * 2 - 180]) # Menu "File" self.ui.actionOpen.triggered.connect(self.openFile) self.ui.actionNew.triggered.connect(self.newFile) self.ui.actionSave.triggered.connect(self.saveFile) self.ui.actionSaveAs.triggered.connect(self.saveFileAs) self.ui.actionQuit.triggered.connect(self.close) # Menu "Edit" self.connectMenuEditSlots() # Menu "View" self.ui.menuView.triggered.connect(self.manageMenuView) self.ui.actionAboutQt.triggered.connect(QApplication.aboutQt) # Menu "Run" self.ui.actionRun.triggered.connect(self.run) self.ui.actionBuild.triggered.connect(self.runCompile) self.ui.actionShowStable.triggered.connect(self.runSemantic) self.ui.actionRunParser.triggered.connect(self.runParser) self.ui.actionRunLexer.triggered.connect(self.runLexer)
class FortuneThread(QThread): newFortune = pyqtSignal(str) error = pyqtSignal(int, str) def __init__(self, parent=None): super(FortuneThread, self).__init__(parent) self.quit = False self.hostName = '' self.cond = QWaitCondition() self.mutex = QMutex() self.port = 0 def __del__(self): self.mutex.lock() self.quit = True self.cond.wakeOne() self.mutex.unlock() self.wait() def requestNewFortune(self, hostname, port): locker = QMutexLocker(self.mutex) self.hostName = hostname self.port = port if not self.isRunning(): self.start() else: self.cond.wakeOne() def run(self): self.mutex.lock() serverName = self.hostName serverPort = self.port self.mutex.unlock() while not self.quit: Timeout = 5 * 1000 socket = QTcpSocket() socket.connectToHost(serverName, serverPort) if not socket.waitForConnected(Timeout): self.error.emit(socket.error(), socket.errorString()) return while socket.bytesAvailable() < 2: if not socket.waitForReadyRead(Timeout): self.error.emit(socket.error(), socket.errorString()) return instr = QDataStream(socket) instr.setVersion(QDataStream.Qt_4_0) blockSize = instr.readUInt16() while socket.bytesAvailable() < blockSize: if not socket.waitForReadyRead(Timeout): self.error.emit(socket.error(), socket.errorString()) return self.mutex.lock() fortune = instr.readQString() self.newFortune.emit(fortune) self.cond.wait(self.mutex) serverName = self.hostName serverPort = self.port self.mutex.unlock()
class RequestHandler(QObject): """ Worker object for handling requests. """ waitingRequest = pyqtSignal() requestAccepted = pyqtSignal() error = pyqtSignal(Exception) terminated = pyqtSignal() def __init__(self, parent): super(RequestHandler, self).__init__() self.parent = parent self.__terminated = False self.mutex = QMutex() self.waitForClick = QWaitCondition() def run(self): """ Uses parent's server to listen for request. When a valid request is handled, emits requestAccepted singal and waits on Mutex condition. The parent should wake the worker when a click is made via wakeOnClick() method. When woken respond to the request with the click that was made. Can be terminated from the parent. Listening ignores bad requests. If OSError occurres, terminates itself and emits error signal. On termination emits the terminate signal. """ # print('run') self.__terminated = False while not self.__terminated: # print('Waiting for request') self.waitingRequest.emit() try: self.parent.server.listen(self.onMoveRequest) except OSError as e: print('error ', e) self.error.emit(e) self.__terminated = True except BadRequestError as e: print(e) continue print('Worker terminated') self.terminated.emit() def onMoveRequest(self, name, macroboard): if self.__terminated: return None self.opponentName = name self.macroboard = macroboard self.requestAccepted.emit() self.__sleepUntilClick() if self.__terminated: return None move = self.parent.last_click return move def __sleepUntilClick(self): self.mutex.lock() self.waitForClick.wait(self.mutex) self.mutex.unlock() def wakeOnClick(self): self.mutex.lock() self.waitForClick.wakeOne() self.mutex.unlock() def terminate(self): """ Terminates the worker. """ if self.__terminated: return self.__terminated = True self.wakeOnClick() self.parent.server.stop()
class VcsStatusMonitorThread(QThread): """ Class implementing the VCS status monitor thread base class. @signal vcsStatusMonitorData(list of str) emitted to update the VCS status @signal vcsStatusMonitorStatus(str, str) emitted to signal the status of the monitoring thread (ok, nok, op) and a status message """ vcsStatusMonitorData = pyqtSignal(list) vcsStatusMonitorStatus = pyqtSignal(str, str) def __init__(self, interval, project, vcs, parent=None): """ Constructor @param interval new interval in seconds (integer) @param project reference to the project object (Project) @param vcs reference to the version control object @param parent reference to the parent object (QObject) """ super(VcsStatusMonitorThread, self).__init__(parent) self.setObjectName("VcsStatusMonitorThread") self.setTerminationEnabled(True) self.projectDir = project.getProjectPath() self.project = project self.vcs = vcs self.interval = interval self.autoUpdate = False self.statusList = [] self.reportedStates = {} self.shouldUpdate = False self.monitorMutex = QMutex() self.monitorCondition = QWaitCondition() self.__stopIt = False def run(self): """ Public method implementing the tasks action. """ while not self.__stopIt: # perform the checking task self.statusList = [] self.vcsStatusMonitorStatus.emit( "wait", self.tr("Waiting for lock")) try: locked = self.vcs.vcsExecutionMutex.tryLock(5000) except TypeError: locked = self.vcs.vcsExecutionMutex.tryLock() if locked: try: self.vcsStatusMonitorStatus.emit( "op", self.tr("Checking repository status")) res, statusMsg = self._performMonitor() finally: self.vcs.vcsExecutionMutex.unlock() if res: status = "ok" else: status = "nok" self.vcsStatusMonitorStatus.emit( "send", self.tr("Sending data")) self.vcsStatusMonitorData.emit(self.statusList) self.vcsStatusMonitorStatus.emit(status, statusMsg) else: self.vcsStatusMonitorStatus.emit( "timeout", self.tr("Timed out waiting for lock")) if self.autoUpdate and self.shouldUpdate: self.vcs.vcsUpdate(self.projectDir, True) continue # check again self.shouldUpdate = False # wait until interval has expired checking for a stop condition self.monitorMutex.lock() if not self.__stopIt: self.monitorCondition.wait( self.monitorMutex, self.interval * 1000) self.monitorMutex.unlock() self._shutdown() self.exit() def setInterval(self, interval): """ Public method to change the monitor interval. @param interval new interval in seconds (integer) """ locked = self.monitorMutex.tryLock() self.interval = interval self.monitorCondition.wakeAll() if locked: self.monitorMutex.unlock() def getInterval(self): """ Public method to get the monitor interval. @return interval in seconds (integer) """ return self.interval def setAutoUpdate(self, auto): """ Public method to enable the auto update function. @param auto status of the auto update function (boolean) """ self.autoUpdate = auto def getAutoUpdate(self): """ Public method to retrieve the status of the auto update function. @return status of the auto update function (boolean) """ return self.autoUpdate def checkStatus(self): """ Public method to wake up the status monitor thread. """ locked = self.monitorMutex.tryLock() self.monitorCondition.wakeAll() if locked: self.monitorMutex.unlock() def stop(self): """ Public method to stop the monitor thread. """ locked = self.monitorMutex.tryLock() self.__stopIt = True self.monitorCondition.wakeAll() if locked: self.monitorMutex.unlock() def clearCachedState(self, name): """ Public method to clear the cached VCS state of a file/directory. @param name name of the entry to be cleared (string) """ key = self.project.getRelativePath(name) try: del self.reportedStates[key] except KeyError: pass def _performMonitor(self): """ Protected method implementing the real monitoring action. This method must be overridden and populate the statusList member variable with a list of strings giving the status in the first column and the path relative to the project directory starting with the third column. The allowed status flags are: <ul> <li>"A" path was added but not yet comitted</li> <li>"M" path has local changes</li> <li>"O" path was removed</li> <li>"R" path was deleted and then re-added</li> <li>"U" path needs an update</li> <li>"Z" path contains a conflict</li> <li>" " path is back at normal</li> </ul> @ireturn tuple of flag indicating successful operation (boolean) and a status message in case of non successful operation (string) @exception RuntimeError to indicate that this method must be implemented by a subclass """ raise RuntimeError('Not implemented') def _shutdown(self): """ Protected method performing shutdown actions. The default implementation does nothing. """ pass