def _wait_reply(self, call_id, call_name, timeout): """Wait for the other side reply.""" if call_id in self._reply_inbox: return # Create event loop to wait with wait_loop = QEventLoop() self._sig_got_reply.connect(wait_loop.quit) wait_timeout = QTimer() wait_timeout.setSingleShot(True) wait_timeout.timeout.connect(wait_loop.quit) # Wait until the kernel returns the value wait_timeout.start(timeout * 1000) while len(self._reply_waitlist) > 0: if not wait_timeout.isActive(): self._sig_got_reply.disconnect(wait_loop.quit) if call_id in self._reply_waitlist: raise TimeoutError("Timeout while waiting for {}".format( self._reply_waitlist)) return wait_loop.exec_() wait_timeout.stop() self._sig_got_reply.disconnect(wait_loop.quit)
def onHelp(self): """ Shows the help page """ try: from pymantidplot.proxies import showCustomInterfaceHelp showCustomInterfaceHelp("PyChop") except ImportError: helpTxt = "PyChop is a tool to allow direct inelastic neutron\nscattering users to estimate the inelastic resolution\n" helpTxt += "and incident flux for a given spectrometer setting.\n\nFirst select the instrument, chopper settings and\n" helpTxt += "Ei, and then click 'Calculate and Plot'. Data for all\nthe graphs will be generated (may take 1-2s) and\n" helpTxt += "all graphs will be updated. If the 'Hold current plot'\ncheck box is ticked, additional settings will be\n" helpTxt += "overplotted on the existing graphs if they are\ndifferent from previous settings.\n\nMore in-depth help " helpTxt += "can be obtained from the\nMantid help pages." self.hlpwin = QDialog() self.hlpedt = QLabel(helpTxt) self.hlpbtn = QPushButton('OK') self.hlpwin.layout = QVBoxLayout(self.hlpwin) self.hlpwin.layout.addWidget(self.hlpedt) self.hlpwin.layout.addWidget(self.hlpbtn) self.hlpbtn.clicked.connect(self.hlpwin.deleteLater) self.hlpwin.setWindowTitle('Help') self.hlpwin.setWindowModality(Qt.ApplicationModal) self.hlpwin.setAttribute(Qt.WA_DeleteOnClose) self.hlpwin.setMinimumSize(370, 300) self.hlpwin.resize(370, 300) self.hlpwin.show() self.hlploop = QEventLoop() self.hlploop.exec_()
def get_value(self, name): """Ask kernel for a value""" # Don't ask for values while reading (ipdb) is active if self._reading: raise ValueError( _("Inspecting and setting values while debugging " "in IPython consoles is not supported yet by " "TRex.")) # Wait until the kernel returns the value wait_loop = QEventLoop() self.sig_got_reply.connect(wait_loop.quit) self.silent_execute("get_ipython().kernel.get_value('%s')" % name) wait_loop.exec_() # Remove loop connection and loop self.sig_got_reply.disconnect(wait_loop.quit) wait_loop = None # Handle exceptions if self._kernel_value is None: if self._kernel_reply: msg = self._kernel_reply[:] self._kernel_reply = None raise ValueError(msg) return self._kernel_value
def save_notebook(self, client): """ Save notebook corresponding to given client. If the notebook is newly created and not empty, then ask the user for a new filename and save under that name. This function is called when the user closes a tab. """ client.save() # Check filename to find out whether notebook is newly created path = client.get_filename() dirname, basename = osp.split(path) if dirname != NOTEBOOK_TMPDIR or not basename.startswith('untitled'): return # Read file to see whether notebook is empty wait_save = QEventLoop() QTimer.singleShot(1000, wait_save.quit) wait_save.exec_() nb_contents = nbformat.read(path, as_version=4) if (len(nb_contents['cells']) == 0 or len(nb_contents['cells'][0]['source']) == 0): return # Ask user to save notebook with new filename buttons = QMessageBox.Yes | QMessageBox.No text = _("<b>{0}</b> has been modified.<br>" "Do you want to save changes?").format(basename) answer = QMessageBox.question(self, self.get_plugin_title(), text, buttons) if answer == QMessageBox.Yes: self.save_as(close=True)
def _loadPage(self): html_path = self._get_page_path() # QEventLoop is used to make the page loading behave syncronously init_loop = QEventLoop() self._page.loadFinished.connect(init_loop.quit) self._page.load(QUrl().fromLocalFile(html_path)) init_loop.exec_()
def get_value(self, name): """Ask kernel for a value""" code = u"get_ipython().kernel.get_value('%s')" % name if self._reading: method = self.kernel_client.input code = u'!' + code else: method = self.silent_execute # Wait until the kernel returns the value wait_loop = QEventLoop() self.sig_got_reply.connect(wait_loop.quit) method(code) wait_loop.exec_() # Remove loop connection and loop self.sig_got_reply.disconnect(wait_loop.quit) wait_loop = None # Handle exceptions if self._kernel_value is None: if self._kernel_reply: msg = self._kernel_reply[:] self._kernel_reply = None raise ValueError(msg) return self._kernel_value
def silent_exec_input(self, code): """Silently execute code through stdin""" self._hidden = True # Wait until the kernel returns an answer wait_loop = QEventLoop() self.sig_input_reply.connect(wait_loop.quit) self.kernel_client.iopub_channel.flush() self.kernel_client.input(code) wait_loop.exec_() # Remove loop connection and loop self.sig_input_reply.disconnect(wait_loop.quit) wait_loop = None # Restore hidden state self._hidden = False # Emit signal if 'pdb_step' in code and self._input_reply is not None: fname = self._input_reply['fname'] lineno = self._input_reply['lineno'] self.sig_pdb_step.emit(fname, lineno) elif 'get_namespace_view' in code: view = self._input_reply self.sig_namespace_view.emit(view) elif 'get_var_properties' in code: properties = self._input_reply self.sig_var_properties.emit(properties)
def showText(self): """ Creates a dialog to show the generated text output. """ try: generatedText = self.genText() except ValueError: return self.txtwin = QDialog() self.txtedt = QTextEdit() self.txtbtn = QPushButton('OK') self.txtwin.layout = QVBoxLayout(self.txtwin) self.txtwin.layout.addWidget(self.txtedt) self.txtwin.layout.addWidget(self.txtbtn) self.txtbtn.clicked.connect(self.txtwin.deleteLater) self.txtedt.setText(generatedText) self.txtedt.setReadOnly(True) self.txtwin.setWindowTitle('Resolution information') self.txtwin.setWindowModality(Qt.ApplicationModal) self.txtwin.setAttribute(Qt.WA_DeleteOnClose) self.txtwin.setMinimumSize(400, 600) self.txtwin.resize(400, 600) self.txtwin.show() self.txtloop = QEventLoop() self.txtloop.exec_()
def _wait(self, condition, signal, timeout_msg, timeout): """ Wait until condition() is True by running an event loop. signal: qt signal that should interrupt the event loop. timeout_msg: Message to display in case of a timeout. timeout: time in seconds before a timeout """ if condition(): return # Create event loop to wait with wait_loop = QEventLoop() signal.connect(wait_loop.quit) wait_timeout = QTimer() wait_timeout.setSingleShot(True) wait_timeout.timeout.connect(wait_loop.quit) # Wait until the kernel returns the value wait_timeout.start(timeout * 1000) while not condition(): if not wait_timeout.isActive(): signal.disconnect(wait_loop.quit) if not condition(): raise TimeoutError(timeout_msg) return wait_loop.exec_() wait_timeout.stop() signal.disconnect(wait_loop.quit)
def wait_input(self, prompt=''): """Wait for input (raw_input support)""" self.new_prompt(prompt) self.setFocus() self.input_mode = True self.input_loop = QEventLoop() self.input_loop.exec_() self.input_loop = None
def run(self, installSignalHandlers=True): if self._ownApp: self._blockApp = self.qApp else: self._blockApp = QEventLoop() self.runReturn() self._blockApp.exec_() if self.running: self.stop() self.runUntilCurrent()
def get_doc(self, objtxt): """Get object documentation dictionary""" wait_loop = QEventLoop() self.sig_got_reply.connect(wait_loop.quit) self.silent_exec_method("get_ipython().kernel.get_doc('%s')" % objtxt) wait_loop.exec_() # Remove loop connection and loop self.sig_got_reply.disconnect(wait_loop.quit) wait_loop = None return self._kernel_reply
def load_data(self, filename, ext): # Wait until the kernel tries to load the file wait_loop = QEventLoop() self.sig_got_reply.connect(wait_loop.quit) self.silent_exec_method(r"get_ipython().kernel.load_data('%s', '%s')" % (filename, ext)) wait_loop.exec_() # Remove loop connection and loop self.sig_got_reply.disconnect(wait_loop.quit) wait_loop = None return self._kernel_reply
def openMovieSelection(self, movie: Movie(), result: list()): select = MovieSelectionWindow(movie.file.fullNameAndPath, result) select.setWindowModality(Qt.WindowModal) mw = qtmodern.windows.ModernWindow(select) mw.setWindowModality(Qt.WindowModal) mw.show() # This loop will wait for the window is destroyed loop = QEventLoop() select.finished.connect(loop.quit) loop.exec() return select.acceptedId
def write_to_stdin(self, line): """Send raw characters to the IPython kernel through stdin""" wait_loop = QEventLoop() self.sig_prompt_ready.connect(wait_loop.quit) self.kernel_client.input(line) wait_loop.exec_() # Remove loop connection and loop self.sig_prompt_ready.disconnect(wait_loop.quit) wait_loop = None # Run post exec commands self._post_exec_input(line)
def openShowSelection(self, show: TvShow(), result: list()): select = ShowSelectionWindow(show.estimatedTitle, result) select.setWindowModality(Qt.WindowModal) mw = qtmodern.windows.ModernWindow(select) mw.setWindowModality(Qt.WindowModal) mw.show() # This loop will wait for the window is destroyed loop = QEventLoop() select.finished.connect(loop.quit) loop.exec() return select.acceptedId
def save_namespace(self, filename): # Wait until the kernel tries to save the file wait_loop = QEventLoop() self.sig_got_reply.connect(wait_loop.quit) self.silent_exec_method(r"get_ipython().kernel.save_namespace('%s')" % filename) wait_loop.exec_() # Remove loop connection and loop self.sig_got_reply.disconnect(wait_loop.quit) wait_loop = None return self._kernel_reply
def is_defined(self, objtxt, force_import=False): """Return True if object is defined""" wait_loop = QEventLoop() self.sig_got_reply.connect(wait_loop.quit) self.silent_exec_method( "get_ipython().kernel.is_defined('%s', force_import=%s)" % (objtxt, force_import)) wait_loop.exec_() # Remove loop connection and loop self.sig_got_reply.disconnect(wait_loop.quit) wait_loop = None return self._kernel_reply
def get_source(self, objtxt): """Get object source""" if self._reading: return wait_loop = QEventLoop() self.sig_got_reply.connect(wait_loop.quit) self.silent_exec_method("get_ipython().kernel.get_source('%s')" % objtxt) wait_loop.exec_() # Remove loop connection and loop self.sig_got_reply.disconnect(wait_loop.quit) wait_loop = None return self._kernel_reply
def __enterTitleWindow__(self, search): select = CustomEnterWindow(False) select.setWindowModality(Qt.WindowModal) mw = qtmodern.windows.ModernWindow(select) mw.setWindowModality(Qt.WindowModal) mw.show() select.ui.txtId.setFocus() loop = QEventLoop() select.finished.connect(loop.quit) loop.exec() if select.result != None: self.__possibilities__ = search(select.result) self.actualizeTable()
def enterId(self): select = CustomEnterWindow(True) select.setWindowModality(Qt.WindowModal) mw = qtmodern.windows.ModernWindow(select) mw.setWindowModality(Qt.WindowModal) mw.show() select.ui.txtId.setFocus() loop = QEventLoop() select.finished.connect(loop.quit) loop.exec() if select.result != None and select.result.isdecimal(): self.acceptedId = int(select.result) self.close()
def close_client(self, index=None, client=None, save=False): """Close client tab from index or widget (or close current tab).""" if not self.tabwidget.count(): return if client is not None: index = self.tabwidget.indexOf(client) if index is None and client is None: index = self.tabwidget.currentIndex() if index is not None: client = self.tabwidget.widget(index) is_welcome = client.get_filename() == WELCOME if not save and not is_welcome: client.save() wait_save = QEventLoop() QTimer.singleShot(1000, wait_save.quit) wait_save.exec_() path = client.get_filename() fname = osp.basename(path) nb_contents = nbformat.read(path, as_version=4) if ('untitled' in fname and len(nb_contents['cells']) > 0 and len(nb_contents['cells'][0]['source']) > 0): buttons = QMessageBox.Yes | QMessageBox.No answer = QMessageBox.question( self, self.get_plugin_title(), _("<b>{0}</b> has been modified." "<br>Do you want to " "save changes?".format(fname)), buttons) if answer == QMessageBox.Yes: self.save_as(close=True) if not is_welcome: client.shutdown_kernel() client.close() # Delete notebook file if it is in temporary directory filename = client.get_filename() if filename.startswith(get_temp_dir()): try: os.remove(filename) except EnvironmentError: pass # Note: notebook index may have changed after closing related widgets self.tabwidget.removeTab(self.tabwidget.indexOf(client)) self.clients.remove(client) self.create_welcome_client()
def get_text(self) -> str: """ 获取文本内容 :return: """ self.contentEdit.signal_request_text.emit() self.loop = QEventLoop() _text = '' def f(text): self.loop.quit() _text = text self.contentEdit.signal_text_got.connect(f) self.loop.exec_() return _text
def save_namespace(self, filename): if self._reading: message = _("Saving data while debugging is not supported.") QMessageBox.warning(self, _("Warning"), message) return # Wait until the kernel tries to save the file wait_loop = QEventLoop() self.sig_got_reply.connect(wait_loop.quit) self.silent_exec_method(r"get_ipython().kernel.save_namespace('%s')" % filename) wait_loop.exec_() # Remove loop connection and loop self.sig_got_reply.disconnect(wait_loop.quit) wait_loop = None return self._kernel_reply
def load_data(self, filename, ext): if self._reading: message = _("Loading this kind of data while debugging is not " "supported.") QMessageBox.warning(self, _("Warning"), message) return # Wait until the kernel tries to load the file wait_loop = QEventLoop() self.sig_got_reply.connect(wait_loop.quit) self.silent_exec_method( r"get_ipython().kernel.load_data('%s', '%s')" % (filename, ext)) wait_loop.exec_() # Remove loop connection and loop self.sig_got_reply.disconnect(wait_loop.quit) wait_loop = None return self._kernel_reply
def _wait(self, condition, signal, timeout_msg, timeout): """ Wait until condition() is True by running an event loop. signal: qt signal that should interrupt the event loop. timeout_msg: Message to display in case of a timeout. timeout: time in seconds before a timeout """ # Exit if condition is fulfilled or the kernel is dead. if condition(): return if not self.kernel_client.is_alive(): raise RuntimeError("Kernel is dead") # Create event loop to wait with wait_loop = QEventLoop() wait_timeout = QTimer() wait_timeout.setSingleShot(True) # Connect signals to stop kernel loop wait_timeout.timeout.connect(wait_loop.quit) self.kernel_client.hb_channel.kernel_died.connect(wait_loop.quit) signal.connect(wait_loop.quit) # Wait until the kernel returns the value wait_timeout.start(timeout * 1000) while not condition(): if not wait_timeout.isActive(): signal.disconnect(wait_loop.quit) self.kernel_client.hb_channel.kernel_died.disconnect( wait_loop.quit) if condition(): return if not self.kernel_client.is_alive(): raise RuntimeError("Kernel is dead") raise TimeoutError(timeout_msg) wait_loop.exec_() wait_timeout.stop() signal.disconnect(wait_loop.quit) self.kernel_client.hb_channel.kernel_died.disconnect( wait_loop.quit)
def wait_and_check_if_empty(filename): """ Wait until notebook is created and check whether it is empty. Repeatedly try to read the file, waiting a bit after every attempt. At the first attempt where the file exists, test whether it is empty and return. If it takes too long before the file is created, pretend it is empty. Parameters ---------- filename : str File name of notebook to be checked. Returns ------- True if notebook is empty or on timeout, False otherwise. """ for iteration in range(WAIT_SAVE_ITERATIONS): # Wait a bit wait_save = QEventLoop() QTimer.singleShot(WAIT_SAVE_DELAY, wait_save.quit) wait_save.exec_() # Try reading the file try: nb_contents = nbformat.read(filename, as_version=4) except FileNotFoundError: continue # If empty, we are done if (len(nb_contents['cells']) == 0 or len(nb_contents['cells'][0]['source']) == 0): return True else: return False else: # It is taking longer than expected; # Just return True and hope for the best return True
def save_notebook(self, client): """ Save notebook corresponding to given client. If the notebook is newly created and not empty, then ask the user whether to save it under a new name. Parameters ---------- client : NotebookClient Client of notebook to be saved. Returns ------- The file name of the notebook. """ client.save() filename = client.filename if not self.is_newly_created(client): return filename # Read file to see whether notebook is empty wait_save = QEventLoop() QTimer.singleShot(1000, wait_save.quit) wait_save.exec_() nb_contents = nbformat.read(filename, as_version=4) if (len(nb_contents['cells']) == 0 or len(nb_contents['cells'][0]['source']) == 0): return filename # Ask user to save notebook with new filename buttons = QMessageBox.Yes | QMessageBox.No text = _("<b>{0}</b> has been modified.<br>" "Do you want to save changes?").format(osp.basename(filename)) answer = QMessageBox.question( self, _('Save changes'), text, buttons) if answer == QMessageBox.Yes: return self.save_as(reopen_after_save=False) else: return filename
def _mx_wait_reply(self, usrexp, sig, code=''): wait_loop = QEventLoop() sig.connect(wait_loop.quit) self.mx_silent_exec_method(usrexp, code) wait_loop.exec_() # Remove loop connection and loop sig.disconnect(wait_loop.quit) wait_loop = None if spyder.version_info < (4, ): # Handle exceptions if sig not in self.mx_nondata_msgs: if self._mx_value is None: if self._kernel_reply: msg = self._kernel_reply[:] self._kernel_reply = None raise ValueError(msg) result = self._mx_value self._mx_value = None return result
def run(self): # immediately advance one frame self.advance() self.timer.start() loop = QEventLoop() loop.exec_()