def load_ipython_extension(ip):
    global _unregister_key_bindings
    _unregister_key_bindings = register_key_bindings(ip)

    from IPython.terminal.pt_inputhooks import register
    register("julia", julia_inputhook)
    if not ip.active_eventloop:
        ip.enable_gui("julia")

    maybe_load_pyjulia()

    ip.set_hook("complete_command", _julia_completer,
                re_key=r""".*\bMain\.eval\(["']""")
예제 #2
0
    def embed(self, close_scene_on_exit: bool = True) -> None:
        if not self.preview:
            # Ignore embed calls when there is no preview
            return
        self.inside_embed = True
        self.stop_skipping()
        self.linger_after_completion = False
        self.update_frame()
        self.save_state()

        # Configure and launch embedded IPython terminal
        from IPython.terminal import embed, pt_inputhooks
        shell = embed.InteractiveShellEmbed.instance()

        # Use the locals namespace of the caller
        local_ns = inspect.currentframe().f_back.f_locals
        # Add a few custom shortcuts
        local_ns.update({
            name: getattr(self, name)
            for name in [
                "play", "wait", "add", "remove", "clear",
                "save_state", "undo", "redo", "i2g", "i2m"
            ]
        })

        # Enables gui interactions during the embed
        def inputhook(context):
            while not context.input_is_ready():
                if not self.window.is_closing:
                    self.update_frame(dt=0)

        pt_inputhooks.register("manim", inputhook)
        shell.enable_gui("manim")

        # Operation to run after each ipython command
        def post_cell_func(*args, **kwargs):
            self.refresh_static_mobjects()
            self.save_state()

        shell.events.register("post_run_cell", post_cell_func)

        # Launch shell, with stack_depth=2 indicating we should use caller globals/locals
        shell(local_ns=local_ns, stack_depth=2)

        self.inside_embed = False
        # End scene when exiting an embed
        if close_scene_on_exit:
            raise EndSceneEarlyException()
예제 #3
0
    def registerInputHook():
        """
        Registers the mechanica input hook with the ipython pt_inputhooks
        class.

        The ipython TerminalInteractiveShell.enable_gui('name') method
        looks in the registered input hooks in pt_inputhooks, and if it
        finds one, it activtes that hook.

        To acrtivate the gui mode, call:

        ip = IPython.get_ipython()
        ip.
        """
        import IPython.terminal.pt_inputhooks as pt_inputhooks
        pt_inputhooks.register("mechanica", inputhook)
예제 #4
0
파일: _application.py 프로젝트: zuysal/root
    def _ipython_config():
        # Integrate IPython >= 5 with ROOT's event loop
        # Check for new GUI events until there is some user input to process

        from IPython.terminal import pt_inputhooks

        def inputhook(context):
            while not context.input_is_ready():
                gSystem.ProcessEvents()
                time.sleep(0.01)

        pt_inputhooks.register('ROOT', inputhook)

        ipy = get_ipython()
        if ipy:
            get_ipython().run_line_magic('gui', 'ROOT')
예제 #5
0
    def _ipython_config():
        # Integrate IPython >= 5 with ROOT's event loop
        # Check for new GUI events until there is some user input to process

        from IPython.terminal import pt_inputhooks

        def inputhook(context):
            while not context.input_is_ready():
                gSystem.ProcessEvents()
                time.sleep(0.01)

        pt_inputhooks.register('ROOT', inputhook)

        ipy = get_ipython()
        if ipy:
            get_ipython().run_line_magic('gui', 'ROOT')
예제 #6
0

def sage_inputhook(context):
    f = context.fileno()
    while True:
        sage.repl.attach.reload_attached_files_if_modified()
        try:
            r, _, _ = select.select([f], [], [], TIMEOUT)
            if f in r:
                return  # IPython signalled us to stop
        except select.error as e:
            if e[0] != errno.EINTR:
                raise


register('sage', sage_inputhook)


def install():
    """
    Install the Sage input hook

    EXAMPLES::

        sage: from sage.repl.inputhook import install
        sage: install()
    """
    ip = get_ipython()
    if not ip:
        return  # Not running in ipython, e.g. doctests
    ip.enable_gui('sage')
예제 #7
0
파일: inputhook.py 프로젝트: mcognetta/sage

def sage_inputhook(context):
    f = context.fileno()
    while True:
        sage.repl.attach.reload_attached_files_if_modified()
        try:
            r, w, e = select.select([f], [], [], TIMEOUT)
            if f in r:
                return  # IPython signalled us to stop
        except select.error as e:
            if e[0] != errno.EINTR:
                raise


register('sage', sage_inputhook)


def install():
    """
    Install the Sage input hook

    EXAMPLES::

        sage: from sage.repl.inputhook import install
        sage: install()
    """
    ip = get_ipython()
    if not ip:
        return   # Not running in ipython, e.g. doctests
    ip.enable_gui('sage')
예제 #8
0
파일: ROOT.py 프로젝트: satyarth934/root
    def __finalSetup(self):
        # prevent this method from being re-entered through the gROOT wrapper
        self.__dict__['gROOT'] = _root.gROOT

        # switch to running gettattr/setattr
        self.__class__.__getattr__ = self.__class__.__getattr2
        del self.__class__.__getattr2
        self.__class__.__setattr__ = self.__class__.__setattr2
        del self.__class__.__setattr2

        # normally, you'll want a ROOT application; don't init any further if
        # one pre-exists from some C++ code somewhere
        hasargv = hasattr(sys, 'argv')
        if hasargv and PyConfig.IgnoreCommandLineOptions:
            argv = sys.argv
            sys.argv = []

        appc = _root.CreateScopeProxy('PyROOT::TPyROOTApplication')
        if (not _builtin_cppyy
                and appc.CreatePyROOTApplication()) or _builtin_cppyy:
            appc.InitROOTGlobals()
            # TODO Cling equivalent needed: appc.InitCINTMessageCallback();
            appc.InitROOTMessageCallback()

        if hasargv and PyConfig.IgnoreCommandLineOptions:
            sys.argv = argv

    # must be called after gApplication creation:
        if _is_ipython:
            # IPython's FakeModule hack otherwise prevents usage of python from Cling (TODO: verify necessity)
            _root.gROOT.ProcessLine('TPython::Exec( "" );')
            sys.modules['__main__'].__builtins__ = __builtins__

    # special case for cout (backwards compatibility)
        if hasattr(cppyy.gbl.std, '__1'):
            attr_1 = getattr(cppyy.gbl.std, '__1')
            if hasattr(attr_1, 'cout'):
                self.__dict__['cout'] = attr_1.cout

    # python side pythonizations (should live in their own file, if we get many)

        def set_size(self, buf):
            buf.SetSize(self.GetN())
            return buf

    # TODO: add pythonization API to pypy-c

        if not PYPY_CPPYY_COMPATIBILITY_FIXME:
            cppyy.add_pythonization(
                cppyy.compose_method("^TGraph(2D)?$|^TGraph.*Errors$",
                                     "GetE?[XYZ]$", set_size))
            gRootDir = self.gRootDir
        else:
            gRootDir = _root.gRootDir

    # custom logon file (must be after creation of ROOT globals)
        if hasargv and not '-n' in sys.argv and not PyConfig.DisableRootLogon:
            rootlogon = os.path.expanduser('~/.rootlogon.py')
            if os.path.exists(rootlogon):
                # could also have used execfile, but import is likely to give fewer surprises
                import imp
                imp.load_module('rootlogon', open(rootlogon, 'r'), rootlogon,
                                ('.py', 'r', 1))
                del imp
            else:  # if the .py version of rootlogon exists, the .C is ignored (the user can
                # load the .C from the .py, if so desired)

                # system logon, user logon, and local logon (skip Rint.Logon)
                name = '.rootlogon.C'
                logons = [
                    os.path.join(str(self.TROOT.GetEtcDir()), 'system' + name),
                    os.path.expanduser(os.path.join('~', name))
                ]
                if logons[-1] != os.path.join(os.getcwd(), name):
                    logons.append(name)
                for rootlogon in logons:
                    if os.path.exists(rootlogon):
                        appc.ExecuteFile(rootlogon)
                del rootlogon, logons

    # use either the input hook or thread to send events to GUIs
        if self.PyConfig.StartGuiThread and \
              not ( self.keeppolling or _root.gROOT.IsBatch() ):
            if _is_ipython and 'IPython' in sys.modules and sys.modules[
                    'IPython'].version_info[0] >= 5:
                from IPython.terminal import pt_inputhooks

                def _inputhook(context):
                    while not context.input_is_ready():
                        _root.gSystem.ProcessEvents()

                pt_inputhooks.register('ROOT', _inputhook)
                get_ipython().run_line_magic('gui', 'ROOT')
            elif self.PyConfig.StartGuiThread == 'inputhook' or\
                  _root.gSystem.InheritsFrom( 'TMacOSXSystem' ):
                # new, PyOS_InputHook based mechanism
                if PyConfig.GUIThreadScheduleOnce:
                    for guicall in PyConfig.GUIThreadScheduleOnce:
                        guicall()
                    PyConfig.GUIThreadScheduleOnce = []
                _root.InstallGUIEventInputHook()
            else:
                # original, threading based approach
                import threading
                self.__dict__['keeppolling'] = 1
                self.__dict__[ 'PyGUIThread' ] = \
                   threading.Thread( None, _processRootEvents, None, ( self, ) )

                def _finishSchedule(ROOT=self):
                    import threading
                    if threading.currentThread() != self.PyGUIThread:
                        while self.PyConfig.GUIThreadScheduleOnce:
                            self.PyGUIThread.join(0.1)

                self.PyGUIThread.finishSchedule = _finishSchedule
                self.PyGUIThread.setDaemon(1)
                self.PyGUIThread.start()

    # store already available ROOT objects to prevent spurious lookups
        for name in self.module.__pseudo__all__ + _memPolicyAPI + _sigPolicyAPI:
            self.__dict__[name] = getattr(_root, name)

    # the macro NULL is not available from Cling globals, but might be useful
        setattr(_root, 'NULL', 0)

        # TODO: is the following still necessary? Note: dupe of classes in cppyy.py
        for name in ('complex', 'pair', 'deque', 'list', 'queue', 'stack',
                     'vector', 'map', 'multimap', 'set', 'multiset'):
            setattr(_root, name, getattr(cppyy.gbl.std, name))

    # set the display hook
        sys.displayhook = _displayhook

        # manually load libMathCore, for example to obtain gRandom
        # This can be removed once autoloading on selected variables is available
        _root.gSystem.Load("libMathCore")
예제 #9
0
파일: ROOT.py 프로젝트: SwapneelM/root
   def __finalSetup( self ):
    # prevent this method from being re-entered through the gROOT wrapper
      self.__dict__[ 'gROOT' ] = _root.gROOT

    # switch to running gettattr/setattr
      self.__class__.__getattr__ = self.__class__.__getattr2
      del self.__class__.__getattr2
      self.__class__.__setattr__ = self.__class__.__setattr2
      del self.__class__.__setattr2

    # normally, you'll want a ROOT application; don't init any further if
    # one pre-exists from some C++ code somewhere
      hasargv = hasattr( sys, 'argv' )
      if hasargv and PyConfig.IgnoreCommandLineOptions:
         argv = sys.argv
         sys.argv = []

      appc = _root.CreateScopeProxy( 'PyROOT::TPyROOTApplication' )
      if (not _builtin_cppyy and appc.CreatePyROOTApplication()) or _builtin_cppyy:
            appc.InitROOTGlobals()
            # TODO Cling equivalent needed: appc.InitCINTMessageCallback();
            appc.InitROOTMessageCallback();

      if hasargv and PyConfig.IgnoreCommandLineOptions:
         sys.argv = argv

    # must be called after gApplication creation:
      if _is_ipython:
       # IPython's FakeModule hack otherwise prevents usage of python from Cling (TODO: verify necessity)
         _root.gROOT.ProcessLine( 'TPython::Exec( "" );' )
         sys.modules[ '__main__' ].__builtins__ = __builtins__

    # special case for cout (backwards compatibility)
      if hasattr( cppyy.gbl.std, '__1' ):
         attr_1 = getattr( cppyy.gbl.std, '__1' )
         if hasattr( attr_1, 'cout' ):
            self.__dict__[ 'cout' ] = attr_1.cout

    # python side pythonizations (should live in their own file, if we get many)
      def set_size(self, buf):
         buf.SetSize(self.GetN())
         return buf

    # TODO: add pythonization API to pypy-c
      if not PYPY_CPPYY_COMPATIBILITY_FIXME:
         cppyy.add_pythonization(
            cppyy.compose_method("^TGraph(2D)?$|^TGraph.*Errors$", "GetE?[XYZ]$", set_size))
         gRootDir = self.gRootDir
      else:
         gRootDir = _root.gRootDir

    # custom logon file (must be after creation of ROOT globals)
      if hasargv and not '-n' in sys.argv and not PyConfig.DisableRootLogon:
         rootlogon = os.path.expanduser( '~/.rootlogon.py' )
         if os.path.exists( rootlogon ):
          # could also have used execfile, but import is likely to give fewer surprises
            import imp
            imp.load_module( 'rootlogon', open( rootlogon, 'r' ), rootlogon, ('.py','r',1) )
            del imp
         else:  # if the .py version of rootlogon exists, the .C is ignored (the user can
                # load the .C from the .py, if so desired)

          # system logon, user logon, and local logon (skip Rint.Logon)
            name = '.rootlogon.C'
            logons = [ os.path.join( str(self.TROOT.GetEtcDir()), 'system' + name ),
                       os.path.expanduser( os.path.join( '~', name ) ) ]
            if logons[-1] != os.path.join( os.getcwd(), name ):
               logons.append( name )
            for rootlogon in logons:
               if os.path.exists( rootlogon ):
                  appc.ExecuteFile( rootlogon )
            del rootlogon, logons

    # use either the input hook or thread to send events to GUIs
      if self.PyConfig.StartGuiThread and \
            not ( self.keeppolling or _root.gROOT.IsBatch() ):
         if _is_ipython and 'IPython' in sys.modules and sys.modules['IPython'].version_info[0] >= 5 :
            from IPython.terminal import pt_inputhooks
            import time
            def _inputhook(context):
               while not context.input_is_ready():
                  _root.gSystem.ProcessEvents()  
                  time.sleep( 0.01 )
            pt_inputhooks.register('ROOT',_inputhook)
            if get_ipython() : get_ipython().run_line_magic('gui', 'ROOT')
         elif self.PyConfig.StartGuiThread == 'inputhook' or\
               _root.gSystem.InheritsFrom( 'TMacOSXSystem' ):
          # new, PyOS_InputHook based mechanism
            if PyConfig.GUIThreadScheduleOnce:
               for guicall in PyConfig.GUIThreadScheduleOnce:
                  guicall()
               PyConfig.GUIThreadScheduleOnce = []
            _root.InstallGUIEventInputHook()
         else:
          # original, threading based approach
            import threading
            self.__dict__[ 'keeppolling' ] = 1
            self.__dict__[ 'PyGUIThread' ] = \
               threading.Thread( None, _processRootEvents, None, ( self, ) )

            def _finishSchedule( ROOT = self ):
               import threading
               if threading.currentThread() != self.PyGUIThread:
                  while self.PyConfig.GUIThreadScheduleOnce:
                     self.PyGUIThread.join( 0.1 )

            self.PyGUIThread.finishSchedule = _finishSchedule
            self.PyGUIThread.setDaemon( 1 )
            self.PyGUIThread.start()

    # store already available ROOT objects to prevent spurious lookups
      for name in self.module.__pseudo__all__ + _memPolicyAPI + _sigPolicyAPI:
         self.__dict__[ name ] = getattr( _root, name )

    # the macro NULL is not available from Cling globals, but might be useful
      setattr( _root, 'NULL', 0 )

    # TODO: is the following still necessary? Note: dupe of classes in cppyy.py
      for name in ( 'complex', 'pair', 'deque', 'list', 'queue', 'stack',
            'vector', 'map', 'multimap', 'set', 'multiset' ):
         setattr( _root, name, getattr( cppyy.gbl.std, name ) )

    # set the display hook
      sys.displayhook = _displayhook

    # manually load libMathCore, for example to obtain gRandom
    # This can be removed once autoloading on selected variables is available
      _root.gSystem.Load( "libMathCore" )
예제 #10
0
        logger.debug("automatically creating a Datoviz app")
        _APP = app()
    assert _APP is not None
    _EVENT_LOOP_INTEGRATION = True
    while not context.input_is_ready():
        _APP.run_one_frame()


def enable_ipython():
    ipython = get_ipython()
    if ipython is not None:
        ipython.magic('%gui datoviz')


# _IN_IPYTHON = in_ipython()
register('datoviz', inputhook)

# print(is_interactive())

# def enable_ipython():
#     ipython = get_ipython()
#     if ipython is not None:
#         ipython.magic('%gui datoviz')
#     global _IN_IPYTHON
#     if _IN_IPYTHON:
#         return
#     try:
#         # Try to activate the GUI integration only if we are in IPython, and if
#         # IPython event loop has not yet been activated.
#         from IPython import get_ipython
#         ipython = get_ipython()
예제 #11
0
파일: scene.py 프로젝트: 0Shark/manim
    def embed(self, close_scene_on_exit: bool = True) -> None:
        if not self.preview:
            return  # Embed is only relevant with a preview
        self.inside_embed = True
        self.stop_skipping()
        self.update_frame()
        self.save_state()

        # Configure and launch embedded IPython terminal
        from IPython.terminal import embed, pt_inputhooks
        shell = embed.InteractiveShellEmbed.instance()

        # Use the locals namespace of the caller
        local_ns = inspect.currentframe().f_back.f_locals
        # Add a few custom shortcuts
        local_ns.update({
            name: getattr(self, name)
            for name in [
                "play", "wait", "add", "remove", "clear", "save_state", "undo",
                "redo", "i2g", "i2m"
            ]
        })

        # This is useful if one wants to re-run a block of scene
        # code, while developing, tweaking it each time.
        # As long as the copied selection starts with a comment,
        # this will revert to the state of the scene at the first
        # point of running.
        def checkpoint_paste(skip=False, show_progress=True):
            pasted = pyperclip.paste()
            line0 = pasted.lstrip().split("\n")[0]
            if line0.startswith("#"):
                if line0 not in self.checkpoint_states:
                    self.checkpoint(line0)
                else:
                    self.revert_to_checkpoint(line0)
                    self.update_frame(dt=0)
            if skip:
                originally_skip = self.skip_animations
                self.skip_animations = True
            if show_progress:
                originally_show_animation_progress = self.show_animation_progress
                self.show_animation_progress = True
            shell.run_line_magic("paste", "")
            if skip:
                self.skip_animations = originally_skip
            if show_progress:
                self.show_animation_progress = originally_show_animation_progress

        local_ns['checkpoint_paste'] = checkpoint_paste

        # Enables gui interactions during the embed
        def inputhook(context):
            while not context.input_is_ready():
                if not self.is_window_closing():
                    self.update_frame(dt=0)
            if self.is_window_closing():
                shell.ask_exit()

        pt_inputhooks.register("manim", inputhook)
        shell.enable_gui("manim")

        # This is hacky, but there's an issue with ipython which is that
        # when you define lambda's or list comprehensions during a shell session,
        # they are not aware of local variables in the surrounding scope. Because
        # That comes up a fair bit during scene construction, to get around this,
        # we (admittedly sketchily) update the global namespace to match the local
        # namespace, since this is just a shell session anyway.
        shell.events.register(
            "pre_run_cell", lambda: shell.user_global_ns.update(shell.user_ns))

        # Operation to run after each ipython command
        def post_cell_func():
            self.refresh_static_mobjects()
            if not self.is_window_closing():
                self.update_frame(dt=0, ignore_skipping=True)
            self.save_state()

        shell.events.register("post_run_cell", post_cell_func)

        shell(local_ns=local_ns, stack_depth=2)

        # End scene when exiting an embed
        if close_scene_on_exit:
            raise EndScene()