Exemplo n.º 1
0
    def createConsoleTab(self):
        """ Initialize a python console and return its widget """
        from qtconsole.rich_jupyter_widget import RichJupyterWidget
        from qtconsole.manager import QtKernelManager

        kernel_manager = QtKernelManager(kernel_name='python3')
        kernel_manager.start_kernel()
        kernel = kernel_manager.kernel
        kernel.gui = 'qt'

        kernel_client = kernel_manager.client()
        kernel_client.start_channels()
        kernel_client.namespace = self

        def stop():
            kernel_client.stop_channels()
            kernel_manager.shutdown_kernel()

        widget = RichJupyterWidget(parent=self)
        widget.kernel_manager = kernel_manager
        widget.kernel_client = kernel_client
        widget.exit_requested.connect(stop)
        ipython_widget = widget
        ipython_widget.show()
        self.kernel_client = kernel_client
        #kernel_client.execute("import devices.demo.demo")
        return widget
Exemplo n.º 2
0
    def createJupyterWidget(self):
        """Create the Jupyter widget"""

        self.consoleWidget = RichJupyterWidget()
        #self.consoleWidget.setMinimumSize(600, 550)

        # Show the banner
        self.consoleWidget.banner = constants.QtipBanner
        self.consoleWidget.kernel_manager = self.kernelManager

        # Couple the client
        self.consoleWidget.kernel_client = self.kernelClient
        self.consoleWidget.exit_requested.connect(self.toggleJupyter)
        self.consoleWidget.set_default_style(colors='linux')
        self.consoleWidget.hide()

        # Register a call-back function for the Jupyter shell. This one is
        # executed insite the child-kernel.
        #self.kernel.shell.register_post_execute(self.postExecute)
        #
        # In Jupyter >= 2, we can use the event register
        # Events: post_run_cell, pre_run_cell, etc...`
        self.kernel.shell.events.register('pre_execute', self.preExecute)
        self.kernel.shell.events.register('post_execute', self.postExecute)
        self.kernel.shell.events.register('post_run_cell', self.postRunCell)
Exemplo n.º 3
0
def createConsole(parent):
    """
    disclaimer: this code is not mine. I copied it to get an embedded console
    It will be modified at some point to attempt interactability

    source: https://stackoverflow.com/a/26676570

    :param parent:
    :return:
    """
    kernel_manager = QtInProcessKernelManager()
    kernel_manager.start_kernel()
    kernel = kernel_manager.kernel
    kernel.gui = 'qt4'

    kernel_client = kernel_manager.client()
    kernel_client.start_channels()
    kernel_client.namespace = parent

    def stop():
        kernel_client.stop_channels()
        kernel_manager.shutdown_kernel()

    layout = QVBoxLayout(parent)
    widget = RichJupyterWidget(parent=parent)
    layout.addWidget(widget, Qt.AlignRight)
    widget.kernel_manager = kernel_manager
    widget.kernel_client = kernel_client
    widget.exit_requested.connect(stop)
    ipython_widget = widget
    ipython_widget.show()
    kernel.shell.push({'widget': widget, 'kernel': kernel, 'parent': parent})
    return {'widget': widget, 'kernel': kernel}
Exemplo n.º 4
0
    def __init__(self, title, icon):
        DockWidget.__init__(self, core.mainWindow(), title, icon, "Alt+I")
        self.setObjectName(title)

        self.setAllowedAreas(Qt.BottomDockWidgetArea | Qt.LeftDockWidgetArea
                             | Qt.RightDockWidgetArea)

        # Copied from https://github.com/jupyter/qtconsole/blob/master/examples/inprocess_qtconsole.py, then modified based on https://github.com/jupyter/qtconsole/blob/master/qtconsole/qtconsoleapp.py -- the QtInProcessKernelManager is blocking, so infinite loops crash Enki!
        kernel_manager = QtKernelManager()
        kernel_manager.start_kernel()
        kernel_manager.client_factory = QtKernelClient
        kernel_manager.kernel.gui = 'qt'

        kernel_client = kernel_manager.client()
        kernel_client.start_channels()

        self.ipython_widget = RichJupyterWidget()
        self.ipython_widget.kernel_manager = kernel_manager
        self.ipython_widget.kernel_client = kernel_client
        # By default, iPython adds a blank line between inputs. Per Monika's request, this eliminates the extra line. See https://qtconsole.readthedocs.io/en/latest/config_options.html#options; this fix was based on info from https://stackoverflow.com/questions/38652671/ipython-5-0-remove-spaces-between-input-lines.
        self.ipython_widget.input_sep = ''
        self.ipython_widget.show()

        self.setWidget(self.ipython_widget)
        self.setFocusProxy(self.ipython_widget)
Exemplo n.º 5
0
    def __init__(self, parent=None):
        """
        :param  parent: specifies the parent widget.
        If no parent widget has been specified, it is possible to
        exit the interpreter by Ctrl-D.
        """
        if sys.executable.endswith('pythonw.exe'):
            lpylog = open(tempfile.gettempdir() + '/lpylog.txt', 'w')
            sys.stdout = lpylog
            sys.stderr = lpylog

        RichJupyterWidget.__init__(self, parent)

        self.kernel_manager = QtInProcessKernelManager()
        self.kernel_manager.start_kernel(show_banner=False)

        self.kernel = self.kernel_manager.kernel
        self.kernel.gui = 'qt'

        self.shell = self.kernel.shell

        self.kernel_client = self.kernel_manager.client()
        self.kernel_client.start_channels()

        self.kernel.locals = self.kernel.shell.user_ns
Exemplo n.º 6
0
    def __init__(
            self,
            parent=None,
            profile='spockdoor',
            use_model_from_profile=False,
            extensions=None,
            kernel='python3',
            **kw):
        RichJupyterWidget.__init__(self, parent=parent, **kw)
        TaurusBaseWidget.__init__(self)
        self.setObjectName(self.__class__.__name__)
        self.setModelInConfig(True)

        self._profile = profile
        self.use_model_from_profile = use_model_from_profile

        if extensions is None:
            extensions = []
        extensions.insert(
            0, "sardana.taurus.qt.qtgui.extra_sardana.qtspock_ext")

        self._extensions = extensions
        self._kernel_name = kernel

        self._macro_server_name = None
        self._macro_server_alias = None
        self._door_name = None
        self._door_alias = None

        self.kernel_manager = SpockKernelManager(kernel_name=kernel)
        self.kernel_manager.kernel_about_to_launch.connect(
            self._handle_kernel_lauched)
Exemplo n.º 7
0
def show():
    """
    An example of embedding a RichJupyterWidget with an in-process kernel.
    We recommend using a kernel in a separate process as the normal option - see
    embed_qtconsole.py for more information. In-process kernels are not well
    supported.
    To run this example:
        python3 inprocess_qtconsole.py
    """

    #global ipython_widget  # Prevent from being garbage collected

    # Create an in-process kernel
    kernel_manager = QtInProcessKernelManager()
    kernel_manager.start_kernel(show_banner=True)
    # kernel = kernel_manager.kernel
    # kernel.gui = 'qt5'

    kernel_client = kernel_manager.client()
    kernel_client.start_channels()

    ipython_widget = RichJupyterWidget()
    ipython_widget.kernel_manager = kernel_manager
    ipython_widget.kernel_client = kernel_client
    return ipython_widget
Exemplo n.º 8
0
Arquivo: repl.py Projeto: bjones1/enki
class ReplDock(DockWidget):
    """Dock widget with terminal emulator
    """

    def __init__(self, title, icon):
        DockWidget.__init__(self, core.mainWindow(), title, icon, "Alt+I")
        self.setObjectName(title)

        self.setAllowedAreas(Qt.BottomDockWidgetArea | Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea)

        # Copied from https://github.com/jupyter/qtconsole/blob/master/examples/inprocess_qtconsole.py, then modified based on https://github.com/jupyter/qtconsole/blob/master/qtconsole/qtconsoleapp.py -- the QtInProcessKernelManager is blocking, so infinite loops crash Enki!
        kernel_manager = QtKernelManager()
        kernel_manager.start_kernel()
        kernel_manager.client_factory = QtKernelClient
        kernel_manager.kernel.gui = 'qt'

        kernel_client = kernel_manager.client()
        kernel_client.start_channels()

        self.ipython_widget = RichJupyterWidget()
        self.ipython_widget.kernel_manager = kernel_manager
        self.ipython_widget.kernel_client = kernel_client
        # By default, iPython adds a blank line between inputs. Per Monika's request, this eliminates the extra line. See https://qtconsole.readthedocs.io/en/latest/config_options.html#options; this fix was based on info from https://stackoverflow.com/questions/38652671/ipython-5-0-remove-spaces-between-input-lines.
        self.ipython_widget.input_sep = ''
        self.ipython_widget.show()

        self.setWidget(self.ipython_widget)
        self.setFocusProxy(self.ipython_widget)
Exemplo n.º 9
0
 def __init__(self, *args, **kwargs):
     super(IPythonDock, self).__init__(*args, **kwargs)
     self.setMinimumHeight(25)
     self.setMinimumWidth(500)
     self.setWindowTitle("IPython Shell")
     self.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
     self.console = RichJupyterWidget(name="console")
     self.console.font_size = 7
     self.setWidget(self.console)
Exemplo n.º 10
0
class TyphonConsole(TyphonBase):
    """
    IPython Widget for Typhon Display

    This widget handles starting a ``JupyterKernel`` and connecting an IPython
    console in which the user can type Python commands. It is important to note
    that the kernel in which commands are executed is a completely separate
    process. This protects the user against locking themselves out of the GUI,
    but makes it difficult to pass the Device.

    To get around this caveat, this widget uses ``happi`` to pass the Device
    between the processes. This is not a strict requirement, but if ``happi``
    is not installed, users will need to create a custom ``add_device`` method
    if they want their devices loaded in both the GUI and console.
    """
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        # Setup widget
        self.kernel = RichJupyterWidget()
        self.setLayout(QHBoxLayout())
        self.layout().setContentsMargins(0, 0, 0, 0)
        self.layout().addWidget(self.kernel)
        # Create a Kernel
        logger.debug("Starting Jupyter Kernel ...")
        kernel_manager = QtKernelManager(kernel_name='python3')
        kernel_manager.start_kernel()
        kernel_client = kernel_manager.client()
        kernel_client.start_channels()
        self.kernel.kernel_manager = kernel_manager
        self.kernel.kernel_client = kernel_client
        # Ensure we shutdown the kernel
        app = QApplication.instance()
        app.aboutToQuit.connect(self.shutdown)
        # Styling
        self.kernel.syntax_style = 'monokai'
        self.kernel.set_default_style(colors='Linux')
        # Ensure cleanup
        app = QApplication.instance()
        app.aboutToQuit.connect(self.shutdown)

    def sizeHint(self):
        default = super().sizeHint()
        default.setWidth(600)
        return default

    def shutdown(self):
        """Shutdown the Jupyter Kernel"""
        client = self.kernel.kernel_client
        if client.channels_running:
            logger.debug("Stopping Jupyter Client")
            # Stop channels in the background
            t = threading.Thread(target=client.stop_channels)
            t.start()
            self.kernel.kernel_manager.shutdown_kernel()
        else:
            logger.debug("Kernel is already shutdown.")
Exemplo n.º 11
0
    def __init__(self, interpreter=None, message="", log='', parent=None):
        """
        :param interpreter : InteractiveInterpreter in which
        the code will be executed

        :param message: welcome message string

        :param  parent: specifies the parent widget.
        If no parent widget has been specified, it is possible to
        exit the interpreter by Ctrl-D.
        """
        RichJupyterWidget.__init__(self, parent)

        if interpreter is None:
            from openalea.core.service.ipython import interpreter
            interpreter = interpreter()
        # Set interpreter
        self.interpreter = interpreter

        # Set kernel manager
        km = QtInProcessKernelManager()
        km.start_kernel(show_banner=False)
        self.kernel_manager = km

        #km.kernel = self.interpreter
        #km.kernel.gui = 'qt4'

        self.kernel = self.kernel_manager.kernel
        self.kernel.gui = 'qt'
        #self.interpreter = self.kernel

        self.shell = self.kernel.shell

        self.kernel_client = self.kernel_manager.client()
        self.kernel_client.start_channels()

        self.kernel.locals = self.kernel.shell.user_ns

        # For Debug Only
        # self.interpreter.locals['shell'] = self

        # Compatibility with visualea
        self.runsource = self.interpreter.run_cell
        self.runcode = self.interpreter.runcode
        self.loadcode = self.interpreter.loadcode

        # Write welcome message
        self.interpreter.widget = self
        #self.write(message)
        # Multiple Stream Redirection
        GraphicalStreamRedirection.__init__(self, self.kernel.stdout,
                                            self.kernel.stderr)
Exemplo n.º 12
0
def make_jupyter_widget_with_kernel():
    """Start a kernel, connect to it, and create a RichJupyterWidget to use it
    """
    kernel_manager = QtKernelManager(kernel_name=USE_KERNEL)
    kernel_manager.start_kernel()

    kernel_client = kernel_manager.client()
    kernel_client.start_channels()

    jupyter_widget = RichJupyterWidget()
    jupyter_widget.kernel_manager = kernel_manager
    jupyter_widget.kernel_client = kernel_client
    return jupyter_widget
Exemplo n.º 13
0
    def __init__(self):
        RichJupyterWidget.__init__(self)
        # Create an in-process kernel
        kernel_manager = QtInProcessKernelManager()
        kernel_manager.start_kernel(show_banner=False)
        kernel = kernel_manager.kernel
        kernel.gui = 'qt4'

        kernel_client = kernel_manager.client()
        kernel_client.start_channels()

        self.kernel_manager = kernel_manager
        self.kernel_client = kernel_client
Exemplo n.º 14
0
    def make_jupyter_widget_with_kernel(self):
        """Start a kernel, connect to it, and create a RichJupyterWidget to use it
        """
        USE_KERNEL = 'python3'
        kernel_manager = QtKernelManager(kernel_name=USE_KERNEL)
        kernel_manager.start_kernel()

        kernel_client = kernel_manager.client()
        kernel_client.start_channels()

        jupyter_widget = RichJupyterWidget()
        jupyter_widget.kernel_manager = kernel_manager
        jupyter_widget.kernel_client = kernel_client
        jupyter_widget._display_banner = False
        return jupyter_widget
Exemplo n.º 15
0
def create(user_ns):
    """Create an in-process kernel."""
    manager = QtInProcessKernelManager()
    manager.start_kernel(show_banner=False)
    kernel = manager.kernel
    kernel.gui = 'qt4'
    kernel.user_ns = user_ns

    client = manager.client()
    client.start_channels()

    widget = RichJupyterWidget()
    widget.kernel_manager = manager
    widget.kernel_client = client
    return widget
Exemplo n.º 16
0
 def __init__(self, kernel_manager, kernel_client):
     super(MainWindow, self).__init__()
     self.jupyter_widget = RichJupyterWidget()
     self.jupyter_widget.kernel_manager = kernel_manager
     self.jupyter_widget.kernel_client = kernel_client
     kernel_client.hb_channel.kernel_died.connect(self.close)
     self.setCentralWidget(self.jupyter_widget)
def make_jupyter_widget():
    """Start a kernel, connect to it, and create a RichJupyterWidget to use it
    """
    global ipython_widget
    kernel_manager = QtInProcessKernelManager()
    kernel_manager.start_kernel(show_banner=False)
    kernel = kernel_manager.kernel
    kernel.gui = 'qt'

    kernel_client = kernel_manager.client()
    kernel_client.start_channels()

    ipython_widget = RichJupyterWidget()
    ipython_widget.kernel_manager = kernel_manager
    ipython_widget.kernel_client = kernel_client
    return ipython_widget
Exemplo n.º 18
0
def make_jupyter_widget_with_kernel():
    """
    Start a kernel, connect to it, and create a RichJupyterWidget to use it
    """
    kernel_manager = QtInProcessKernelManager(kernel_name='python3')
    kernel_manager.start_kernel(show_banner=True)
    kernel = kernel_manager.kernel
    kernel.io_loop = app.get().asyncio_loop()

    kernel_client = kernel_manager.client()
    kernel_client.start_channels()

    jupyter_widget = RichJupyterWidget(gui_completion="droplist")
    jupyter_widget.kernel_manager = kernel_manager
    jupyter_widget.kernel_client = kernel_client
    return jupyter_widget
Exemplo n.º 19
0
    def create_widget(self):
        """ Create the underlying widget.

        """
        self.widget = QFrame(self.parent_widget())
        self.ipy_widget = RichJupyterWidget()
        assert self.page_control is not None  # always use paging
Exemplo n.º 20
0
 def __init__(self, kernel_manager, kernel_client):
     super(MainWindow, self).__init__()
     self.jupyter_widget = RichJupyterWidget()
     self.jupyter_widget.kernel_manager = kernel_manager
     self.jupyter_widget.kernel_client = kernel_client
     kernel_client.hb_channel.kernel_died.connect(self.close)
     kernel_client.iopub_channel.message_received.connect(self.mrcv)
     menubar = self.menuBar()
     run_script_act = QAction("&Run Script...", self)
     wdir_set_act = QAction("Set &Working Directory...", self)
     exit_act = QAction("&Exit", self)
     show_ui_act = QAction("&Start/Show Model Viewer", self)
     hide_ui_act = QAction("&Hide Model Viewer", self)
     exit_act.triggered.connect(self.close)
     show_ui_act.triggered.connect(self.show_ui)
     hide_ui_act.triggered.connect(self.hide_ui)
     wdir_set_act.triggered.connect(self.wdir_select)
     run_script_act.triggered.connect(self.run_script)
     file_menu = menubar.addMenu('&File')
     view_menu = menubar.addMenu('&View')
     file_menu.addAction(wdir_set_act)
     file_menu.addAction(run_script_act)
     file_menu.addAction(exit_act)
     view_menu.addAction(show_ui_act)
     view_menu.addAction(hide_ui_act)
     self.status_bar = QStatusBar()
     self.setStatusBar(self.status_bar)
     self.status_bar.show()
     self.setCentralWidget(self.jupyter_widget)
     self._ui_created = False
Exemplo n.º 21
0
    def __init__(self, session, tool_name):
        ToolInstance.__init__(self, session, tool_name)
        # 'display_name' defaults to class name with spaces inserted
        # between lower-then-upper-case characters (therefore "Tool UI"
        # in this case), so only override if different name desired
        self.display_name = "ChimeraX Python Shell"
        from chimerax.ui import MainToolWindow
        self.tool_window = MainToolWindow(self)
        parent = self.tool_window.ui_area
        # UI content code
        from ipykernel.ipkernel import IPythonKernel
        save_ns = IPythonKernel.user_ns
        IPythonKernel.user_ns = {'session': session}
        from qtconsole.inprocess import QtInProcessKernelManager
        kernel_manager = QtInProcessKernelManager()
        kernel_manager.start_kernel()
        kernel_client = kernel_manager.client()
        kernel_client.start_channels()

        from qtconsole.rich_jupyter_widget import RichJupyterWidget
        self.shell = RichJupyterWidget(parent)
        def_banner = self.shell.banner
        self.shell.banner = "{}\nCurrent ChimeraX session available as 'session'.\n\n".format(
            def_banner)
        self.shell.kernel_manager = kernel_manager
        self.shell.kernel_client = kernel_client
        IPythonKernel.user_ns = save_ns

        from PyQt5.QtWidgets import QHBoxLayout
        layout = QHBoxLayout()
        layout.addWidget(self.shell)
        layout.setStretchFactor(self.shell, 1)
        parent.setLayout(layout)
        self.tool_window.manage(placement=None)
Exemplo n.º 22
0
    def _createConsoleWidget(self):
        if is_using_pyqt5():
            layout = QtWidgets.QVBoxLayout()
        else:
            layout = QtGui.QVBoxLayout()
        connection_file = find_connection_file(self.connection_file)
        self.kernel_manager = QtKernelManager(connection_file=connection_file)
        self.kernel_manager.load_connection_file()
        self.kernel_manager.client_factory = QtKernelClient
        self.kernel_client = self.kernel_manager.client()
        self.kernel_client.start_channels()

        widget_options = {}
        if sys.platform.startswith('linux'):
            # Some upstream bug crashes IDA when the ncurses completion is
            # used. I'm not sure where the bug is exactly (IDA's Qt5 bindings?)
            # but using the "droplist" instead works around the crash. The
            # problem is present only on Linux.
            # See: https://github.com/eset/ipyida/issues/8
            widget_options["gui_completion"] = 'droplist'
        widget_options.update(_user_widget_options)
        if ipyida.kernel.is_using_ipykernel_5():
            self.ipython_widget = RichJupyterWidget(self.parent,
                                                    **widget_options)
        else:
            self.ipython_widget = IdaRichJupyterWidget(self.parent,
                                                       **widget_options)
        self.ipython_widget.kernel_manager = self.kernel_manager
        self.ipython_widget.kernel_client = self.kernel_client
        layout.addWidget(self.ipython_widget)

        return layout
Exemplo n.º 23
0
    def __init__(self, main_window):
        """
		desc:
			Constructor.

		arguments:
			main_window:	The main window object.
		"""

        super(ipython_console, self).__init__(main_window)
        kernel_manager = QtInProcessKernelManager()
        kernel_manager.start_kernel()
        self.kernel = kernel_manager.kernel
        self.kernel.gui = 'qt4'
        self.kernel.shell.banner1 = ''
        kernel_client = kernel_manager.client()
        kernel_client.start_channels()
        self.control = RichIPythonWidget()
        self.control.banner = self.banner()
        self.control.kernel_manager = kernel_manager
        self.control.kernel_client = kernel_client
        self.verticalLayout = QtWidgets.QVBoxLayout(self)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(self.verticalLayout)
        self.verticalLayout.addWidget(self.control)
Exemplo n.º 24
0
def show():
    global ipython_widget  # Prevent from being garbage collected

    # Create an in-process kernel
    kernel_manager = QtInProcessKernelManager()
    kernel_manager.start_kernel(show_banner=False)
    kernel = kernel_manager.kernel
    kernel.gui = 'qt4'

    kernel_client = kernel_manager.client()
    kernel_client.start_channels()

    ipython_widget = RichJupyterWidget()
    ipython_widget.kernel_manager = kernel_manager
    ipython_widget.kernel_client = kernel_client
    ipython_widget.show()
Exemplo n.º 25
0
	def __init__(self, main_window):

		"""
		desc:
			Constructor.

		arguments:
			main_window:	The main window object.
		"""

		super(ipython_console, self).__init__(main_window)
		kernel_manager = QtInProcessKernelManager()
		kernel_manager.start_kernel()
		self.kernel = kernel_manager.kernel
		self.kernel.gui = 'qt4'
		self.kernel.shell.banner1 = ''
		kernel_client = kernel_manager.client()
		kernel_client.start_channels()
		self.control = RichIPythonWidget()
		self.control.banner = self.banner()
		self.control.kernel_manager = kernel_manager
		self.control.kernel_client = kernel_client
		self.verticalLayout = QtWidgets.QVBoxLayout(self)
		self.verticalLayout.setContentsMargins(0,0,0,0)
		self.setLayout(self.verticalLayout)
		self.verticalLayout.addWidget(self.control)
Exemplo n.º 26
0
    def __init__(self, *args, **kwargs):
        RichJupyterWidget.__init__(self, *args, **kwargs)
        # QIPythonWidget.__init__(self, *args, **kwargs)
        # super(QIPythonWidget, self).__init__(*args, **kwargs)
        # if customBanner is not None: self.banner=customBanner
        self.kernel_manager = kernel_manager = QtInProcessKernelManager()
        kernel_manager.start_kernel()
        kernel_manager.kernel.gui = 'qt4'
        # self.kernel_manager.kernel.shell.push(kwargs)
        self.kernel_client = kernel_client = self._kernel_manager.client()
        kernel_client.start_channels()

        def stop():
            kernel_client.stop_channels()
            kernel_manager.shutdown_kernel()
            guisupport.get_app_qt4().exit()            
        self.exit_requested.connect(stop)
Exemplo n.º 27
0
def terminal_widget(**kwargs):

    # Create an in-process kernel
    # >>> print_process_id()
    # will print the same process ID as the main process
    kernel_manager = QtInProcessKernelManager()
    kernel_manager.start_kernel()
    kernel = kernel_manager.kernel
    kernel.gui = 'qt4'
    kernel.shell.push(kwargs)

    kernel_client = kernel_manager.client()
    kernel_client.start_channels()

    control = RichJupyterWidget()
    control.kernel_manager = kernel_manager
    control.kernel_client = kernel_client
    return control
Exemplo n.º 28
0
def terminal_widget(**kwargs):

    # Create an in-process kernel
    # >>> print_process_id()
    # will print the same process ID as the main process
    kernel_manager = QtInProcessKernelManager()
    kernel_manager.start_kernel()
    kernel = kernel_manager.kernel
    kernel.gui = 'qt4'
    kernel.shell.push(kwargs)

    kernel_client = kernel_manager.client()
    kernel_client.start_channels()

    control = RichJupyterWidget()
    control.kernel_manager = kernel_manager
    control.kernel_client = kernel_client
    return control
Exemplo n.º 29
0
def _make_jupyter_widget_with_kernel(kernel_name):
    """
    Start a kernel, connect to it, and create a RichJupyterWidget to use it.

    Parameters
    ----------
    kernel_name : str
        Kernel name to use.
    """
    kernel_manager = QtKernelManager(kernel_name=kernel_name)
    kernel_manager.start_kernel()

    kernel_client = kernel_manager.client()
    kernel_client.start_channels()

    jupyter_widget = RichJupyterWidget()
    jupyter_widget.kernel_manager = kernel_manager
    jupyter_widget.kernel_client = kernel_client
    return jupyter_widget
Exemplo n.º 30
0
    def __init__(self, layout, sim, gui):
        # Create an in-process kernel
        # >>> print_process_id()
        # will print the same process ID as the main process
        self.kernel_manager = QtInProcessKernelManager()
        self.kernel_manager.start_kernel()
        self.kernel = self.kernel_manager.kernel
        self.kernel.gui = 'qt4'

        self.kernel.shell.write("Welcome to AO Sim!")

        config = sim.config
        #Pass some useful objects to the user
        usefulObjects = {
            "sim": sim,
            "gui": gui,
            "config": config,
            "simConfig": sim.config.sim,
            "telConfig": sim.config.tel,
            "atmosConfig": sim.config.atmos
        }

        for i in range(sim.config.sim.nGS):
            usefulObjects["wfs{}Config".format(i)] = sim.config.wfss[i]
        for i in range(sim.config.sim.nDM):
            usefulObjects["dm{}Config".format(i)] = sim.config.dms[i]
        for i in range(sim.config.sim.nSci):
            usefulObjects["sci{}Config".format(i)] = sim.config.scis[i]

        self.kernel.shell.push(usefulObjects)
        #kernel.shell.push({'foo': 43, 'print_process_id': print_process_id})

        self.kernel_client = self.kernel_manager.client()
        self.kernel_client.start_channels()

        control = RichIPythonWidget()
        control.kernel_manager = self.kernel_manager
        control.kernel_client = self.kernel_client
        control.exit_requested.connect(self.stop)
        layout.addWidget(control)

        self.kernel.shell.ex("")
Exemplo n.º 31
0
    def __init__(self, parent=None, custom_banner=None, **kwargs):
        super(QIPythonWidget_embed, self).__init__(parent=parent, **kwargs)

        self.plugin = parent

        kernel_manager = QtKernelManager(kernel_name=USE_KERNEL)
        kernel_manager.start_kernel()

        kernel_client = kernel_manager.client()
        kernel_client.start_channels()

        self.jupyter_widget = RichJupyterWidget()
        self.jupyter_widget.kernel_manager = kernel_manager
        self.jupyter_widget.kernel_client = kernel_client

        if custom_banner is not None:
            self.jupyter_widget.banner = custom_banner

        layout = QHBoxLayout()
        layout.addWidget(self.jupyter_widget)
Exemplo n.º 32
0
    def __init__(self, customBanner=None, *args, **kwargs):
        RichJupyterWidget.__init__(self, *args, **kwargs)

        if customBanner is not None:
            self.banner = customBanner

        self.font_size = 6
        self.gui_completion = 'droplist'
        self.kernel_manager = QtInProcessKernelManager()
        self.kernel_manager.start_kernel(show_banner=False)
        self.kernel_manager.kernel.gui = 'qt'
        self.kernel_client = kernel_client = self._kernel_manager.client()
        kernel_client.start_channels()

        def stop():
            kernel_client.stop_channels()
            self.kernel_manager.shutdown_kernel()
            # guisupport.get_app_qt().exit()

        self.exit_requested.connect(stop)
Exemplo n.º 33
0
    def __init__(self, layout, sim, gui):
        # Create an in-process kernel
        # >>> print_process_id()
        # will print the same process ID as the main process
        self.kernel_manager = QtInProcessKernelManager()
        self.kernel_manager.start_kernel()
        self.kernel = self.kernel_manager.kernel
        self.kernel.gui = 'qt4'

        self.kernel.shell.write("Welcome to AO Sim!")

        config = sim.config
        #Pass some useful objects to the user
        usefulObjects = {    "sim" : sim,
                            "gui" : gui,
                            "config" : config,
                            "simConfig" : sim.config.sim,
                            "telConfig" : sim.config.tel,
                            "atmosConfig" : sim.config.atmos}

        for i in range(sim.config.sim.nGS):
            usefulObjects["wfs{}Config".format(i)] = sim.config.wfss[i]
        for i in range(sim.config.sim.nDM):
            usefulObjects["dm{}Config".format(i)] = sim.config.dms[i]
        for i in range(sim.config.sim.nSci):
            usefulObjects["sci{}Config".format(i)] = sim.config.scis[i]

        self.kernel.shell.push(usefulObjects)
        #kernel.shell.push({'foo': 43, 'print_process_id': print_process_id})

        self.kernel_client = self.kernel_manager.client()
        self.kernel_client.start_channels()


        control = RichIPythonWidget()
        control.kernel_manager = self.kernel_manager
        control.kernel_client = self.kernel_client
        control.exit_requested.connect(self.stop)
        layout.addWidget(control)

        self.kernel.shell.ex("")
Exemplo n.º 34
0
    def __init__(self, layout, sim, gui):
        # Create an in-process kernel

        self.kernel_manager = QtInProcessKernelManager()
        # self.kernel_manager = QtKernelManager()
        self.kernel_manager.start_kernel()

        self.kernel = self.kernel_manager.kernel

        # self.kernel.shell.write("Welcome to AO Sim!\n")

        config = sim.config
        #Pass some useful objects to the user
        usefulObjects = {
            "sim": sim,
            "gui": gui,
            "config": config,
            "simConfig": sim.config.sim,
            "telConfig": sim.config.tel,
            "atmosConfig": sim.config.atmos,
            "np": numpy,
            "plt": pyplot
        }

        for i in range(sim.config.sim.nGS):
            usefulObjects["wfs{}Config".format(i)] = sim.config.wfss[i]
        for i in range(sim.config.sim.nDM):
            usefulObjects["dm{}Config".format(i)] = sim.config.dms[i]
        for i in range(sim.config.sim.nSci):
            usefulObjects["sci{}Config".format(i)] = sim.config.scis[i]

        self.kernel.shell.push(usefulObjects)

        self.kernel_client = self.kernel_manager.client()
        self.kernel_client.start_channels()

        control = RichIPythonWidget()
        control.kernel_manager = self.kernel_manager
        control.kernel_client = self.kernel_client
        control.exit_requested.connect(self.stop)
        layout.addWidget(control)
    def __init__(self, banner=None, namespace=None, *args, **kwargs):
        if banner is not None:
            self.banner = banner
        RichJupyterWidget.__init__(self, *args, **kwargs)

        self.kernel_manager = kernel_manager = QtInProcessKernelManager()
        kernel_manager.start_kernel()
        kernel_manager.kernel.gui = 'qt4'

        if namespace is not None:
            self.push_namespace(namespace)

        self.kernel_client = kernel_client = self._kernel_manager.client()
        kernel_client.start_channels()

        def stop():
            kernel_client.stop_channels()
            kernel_manager.shutdown_kernel()
            guisupport.get_app_qt4().exit()

        self.exit_requested.connect(stop)
Exemplo n.º 36
0
    def __init__(self, project: 'Project') -> None:
        super(JupyterConsoleDockWidget, self).__init__("Console")
        self.setAllowedAreas(QtCore.Qt.BottomDockWidgetArea)

        self.project = project

        # Create an in-process kernel
        kernel_manager = QtInProcessKernelManager()
        kernel_manager.start_kernel(show_banner=False)
        kernel = kernel_manager.kernel

        kernel.shell.push({'project': project})

        kernel_client = kernel_manager.client()
        kernel_client.start_channels()

        ipython_widget = RichJupyterWidget()
        ipython_widget.kernel_manager = kernel_manager
        ipython_widget.kernel_client = kernel_client

        self.setWidget(ipython_widget)
Exemplo n.º 37
0
    def __init__(self, layout, sim, gui):
        # Create an in-process kernel

        self.kernel_manager = QtInProcessKernelManager()
        self.kernel_manager.start_kernel()
        self.kernel = self.kernel_manager.kernel

        self.kernel.shell.write("Welcome to AO Sim!\n")

        config = sim.config
        #Pass some useful objects to the user
        usefulObjects = {    "sim" : sim,
                            "gui" : gui,
                            "config" : config,
                            "simConfig" : sim.config.sim,
                            "telConfig" : sim.config.tel,
                            "atmosConfig" : sim.config.atmos,
                            "np" : numpy,
                            "plt" : pyplot}

        for i in range(sim.config.sim.nGS):
            usefulObjects["wfs{}Config".format(i)] = sim.config.wfss[i]
        for i in range(sim.config.sim.nDM):
            usefulObjects["dm{}Config".format(i)] = sim.config.dms[i]
        for i in range(sim.config.sim.nSci):
            usefulObjects["sci{}Config".format(i)] = sim.config.scis[i]

        self.kernel.shell.push(usefulObjects)

        self.kernel_client = self.kernel_manager.client()
        self.kernel_client.start_channels()


        control = RichIPythonWidget()
        control.kernel_manager = self.kernel_manager
        control.kernel_client = self.kernel_client
        control.exit_requested.connect(self.stop)
        layout.addWidget(control)

        self.kernel.shell.ex("")
Exemplo n.º 38
0
def embed_ipy(parent, passthrough=None):
    """
    Embed an ipython kernel into the parent widget using a RichJupyterWidget
    :param parent: Qt Widget to receive the RichJupyterWidget
    :param passthrough: dict containing variables to pass into scope of the IPython Kernel
            Use this with caution; strange things can happen if you pass GUI elements to the IPython scope
            and then call any of their show() or draw() methods.
    :return: dict with reference to jupyter widget and ipython kernel
    """
    kernel_manager = QtInProcessKernelManager()
    kernel_manager.start_kernel()
    kernel = kernel_manager.kernel
    kernel.gui = 'qt4'

    kernel_client = kernel_manager.client()
    kernel_client.start_channels()
    kernel_client.namespace = parent

    def stop():
        kernel_client.stop_channels()
        kernel_manager.shutdown_kernel()

    layout = QtGui.QVBoxLayout(parent)
    widget = RichJupyterWidget(parent=parent)
    layout.addWidget(widget)
    widget.kernel_manager = kernel_manager
    widget.kernel_client = kernel_client
    widget.exit_requested.connect(stop)
    ipython_widget = widget
    ipython_widget.show()
    kernel.shell.push({'widget': widget, 'kernel': kernel, 'parent': parent})

    # pass variables from main GUI environment into IPython Kernel namespace
    if passthrough is not None:
        kernel.shell.push(passthrough)
        # variables stored in this dict are now accessible in the IPython shell
    return {'widget': widget, 'kernel': kernel}
Exemplo n.º 39
0
 def __init__(self, namespace, windowtitle=None):
     from .. import qt_error
     if qt_error is not None:
         self._dummy = True
         return
     self.namespace = namespace
     self.kernel_manager = MyQtInProcessKernelManager()
     self.kernel_manager.start_kernel(namespace)
     self.kernel_client = self.kernel_manager.client()
     self.kernel_client.start_channels()
     control = RichJupyterWidget()
     self.control = control
     control.kernel_manager = self.kernel_manager
     control.kernel_client = self.kernel_client
     if windowtitle is not None:
         control.setWindowTitle("Seamless shell: " + windowtitle)
     control.show()
Exemplo n.º 40
0
class QtipWindow(QtGui.QMainWindow):
    """Main Qtip window class"""
    
    def __init__(self, parent=None, engine='pint', \
            parfile=None, timfile=None, **kwargs):
        """
        Initialize the main window

        :param parent:
            The parent window that embeds the Qtip window

        :param engine:
            The preferred timing package to use ('pint'/'libstempo') ['pint']

        :param parfile:
            Par-file top open on startup

        :param timfile:
            Tim-file top open on startup

        """

        super(QtipWindow, self).__init__(parent)
        self.setWindowTitle('Jupyter interface for pulsar timing')

        # Initialise basic gui elements
        self.initUI()

        # Start the embedded Jupyter kernel
        self.createJupyterKernel()

        # Create the display widgets
        self.createPlkWidget()
        self.createJupyterWidget()
        self.createOpenSomethingWidget()

        # Position the widgets
        self.initQtipLayout()

        # Initialize the main widget (the plk emulator)
        self.setQtipLayout(whichWidget='plk',
                showJupyter=False, firsttime=True)

        # The preferred engine to use (PINT)
        self.pref_engine = engine

        # We are still in MAJOR testing mode, so open a test-pulsar right away
        # if no par/tim file is given
        if parfile is None or timfile is None:
            testpulsar = True
        else:
            testpulsar = False

        # Open plk as the main widget
        self.requestOpenPlk(testpulsar=testpulsar, parfilename=parfile, \
                timfilename=timfile, engine=self.pref_engine)

        self.show()

    def __del__(self):
        pass

    def onAbout(self):
        """Show an about box"""

        msg = constants.QtipBanner
        QtGui.QMessageBox.about(self, "About Qtip", msg.strip())

    def initUI(self):
        """Initialise the user-interface elements"""

        # Create the main-frame widget, and the layout
        self.mainFrame = QtGui.QWidget()
        self.setCentralWidget(self.mainFrame)
        self.hbox = QtGui.QHBoxLayout()     # HBox contains all widgets

        # Menu item: open par/tim files
        self.openParTimAction = QtGui.QAction('&Open par/tim', self)        
        self.openParTimAction.setShortcut('Ctrl+O')
        self.openParTimAction.setStatusTip('Open par/tim')
        self.openParTimAction.triggered.connect(self.openParTim)

        # Menu item: exit Qtip
        self.exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Exit', self)        
        self.exitAction.setShortcut('Ctrl+Q')
        self.exitAction.setStatusTip('Exit application')
        self.exitAction.triggered.connect(self.close)

        # Previously, it was possible to switch out the 'plk' widget for another
        # main widget (the binary pulsar one). That one has been stripped out
        # now, so for now it makes no sense to 'toggle' on or off the plk
        # widget. However, the option is still there for now...
        self.togglePlkAction = QtGui.QAction('&Plk', self)        
        self.togglePlkAction.setShortcut('Ctrl+P')
        self.togglePlkAction.setStatusTip('Toggle plk widget')
        self.togglePlkAction.triggered.connect(self.togglePlk)

        # Menu item: toggle the Jupyter window
        self.toggleJupyterAction = QtGui.QAction('&Jupyter', self)        
        self.toggleJupyterAction.setShortcut('Ctrl+J')
        self.toggleJupyterAction.setStatusTip('Toggle Jupyter')
        self.toggleJupyterAction.triggered.connect(self.toggleJupyter)

        # Menu item: about Qtip
        self.aboutAction = QtGui.QAction('&About', self)        
        self.aboutAction.setShortcut('Ctrl+A')
        self.aboutAction.setStatusTip('About Qtip')
        self.aboutAction.triggered.connect(self.onAbout)

        # The status bar
        self.theStatusBar = QtGui.QStatusBar()
        #self.statusBar()
        self.setStatusBar(self.theStatusBar)

        # A label that shows what engine is being used (hardcoded: PINT)
        self.engine_label = QtGui.QLabel("PINT")
        self.engine_label.setFrameStyle( QtGui.QFrame.Sunken|QtGui.QFrame.Panel)
        self.engine_label.setLineWidth(4)
        self.engine_label.setMidLineWidth(4)
        self.engine_label.setStyleSheet("QLabel{color:black;background-color:red}")
        self.theStatusBar.addPermanentWidget(self.engine_label)

        # On OSX, make sure the menu can be displayed (in the window itself)
        if sys.platform == 'darwin':
            # On OSX, the menubar is usually on the top of the screen, not in
            # the window. To make it in the window:
            QtGui.qt_mac_set_native_menubar(False) 

            # Otherwise, if we'd like to get the system menubar at the top, then
            # we need another menubar object, not self.menuBar as below. In that
            # case, use:
            # self.menubar = QtGui.QMenuBar()
            # TODO: Somehow this does not work. Per-window one does though

        # Create the menu bar, and link the action items
        self.menubar = self.menuBar()
        self.fileMenu = self.menubar.addMenu('&File')
        self.fileMenu.addAction(self.openParTimAction)
        self.fileMenu.addAction(self.exitAction)
        self.viewMenu = self.menubar.addMenu('&View')
        self.viewMenu.addAction(self.togglePlkAction)
        self.viewMenu.addAction(self.toggleJupyterAction)
        self.helpMenu = self.menubar.addMenu('&Help')
        self.helpMenu.addAction(self.aboutAction)

        # What is the status quo of the user interface?
        self.showJupyter = False
        self.whichWidget = 'None'
        self.prevShowJupyter = None
        self.prevWhichWidget = 'None'

    def createJupyterKernel(self):
        """Create and start the embedded Jupyter Kernel"""

        # Create an in-process kernel
        self.kernelManager = QtInProcessKernelManager()
        self.kernelManager.start_kernel()
        self.kernel = self.kernelManager.kernel

        # Launch the kernel
        self.kernelClient = self.kernelManager.client()
        self.kernelClient.start_channels()

        # Allow inline matplotlib figures
        self.kernel.shell.enable_matplotlib(gui='inline')

        # Load the necessary packages in the embedded kernel
        # TODO: show this line in a cell of it's own
        cell = "import numpy as np, matplotlib.pyplot as plt, qtpulsar as qp"
        self.kernel.shell.run_cell(cell, store_history=False)

        # Set the in-kernel matplotlib color scheme to black.
        self.setMplColorScheme('black')     # Outside as well (do we need this?)
        self.kernel.shell.run_cell(constants.matplotlib_rc_cell_black,
                store_history=False)

    def createJupyterWidget(self):
        """Create the Jupyter widget"""

        self.consoleWidget = RichJupyterWidget()
        #self.consoleWidget.setMinimumSize(600, 550)

        # Show the banner
        self.consoleWidget.banner = constants.QtipBanner
        self.consoleWidget.kernel_manager = self.kernelManager

        # Couple the client
        self.consoleWidget.kernel_client = self.kernelClient
        self.consoleWidget.exit_requested.connect(self.toggleJupyter)
        self.consoleWidget.set_default_style(colors='linux')
        self.consoleWidget.hide()

        # Register a call-back function for the Jupyter shell. This one is
        # executed insite the child-kernel.
        #self.kernel.shell.register_post_execute(self.postExecute)
        #
        # In Jupyter >= 2, we can use the event register
        # Events: post_run_cell, pre_run_cell, etc...`
        self.kernel.shell.events.register('pre_execute', self.preExecute)
        self.kernel.shell.events.register('post_execute', self.postExecute)
        self.kernel.shell.events.register('post_run_cell', self.postRunCell)


    def createOpenSomethingWidget(self):
        """Create the OpenSomething widget. Do not add it to the layout yet

        TODO:   This widget should become the first main widget to see? At the
                moment, we're avoiding it for the sake of testing purposes
        """

        self.openSomethingWidget = OpenSomethingWidget(parent=self.mainFrame, \
                openFile=self.requestOpenPlk)
        self.openSomethingWidget.hide()

    def createPlkWidget(self):
        """Create the Plk widget"""

        self.plkWidget = PlkWidget(parent=self.mainFrame)
        self.plkWidget.hide()

    def toggleJupyter(self):
        """Toggle the Jupyter widget on or off"""

        self.setQtipLayout(showJupyter = not self.showJupyter)

    def togglePlk(self):
        """Toggle the plk widget on or off"""

        self.setQtipLayout(whichWidget='plk')

    def initQtipLayout(self):
        """Initialise the Qtip layout"""

        # If other 'main' widgets exist, they can be added here
        self.hbox.addWidget(self.openSomethingWidget)
        self.hbox.addWidget(self.plkWidget)

        self.hbox.addStretch(1)
        self.hbox.addWidget(self.consoleWidget)
        self.mainFrame.setLayout(self.hbox)

    def hideAllWidgets(self):
        """Hide all widgets of the mainFrame"""

        # Remove all widgets from the main window
        # No, hiding seems to work better
        """
        while self.hbox.count():
            item = self.hbox.takeAt(0)
            if isinstance(item, QtGui.QWidgetItem):
                #item.widget().deleteLater()
                item.widget().hide()
            elif isinstance(item, QtGui.QSpacerItem):
                #self.hbox.removeItem(item)
                pass
            else:
                #fcbox.clearLayout(item.layout())
                #self.hbox.removeItem(item)
                pass
        """
        self.openSomethingWidget.hide()
        self.plkWidget.hide()
        self.consoleWidget.hide()

    def showVisibleWidgets(self):
        """Show the correct widgets in the mainFrame"""

        # Add the widgets we need
        if self.whichWidget.lower() == 'opensomething':
            self.openSomethingWidget.show()
        elif self.whichWidget.lower() == 'plk':
            self.plkWidget.show()
        # Other widgets can be added here

        if self.showJupyter:
            self.consoleWidget.show()
        else:
            pass

        # Request focus back to the main widget
        if self.whichWidget.lower() == 'plk' and not self.showJupyter:
            self.plkWidget.setFocusToCanvas()
        # Do it for other main widgets, if they exist
        #elif self.whichWidget.lower() == 'binary' and not self.showJupyter:
        #    self.binaryWidget.setFocusToCanvas()

        # Do we immediately get focus to the Jupyter console?
        #elif self.showJupyter:
        #    self.consoleWidget.setFocus()

    def setQtipLayout(self, whichWidget=None, showJupyter=None, firsttime=False):
        """Given the current main widget, hide all the other widgets
        
        :param whichWidget:
            Which main widget we are showing right now

        :param showJupyter:
            Whether to show the Jupyter console

        :param firsttime:
            Whether or not this is the first time setting the layout. If so,
            resize to proper dimensions.
            TODO: How to do this more elegantly?
        """

        if not whichWidget is None:
            self.whichWidget = whichWidget
        if not showJupyter is None:
            self.showJupyter = showJupyter

        # After hiding the widgets, wait 0 milliseonds before showing them again
        # (what a dirty hack, ugh!)
        self.hideAllWidgets()
        QtCore.QTimer.singleShot(0, self.showVisibleWidgets)

        self.prevWhichWidget = self.whichWidget

        if self.showJupyter != self.prevShowJupyter:
            # Jupyter has been toggled
            self.prevShowJupyter = self.showJupyter
            if self.showJupyter:
                self.resize(1350, 550)
                self.mainFrame.resize(1350, 550)
            else:
                self.resize(650, 550)
                self.mainFrame.resize(650, 550)

        # TODO: How to do this more elegantly?
        if firsttime:
            # Set position slightly more to the left of the screen, so we can
            # still open Jupyter
            self.move(50, 100)

        self.mainFrame.setLayout(self.hbox)
        self.mainFrame.show()

    def requestOpenPlk(self, parfilename=None, timfilename=None, \
            testpulsar=False, engine='pint'):
        """Request to open a file in the plk widget

        :param parfilename:
            The parfile to open. If none, ask the user
        :param timfilename:
            The timfile to open. If none, ask the user
        """

        self.setQtipLayout(whichWidget='plk', showJupyter=self.showJupyter)

        if parfilename is None and not testpulsar:
            parfilename = QtGui.QFileDialog.getOpenFileName(self, 'Open par-file', '~/')

        if timfilename is None and not testpulsar:
            timfilename = QtGui.QFileDialog.getOpenFileName(self, 'Open tim-file', '~/')

        # Load the pulsar
        self.openPlkPulsar(parfilename, timfilename, engine=engine, \
                testpulsar=testpulsar)

    def setMplColorScheme(self, scheme):
        """
        Set the matplotlib color scheme

        :param scheme: 'black'/'white', the color scheme
        """

        # Obtain the Widget background color
        color = self.palette().color(QtGui.QPalette.Window)
        r, g, b = color.red(), color.green(), color.blue()
        rgbcolor = (r/255.0, g/255.0, b/255.0)

        if scheme == 'white':
            rcP = constants.mpl_rcParams_white

            rcP['axes.facecolor'] = rgbcolor
            rcP['figure.facecolor'] = rgbcolor
            rcP['figure.edgecolor'] = rgbcolor
            rcP['savefig.facecolor'] = rgbcolor
            rcP['savefig.edgecolor'] = rgbcolor
        elif scheme == 'black':
            rcP = constants.mpl_rcParams_black

        for key, value in rcP.iteritems():
            matplotlib.rcParams[key] = value


    def openParTim(self):
        """Open a par-file and a tim-file"""

        # Ask the user for a par and tim file, and open these with libstempo/pint
        parfilename = QtGui.QFileDialog.getOpenFileName(self, 'Open par-file', '~/')
        timfilename = QtGui.QFileDialog.getOpenFileName(self, 'Open tim-file', '~/')

        # Load the pulsar
        self.openPlkPulsar(parfilename, timfilename, engine=self.pref_engine)

    def openPlkPulsar(self, parfilename, timfilename, engine='pint', \
            testpulsar=False):
        """Open a pulsar, given a parfile and a timfile

        :param parfilename: The name of the parfile to open
        :param timfilename: The name fo the timfile to open
        :param engine:      Which pulsar timing engine to use [pint]
        :param testpulsar:  If True, open the test pulsar (J1744, NANOGrav)
        """

        if engine=='pint':
            trypint = True
        else:
            trypint = False

        engine, pclass = qp.get_engine(trypint=trypint)

        # This all is a bit ugly...
        if engine == 'libstempo':
            if not testpulsar:
                # Obtain the directory name of the timfile, and change to it
                timfiletup = os.path.split(timfilename)
                dirname = timfiletup[0]
                reltimfile = timfiletup[-1]
                relparfile = os.path.relpath(parfilename, dirname)
                savedir = os.getcwd()

                # Change directory to the base directory of the tim-file to deal with
                # INCLUDE statements in the tim-file
                if dirname != '':
                    os.chdir(dirname)

                # Load the pulsar
                cell = "psr = qp."+pclass+"('"+relparfile+"', '"+reltimfile+"')"
                self.kernel.shell.run_cell(cell)
                psr = self.kernel.shell.ns_table['user_local']['psr']

                # Change directory back to where we were
                if dirname != '':
                    os.chdir(savedir)
            else:
                cell = "psr = qp."+pclass+"(testpulsar=True)"
                self.kernel.shell.run_cell(cell)
                psr = self.kernel.shell.ns_table['user_local']['psr']
        elif engine == 'pint':
            if not testpulsar:
                psr = qp.PPulsar(parfilename, timfilename)
                cell = "psr = qp."+pclass+"('"+parfilename+"', '"+timfilename+"')"
            else:
                psr = qp.PPulsar(testpulsar=True)
                cell = "psr = qp."+pclass+"(testpulsar=True)"
            self.kernel.shell.run_cell(cell)
            psr = self.kernel.shell.ns_table['user_local']['psr']
        else:
            print("Engine = ", engine)
            raise NotImplemented("Only works with PINT/libstempo")

        # Update the plk widget
        self.plkWidget.setPulsar(psr)

        # Communicating with the kernel goes as follows
        # self.kernel.shell.push({'foo': 43, 'print_process_id': print_process_id}, interactive=True)
        # print("Embedded, we have:", self.kernel.shell.ns_table['user_local']['foo'])


    def keyPressEvent(self, event, **kwargs):
        """Handle a key-press event

        :param event:   event that is handled here
        """

        key = event.key()

        if key == QtCore.Qt.Key_Escape:
            self.close()
        elif key == QtCore.Qt.Key_Left:
            #print("Left pressed")
            pass
        else:
            #print("Other key")
            pass

        #print("QtipWindow: key press")
        super(QtipWindow, self).keyPressEvent(event, **kwargs)

    def mousePressEvent(self, event, **kwargs):
        """Handle a mouse-click event

        :param event:   event that is handled here
        """

        super(QtipWindow, self).mousePressEvent(event, **kwargs)

    def preExecute(self):
        """Callback function that is run prior to execution of a cell"""
        pass

    def postExecute(self):
        """Callback function that is run after execution of a code"""
        pass

    def postRunCell(self):
        """Callback function that is run after execution of a cell (after
        post-execute)
        """

        # TODO: Do more than just update the plot, but also update _all_ the
        # widgets. Make a callback in plkWidget for that. QtipWindow might also
        # want to loop over some stuff.
        if self.whichWidget == 'plk':
            #self.plkWidget.updatePlot()
            pass
Exemplo n.º 41
0
class ipython_console(base_console, QtWidgets.QWidget):

	"""
	desc:
		An IPython-based debug window.
	"""

	def __init__(self, main_window):

		"""
		desc:
			Constructor.

		arguments:
			main_window:	The main window object.
		"""

		super(ipython_console, self).__init__(main_window)
		kernel_manager = QtInProcessKernelManager()
		kernel_manager.start_kernel()
		self.kernel = kernel_manager.kernel
		self.kernel.gui = 'qt4'
		self.kernel.shell.banner1 = ''
		kernel_client = kernel_manager.client()
		kernel_client.start_channels()
		self.control = RichIPythonWidget()
		self.control.banner = self.banner()
		self.control.kernel_manager = kernel_manager
		self.control.kernel_client = kernel_client
		self.verticalLayout = QtWidgets.QVBoxLayout(self)
		self.verticalLayout.setContentsMargins(0,0,0,0)
		self.setLayout(self.verticalLayout)
		self.verticalLayout.addWidget(self.control)

	def clear(self):

		"""See base_console."""

		self.control.reset(clear=True)

	def focus(self):

		"""See base_console."""

		self.control._control.setFocus()

	def reset(self):

		"""See base_console."""

		self.kernel.shell.reset()
		self.kernel.shell.push(self.default_globals())
		self.clear()
		super(ipython_console, self).reset()

	def show_prompt(self):

		"""See base_console."""

		self.control._show_interpreter_prompt()

	def get_workspace_globals(self):

		"""See base_console."""

		return self.kernel.shell.user_global_ns.copy()

	def set_workspace_globals(self, _globals={}):

		"""See base_console."""

		self.kernel.shell.push(_globals)

	def validTheme(self, cs):

		"""
		returns:
			desc:	True if the colorscheme is valid, False otherwise.
			type:	bool
		"""

		for key in [
			u'Background',
			u'Default',
			u'Prompt in',
			u'Prompt out',
			u'Comment',
			u'Keyword',
			u'Identifier',
			u'Double-quoted string',
			u'Invalid',
			u'Number',
			u'Operator',
			]:
			if key not in cs:
				return False
		return True

	def setTheme(self):

		"""
		desc:
			Sets the theme, based on the QProgEdit settings.
		"""

		from QProgEdit import QColorScheme
		if not hasattr(QColorScheme, cfg.qProgEditColorScheme):
			debug.msg(u'Failed to set debug-output colorscheme')
			return u''
		cs = getattr(QColorScheme, cfg.qProgEditColorScheme)
		if not self.validTheme(cs):
			debug.msg(u'Invalid debug-output colorscheme')
			return u''
		self.control._highlighter.set_style(pygments_style_factory(cs))
		qss = u'''QPlainTextEdit, QTextEdit {
				background-color: %(Background)s;
				color: %(Default)s;
			}
			.in-prompt { color: %(Prompt in)s; }
			.in-prompt-number { font-weight: bold; }
			.out-prompt { color: %(Prompt out)s; }
			.out-prompt-number { font-weight: bold; }
			''' % cs
		self.control.style_sheet = qss
		self.control._control.setFont(QtGui.QFont(cfg.qProgEditFontFamily,
			cfg.qProgEditFontSize))

	def setup(self, main_window):

		"""See base_subcomponent."""

		super(ipython_console, self).setup(main_window)
		self.kernel.shell.push(self.default_globals())

	def write(self, s):

		"""See base_console."""

		self.control._append_plain_text(str(s))
		self.control._control.ensureCursorVisible()

	def execute(self, s):

		"""See base_console."""

		self.main_window.ui.dock_stdout.setVisible(True)
		self.control.execute(s)

	def focusInEvent(self, e):

		self.control.setFocus()
		e.accept()
Exemplo n.º 42
0
    def __init__(self, args):
        """Initializes application"""
        super(QSceneGraphEditor, self).__init__(args)

        self._mainWindow = QtGui.QMainWindow()
        self._editor = QSceneGraphEditorWindow()
        self._mainWindow.setCentralWidget(self._editor)
    
        exitAction = QtGui.QAction('&Exit', self._mainWindow)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self._mainWindow.close)

        newAction = QtGui.QAction('&New', self._mainWindow)
        newAction.setShortcut('Ctrl+N')
        newAction.setStatusTip('Creates a simple default scene')
        newAction.triggered.connect(self._editor.new)

        openAction = QtGui.QAction('&Open...', self._mainWindow)
        openAction.setShortcut('Ctrl+O')
        openAction.setStatusTip('Open scene graph from file')
        openAction.triggered.connect(self._editor.open)

        saveAction = QtGui.QAction('&Save', self._mainWindow)
        saveAction.setShortcut('Ctrl+S')
        saveAction.setStatusTip('Save scene graph')
        saveAction.triggered.connect(self._editor.save)

        saveAsAction = QtGui.QAction('&Save As...', self._mainWindow)
        saveAsAction.setStatusTip('Save scene graph to another file')
        saveAsAction.triggered.connect(self._editor.saveAs)

        insertObjectAction = QtGui.QAction('&Insert...', self._mainWindow)
        insertObjectAction.setShortcut('Ctrl+I')
        insertObjectAction.setStatusTip('Inserts new scene object before current one')
        insertObjectAction.triggered.connect(self._editor.inspectorWidget.insertObject)

        appendObjectAction = QtGui.QAction('&Append...', self._mainWindow)
        appendObjectAction.setShortcut('Ctrl+K')
        appendObjectAction.setStatusTip('Inserts new scene object after current one')
        appendObjectAction.triggered.connect(self._editor.inspectorWidget.appendObject)

        deleteObjectAction = QtGui.QAction('&Delete', self._mainWindow)
        deleteObjectAction.setShortcut('DEL')
        deleteObjectAction.setStatusTip('Deletes currently selected scene object')
        deleteObjectAction.triggered.connect(self._editor.inspectorWidget.deleteObject)

        refreshObjectAction = QtGui.QAction('&Refresh', self._mainWindow)
        refreshObjectAction.setShortcut('F5')
        refreshObjectAction.setStatusTip('Recreates tree view from root node')
        refreshObjectAction.triggered.connect(self._editor.refresh)

        viewAllAction = QtGui.QAction('View &All', self._mainWindow)
        viewAllAction.setShortcut('Ctrl+A')
        viewAllAction.setStatusTip('Resets camera in scene so all object are visible')
        viewAllAction.triggered.connect(self._editor.previewWidget.sceneManager.view_all)

        viewManipAction = QtGui.QAction('Camera &Manipulation', self._mainWindow)
        viewManipAction.setShortcut('Ctrl+M')
        viewManipAction.setStatusTip('Enables manipulation of camera in the scene')
        viewManipAction.setCheckable(True)
        viewManipAction.setChecked(True)
        viewManipAction.connect(QtCore.SIGNAL("triggered(bool)"), self._editor.previewWidget.sceneManager.interaction)
        self._editor.previewWidget.sceneManager.interaction(True)

        #self._mainWindow.statusBar()

        menubar = self._mainWindow.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(newAction)
        fileMenu.addAction(openAction)
        fileMenu.addAction(saveAction)
        fileMenu.addAction(saveAsAction)
        fileMenu.addSeparator()
        fileMenu.addAction(exitAction)
    
        objectsMenu = menubar.addMenu('&Scene Object')
        objectsMenu.addAction(insertObjectAction)
        objectsMenu.addAction(appendObjectAction)
        objectsMenu.addAction(deleteObjectAction)
        objectsMenu.addSeparator()
        objectsMenu.addAction(refreshObjectAction)
    
        viewMenu = menubar.addMenu('&View')
        viewMenu.addAction(viewAllAction)
        viewMenu.addAction(viewManipAction)

        if "--console" in self.arguments() or "--ipython" in self.arguments():
            # start with IPython console at bottom of application
            from qtconsole.rich_jupyter_widget import RichJupyterWidget
            from qtconsole.inprocess import QtInProcessKernelManager
            import inventor
            
            # Create an in-process kernel
            kernel_manager = QtInProcessKernelManager()
            kernel_manager.start_kernel()
            kernel = kernel_manager.kernel
            kernel.gui = 'qt4'
            kernel.shell.push({'iv': inventor, 'root': self._editor._root, 'view': self._editor.previewWidget.sceneManager })

            kernel_client = kernel_manager.client()
            kernel_client.start_channels()

            def stop():
                kernel_client.stop_channels()
                kernel_manager.shutdown_kernel()
                self.exit()

            control = RichJupyterWidget()
            control.kernel_manager = kernel_manager
            control.kernel_client = kernel_client
            control.exit_requested.connect(stop)
            control.font = QtGui.QFont(control.font.family(), 10);

            self.addVerticalWidget(control)

        # load default scene or from file if argument is given
        file = "#Inventor V2.1 ascii\n\nSeparator { " \
               "DirectionalLight {} OrthographicCamera { position 0 0 5 height 5 }" \
               "TrackballManip {} Material { diffuseColor 1 0 0 }" \
               "Cone {} }"
        if (len(self.arguments()) > 1) and ("." in self.arguments()[-1]):
            extension = self.arguments()[-1].split('.')[-1].lower()
            if extension in [ 'iv', 'vrml', '3ds', 'stl' ]:
                file = self.arguments()[-1];

        self._editor.load(file)