Ejemplo n.º 1
0
    def enable(self, app=None):
        """Enable event loop integration with PyQt4.
        
        Parameters
        ----------
        app : Qt Application, optional.
            Running application to use.  If not given, we probe Qt for an
            existing application object, and create a new one if none is found.

        Notes
        -----
        This methods sets the PyOS_InputHook for PyQt4, which allows
        the PyQt4 to integrate with terminal based applications like
        IPython.

        If ``app`` is not given we probe for an existing one, and return it if
        found.  If no existing app is found, we create an :class:`QApplication`
        as follows::

            from PyQt4 import QtCore
            app = QtGui.QApplication(sys.argv)
        """
        from IPython.lib.inputhookqt4 import create_inputhook_qt4
        app, inputhook_qt4 = create_inputhook_qt4(self.manager, app)
        self.manager.set_inputhook(inputhook_qt4)
        if _use_appnope():
            from appnope import nope
            nope()

        return app
Ejemplo n.º 2
0
    def getConfiguration(self):
        iniPath = self._getConfigurationFilePath()
        self._parseConfigFile(iniPath)
        #
        # Watch out for the method self._overrideConfigWithArgs when you're adding custom multi-word command line arguments
        #
        if self._config['language']:
            setLanguage(self._config['language'])
        self._argparser = argparse.ArgumentParser(description=getMessage("argument-description"),
                                         epilog=getMessage("argument-epilog"))
        self._argparser.add_argument('--no-gui', action='store_true', help=getMessage("nogui-argument"))
        self._argparser.add_argument('-a', '--host', metavar='hostname', type=str, help=getMessage("host-argument"))
        self._argparser.add_argument('-n', '--name', metavar='username', type=str, help=getMessage("name-argument"))
        self._argparser.add_argument('-d', '--debug', action='store_true', help=getMessage("debug-argument"))
        self._argparser.add_argument('-g', '--force-gui-prompt', action='store_true', help=getMessage("force-gui-prompt-argument"))
        self._argparser.add_argument('--no-store', action='store_true', help=getMessage("no-store-argument"))
        self._argparser.add_argument('-r', '--room', metavar='room', type=str, nargs='?', help=getMessage("room-argument"))
        self._argparser.add_argument('-p', '--password', metavar='password', type=str, nargs='?', help=getMessage("password-argument"))
        self._argparser.add_argument('--player-path', metavar='path', type=str, help=getMessage("player-path-argument"))
        self._argparser.add_argument('--language', metavar='language', type=str, help=getMessage("language-argument"))
        self._argparser.add_argument('file', metavar='file', type=lambda s: unicode(s, 'utf8'), nargs='?', help=getMessage("file-argument"))
        self._argparser.add_argument('--clear-gui-data', action='store_true', help=getMessage("clear-gui-data-argument"))
        self._argparser.add_argument('-v', '--version', action='store_true', help=getMessage("version-argument"))
        self._argparser.add_argument('_args', metavar='options', type=str, nargs='*', help=getMessage("args-argument"))
        args = self._argparser.parse_args()
        if args.version:
            print getMessage("version-message").format(version, milestone)
            sys.exit()
        self._overrideConfigWithArgs(args)
        if not self._config['noGui']:
            try:
	            from syncplay.vendor.Qt import QtWidgets, IsPySide, IsPySide2
	            from syncplay.vendor.Qt.QtCore import QCoreApplication
	            from syncplay.vendor import qt5reactor
	            if not (IsPySide2 or IsPySide):
	                raise ImportError
	            if QCoreApplication.instance() is None:
	              self.app = QtWidgets.QApplication(sys.argv)
	            qt5reactor.install()
	            if isMacOS():
	                import appnope
	                appnope.nope()
            except ImportError:
                print getMessage("unable-import-gui-error")
                self._config['noGui'] = True
        if self._config['file'] and self._config['file'][:2] == "--":
            self._config['playerArgs'].insert(0, self._config['file'])
            self._config['file'] = None
        # Arguments not validated yet - booleans are still text values
        if self._config['language']:
            setLanguage(self._config['language'])
        if (self._config['forceGuiPrompt'] == "True" or not self._config['file']) and not self._config['noGui']:
            self._forceGuiPrompt()
        self._checkConfig()
        self._saveConfig(iniPath)
        if self._config['file']:
            self._config['loadedRelativePaths'] = self._loadRelativeConfiguration()
        if self._config['language']:
            setLanguage(self._config['language'])
        return self._config
Ejemplo n.º 3
0
def main():
    """Launch plover."""
    description = "Run the plover stenotype engine. This is a graphical application."
    parser = argparse.ArgumentParser(description=description)
    parser.add_argument('--version', action='version', version='%s %s'
                        % (__software_name__.capitalize(), __version__))
    parser.add_argument('-l', '--log-level', choices=['debug', 'info', 'warning', 'error'],
                        default=None, help='set log level')
    args = parser.parse_args(args=sys.argv[1:])
    if args.log_level is not None:
        log.set_level(args.log_level.upper())
    try:
        # Ensure only one instance of Plover is running at a time.
        with plover.oslayer.processlock.PloverLock():
            if sys.platform.startswith('darwin'):
                appnope.nope()
            init_config_dir()
            # This must be done after calling init_config_dir, so
            # Plover's configuration directory actually exists.
            log.setup_logfile()
            log.info('Plover %s', __version__)
            config = Config()
            config.target_file = CONFIG_FILE
            gui = plover.gui.main.PloverGUI(config)
            gui.MainLoop()
            with open(config.target_file, 'wb') as f:
                config.save(f)
    except plover.oslayer.processlock.LockNotAcquiredException:
        show_error('Error', 'Another instance of Plover is already running.')
    except:
        show_error('Unexpected error', traceback.format_exc())
    os._exit(1)
Ejemplo n.º 4
0
def loop_wx(kernel):
    """Start a kernel with wx event loop support."""

    import wx

    if _use_appnope() and kernel._darwin_app_nap:
        # we don't hook up App Nap contexts for Wx,
        # just disable it outright.
        from appnope import nope
        nope()

     # Wx uses milliseconds
    poll_interval = int(1000 * kernel._poll_interval)

    def wake():
        """wake from wx"""
        for stream in kernel.shell_streams:
            if stream.flush(limit=1):
                kernel.app.ExitMainLoop()
                return

    # We have to put the wx.Timer in a wx.Frame for it to fire properly.
    # We make the Frame hidden when we create it in the main app below.
    class TimerFrame(wx.Frame):
        def __init__(self, func):
            wx.Frame.__init__(self, None, -1)
            self.timer = wx.Timer(self)
            # Units for the timer are in milliseconds
            self.timer.Start(poll_interval)
            self.Bind(wx.EVT_TIMER, self.on_timer)
            self.func = func

        def on_timer(self, event):
            self.func()

    # We need a custom wx.App to create our Frame subclass that has the
    # wx.Timer to defer back to the tornado event loop.
    class IPWxApp(wx.App):
        def OnInit(self):
            self.frame = TimerFrame(wake)
            self.frame.Show(False)
            return True

    # The redirect=False here makes sure that wx doesn't replace
    # sys.stdout/stderr with its own classes.
    if not (
        getattr(kernel, 'app', None)
        and isinstance(kernel.app, wx.App)
    ):
        kernel.app = IPWxApp(redirect=False)

    # The import of wx on Linux sets the handler for signal.SIGINT
    # to 0.  This is a bug in wx or gtk.  We fix by just setting it
    # back to the Python default.
    import signal
    if not callable(signal.getsignal(signal.SIGINT)):
        signal.signal(signal.SIGINT, signal.default_int_handler)

    _loop_wx(kernel.app)
def stimDisplayMirrorChildFunction(
qTo
,qFrom
, window_size = [1920/2,1080/2]
, window_position = [0,0]
):
	import sdl2
	import sdl2.ext
	import sys
	import time
	from PIL import Image #for image manipulation
	try:
		import appnope
		appnope.nope()
	except:
		pass

	sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO)
	window = sdl2.ext.Window("mirror",size=window_size,position=window_position,flags=sdl2.SDL_WINDOW_SHOWN)
	windowID = sdl2.SDL_GetWindowID(window.window)
	windowSurf = sdl2.SDL_GetWindowSurface(window.window)
	windowArray = sdl2.ext.pixels3d(windowSurf.contents)

	sdl2.ext.fill(windowSurf.contents,sdl2.pixels.SDL_Color(r=255, g=255, b=255, a=255))
	window.refresh()

	for i in range(10):
		sdl2.SDL_PumpEvents() #to show the windows

	def exitSafely():
		sys.exit()

	while True:
		if not qTo.empty():
			message = qTo.get()
			if message=='quit':
				exitSafely()
			elif message[0]=='frame':
				# print ['q',time.time()-message[3]] #time spent in queue
				res = message[1]
				buffer = message[2]
				image = Image.fromstring(mode="RGB", size=res, data=buffer)
				image = image.transpose(Image.ROTATE_270)
				# start = time.time()
				image.thumbnail([res[1]/2,res[0]/2],Image.LANCZOS)
				# print ['resize',time.time()-start]
				windowArray[:,:,0:3] = image
				window.refresh()
		sdl2.SDL_PumpEvents()
		for event in sdl2.ext.get_events():
			if event.type==sdl2.SDL_WINDOWEVENT:
				if (event.window.event==sdl2.SDL_WINDOWEVENT_CLOSE):
					exitSafely()
def writerChildFunction(
qTo
,qFrom
, window_size = [200,200]
, window_position = [0,0]
):
	import sdl2
	import sdl2.ext
	import sys
	import time
	try:
		import appnope
		appnope.nope()
	except:
		pass

	sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO)
	window = sdl2.ext.Window("writer",size=window_size,position=window_position,flags=sdl2.SDL_WINDOW_SHOWN)
	windowID = sdl2.SDL_GetWindowID(window.window)
	windowSurf = sdl2.SDL_GetWindowSurface(window.window)
	sdl2.ext.fill(windowSurf.contents,sdl2.pixels.SDL_Color(r=255, g=255, b=255, a=255))
	window.refresh()

	for i in range(10):
		sdl2.SDL_PumpEvents() #to show the windows

	files = {}

	def exitSafely():
		try:
			for index,fileObj in files.items():
				fileObj.close()
				# gpg -r "Michael Lawrence <*****@*****.**>" -e mac.txt
		except:
			pass
		sys.exit()

	while True:
		if not qTo.empty():
			message = qTo.get()
			if message=='quit':
				exitSafely()
			elif message[0]=='new_file':
				files[message[1]] = open(message[2],'w')
			elif message[0]=='write':
				files[message[1]].write(message[2]+'\n')
		else:
			time.sleep(1)
		sdl2.SDL_PumpEvents()
		for event in sdl2.ext.get_events():
			if event.type==sdl2.SDL_WINDOWEVENT:
				if (event.window.event==sdl2.SDL_WINDOWEVENT_CLOSE):
					exitSafely()
Ejemplo n.º 7
0
    def enable(self, app=None):
        """DEPRECATED since IPython 5.0

        Enable event loop integration with wxPython.

        Parameters
        ----------
        app : WX Application, optional.
            Running application to use.  If not given, we probe WX for an
            existing application object, and create a new one if none is found.

        Notes
        -----
        This methods sets the ``PyOS_InputHook`` for wxPython, which allows
        the wxPython to integrate with terminal based applications like
        IPython.

        If ``app`` is not given we probe for an existing one, and return it if
        found.  If no existing app is found, we create an :class:`wx.App` as
        follows::

            import wx
            app = wx.App(redirect=False, clearSigInt=False)
        """
        warn(
            "This function is deprecated since IPython 5.0 and will be removed in future versions.",
            DeprecationWarning,
            stacklevel=2,
        )
        import wx

        wx_version = V(wx.__version__).version

        if wx_version < [2, 8]:
            raise ValueError("requires wxPython >= 2.8, but you have %s" % wx.__version__)

        from IPython.lib.inputhookwx import inputhook_wx

        self.manager.set_inputhook(inputhook_wx)
        if _use_appnope():
            from appnope import nope

            nope()

        import wx

        if app is None:
            app = wx.GetApp()
        if app is None:
            app = wx.App(redirect=False, clearSigInt=False)

        return app
Ejemplo n.º 8
0
def loop_wx(kernel):
    """Start a kernel with wx event loop support."""

    import wx

    if _use_appnope() and kernel._darwin_app_nap:
        # we don't hook up App Nap contexts for Wx,
        # just disable it outright.
        from appnope import nope
        nope()

    doi = kernel.do_one_iteration
    # Wx uses milliseconds
    poll_interval = int(1000 * kernel._poll_interval)

    # We have to put the wx.Timer in a wx.Frame for it to fire properly.
    # We make the Frame hidden when we create it in the main app below.
    class TimerFrame(wx.Frame):
        def __init__(self, func):
            wx.Frame.__init__(self, None, -1)
            self.timer = wx.Timer(self)
            # Units for the timer are in milliseconds
            self.timer.Start(poll_interval)
            self.Bind(wx.EVT_TIMER, self.on_timer)
            self.func = func

        def on_timer(self, event):
            self.func()

    # We need a custom wx.App to create our Frame subclass that has the
    # wx.Timer to drive the ZMQ event loop.
    class IPWxApp(wx.App):
        def OnInit(self):
            self.frame = TimerFrame(doi)
            self.frame.Show(False)
            return True

    # The redirect=False here makes sure that wx doesn't replace
    # sys.stdout/stderr with its own classes.
    kernel.app = IPWxApp(redirect=False)

    # The import of wx on Linux sets the handler for signal.SIGINT
    # to 0.  This is a bug in wx or gtk.  We fix by just setting it
    # back to the Python default.
    import signal
    if not callable(signal.getsignal(signal.SIGINT)):
        signal.signal(signal.SIGINT, signal.default_int_handler)

    _loop_wx(kernel.app)
Ejemplo n.º 9
0
    def enable(self, app=None):
        """DEPRECATED since IPython 5.0

        Enable event loop integration with wxPython.

        Parameters
        ----------
        app : WX Application, optional.
            Running application to use.  If not given, we probe WX for an
            existing application object, and create a new one if none is found.

        Notes
        -----
        This methods sets the ``PyOS_InputHook`` for wxPython, which allows
        the wxPython to integrate with terminal based applications like
        yap_ipython.

        If ``app`` is not given we probe for an existing one, and return it if
        found.  If no existing app is found, we create an :class:`wx.App` as
        follows::

            import wx
            app = wx.App(redirect=False, clearSigInt=False)
        """
        warn(
            "This function is deprecated since IPython 5.0 and will be removed in future versions.",
            DeprecationWarning,
            stacklevel=2)
        import wx

        wx_version = V(wx.__version__).version

        if wx_version < [2, 8]:
            raise ValueError("requires wxPython >= 2.8, but you have %s" %
                             wx.__version__)

        from yap_ipython.lib.inputhookwx import inputhook_wx
        self.manager.set_inputhook(inputhook_wx)
        if _use_appnope():
            from appnope import nope
            nope()

        import wx
        if app is None:
            app = wx.GetApp()
        if app is None:
            app = wx.App(redirect=False, clearSigInt=False)

        return app
Ejemplo n.º 10
0
def main():
    initials = raw_input('Your initials: ')
    run_nr = int(raw_input('Run number: '))
    scanner = raw_input('Are you in the scanner (y/n)?: ')
    track_eyes = raw_input('Are you recording gaze (y/n)?: ')
    if track_eyes == 'y':
        tracker_on = True
    elif track_eyes == 'n':
        tracker_on = False
    appnope.nope()

    ts = MapperSession(initials, run_nr, scanner, tracker_on)
    ts.run()

    plot_mapper_staircase(initials, run_nr)
Ejemplo n.º 11
0
def main():
    """Launch plover."""
    description = "Run the plover stenotype engine. This is a graphical application."
    parser = argparse.ArgumentParser(description=description)
    parser.add_argument('--version',
                        action='version',
                        version='%s %s' %
                        (__software_name__.capitalize(), __version__))
    parser.add_argument('-l',
                        '--log-level',
                        choices=['debug', 'info', 'warning', 'error'],
                        default=None,
                        help='set log level')
    parser.add_argument('-g', '--gui', default='qt', help='set gui')
    args = parser.parse_args(args=sys.argv[1:])
    if args.log_level is not None:
        log.set_level(args.log_level.upper())
    log.setup_platform_handler()

    registry.load_plugins()
    registry.update()

    gui = registry.get_plugin('gui', args.gui).obj

    try:
        # Ensure only one instance of Plover is running at a time.
        with plover.oslayer.processlock.PloverLock():
            if sys.platform.startswith('darwin'):
                appnope.nope()
            init_config_dir()
            # This must be done after calling init_config_dir, so
            # Plover's configuration directory actually exists.
            log.setup_logfile()
            log.info('Plover %s', __version__)
            config = Config()
            config.target_file = CONFIG_FILE
            code = gui.main(config)
            with open(config.target_file, 'wb') as f:
                config.save(f)
    except plover.oslayer.processlock.LockNotAcquiredException:
        gui.show_error('Error',
                       'Another instance of Plover is already running.')
        code = 1
    except:
        gui.show_error('Unexpected error', traceback.format_exc())
        code = 2
    os._exit(code)
Ejemplo n.º 12
0
def main():
    initials = sys.argv[1]
    #initials = raw_input('Your initials: ')
    #run_nr = int(raw_input('Run number: '))
    #scanner = raw_input('Are you in the scanner (y/n)?: ')
    #track_eyes = raw_input('Are you recording gaze (y/n)?: ')
    # if track_eyes == 'y':
        #tracker_on = True
    # elif track_eyes == 'n':
        #tracker_on = False

    # initials = 'tk'
    run = 2
    appnope.nope()

    ts = MSSession(subject_initials=initials, index_number=run, tracker_on=False)
    ts.run()
Ejemplo n.º 13
0
    async def start_check(self,  # type: HummingbotApplication
                          log_level: Optional[str] = None,
                          restore: Optional[bool] = False):

        if self.strategy_task is not None and not self.strategy_task.done():
            self._notify('The bot is already running - please run "stop" first')
            return

        is_valid = await self.status_check_all(notify_success=False)
        if not is_valid:
            return

        if self._last_started_strategy_file != self.strategy_file_name:
            init_logging("hummingbot_logs.yml",
                         override_log_level=log_level.upper() if log_level else None,
                         strategy_file_path=self.strategy_file_name)
            self._last_started_strategy_file = self.strategy_file_name

        # If macOS, disable App Nap.
        if platform.system() == "Darwin":
            import appnope
            appnope.nope()

        self._initialize_notifiers()

        self._notify(f"\nStatus check complete. Starting '{self.strategy_name}' strategy...")
        if global_config_map.get("paper_trade_enabled").value:
            self._notify("\nPaper Trading ON: All orders are simulated, and no real orders are placed.")

        for exchange in required_exchanges:
            connector = str(exchange)
            status = get_connector_status(connector)

            # Display custom warning message for specific connectors
            warning_msg = warning_messages.get(connector, None)
            if warning_msg is not None:
                self._notify(f"\nConnector status: {status}\n"
                             f"{warning_msg}")

            # Display warning message if the exchange connector has outstanding issues or not working
            elif status != "GREEN":
                self._notify(f"\nConnector status: {status}. This connector has one or more issues.\n"
                             "Refer to our Github page for more info: https://github.com/coinalpha/hummingbot")

        await self.start_market_making(self.strategy_name, restore)
Ejemplo n.º 14
0
    def setUpClass(cls):
        """Prepare for test execution.

        Ensure that a (single copy of) QApplication has been created
        """
        global app
        if app is None:
            app = QApplication([])
        # Disable App Nap on macOS (see
        # https://codereview.qt-project.org/c/qt/qtbase/+/202515 for more)
        if sys.platform == "darwin":
            try:
                import appnope
            except ImportError:
                pass
            else:
                appnope.nope()
        super().setUpClass()
Ejemplo n.º 15
0
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        # Initialize the Debugger
        if _is_debugpy_available:
            self.debugger = Debugger(
                self.log,
                self.debugpy_stream,
                self._publish_debug_event,
                self.debug_shell_socket,
                self.session,
                self.debug_just_my_code,
            )

        # Initialize the InteractiveShell subclass
        self.shell = self.shell_class.instance(
            parent=self,
            profile_dir=self.profile_dir,
            user_module=self.user_module,
            user_ns=self.user_ns,
            kernel=self,
            compiler_class=XCachingCompiler,
        )
        self.shell.displayhook.session = self.session
        self.shell.displayhook.pub_socket = self.iopub_socket
        self.shell.displayhook.topic = self._topic("execute_result")
        self.shell.display_pub.session = self.session
        self.shell.display_pub.pub_socket = self.iopub_socket

        self.comm_manager = CommManager(parent=self, kernel=self)

        self.shell.configurables.append(self.comm_manager)
        comm_msg_types = ["comm_open", "comm_msg", "comm_close"]
        for msg_type in comm_msg_types:
            self.shell_handlers[msg_type] = getattr(self.comm_manager,
                                                    msg_type)

        if _use_appnope() and self._darwin_app_nap:
            # Disable app-nap as the kernel is not a gui but can have guis
            import appnope

            appnope.nope()
Ejemplo n.º 16
0
def main():

    subject_initials = str(raw_input('Your initials: '))
    index_number = int(raw_input('Which run: '))
    version_number = int(raw_input('Version: '))

    # subject_initials = 'test'
    # index_number = 1
    # version_number = 1

    tracker_on = 1
    screen_params = {
        'size': (1920, 1080),
        'full_screen': True,
        'background_color': (0.5, 0.5, 0.5)
    }

    appnope.nope()

    ts = PRSession(subject_initials=subject_initials,
                   index_number=index_number,
                   version_number=version_number,
                   tracker_on=tracker_on,
                   **screen_params)
    ts.run()

    # autmatically move files:
    if not os.path.exists('data/{}/'.format(subject_initials)):
        os.makedirs('data/{}/'.format(subject_initials))
    os.system('mv %s %s' %
              (ts.output_file + '.edf', 'data/' + subject_initials + '/' +
               os.path.split(ts.output_file)[1] + '.edf'))
    os.system('mv %s %s' %
              (ts.output_file + '.tsv', 'data/' + subject_initials + '/' +
               os.path.split(ts.output_file)[1] + '.tsv'))
    os.system('mv %s %s' %
              (ts.output_file + '_outputDict.pkl', 'data/' + subject_initials +
               '/' + os.path.split(ts.output_file)[1] + '_outputDict.pkl'))

    # run behavioural analysis:
    analyse_yesno(filename='data/' + subject_initials + '/' +
                  os.path.split(ts.output_file)[1] + '.tsv')
Ejemplo n.º 17
0
def stamperLoop(windowSize,windowPosition,windowColor,doBorder,qTo,qFrom):
	import sdl2
	import sdl2.ext
	import sys
	try:
		import appnope
		appnope.nope()
	except:
		pass
	sdl2.SDL_Init(sdl2.SDL_INIT_TIMER)
	timeFreq = 1.0/sdl2.SDL_GetPerformanceFrequency()
	sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO)
	if doBorder:
		flags = sdl2.SDL_WINDOW_SHOWN
	else:
		flags = sdl2.SDL_WINDOW_BORDERLESS | sdl2.SDL_WINDOW_SHOWN
	window = sdl2.ext.Window("pyStamper",size=windowSize,position=windowPosition,flags=flags)
	windowSurf = sdl2.SDL_GetWindowSurface(window.window)
	sdl2.ext.fill(windowSurf.contents,sdl2.pixels.SDL_Color(r=windowColor[0], g=windowColor[1], b=windowColor[2], a=255))
	window.refresh()
	#sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK) #uncomment if you want joystick input
	#sdl2.SDL_JoystickOpen(0) #uncomment if you want joystick input
	while True:
		sdl2.SDL_PumpEvents()
		if not qTo.empty():
			message = qTo.get()
			if message[0]=='quit':
				sys.exit()
		for event in sdl2.ext.get_events():
			message = {}
			if event.type==sdl2.SDL_KEYDOWN:
				message['type'] = 'key'
				message['time'] = event.key.timestamp*timeFreq
				message['value'] = sdl2.SDL_GetKeyName(event.key.keysym.sym).lower()
				qFrom.put(message)
			elif event.type == sdl2.SDL_JOYAXISMOTION:
				message['type'] = 'axis'
				message['axis'] = event.jaxis.axis
				message['time'] = event.jaxis.timestamp*timeFreq
				message['value'] = event.jaxis.value
				qFrom.put(message)
Ejemplo n.º 18
0
    def enable(self, app=None):
        """DEPRECATED since IPython 5.0

        Enable event loop integration with PyQt4.
        
        Parameters
        ----------
        app : Qt Application, optional.
            Running application to use.  If not given, we probe Qt for an
            existing application object, and create a new one if none is found.

        Notes
        -----
        This methods sets the PyOS_InputHook for PyQt4, which allows
        the PyQt4 to integrate with terminal based applications like
        IPython.

        If ``app`` is not given we probe for an existing one, and return it if
        found.  If no existing app is found, we create an :class:`QApplication`
        as follows::

            from PyQt4 import QtCore
            app = QtGui.QApplication(sys.argv)
        """
        warn(
            "This function is deprecated since IPython 5.0 and will be removed in future versions.",
            DeprecationWarning,
            stacklevel=2,
        )
        from IPython.lib.inputhookqt4 import create_inputhook_qt4

        app, inputhook_qt4 = create_inputhook_qt4(self.manager, app)
        self.manager.set_inputhook(inputhook_qt4)
        if _use_appnope():
            from appnope import nope

            nope()

        return app
Ejemplo n.º 19
0
    def start(
            self,  # type: HummingbotApplication
            log_level: Optional[str] = None):
        if threading.current_thread() != threading.main_thread():
            self.ev_loop.call_soon_threadsafe(self.start, log_level)
            return

        is_valid = self.status()
        if not is_valid:
            return

        strategy_file_path = in_memory_config_map.get(
            "strategy_file_path").value
        init_logging(
            "hummingbot_logs.yml",
            override_log_level=log_level.upper() if log_level else None,
            strategy_file_path=strategy_file_path)

        # If macOS, disable App Nap.
        if platform.system() == "Darwin":
            import appnope
            appnope.nope()

        # TODO add option to select data feed
        self.data_feed: DataFeedBase = CoinCapDataFeed.get_instance()

        self._initialize_notifiers()

        ExchangeRateConversion.get_instance().start()
        strategy_name = in_memory_config_map.get("strategy").value
        self.init_reporting_module()
        self._notify(
            f"\n  Status check complete. Starting '{strategy_name}' strategy..."
        )
        safe_ensure_future(self.start_market_making(strategy_name),
                           loop=self.ev_loop)
    async def start_check(
            self,  # type: HummingbotApplication
            log_level: Optional[str] = None):

        if self.strategy_task is not None and not self.strategy_task.done():
            self._notify(
                'The bot is already running - please run "stop" first')
            return

        is_valid = await self.status_check_all(notify_success=False)
        if not is_valid:
            return

        init_logging(
            "hummingbot_logs.yml",
            override_log_level=log_level.upper() if log_level else None,
            strategy_file_path=self.strategy_file_name)

        # If macOS, disable App Nap.
        if platform.system() == "Darwin":
            import appnope
            appnope.nope()

        # TODO add option to select data feed
        self.data_feed: DataFeedBase = CoinCapDataFeed.get_instance()

        self._initialize_notifiers()

        self._notify(
            f"\nStatus check complete. Starting '{self.strategy_name}' strategy..."
        )
        if global_config_map.get("paper_trade_enabled").value:
            self._notify(
                "\nPaper Trading ON: All orders are simulated, and no real orders are placed."
            )
        await self.start_market_making(self.strategy_name)
Ejemplo n.º 21
0
    def start(self, log_level: Optional[str] = None):
        is_valid = self.status()
        if not is_valid:
            return

        if log_level is not None:
            init_logging("hummingbot_logs.yml",
                         override_log_level=log_level.upper())

        # If macOS, disable App Nap.
        if platform.system() == "Darwin":
            import appnope
            appnope.nope()

        # TODO add option to select data feed
        self.data_feed: DataFeedBase = CoinCapDataFeed.get_instance()

        ExchangeRateConversion.get_instance().start()
        strategy_name = in_memory_config_map.get("strategy").value
        self.init_reporting_module()
        self.app.log(
            f"\n  Status check complete. Starting '{strategy_name}' strategy..."
        )
        asyncio.ensure_future(self.start_market_making(strategy_name))
Ejemplo n.º 22
0
    async def start_check(
            self,  # type: HummingbotApplication
            log_level: Optional[str] = None,
            restore: Optional[bool] = False):
        if self.strategy_task is not None and not self.strategy_task.done():
            self._notify(
                'The bot is already running - please run "stop" first')
            return

        if settings.required_rate_oracle:
            # If the strategy to run requires using the rate oracle to find FX rates, validate there is a rate for
            # each configured token pair
            if not (await self.confirm_oracle_conversion_rate()):
                self._notify("The strategy failed to start.")
                return

        # We always start the RateOracle. It is required for PNL calculation.
        RateOracle.get_instance().start()

        is_valid = await self.status_check_all(notify_success=False)
        if not is_valid:
            self._notify("Status checks failed. Start aborted.")
            return
        if self._last_started_strategy_file != self.strategy_file_name:
            init_logging(
                "hummingbot_logs.yml",
                override_log_level=log_level.upper() if log_level else None,
                strategy_file_path=self.strategy_file_name)
            self._last_started_strategy_file = self.strategy_file_name

        # If macOS, disable App Nap.
        if platform.system() == "Darwin":
            import appnope
            appnope.nope()

        self._initialize_notifiers()

        self._notify(
            f"\nStatus check complete. Starting '{self.strategy_name}' strategy..."
        )
        if any([
                str(exchange).endswith("paper_trade")
                for exchange in settings.required_exchanges
        ]):
            self._notify(
                "\nPaper Trading Active: All orders are simulated, and no real orders are placed."
            )

        for exchange in settings.required_exchanges:
            connector = str(exchange)
            status = get_connector_status(connector)

            # Display custom warning message for specific connectors
            warning_msg = warning_messages.get(connector, None)
            if warning_msg is not None:
                self._notify(f"\nConnector status: {status}\n"
                             f"{warning_msg}")

            # Display warning message if the exchange connector has outstanding issues or not working
            elif status != "GREEN":
                self._notify(
                    f"\nConnector status: {status}. This connector has one or more issues.\n"
                    "Refer to our Github page for more info: https://github.com/coinalpha/hummingbot"
                )

        await self.start_market_making(self.strategy_name, restore)
Ejemplo n.º 23
0
def main():
    """Launch plover."""
    description = "Run the plover stenotype engine. This is a graphical application."
    parser = argparse.ArgumentParser(description=description)
    parser.add_argument('--version', action='version', version='%s %s'
                        % (__software_name__.capitalize(), __version__))
    parser.add_argument('-s', '--script', default=None, nargs=argparse.REMAINDER,
                        help='use another plugin console script as main entrypoint, '
                        'passing in the rest of the command line arguments, '
                        'print list of available scripts when no argument is given')
    parser.add_argument('-l', '--log-level', choices=['debug', 'info', 'warning', 'error'],
                        default=None, help='set log level')
    parser.add_argument('-g', '--gui', default=None, help='set gui')
    args = parser.parse_args(args=sys.argv[1:])
    if args.log_level is not None:
        log.set_level(args.log_level.upper())
    log.setup_platform_handler()

    log.info('Plover %s', __version__)
    log.info('configuration directory: %s', CONFIG_DIR)

    registry.update()

    if args.gui is None:
        gui_priority = {
            'qt': 1,
            'none': -1,
        }
        gui_list = sorted(registry.list_plugins('gui'), reverse=True,
                          key=lambda gui: gui_priority.get(gui.name, 0))
        gui = gui_list[0].obj
    else:
        gui = registry.get_plugin('gui', args.gui).obj

    try:
        if args.script is not None:
            if args.script:
                # Create a mapping of available console script,
                # with the following priorities (highest first):
                # - {project_name}-{version}:{script_name}
                # - {project_name}:{script_name}
                # - {script_name}
                console_scripts = {}
                for e in sorted(pkg_resources.iter_entry_points('console_scripts'),
                                key=lambda e: (e.dist, e.name)):
                    for key in (
                        '%s-%s:%s' % (e.dist.project_name, e.dist.version, e.name),
                        '%s:%s' % (e.dist.project_name, e.name),
                        e.name,
                    ):
                        console_scripts[key] = e
                entrypoint = console_scripts.get(args.script[0])
                if entrypoint is None:
                    log.error('no such script: %s', args.script[0])
                    code = 1
                else:
                    sys.argv = args.script
                    try:
                        code = entrypoint.load()()
                    except SystemExit as e:
                        code = e.code
                if code is None:
                    code = 0
            else:
                print('available script(s):')
                dist = None
                for e in sorted(pkg_resources.iter_entry_points('console_scripts'),
                                key=lambda e: (str(e.dist), e.name)):
                    if dist != e.dist:
                        dist = e.dist
                        print('%s:' % dist)
                    print('- %s' % e.name)
                code = 0
            os._exit(code)

        # Ensure only one instance of Plover is running at a time.
        with processlock.PloverLock():
            if sys.platform.startswith('darwin'):
                appnope.nope()
            init_config_dir()
            # This must be done after calling init_config_dir, so
            # Plover's configuration directory actually exists.
            log.setup_logfile()
            config = Config()
            config.target_file = CONFIG_FILE
            code = gui.main(config)
            with open(config.target_file, 'wb') as f:
                config.save(f)
    except processlock.LockNotAcquiredException:
        gui.show_error('Error', 'Another instance of Plover is already running.')
        code = 1
    except:
        gui.show_error('Unexpected error', traceback.format_exc())
        code = 2
    if code == -1:
        # Restart.
        args = sys.argv[:]
        if args[0].endswith('.py') or args[0].endswith('.pyc'):
            # We're running from source.
            assert args[0] == __file__
            args[0:1] = [sys.executable, '-m', __spec__.name]
        # Execute atexit handlers.
        atexit._run_exitfuncs()
        if sys.platform.startswith('win32'):
            # Workaround https://bugs.python.org/issue19066
            subprocess.Popen(args, cwd=os.getcwd())
            code = 0
        else:
            os.execv(args[0], args)
    os._exit(code)
Ejemplo n.º 24
0
def eyelinkChildFunction(qTo,
                         qFrom,
                         windowSize=[200, 200],
                         windowPosition=[0, 0],
                         stimDisplayRes=[1920, 1080],
                         calibrationDisplaySize=[1920, 1080],
                         calibrationDotSize=10,
                         eyelinkIp='100.1.1.1',
                         edfFileName='temp.edf',
                         edfPath='./_Data/temp.edf',
                         saccadeSoundFile='_Stimuli/stop.wav',
                         blinkSoundFile='_Stimuli/stop.wav'):
    import sdl2
    import sdl2.ext
    import math
    import OpenGL.GL as gl
    import sdl2.sdlmixer
    import pylink
    import numpy
    import sys
    import shutil
    import subprocess
    import time
    import os
    import array
    from PIL import Image
    from PIL import ImageDraw
    try:
        import appnope
        appnope.nope()
    except:
        pass

    byteify = lambda x, enc: x.encode(enc)

    sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO)
    window = sdl2.ext.Window("eyelink",
                             size=windowSize,
                             position=windowPosition,
                             flags=sdl2.SDL_WINDOW_SHOWN)
    windowID = sdl2.SDL_GetWindowID(window.window)
    windowSurf = sdl2.SDL_GetWindowSurface(window.window)
    sdl2.ext.fill(windowSurf.contents,
                  sdl2.pixels.SDL_Color(r=0, g=0, b=0, a=255))
    window.refresh()

    for i in range(10):
        sdl2.SDL_PumpEvents()  #to show the windows

    sdl2.SDL_Init(sdl2.SDL_INIT_AUDIO)
    sdl2.sdlmixer.Mix_OpenAudio(44100, sdl2.sdlmixer.MIX_DEFAULT_FORMAT, 2,
                                1024)

    class Sound:
        def __init__(self, fileName):
            self.sample = sdl2.sdlmixer.Mix_LoadWAV(
                sdl2.ext.compat.byteify(fileName, "utf-8"))
            self.started = False

        def play(self):
            self.channel = sdl2.sdlmixer.Mix_PlayChannel(-1, self.sample, 0)
            self.started = True

        def stillPlaying(self):
            if self.started:
                if sdl2.sdlmixer.Mix_Playing(self.channel):
                    return True
                else:
                    self.started = False
                    return False
            else:
                return False

    saccadeSound = Sound(saccadeSoundFile)
    blinkSound = Sound(blinkSoundFile)

    def exitSafely():
        if 'eyelink' in locals():
            if eyelink.isRecording() == 0:
                eyelink.stopRecording()
            eyelink.setOfflineMode()
            eyelink.closeDataFile()
            eyelink.receiveDataFile(edfFileName, 'temp.edf')
            eyelink.close()
            if os.path.isfile('temp.edf'):
                shutil.move('temp.edf', edfPath)
                # if os.path.isfile(edfPath):
                # 	subprocess.call('./edf2asc -y ./'+edfPath,shell=True)
        sys.exit(
        )  #process gets hung here if called when showing images from eyelink

    pylink.setDriftCorrectSounds('off', 'off', 'off')
    pylink.setCalibrationSounds('off', 'off', 'off')

    edfPath = './_Data/temp.edf'  #temporary default location, to be changed later when ID is established
    done = False
    while not done:
        try:
            # print '\neyelink: Attempting to connect to eyelink (check that wifi is off!)'
            eyelink = pylink.EyeLink(eyelinkIp)
            done = True
        except:
            while not qTo.empty():
                message = qTo.get()
                if message == 'quit':
                    exitSafely()
                else:
                    qTo.put(message)

    # print 'eyelink: connected'
    eyelink.sendCommand(
        'select_parser_configuration 0'
    )  # 0--> standard (cognitive); 1--> sensitive (psychophysical)
    # eyelink.sendCommand('sample_rate 500')
    eyelink.setLinkEventFilter("SACCADE,BLINK,FIXATION,LEFT,RIGHT")
    eyelink.openDataFile(edfFileName)
    eyelink.sendCommand(
        "screen_pixel_coords =  %d %d %d %d" %
        (stimDisplayRes[0] / 2 - calibrationDisplaySize[0] / 2,
         stimDisplayRes[1] / 2 - calibrationDisplaySize[1] / 2,
         stimDisplayRes[0] / 2 + calibrationDisplaySize[0] / 2,
         stimDisplayRes[1] / 2 + calibrationDisplaySize[1] / 2))
    eyelink.sendMessage("DISPLAY_COORDS  0 0 %d %d" %
                        (stimDisplayRes[0], stimDisplayRes[1]))
    eyelink.sendCommand("saccade_velocity_threshold = 60")
    eyelink.sendCommand("saccade_acceleration_threshold = 19500")

    class EyeLinkCoreGraphicsPySDL2(pylink.EyeLinkCustomDisplay):
        def __init__(self):
            # self.__target_beep__ = Sound('_Stimuli/type.wav')
            # self.__target_beep__done__ = Sound('qbeep.wav')
            # self.__target_beep__error__ = Sound('error.wav')
            if sys.byteorder == 'little':
                self.byteorder = 1
            else:
                self.byteorder = 0
            self.imagebuffer = array.array('I')
            self.pal = None
            self.__img__ = None

        def record_abort_hide(self):
            pass

        def play_beep(self, beepid):
            pass
            # if beepid == pylink.DC_TARG_BEEP or beepid == pylink.CAL_TARG_BEEP:
            # 	self.__target_beep__.play()
            # elif beepid == pylink.CAL_ERR_BEEP or beepid == pylink.DC_ERR_BEEP:
            # 	self.__target_beep__error__.play()
            # else:#	CAL_GOOD_BEEP or DC_GOOD_BEEP
            # 	self.__target_beep__done__.play()
        def clear_cal_display(self):
            # # print 'clear_cal_display'
            qFrom.put('clearCalDisplay')

        def setup_cal_display(self):
            # # print 'setup_cal_display'
            qFrom.put('setupCalDisplay')

        def exit_cal_display(self):
            # # print 'exit_cal_display'
            qFrom.put('exitCalDisplay')

        def erase_cal_target(self):
            # # print 'erase_cal_target'
            qFrom.put('eraseCalTarget')

        def draw_cal_target(self, x, y):
            # # print 'draw_cal_target'
            qFrom.put(['drawCalTarget', x, y])

        def setup_image_display(self, width, height):
            # # print 'eyelink: setup_image_display'
            self.img_size = (width, height)
            return (0)

        def exit_image_display(self):
            # # print 'eyelink: exit_image_display'
            pass

        def image_title(self, text):
            # # print 'eyelink: image_title'
            pass

        def set_image_palette(self, r, g, b):
            # # print 'eyelink: set_image_palette'
            self.imagebuffer = array.array('I')
            sz = len(r)
            i = 0
            self.pal = []
            while i < sz:
                rf = int(b[i])
                gf = int(g[i])
                bf = int(r[i])
                if self.byteorder:
                    self.pal.append((rf << 16) | (gf << 8) | (bf))
                else:
                    self.pal.append(
                        (bf << 24) | (gf << 16) | (rf << 8))  #for mac
                i = i + 1

        def draw_image_line(self, width, line, totlines, buff):
            # # print 'eyelink: draw_image_line'
            i = 0
            while i < width:
                if buff[i] >= len(self.pal):
                    buff[i] = len(self.pal) - 1
                self.imagebuffer.append(self.pal[buff[i] & 0x000000FF])
                i = i + 1
            if line == totlines:
                img = Image.fromstring('RGBX', (width, totlines),
                                       self.imagebuffer.tostring())
                img = img.convert('RGBA')
                self.__img__ = img.copy()
                self.__draw__ = ImageDraw.Draw(self.__img__)
                self.draw_cross_hair(
                )  #inherited method, calls draw_line and draw_losenge
                qFrom.put([
                    'image',
                    numpy.array(
                        self.__img__.resize([
                            self.__img__.size[0] * 4, self.__img__.size[1] * 4
                        ], Image.BICUBIC))
                ])
                self.__img__ = None
                self.__draw__ = None
                self.imagebuffer = array.array('I')

        def getColorFromIndex(self, colorindex):
            if colorindex == pylink.CR_HAIR_COLOR: return (255, 255, 255, 255)
            elif colorindex == pylink.PUPIL_HAIR_COLOR:
                return (255, 255, 255, 255)
            elif colorindex == pylink.PUPIL_BOX_COLOR:
                return (0, 255, 0, 255)
            elif colorindex == pylink.SEARCH_LIMIT_BOX_COLOR:
                return (255, 0, 0, 255)
            elif colorindex == pylink.MOUSE_CURSOR_COLOR:
                return (255, 0, 0, 255)
            else:
                return (0, 0, 0, 0)

        def draw_line(self, x1, y1, x2, y2, colorindex):
            # # print 'eyelink: draw_line'
            if x1 < 0: x1 = 0
            if x2 < 0: x2 = 0
            if y1 < 0: y1 = 0
            if y2 < 0: y2 = 0
            if x1 > self.img_size[0]: x1 = self.img_size[0]
            if x2 > self.img_size[0]: x2 = self.img_size[0]
            if y1 > self.img_size[1]: y1 = self.img_size[1]
            if y2 > self.img_size[1]: y2 = self.img_size[1]
            imr = self.__img__.size
            x1 = int((float(x1) / float(self.img_size[0])) * imr[0])
            x2 = int((float(x2) / float(self.img_size[0])) * imr[0])
            y1 = int((float(y1) / float(self.img_size[1])) * imr[1])
            y2 = int((float(y2) / float(self.img_size[1])) * imr[1])
            color = self.getColorFromIndex(colorindex)
            self.__draw__.line([(x1, y1), (x2, y2)], fill=color)
            return 0

        def draw_lozenge(self, x, y, width, height, colorindex):
            # # print 'eyelink: draw_lozenge'
            color = self.getColorFromIndex(colorindex)
            imr = self.__img__.size
            x = int((float(x) / float(self.img_size[0])) * imr[0])
            width = int((float(width) / float(self.img_size[0])) * imr[0])
            y = int((float(y) / float(self.img_size[1])) * imr[1])
            height = int((float(height) / float(self.img_size[1])) * imr[1])
            if width > height:
                rad = height / 2
                self.__draw__.line([(x + rad, y), (x + width - rad, y)],
                                   fill=color)
                self.__draw__.line([(x + rad, y + height),
                                    (x + width - rad, y + height)],
                                   fill=color)
                clip = (x, y, x + height, y + height)
                self.__draw__.arc(clip, 90, 270, fill=color)
                clip = ((x + width - height), y, x + width, y + height)
                self.__draw__.arc(clip, 270, 90, fill=color)
            else:
                rad = width / 2
                self.__draw__.line([(x, y + rad), (x, y + height - rad)],
                                   fill=color)
                self.__draw__.line([(x + width, y + rad),
                                    (x + width, y + height - rad)],
                                   fill=color)
                clip = (x, y, x + width, y + width)
                self.__draw__.arc(clip, 180, 360, fill=color)
                clip = (x, y + height - width, x + width, y + height)
                self.__draw__.arc(clip, 360, 180, fill=color)
            return 0

        def get_mouse_state(self):
            # pos = pygame.mouse.get_pos()
            # state = pygame.mouse.get_pressed()
            # return (pos,state[0])
            pass

        def get_input_key(self):
            ky = []
            while not qTo.empty():
                message = qTo.get()
                # print 'eyelink: '
                # print message
                if message == 'button':
                    ky.append(
                        pylink.KeyInput(32, 0)
                    )  #button translated to space keypress (for drift correct)
                # if message=='quit':
                # 	# print 'received message to exit'
                # 	exitSafely()
                # el
                elif message[0] == 'keycode':
                    keysym = message[1]
                    keycode = keysym.sym
                    if keycode == sdl2.SDLK_F1: keycode = pylink.F1_KEY
                    elif keycode == sdl2.SDLK_F2: keycode = pylink.F2_KEY
                    elif keycode == sdl2.SDLK_F3: keycode = pylink.F3_KEY
                    elif keycode == sdl2.SDLK_F4: keycode = pylink.F4_KEY
                    elif keycode == sdl2.SDLK_F5: keycode = pylink.F5_KEY
                    elif keycode == sdl2.SDLK_F6: keycode = pylink.F6_KEY
                    elif keycode == sdl2.SDLK_F7: keycode = pylink.F7_KEY
                    elif keycode == sdl2.SDLK_F8: keycode = pylink.F8_KEY
                    elif keycode == sdl2.SDLK_F9: keycode = pylink.F9_KEY
                    elif keycode == sdl2.SDLK_F10: keycode = pylink.F10_KEY
                    elif keycode == sdl2.SDLK_PAGEUP: keycode = pylink.PAGE_UP
                    elif keycode == sdl2.SDLK_PAGEDOWN:
                        keycode = pylink.PAGE_DOWN
                    elif keycode == sdl2.SDLK_UP:
                        keycode = pylink.CURS_UP
                    elif keycode == sdl2.SDLK_DOWN:
                        keycode = pylink.CURS_DOWN
                    elif keycode == sdl2.SDLK_LEFT:
                        keycode = pylink.CURS_LEFT
                    elif keycode == sdl2.SDLK_RIGHT:
                        keycode = pylink.CURS_RIGHT
                    elif keycode == sdl2.SDLK_BACKSPACE:
                        keycode = ord('\b')
                    elif keycode == sdl2.SDLK_RETURN:
                        keycode = pylink.ENTER_KEY
                    elif keycode == sdl2.SDLK_ESCAPE:
                        keycode = pylink.ESC_KEY
                    elif keycode == sdl2.SDLK_TAB:
                        keycode = ord('\t')
                    elif keycode == pylink.JUNK_KEY:
                        keycode = 0
                    ky.append(pylink.KeyInput(keycode, keysym.mod))
            return ky

    customDisplay = EyeLinkCoreGraphicsPySDL2()
    pylink.openGraphicsEx(customDisplay)
    newGazeTarget = False
    gazeTarget = numpy.array(calibrationDisplaySize) / 2.0
    gazeTargetCriterion = calibrationDotSize
    doSounds = False
    reportSaccades = False
    reportBlinks = False
    lastMessageTime = time.time()
    lastStartBlinkTime = time.time()
    while True:
        sdl2.SDL_PumpEvents()
        for event in sdl2.ext.get_events():
            if event.type == sdl2.SDL_WINDOWEVENT:
                if (event.window.event == sdl2.SDL_WINDOWEVENT_CLOSE):
                    exitSafely()
        if not qTo.empty():
            message = qTo.get()
            if message == 'quit':
                exitSafely()
            elif message[0] == 'edfPath':
                edfPath = message[1]
            elif message[0] == 'doSounds':
                doSounds = message[1]
            elif message[0] == 'reportSaccades':
                reportSaccades = message[1]
            elif message[0] == 'reportBlinks':
                reportBlinks = message[1]
            elif message[0] == 'sendMessage':
                eyelink.sendMessage(message[1])
            elif message[0] == 'doDriftCorrect':
                # print 'eyelink: drift correct requested'
                if eyelink.isRecording() == 0:
                    eyelink.stopRecording()
                try:
                    location = message[1]
                    error = eyelink.doDriftCorrect(location[0], location[1], 0,
                                                   1)
                    # print error
                    # print 'eyelink: drift correct attempted'
                    if error != 27:
                        qFrom.put('driftCorrectComplete')
                    else:
                        qFrom.put('doCalibration')
                except:
                    qFrom.put('doCalibration')
            elif message == 'startRecording':
                # print 'eyelink: received message to begin recording'
                eyelink.startRecording(
                    1, 1, 1, 1
                )  #this retuns immediately takes 10-30ms to actually kick in on the tracker
                while not (eyelink.isRecording() == 0):
                    pass
                    # print eyelink.isRecording()
                qFrom.put('recordingStarted')
            elif message[0] == 'newGazeTarget':
                # # print message
                newGazeTarget = True
                gazeTarget = numpy.array(message[1])
                gazeTargetCriterion = numpy.array(message[2])
                # # print message
                # # print 'waiting for gaze confirmation'
            elif message[0] == 'acceptTrigger':
                eyelink.accept_trigger()
            elif message == 'doCalibration':
                doSounds = False
                if eyelink.isRecording() == 0:
                    eyelink.stopRecording()
                eyelink.doTrackerSetup()
                # # print 'calComplete'
                qFrom.put('calibrationComplete')
        if eyelink.isRecording(
        ) == 0:  #stupid, I know, but eyelink.isRecording() returns 0 if it *is* indeed recording!
            eyeData = eyelink.getNextData()
            # if eyeData==pylink.SAMPLE_TYPE:
            # 	eyeSample = eyelink.getFloatData()
            # 	gaze = None
            # 	if eyeSample.isRightSample():
            # 		gaze = eyeSample.getRightEye().getGaze()
            # 	elif eyeSample.isLeftSample():
            # 		gaze = eyeSample.getLeftEye().getGaze()
            # 	if gaze!=None:
            # 		if gaze[0]!=-32768.0:
            # 			gazeDistFromGazeTarget = numpy.linalg.norm(numpy.array(gaze)-gazeTarget)
            # 			if newGazeTarget:
            # 				if gazeDistFromGazeTarget<gazeTargetCriterion:
            # 					# print ['gazeTargetMet',gaze,gazeTargetCriterion,gazeTarget,gazeDistFromGazeTarget]
            # 					qFrom.put(['gazeTargetMet',gazeTarget])
            # 					newGazeTarget = False
            # 				else:
            # 					qFrom.put(['gazeTargetNotMet',gazeTarget])
            # 					# print ['gazeTargetNotMet',gaze,gazeTarget,gazeDistFromGazeTarget,gazeTargetCriterion]
            if eyeData == pylink.ENDSACC:
                eyeSample = eyelink.getFloatData()
                gazeStartTime = eyeSample.getStartTime()
                gazeStart = eyeSample.getStartGaze()
                gazeEnd = eyeSample.getEndGaze()
                # # print ['eyelink: saccade',gazeStart,gazeEnd]
                if (gazeStart[0] != -32768.0) & (gazeEnd[0] != -32768.0):
                    gazeDistFromGazeTarget = numpy.linalg.norm(
                        numpy.array(gazeEnd) - gazeTarget)
                    if gazeDistFromGazeTarget < 1000:
                        if newGazeTarget:
                            # # print [gazeDistFromGazeTarget,gazeTargetCriterion,gazeTarget,gazeEnd]
                            if gazeDistFromGazeTarget < gazeTargetCriterion:
                                # # print ['gazeTargetMet',gazeEnd,gazeTargetCriterion,gazeTarget,gazeDistFromGazeTarget]
                                qFrom.put([
                                    'gazeTargetMet', gazeTarget, gazeStartTime
                                ])
                                newGazeTarget = False
                                # # print 'gazeTargetMet'
                        elif gazeDistFromGazeTarget > gazeTargetCriterion:
                            if reportSaccades:
                                qFrom.put(['gazeTargetLost', gazeTarget])
                                # # print ['gazeTargetLost',gazeTarget]
                            if (not saccadeSound.stillPlaying()) and (
                                    not blinkSound.stillPlaying()):
                                if doSounds:
                                    saccadeSound.play()
            elif eyeData == pylink.STARTBLINK:
                # 	lastStartBlinkTime = time.time()
                # elif eyeData==pylink.ENDBLINK:
                # 	if (time.time()-lastStartBlinkTime)>.1:
                if reportBlinks:
                    qFrom.put('blink')
                    # # print 'eyelink: blink'
                if (not saccadeSound.stillPlaying()) and (
                        not blinkSound.stillPlaying()):
                    if doSounds:
                        #blinkSound.play()
                        qFrom.put('blink')
def eyelink_child_function(
qTo
, qFrom
, window_size = [200,200]
, window_position = [0,0]
, stim_display_res = [1920,1080]
, stim_display_position = [1920,0]
, calibration_display_size = [1920,1080]
, calibration_dot_size = 10
, eyelink_ip = '100.1.1.1'
, edf_file_name = 'temp.edf'
, edf_path = './_Data/temp.edf'
, saccade_sound_file = '_Stimuli/stop.wav'
, blink_sound_file = '_Stimuli/stop.wav'
):
	import sdl2
	import sdl2.ext
	import math
	import OpenGL.GL as gl
	import sdl2.sdlmixer
	import pylink
	import numpy
	import sys
	import shutil
	import subprocess
	import time
	import os
	import array
	from PIL import Image
	from PIL import ImageDraw
	try:
		import appnope
		appnope.nope()
	except:
		pass

	byteify = lambda x, enc: x.encode(enc)

	sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO)
	window = sdl2.ext.Window("eyelink",size=window_size,position=window_position,flags=sdl2.SDL_WINDOW_SHOWN)
	windowID = sdl2.SDL_GetWindowID(window.window)
	windowSurf = sdl2.SDL_GetWindowSurface(window.window)
	sdl2.ext.fill(windowSurf.contents,sdl2.pixels.SDL_Color(r=0, g=0, b=0, a=255))
	window.refresh()

	for i in range(10):
		sdl2.SDL_PumpEvents() #to show the windows


	sdl2.SDL_Init(sdl2.SDL_INIT_AUDIO)
	sdl2.sdlmixer.Mix_OpenAudio(44100, sdl2.sdlmixer.MIX_DEFAULT_FORMAT, 2, 1024)
	class Sound:
		def __init__(self, fileName):
			self.sample = sdl2.sdlmixer.Mix_LoadWAV(sdl2.ext.compat.byteify(fileName, "utf-8"))
			self.started = False
		def play(self):
			self.channel = sdl2.sdlmixer.Mix_PlayChannel(-1, self.sample, 0)
			self.started = True
		def still_playing(self):
			if self.started:
				if sdl2.sdlmixer.Mix_Playing(self.channel):
					return True
				else:
					self.started = False
					return False
			else:
				return False

	saccade_sound = Sound(saccade_sound_file)
	blink_sound = Sound(blink_sound_file)

	def exit_safely():
		if 'eyelink' in locals():
			if eyelink.isRecording()==0:
				eyelink.stopRecording()
			eyelink.setOfflineMode()
			eyelink.closeDataFile()
			eyelink.receiveDataFile(edf_file_name,'temp.edf')
			eyelink.close()
			if os.path.isfile('temp.edf'):
				shutil.move('temp.edf', edf_path)
				# if os.path.isfile(edf_path):
				# 	subprocess.call('./edf2asc -y ./'+edf_path,shell=True)
		sys.exit() #process gets hung here if called when showing images from eyelink



	edf_path = './_Data/temp.edf' #temporary default location, to be changed later when ID is established
	done = False
	while not done:
		try:
			print '\nAttempting to connect to eyelink (check that wifi is off!)'
			eyelink = pylink.EyeLink(eyelink_ip)
			done = True
		except:
			while not qTo.empty():
				message = qTo.get()
				if message=='quit':
					exit_safely()
				else:
					qTo.put(message)		

	print 'Eyelink connected'
	eyelink.sendCommand('select_parser_configuration 0')# 0--> standard (cognitive); 1--> sensitive (psychophysical)
	eyelink.sendCommand('sample_rate 500')
	eyelink.setLinkEventFilter("SACCADE,BLINK,FIXATION,LEFT,RIGHT")
	eyelink.openDataFile(edf_file_name)
	eyelink.sendCommand("screen_pixel_coords =  %d %d %d %d" %(stim_display_res[0]/2 - calibration_display_size[0]/2 , stim_display_res[1]/2 - calibration_display_size[1]/2 , stim_display_res[0]/2 + calibration_display_size[0]/2 , stim_display_res[1]/2 + calibration_display_size[1]/2 ))
	eyelink.sendMessage("DISPLAY_COORDS  0 0 %d %d" %(stim_display_res[0],stim_display_res[1]))
	# eyelink.sendCommand("saccade_velocity_threshold = 60")
	# eyelink.sendCommand("saccade_acceleration_threshold = 19500")

	class EyeLinkCoreGraphicsPySDL2(pylink.EyeLinkCustomDisplay):
		def __init__(self):
			self.__target_beep__ = Sound('_Stimuli/type.wav')
			self.__target_beep__done__ = Sound('qbeep.wav')
			self.__target_beep__error__ = Sound('error.wav')
			if sys.byteorder == 'little':
				self.byteorder = 1
			else:
				self.byteorder = 0
			self.imagebuffer = array.array('I')
			self.pal = None
			self.__img__ = None
		def record_abort_hide(self):
			pass
		def play_beep(self,beepid):
			# if beepid == pylink.DC_TARG_BEEP or beepid == pylink.CAL_TARG_BEEP:
			if beepid == pylink.CAL_TARG_BEEP:
				self.__target_beep__.play()
			elif beepid == pylink.CAL_ERR_BEEP or beepid == pylink.DC_ERR_BEEP:
				self.__target_beep__error__.play()
			else:#	CAL_GOOD_BEEP or DC_GOOD_BEEP
				self.__target_beep__done__.play()
		def clear_cal_display(self):
			# print 'clear_cal_display'
			qFrom.put('clear_cal_display')
		def setup_cal_display(self):
			# print 'setup_cal_display'
			qFrom.put('setup_cal_display')
		def exit_cal_display(self): 
			# print 'exit_cal_display'
			qFrom.put('exit_cal_display')
		def erase_cal_target(self):
			# print 'erase_cal_target'
			qFrom.put('erase_cal_target')
		def draw_cal_target(self, x, y):
			# print 'draw_cal_target'
			qFrom.put(['draw_cal_target',x,y])
		def setup_image_display(self, width, height):
			# print 'eyelink: setup_image_display'
			self.img_size = (width,height)
			return 0
		def exit_image_display(self):
			# print 'eyelink: exit_image_display'
			pass
		def image_title(self,text):
			# print 'eyelink: image_title'
			pass
		def set_image_palette(self, r,g,b):
			# print 'eyelink: set_image_palette'
			self.imagebuffer = array.array('I')
			sz = len(r)
			i = 0
			self.pal = []
			while i < sz:
				rf = int(b[i])
				gf = int(g[i])
				bf = int(r[i])
				if self.byteorder:
					self.pal.append((rf<<16) | (gf<<8) | (bf))
				else:
					self.pal.append((bf<<24) |  (gf<<16) | (rf<<8)) #for mac
				i = i+1
		def draw_image_line(self, width, line, totlines,buff):
			# print 'eyelink: draw_image_line'
			i = 0
			while i < width:
				if buff[i]>=len(self.pal):
					buff[i] = len(self.pal)-1
				self.imagebuffer.append(self.pal[buff[i]&0x000000FF])
				i = i+1
			if line == totlines:
				img = Image.fromstring('RGBX', (width,totlines), self.imagebuffer.tostring())
 				img = img.convert('RGBA')
				self.__img__ = img.copy()
				self.__draw__ = ImageDraw.Draw(self.__img__)
				self.draw_cross_hair() #inherited method, calls draw_line and draw_losenge
				qFrom.put(['image',numpy.array(self.__img__)])
				self.__img__ = None
				self.__draw__ = None
				self.imagebuffer = array.array('I')
		def get_color_from_index(self,colorindex):
			if colorindex   ==  pylink.CR_HAIR_COLOR:          return (255,255,255,255)
			elif colorindex ==  pylink.PUPIL_HAIR_COLOR:       return (255,255,255,255)
			elif colorindex ==  pylink.PUPIL_BOX_COLOR:        return (0,255,0,255)
			elif colorindex ==  pylink.SEARCH_LIMIT_BOX_COLOR: return (255,0,0,255)
			elif colorindex ==  pylink.MOUSE_CURSOR_COLOR:     return (255,0,0,255)
			else: return (0,0,0,0)
		def draw_line(self,x1,y1,x2,y2,colorindex):
			# print 'eyelink: draw_line'
			if x1<0: x1 = 0
			if x2<0: x2 = 0
			if y1<0: y1 = 0
			if y2<0: y2 = 0
			if x1>self.img_size[0]: x1 = self.img_size[0]
			if x2>self.img_size[0]: x2 = self.img_size[0]
			if y1>self.img_size[1]: y1 = self.img_size[1]
			if y2>self.img_size[1]: y2 = self.img_size[1]
			imr = self.__img__.size
			x1 = int((float(x1)/float(self.img_size[0]))*imr[0])
			x2 = int((float(x2)/float(self.img_size[0]))*imr[0])
			y1 = int((float(y1)/float(self.img_size[1]))*imr[1])
			y2 = int((float(y2)/float(self.img_size[1]))*imr[1])
			color = self.get_color_from_index(colorindex)
			self.__draw__.line( [(x1,y1),(x2,y2)] , fill=color)
		def draw_lozenge(self,x,y,width,height,colorindex):
			# print 'eyelink: draw_lozenge'
			color = self.get_color_from_index(colorindex)
			imr = self.__img__.size
			x=int((float(x)/float(self.img_size[0]))*imr[0])
			width=int((float(width)/float(self.img_size[0]))*imr[0])
			y=int((float(y)/float(self.img_size[1]))*imr[1])
			height=int((float(height)/float(self.img_size[1]))*imr[1])
			if width>height:
				rad = height/2
				self.__draw__.line([(x+rad,y),(x+width-rad,y)],fill=color)
				self.__draw__.line([(x+rad,y+height),(x+width-rad,y+height)],fill=color)
				clip = (x,y,x+height,y+height)
				self.__draw__.arc(clip,90,270,fill=color)
				clip = ((x+width-height),y,x+width,y+height)
				self.__draw__.arc(clip,270,90,fill=color)
			else:
				rad = width/2
				self.__draw__.line([(x,y+rad),(x,y+height-rad)],fill=color)
				self.__draw__.line([(x+width,y+rad),(x+width,y+height-rad)],fill=color)
				clip = (x,y,x+width,y+width)
				self.__draw__.arc(clip,180,360,fill=color)
				clip = (x,y+height-width,x+width,y+height)
				self.__draw__.arc(clip,360,180,fill=color)
		def get_mouse_state(self):
			# pos = pygame.mouse.get_pos()
			# state = pygame.mouse.get_pressed()
			# return (pos,state[0])
			pass
		def get_input_key(self):
			ky=[]
			while not qTo.empty():
				message = qTo.get()
				if message=='quit':
					print 'received message to exit'
					exit_safely()
				elif message=='voice':
					ky.append(pylink.KeyInput(32,0)) #voicekey response translated to space keypress (for drift correct)
				elif message[0]=='keycode':
					keysym = message[1]
					keycode = keysym.sym
					if keycode == sdl2.SDLK_F1:           keycode = pylink.F1_KEY
					elif keycode == sdl2.SDLK_F2:         keycode = pylink.F2_KEY
					elif keycode == sdl2.SDLK_F3:         keycode = pylink.F3_KEY
					elif keycode == sdl2.SDLK_F4:         keycode = pylink.F4_KEY
					elif keycode == sdl2.SDLK_F5:         keycode = pylink.F5_KEY
					elif keycode == sdl2.SDLK_F6:         keycode = pylink.F6_KEY
					elif keycode == sdl2.SDLK_F7:         keycode = pylink.F7_KEY
					elif keycode == sdl2.SDLK_F8:         keycode = pylink.F8_KEY
					elif keycode == sdl2.SDLK_F9:         keycode = pylink.F9_KEY
					elif keycode == sdl2.SDLK_F10:        keycode = pylink.F10_KEY
					elif keycode == sdl2.SDLK_PAGEUP:     keycode = pylink.PAGE_UP
					elif keycode == sdl2.SDLK_PAGEDOWN:   keycode = pylink.PAGE_DOWN
					elif keycode == sdl2.SDLK_UP:         keycode = pylink.CURS_UP
					elif keycode == sdl2.SDLK_DOWN:       keycode = pylink.CURS_DOWN
					elif keycode == sdl2.SDLK_LEFT:       keycode = pylink.CURS_LEFT
					elif keycode == sdl2.SDLK_RIGHT:      keycode = pylink.CURS_RIGHT
					elif keycode == sdl2.SDLK_BACKSPACE:  keycode = ord('\b')
					elif keycode == sdl2.SDLK_RETURN:     keycode = pylink.ENTER_KEY
					elif keycode == sdl2.SDLK_ESCAPE:     keycode = pylink.ESC_KEY
					elif keycode == sdl2.SDLK_TAB:        keycode = ord('\t')
					elif keycode == pylink.JUNK_KEY:      keycode = 0
					ky.append(pylink.KeyInput(keycode,keysym.mod))
			return ky

	custom_display = EyeLinkCoreGraphicsPySDL2()
	pylink.openGraphicsEx(custom_display)
	new_gaze_target = False
	gaze_target = numpy.array(calibration_display_size)/2.0
	real_gaze_target = gaze_target * 2.0
	gaze_target_criterion = calibration_dot_size
	do_sounds = False
	report_saccades = False
	report_blinks = False
	last_message_time = time.time()
	last_start_blink_time = time.time()
	while True:
		sdl2.SDL_PumpEvents()
		for event in sdl2.ext.get_events():
			if event.type==sdl2.SDL_WINDOWEVENT:
				if (event.window.event==sdl2.SDL_WINDOWEVENT_CLOSE):
					exit_safely()
		if not qTo.empty():
			message = qTo.get()
			if message=='quit':
				exit_safely()
			elif message[0]=='edf_path':
				edf_path = message[1]
			elif message[0]=='do_sounds':
				do_sounds = message[1]
			elif message[0]=='report_saccades':
				report_saccades = message[1]
			elif message[0]=='report_blinks':
				report_blinks = message[1]
			elif message[0]=='send_message':
				eyelink.sendMessage(message[1])
			elif message=='do_drift_correct':
				if eyelink.isRecording()==0:
					eyelink.stopRecording()
				try:
					error = eyelink.doDriftCorrect(stim_display_res[0]/2,stim_display_res[1]/2,0,1)
					# print error
					if error != 27: 
						qFrom.put('drift_correct_complete')
						eyelink.startRecording(1,1,1,1) #this retuns immediately takes 10-30ms to actually kick in on the tracker
					else:
						qFrom.put('do_calibration')
				except:
					qFrom.put('do_calibration')
			elif message[0]=='new_gaze_target':
				# print message
				new_gaze_target = True
				gaze_target = numpy.array(message[1])
				gaze_target_criterion = numpy.array(message[2])
				# print message
				# print 'waiting for gaze confirmation'
			elif message[0]=='accept_trigger':
				eyelink.accept_trigger()
			elif message=='do_calibration':
				do_sounds = False
				if eyelink.isRecording()==0:
					eyelink.stopRecording()
				eyelink.doTrackerSetup()
				qFrom.put('calibration_complete')
		if eyelink.isRecording()==0: #stupid, I know, but eyelink.isRecording() returns 0 if it *is* indeed recording!
			eye_data = eyelink.getNextData()
			# if eye_data==pylink.SAMPLE_TYPE:
			# 	eye_sample = eyelink.getFloatData()
			# 	gaze = None
			# 	if eye_sample.isRightSample():
			# 		gaze = eye_sample.getRightEye().getGaze()
			# 	elif eye_sample.isLeftSample():
			# 		gaze = eye_sample.getLeftEye().getGaze()
			# 	if gaze!=None:
			# 		if gaze[0]!=-32768.0:
			# 			gaze_dist_from_gaze_target = numpy.linalg.norm(numpy.array(gaze)-gaze_target)
			# 			if new_gaze_target:
			# 				if gaze_dist_from_gaze_target<gaze_target_criterion:
			# 					print ['gaze_target_met',gaze,gaze_target_criterion,gaze_target,gaze_dist_from_gaze_target]
			# 					qFrom.put(['gaze_target_met',gaze_target])
			# 					new_gaze_target = False
			# 				else:
			# 					qFrom.put(['gaze_targetNotMet',gaze_target])
			# 					print ['gaze_targetNotMet',gaze,gaze_target,gaze_dist_from_gaze_target,gaze_target_criterion]
			if eye_data==pylink.ENDSACC:
				eye_sample = eyelink.getFloatData()
				gaze_start = eye_sample.getStartGaze()
				gaze_end = eye_sample.getEndGaze()
				print ['eyelink: saccade',gaze_start,gaze_end,gaze_target]
				if (gaze_start[0]!=-32768.0) & (gaze_end[0]!=-32768.0):
					gaze_dist_from_gaze_target = numpy.linalg.norm(numpy.array(gaze_end)-gaze_target)

					real_gaze_dist_from_gaze_target = numpy.linalg.norm(numpy.array(gaze_end)-real_gaze_target)
					print ['real distance', real_gaze_dist_from_gaze_target]

					if gaze_dist_from_gaze_target<1000:
						if new_gaze_target:
							if gaze_dist_from_gaze_target<gaze_target_criterion:
								# print ['gaze_target_met',gaze_end,gaze_target_criterion,gaze_target,gaze_dist_from_gaze_target]
								qFrom.put(['gaze_target_met',gaze_target])
								new_gaze_target = False
						elif gaze_dist_from_gaze_target>gaze_target_criterion:
							if report_saccades:
								qFrom.put('gaze_target_lost')
								print('gaze target lost')
							if (not saccade_sound.still_playing()) and (not blink_sound.still_playing()):
								if do_sounds:
									saccade_sound.play()
						else:
							if report_saccades:
								qFrom.put(['smaller_saccade',gaze_dist_from_gaze_target,])
			elif eye_data==pylink.STARTBLINK:
				last_start_blink_time = time.time()
			elif eye_data==pylink.ENDBLINK:
				if (time.time()-last_start_blink_time)>.1:
					if report_blinks:
						qFrom.put('blink')
						# print 'eyelink: blink'
					if (not saccade_sound.still_playing()) and (not blink_sound.still_playing()):
						if do_sounds:
							blink_sound.play()
Ejemplo n.º 26
0
def main(args=None):
    """*FSLeyes* entry point. Shows a :class:`.FSLeyesSplash` screen, parses
    command line arguments, and shows a :class:`.FSLeyesFrame`. Returns
    an exit code.
    """

    if args is None:
        args = sys.argv[1:]

    # Hack to allow render to
    # be called via fsleyes.main
    if len(args) >= 1 and args[0] == 'render':
        import fsleyes.render as render
        render.main(args[1:])
        sys.exit(0)

    # the fsleyes.initialise function figures
    # out the path to asset files (e.g. cmaps)
    fsleyes.initialise()

    # Hook which allows us to run a jupyter
    # notebook server from a frozen version
    # of FSLeyes
    if len(args) >= 1 and args[0] == 'notebook':
        from fsleyes.actions.notebook import nbmain
        fsleyes.configLogging()
        sys.exit(nbmain(args))

    # initialise colour maps - this must be
    # done before parsing arguments, as if
    # the user asks for help, available
    # colourmaps/luts will be listed.
    colourmaps.init()

    # Function to bootstrap the GUI - keep
    # reading below.
    def initgui():

        # First thing's first. Create a wx.App,
        # and initialise the FSLeyes package.
        app = FSLeyesApp()

        # Create a splash screen frame
        splash = fslsplash.FSLeyesSplash(None)
        return app, splash

    # If it looks like the user is asking for
    # help, or using cliserver to pass arguments
    # to an existing FSLeyes instance, then we
    # parse command line arguments before
    # creating a wx.App and showing the splash
    # screen. This means that FSLeyes help/
    # version information can be retrieved
    # without a display, and hopefully fairly
    # quickly.
    #
    # Otherwise we create the app and splash
    # screen first, so the splash screen gets
    # shown as soon as possible. Arguments
    # will get parsed in the init function below.
    #
    # The argparse.Namespace object is kept in a
    # list so it can be shared between the sub-
    # functions below
    #
    # If argument parsing bombs out, we put the
    # exit code here and return it at the bottom.
    namespace = [None]
    exitCode = [0]

    # user asking for help - parse args first
    if (len(args) > 0) and (args[0]
                            in ('-V', '-h', '-fh', '-cs', '--version',
                                '--help', '--fullhelp', '--cliserver')):
        namespace = [parseArgs(args)]
        app, splash = initgui()

    # otherwise parse arguments on wx.MainLoop
    # below
    else:
        app, splash = initgui()

    # We are going do all processing on the
    # wx.MainLoop, so the GUI can be shown
    # as soon as possible, and because it is
    # difficult to force immediate GUI
    # refreshes when not running on the main
    # loop - this is important for FSLeyes,
    # which displays status updates to the
    # user while it is loading overlays and
    # setting up the interface.
    #
    # All of the work is defined in a series
    # of functions, which are chained together
    # via ugly callbacks, but which are
    # ultimately scheduled and executed on the
    # wx main loop.

    def init(splash):

        # See FSLeyesSplash.Show
        # for horribleness.
        splash.Show()

        # Parse command line arguments if necessary.
        # If arguments are invalid, the parseargs
        # module will raise SystemExit.
        try:
            if namespace[0] is None:

                errmsg = strings.messages['main.parseArgs.error']
                errtitle = strings.titles['main.parseArgs.error']
                with status.reportIfError(errtitle, errmsg, raiseError=True):
                    namespace[0] = parseArgs(args)

        # But the wx.App.MainLoop eats SystemExit
        # exceptions for unknown reasons, and
        # causes the application to exit
        # immediately. This makes testing FSLeyes
        # (e.g. code coverage) impossible. So I'm
        # catching SystemExit here, and then
        # telling the wx.App to exit gracefully.
        except (SystemExit, Exception) as e:
            app.ExitMainLoop()
            exitCode[0] = getattr(e, 'code', 1)
            return

        # Configure logging (this has to be done
        # after cli arguments have been parsed,
        # but before initialise is called).
        fsleyes.configLogging(namespace[0].verbose, namespace[0].noisy)

        # Initialise sub-modules/packages. The
        # buildGui function is passed through
        # as a callback, which gets called when
        # initialisation is complete.
        initialise(splash, namespace[0], buildGui)

    def buildGui():

        # Now the main stuff - create the overlay
        # list and the master display context,
        # and then create the FSLeyesFrame.
        overlayList, displayCtx = makeDisplayContext(namespace[0], splash)
        app.SetOverlayListAndDisplayContext(overlayList, displayCtx)
        frame = makeFrame(namespace[0], displayCtx, overlayList, splash)

        app.SetTopWindow(frame)
        frame.Show()

        # Check that $FSLDIR is set, complain
        # to the user if it isn't
        if not namespace[0].skipfslcheck:
            wx.CallAfter(fslDirWarning, frame)

        # Check for updates. Ignore point
        # releases, otherwise users might
        # get swamped with update notifications.
        if namespace[0].updatecheck:
            import fsleyes.actions.updatecheck as updatecheck
            wx.CallAfter(updatecheck.UpdateCheckAction(),
                         showUpToDateMessage=False,
                         showErrorMessage=False,
                         ignorePoint=False)

        # start notebook server
        if namespace[0].notebookFile is not None:
            namespace[0].notebook = True
            namespace[0].notebookFile = op.abspath(namespace[0].notebookFile)
        if namespace[0].notebook:
            from fsleyes.actions.notebook import NotebookAction
            frame.menuActions[NotebookAction](namespace[0].notebookFile)

        # start CLI server
        if namespace[0].cliserver:
            cliserver.runserver(overlayList, displayCtx)

    # Shut down cleanly on sigint/sigterm.
    # We do this so that any functions
    # registered with atexit will actually
    # get called.
    nsignals = [0]

    def sigHandler(signo, frame):
        log.debug('Signal received - FSLeyes is shutting down...')

        # first signal - try to exit cleanly
        if nsignals[0] == 0:
            nsignals[0] += 1
            exitCode[0] = signo

            # kill any modal windows
            # that are open
            for mdlg in app.modals:
                mdlg.EndModal(wx.ID_CANCEL)

            wx.CallAfter(app.ExitMainLoop)

        # subsequent signals - exit immediately
        else:
            sys.exit(signo)

    signal.signal(signal.SIGINT, sigHandler)
    signal.signal(signal.SIGTERM, sigHandler)

    # Note: If no wx.Frame is created, the
    # wx.MainLoop call will exit immediately,
    # even if we have scheduled something via
    # wx.CallAfter. In this case, we have
    # already created the splash screen, so
    # all is well.
    wx.CallAfter(init, splash)

    # under mac, use appnope to make sure
    # we don't get put to sleep. This is
    # primarily for the jupyter notebook
    # integration - if the user is working
    # with a notebook in the web browser,
    # macos might put FSLeyes to sleep,
    # causing the kernel to become
    # unresponsive.
    try:
        import appnope
        appnope.nope()
    except ImportError:
        pass
    app.MainLoop()
    shutdown()
    return exitCode[0]
Ejemplo n.º 27
0
def main():
    #initials = raw_input('Your initials: ')
    #run_nr = int(raw_input('Run number: '))
    #scanner = raw_input('Are you in the scanner (y/n)?: ')
    #track_eyes = raw_input('Are you recording gaze (y/n)?: ')
    #if track_eyes == 'y':
    #tracker_on = True
    #elif track_eyes == 'n':
    #tracker_on = False

    initials = 'GdH'
    run = 1
    appnope.nope()

    blue_intensity_fn = 'data/blue_intensity_%s.txt' % initials
    red_intensity_fn = 'data/red_intensity_%s.txt' % initials
    purple_intensity_fn = 'data/purple_intensity_%s.txt' % initials

    if not os.path.exists(blue_intensity_fn):
        blue_thr_session = IntensityThresholdSession(initials, run,
                                                     (0.0, 0.0, 1.0))
        blue_thr = blue_thr_session.run()
        np.savetxt(blue_intensity_fn, [blue_thr])

    blue_intensity = np.loadtxt(blue_intensity_fn)

    if not os.path.exists(red_intensity_fn):
        red_thr_session = EquiluminanceCalibrateSession(
            initials, run, (0.0, 0.0, 1.0), (1.0, 0., 0.0))
        red_thr = red_thr_session.run()
        np.savetxt(red_intensity_fn, [red_thr])

    red_intensity = np.loadtxt(red_intensity_fn)

    if not os.path.exists(purple_intensity_fn):
        purple_thr_session = EquiluminanceCalibrateSession(
            initials, run, (0.0, 0.0, 1.0),
            (red_intensity, 0., blue_intensity))
        purple_thr = purple_thr_session.run()
        np.savetxt(purple_intensity_fn, [purple_thr])

    purple_intensity = np.loadtxt(purple_intensity_fn)

    block = 1
    wait = MRIWaitSession(initials, 'wait%d' % block,
                          'Waiting for MRI trigger')
    wait.run()

    while wait.quit is False:
        rdm_session = RDMSession(initials,
                                 'run%d' % block, (0.0, 0.0, blue_intensity),
                                 (red_intensity, 0.0, 0.0),
                                 purple_intensity,
                                 simulate_mri_trigger=True,
                                 tr=4)
        rdm_session.run()

        block += 1
        wait = MRIWaitSession(initials, 'wait%d' % block,
                              'Waiting for MRI trigger')
        wait.run()
Ejemplo n.º 28
0
from FlashSession import *
from psychopy import core

# Kill all background processes (macOS only)
try:
    import appnope
    appnope.nope()
except:
    pass

try:
    # Kill Finder during execution (this will be fun)
    applescript = "\'tell application \"Finder\" to quit\'"
    shellCmd = 'osascript -e ' + applescript
    os.system(shellCmd)
except:
    pass

# Set nice to -20: extremely high PID priority
new_nice = -20
sysErr = os.system("sudo renice -n %s %s" % (new_nice, os.getpid()))
if sysErr:
    print(
        'Warning: Failed to renice, probably you arent authorized as superuser'
    )


def main():
    initials = raw_input('Your initials: ')

    pp_nr = 0
Ejemplo n.º 29
0
    async def start_check(self,  # type: HummingbotApplication
                          log_level: Optional[str] = None,
                          restore: Optional[bool] = False,
                          strategy_file_name: Optional[str] = None):
        if self.strategy_task is not None and not self.strategy_task.done():
            self.notify('The bot is already running - please run "stop" first')
            return

        if settings.required_rate_oracle:
            # If the strategy to run requires using the rate oracle to find FX rates, validate there is a rate for
            # each configured token pair
            if not (await self.confirm_oracle_conversion_rate()):
                self.notify("The strategy failed to start.")
                return

        if strategy_file_name:
            file_name = strategy_file_name.split(".")[0]
            self.strategy_file_name = file_name
            self.strategy_name = file_name
        elif not await self.status_check_all(notify_success=False):
            self.notify("Status checks failed. Start aborted.")
            return
        if self._last_started_strategy_file != self.strategy_file_name:
            init_logging("hummingbot_logs.yml",
                         override_log_level=log_level.upper() if log_level else None,
                         strategy_file_path=self.strategy_file_name)
            self._last_started_strategy_file = self.strategy_file_name

        # If macOS, disable App Nap.
        if platform.system() == "Darwin":
            import appnope
            appnope.nope()

        self._initialize_notifiers()
        try:
            self._initialize_strategy(self.strategy_name)
        except NotImplementedError:
            self.strategy_name = None
            self.strategy_file_name = None
            self.notify("Invalid strategy. Start aborted.")
            raise

        if any([str(exchange).endswith("paper_trade") for exchange in settings.required_exchanges]):
            self.notify("\nPaper Trading Active: All orders are simulated and no real orders are placed.")

        for exchange in settings.required_exchanges:
            connector: str = str(exchange)
            status: str = get_connector_status(connector)
            warning_msg: Optional[str] = warning_messages.get(connector, None)

            # confirm gateway connection
            conn_setting: settings.ConnectorSetting = settings.AllConnectorSettings.get_connector_settings()[connector]
            if conn_setting.uses_gateway_generic_connector():
                connector_details: Dict[str, Any] = conn_setting.conn_init_parameters()
                if connector_details:
                    data: List[List[str]] = [
                        ["chain", connector_details['chain']],
                        ["network", connector_details['network']],
                        ["wallet_address", connector_details['wallet_address']]
                    ]
                    await UserBalances.instance().update_exchange_balance(connector)
                    balances: List[str] = [
                        f"{str(PerformanceMetrics.smart_round(v, 8))} {k}"
                        for k, v in UserBalances.instance().all_balances(connector).items()
                    ]
                    data.append(["balances", ""])
                    for bal in balances:
                        data.append(["", bal])
                    wallet_df: pd.DataFrame = pd.DataFrame(data=data, columns=["", f"{connector} configuration"])
                    self.notify(wallet_df.to_string(index=False))

                    self.app.clear_input()
                    self.placeholder_mode = True
                    use_configuration = await self.app.prompt(prompt="Do you want to continue? (Yes/No) >>> ")
                    self.placeholder_mode = False
                    self.app.change_prompt(prompt=">>> ")

                    if use_configuration in ["N", "n", "No", "no"]:
                        return

                    if use_configuration not in ["Y", "y", "Yes", "yes"]:
                        self.notify("Invalid input. Please execute the `start` command again.")
                        return

            # Display custom warning message for specific connectors
            elif warning_msg is not None:
                self.notify(f"\nConnector status: {status}\n"
                            f"{warning_msg}")

            # Display warning message if the exchange connector has outstanding issues or not working
            elif not status.endswith("GREEN"):
                self.notify(f"\nConnector status: {status}. This connector has one or more issues.\n"
                            "Refer to our Github page for more info: https://github.com/coinalpha/hummingbot")

        self.notify(f"\nStatus check complete. Starting '{self.strategy_name}' strategy...")
        await self.start_market_making(restore)
        # We always start the RateOracle. It is required for PNL calculation.
        RateOracle.get_instance().start()
Ejemplo n.º 30
0
 def run(self):
     if sys.platform.startswith('darwin'):
         import appnope
         appnope.nope()
     super(Engine, self).run()
Ejemplo n.º 31
0
def stamperChildFunction(qTo,
                         qFrom,
                         windowSize=[200, 200],
                         windowPosition=[0, 0],
                         windowColor=[255, 255, 255],
                         doBorder=True):
    import sdl2
    import sdl2.ext
    import sys
    import time
    try:
        import appnope
        appnope.nope()
    except:
        pass
    sdl2.SDL_Init(sdl2.SDL_INIT_TIMER)
    timeFreq = 1.0 / sdl2.SDL_GetPerformanceFrequency()
    sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO)
    if doBorder:
        flags = sdl2.SDL_WINDOW_SHOWN
    else:
        flags = sdl2.SDL_WINDOW_BORDERLESS | sdl2.SDL_WINDOW_SHOWN
    window = sdl2.ext.Window("pyStamper",
                             size=windowSize,
                             position=windowPosition,
                             flags=flags)
    windowID = sdl2.SDL_GetWindowID(window.window)
    windowSurf = sdl2.SDL_GetWindowSurface(window.window)
    red = sdl2.pixels.SDL_Color(r=255, g=0, b=0, a=255)
    green = sdl2.pixels.SDL_Color(r=0, g=255, b=0, a=255)
    black = sdl2.pixels.SDL_Color(r=0, g=0, b=0, a=255)
    white = sdl2.pixels.SDL_Color(r=255, g=255, b=255, a=255)
    if doBorder:
        sdl2.ext.fill(windowSurf.contents, green)
    else:
        sdl2.ext.fill(
            windowSurf.contents,
            sdl2.pixels.SDL_Color(r=windowColor[0],
                                  g=windowColor[1],
                                  b=windowColor[2],
                                  a=255))
    window.refresh()

    for i in range(10):
        sdl2.SDL_PumpEvents()  #to show the windows

    sdl2.SDL_Init(
        sdl2.SDL_INIT_JOYSTICK)  #uncomment if you want joystick input
    sdl2.SDL_JoystickOpen(0)  #uncomment if you want joystick input
    lostFocus = True
    lostColors = [red, black, red, white]
    lastRefreshTime = time.time()
    while True:
        if lostFocus and doBorder:
            if time.time() > (lastRefreshTime + (2.0 / 60)):
                sdl2.ext.fill(windowSurf.contents, lostColors[0])
                window.refresh()
                lostColors.append(lostColors.pop(0))
                lastRefreshTime = time.time()
        sdl2.SDL_PumpEvents()
        if not qTo.empty():
            message = qTo.get()
            if message == 'quit':
                sys.exit()
            elif message == 'raise':
                sdl2.SDL_RaiseWindow(window.window)
        for event in sdl2.ext.get_events():
            if event.type == sdl2.SDL_WINDOWEVENT:
                if event.window.windowID == windowID:
                    if (event.window.event == sdl2.SDL_WINDOWEVENT_CLOSE):
                        qFrom.put({
                            'type': 'key',
                            'time': event.window.timestamp * timeFreq,
                            'value': 'escape'
                        })
                        sys.exit()
                    elif event.window.event == sdl2.SDL_WINDOWEVENT_FOCUS_LOST:
                        lostFocus = True
                    elif event.window.event == sdl2.SDL_WINDOWEVENT_FOCUS_GAINED:
                        lostFocus = False
                        if doBorder:
                            sdl2.ext.fill(windowSurf.contents, green)
                            window.refresh()
            else:
                message = {}
                if event.type == sdl2.SDL_KEYDOWN:
                    message['type'] = 'key'
                    message['time'] = event.key.timestamp * timeFreq
                    message['value'] = sdl2.SDL_GetKeyName(
                        event.key.keysym.sym).lower()
                    message['keysym'] = event.key.keysym
                    qFrom.put(message)
                elif event.type == sdl2.SDL_JOYAXISMOTION:
                    message['type'] = 'axis'
                    message['axis'] = event.jaxis.axis
                    message['time'] = event.jaxis.timestamp * timeFreq
                    message['value'] = event.jaxis.value
                    qFrom.put(message)
                elif event.type == sdl2.SDL_JOYBUTTONDOWN:
                    message['type'] = 'button'
                    message['time'] = event.jbutton.timestamp * timeFreq
                    message['value'] = event.jbutton.button
                    qFrom.put(message)
Ejemplo n.º 32
0
 def run(self):
     if PLATFORM == 'mac':
         import appnope
         appnope.nope()
     super().run()
Ejemplo n.º 33
0
 def getConfiguration(self):
     iniPath = self._getConfigurationFilePath()
     self._parseConfigFile(iniPath)
     #
     # Watch out for the method self._overrideConfigWithArgs when you're adding custom multi-word command line arguments
     #
     if self._config['language']:
         setLanguage(self._config['language'])
     self._argparser = argparse.ArgumentParser(
         description=getMessage("argument-description"),
         epilog=getMessage("argument-epilog"))
     self._argparser.add_argument('--no-gui',
                                  action='store_true',
                                  help=getMessage("nogui-argument"))
     self._argparser.add_argument('-a',
                                  '--host',
                                  metavar='hostname',
                                  type=str,
                                  help=getMessage("host-argument"))
     self._argparser.add_argument('-n',
                                  '--name',
                                  metavar='username',
                                  type=str,
                                  help=getMessage("name-argument"))
     self._argparser.add_argument('-d',
                                  '--debug',
                                  action='store_true',
                                  help=getMessage("debug-argument"))
     self._argparser.add_argument(
         '-g',
         '--force-gui-prompt',
         action='store_true',
         help=getMessage("force-gui-prompt-argument"))
     self._argparser.add_argument('--no-store',
                                  action='store_true',
                                  help=getMessage("no-store-argument"))
     self._argparser.add_argument('-r',
                                  '--room',
                                  metavar='room',
                                  type=str,
                                  nargs='?',
                                  help=getMessage("room-argument"))
     self._argparser.add_argument('-p',
                                  '--password',
                                  metavar='password',
                                  type=str,
                                  nargs='?',
                                  help=getMessage("password-argument"))
     self._argparser.add_argument('--player-path',
                                  metavar='path',
                                  type=str,
                                  help=getMessage("player-path-argument"))
     self._argparser.add_argument('--language',
                                  metavar='language',
                                  type=str,
                                  help=getMessage("language-argument"))
     self._argparser.add_argument('file',
                                  metavar='file',
                                  type=str,
                                  nargs='?',
                                  help=getMessage("file-argument"))
     self._argparser.add_argument(
         '--clear-gui-data',
         action='store_true',
         help=getMessage("clear-gui-data-argument"))
     self._argparser.add_argument('-v',
                                  '--version',
                                  action='store_true',
                                  help=getMessage("version-argument"))
     self._argparser.add_argument('_args',
                                  metavar='options',
                                  type=str,
                                  nargs='*',
                                  help=getMessage("args-argument"))
     args = self._argparser.parse_args()
     if args.version:
         print(getMessage("version-message").format(version, milestone))
         sys.exit()
     self._overrideConfigWithArgs(args)
     if not self._config['noGui']:
         try:
             from syncplay.vendor.Qt import QtWidgets, IsPySide, IsPySide2
             from syncplay.vendor.Qt.QtCore import QCoreApplication
             from syncplay.vendor import qt5reactor
             if not (IsPySide2 or IsPySide):
                 raise ImportError
             if QCoreApplication.instance() is None:
                 self.app = QtWidgets.QApplication(sys.argv)
             qt5reactor.install()
             if isMacOS():
                 import appnope
                 appnope.nope()
         except ImportError:
             try:
                 from twisted.trial import unittest
             except:
                 print(getMessage("unable-import-twisted-error"))
                 sys.exit()
             print(getMessage("unable-import-gui-error"))
             self._config['noGui'] = True
     if self._config['file'] and self._config['file'][:2] == "--":
         self._config['playerArgs'].insert(0, self._config['file'])
         self._config['file'] = None
     # Arguments not validated yet - booleans are still text values
     if self._config['language']:
         setLanguage(self._config['language'])
     if (self._config['forceGuiPrompt'] == "True"
             or not self._config['file']) and not self._config['noGui']:
         self._forceGuiPrompt()
     self._checkConfig()
     self._saveConfig(iniPath)
     if self._config['file']:
         self._config[
             'loadedRelativePaths'] = self._loadRelativeConfiguration()
     if self._config['language']:
         setLanguage(self._config['language'])
     return self._config
Ejemplo n.º 34
0
 def getConfiguration(self):
     iniPath = self._getConfigurationFilePath()
     self._parseConfigFile(iniPath)
     #
     # Watch out for the method self._overrideConfigWithArgs when you're adding custom multi-word command line arguments
     #
     if self._config['language']:
         setLanguage(self._config['language'])
     self._argparser = argparse.ArgumentParser(
         description=getMessage("argument-description"),
         epilog=getMessage("argument-epilog"))
     self._argparser.add_argument('--no-gui',
                                  action='store_true',
                                  help=getMessage("nogui-argument"))
     self._argparser.add_argument('-a',
                                  '--host',
                                  metavar='hostname',
                                  type=str,
                                  help=getMessage("host-argument"))
     self._argparser.add_argument('-n',
                                  '--name',
                                  metavar='username',
                                  type=str,
                                  help=getMessage("name-argument"))
     self._argparser.add_argument('-d',
                                  '--debug',
                                  action='store_true',
                                  help=getMessage("debug-argument"))
     self._argparser.add_argument(
         '-g',
         '--force-gui-prompt',
         action='store_true',
         help=getMessage("force-gui-prompt-argument"))
     self._argparser.add_argument('--no-store',
                                  action='store_true',
                                  help=getMessage("no-store-argument"))
     self._argparser.add_argument('-r',
                                  '--room',
                                  metavar='room',
                                  type=str,
                                  nargs='?',
                                  help=getMessage("room-argument"))
     self._argparser.add_argument('-p',
                                  '--password',
                                  metavar='password',
                                  type=str,
                                  nargs='?',
                                  help=getMessage("password-argument"))
     self._argparser.add_argument('--player-path',
                                  metavar='path',
                                  type=str,
                                  help=getMessage("player-path-argument"))
     self._argparser.add_argument('--language',
                                  metavar='language',
                                  type=str,
                                  help=getMessage("language-argument"))
     self._argparser.add_argument('file',
                                  metavar='file',
                                  type=lambda s: str(s, 'utf8'),
                                  nargs='?',
                                  help=getMessage("file-argument"))
     self._argparser.add_argument(
         '--clear-gui-data',
         action='store_true',
         help=getMessage("clear-gui-data-argument"))
     self._argparser.add_argument('-v',
                                  '--version',
                                  action='store_true',
                                  help=getMessage("version-argument"))
     self._argparser.add_argument('_args',
                                  metavar='options',
                                  type=str,
                                  nargs='*',
                                  help=getMessage("args-argument"))
     args = self._argparser.parse_args()
     if args.version:
         print(getMessage("version-message").format(version, milestone))
         sys.exit()
     self._overrideConfigWithArgs(args)
     if not self._config['noGui']:
         #try:
         from PyQt5 import QtGui, QtWidgets  # @UnresolvedImport
         from PyQt5.QtCore import QCoreApplication
         print("IMPORTED")
         from syncplay.vendor import qt4reactor
         print("imported qt4reactor")
         if QCoreApplication.instance() is None:
             self.app = QtWidgets.QApplication(sys.argv)
         print("going to install")
         qt4reactor.install()
         print("INSTALLED")
         if sys.platform.startswith('darwin'):
             import appnope
             appnope.nope()
         '''
         except ImportError:
             print (getMessage("unable-import-gui-error"))
             self._config['noGui'] = True
             sys.exit()
             '''
     if self._config['file'] and self._config['file'][:2] == "--":
         self._config['playerArgs'].insert(0, self._config['file'])
         self._config['file'] = None
     # Arguments not validated yet - booleans are still text values
     if self._config['language']:
         setLanguage(self._config['language'])
     if (self._config['forceGuiPrompt'] == "True"
             or not self._config['file']) and not self._config['noGui']:
         self._forceGuiPrompt()
     self._checkConfig()
     self._saveConfig(iniPath)
     if self._config['file']:
         self._config[
             'loadedRelativePaths'] = self._loadRelativeConfiguration()
     if self._config['language']:
         setLanguage(self._config['language'])
     return self._config
Ejemplo n.º 35
0
def test_nope():
    assert appnope.napping_allowed()
    appnope.nope()
    assert not appnope.napping_allowed() or sys.platform != "Darwin"
    appnope.nap()
    assert appnope.napping_allowed()
Ejemplo n.º 36
0
def labjackChildFunction(
qTo
, qFrom
, windowSize = [200,200]
, windowPosition = [0,0]
):
	import sdl2
	import sdl2.ext
	import sys
	import time
	try:
		import appnope
		appnope.nope()
	except:
		pass

	sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO)
	window = sdl2.ext.Window("labjack",size=windowSize,position=windowPosition,flags=sdl2.SDL_WINDOW_SHOWN)
	windowID = sdl2.SDL_GetWindowID(window.window)
	windowSurf = sdl2.SDL_GetWindowSurface(window.window)
	sdl2.ext.fill(windowSurf.contents,sdl2.pixels.SDL_Color(r=255, g=255, b=255, a=255))
	window.refresh()

	for i in range(10):
		sdl2.SDL_PumpEvents() #to show the windows

	import u3

	d = u3.U3()
	d.configU3()
	d.getCalibrationData()
	d.configAnalog(u3.FIO0)
	checkForNextZeroTime = False
	checkForTrialNextZeroTime = False

	def exitSafely():
		d.close()
		sys.exit()

	sendTriggers = False
	while True:
		if sendTriggers:
			if not checkForNextZeroTime:
				temp = d.getAIN(0)
				# print temp
				if temp>.5: #photosensor surpasses criterion
					d.getFeedback(u3.BitStateWrite(IONumber=8,State=1))
					nextZeroTime = time.time()+.010 #wait 10ms before setting the state back to zero, giving the amp time to pick it up
					checkForNextZeroTime = True
			else:
				if time.time()>=nextZeroTime: #time to turn the bit back off
					d.getFeedback(u3.BitStateWrite(IONumber=8,State=0))
					checkForNextZeroTime = False
			if checkForTrialNextZeroTime:
				if time.time()>=trialNextZeroTime:
					d.getFeedback(u3.BitStateWrite(IONumber=9,State=0))
					checkForTrialNextZeroTime = False
		if not qTo.empty():
			message = qTo.get()
			if message=='quit':
				exitSafely()
			elif message=='trialDone':
				sendTriggers = False
				checkForTrialNextZeroTime = False
				checkForNextZeroTime = False
				d.getFeedback(u3.BitStateWrite(IONumber=8,State=0)) #should be zero, but just in case...
				d.getFeedback(u3.BitStateWrite(IONumber=9,State=0)) #should be zero, but just in case...
			elif message=='trialStart':
				sendTriggers = True
				d.getFeedback(u3.BitStateWrite(IONumber=9,State=1))
				trialNextZeroTime = time.time()+.010 #wait 10ms before setting the state back to zero, giving the amp time to pick it up
				checkForTrialNextZeroTime = True
		sdl2.SDL_PumpEvents()
		for event in sdl2.ext.get_events():
			if event.type==sdl2.SDL_WINDOWEVENT:
				if (event.window.event==sdl2.SDL_WINDOWEVENT_CLOSE):
					exitSafely()
Ejemplo n.º 37
0
def stamperChildFunction(
    qTo, qFrom, windowSize=[200, 200], windowPosition=[0, 0], windowColor=[255, 255, 255], doBorder=True
):
    import sdl2
    import sdl2.ext
    import sys
    import time

    try:
        import appnope

        appnope.nope()
    except:
        pass
    sdl2.SDL_Init(sdl2.SDL_INIT_TIMER)
    timeFreq = 1.0 / sdl2.SDL_GetPerformanceFrequency()
    sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO)
    if doBorder:
        flags = sdl2.SDL_WINDOW_SHOWN
    else:
        flags = sdl2.SDL_WINDOW_BORDERLESS | sdl2.SDL_WINDOW_SHOWN
    window = sdl2.ext.Window("pyStamper", size=windowSize, position=windowPosition, flags=flags)
    windowID = sdl2.SDL_GetWindowID(window.window)
    windowSurf = sdl2.SDL_GetWindowSurface(window.window)
    red = sdl2.pixels.SDL_Color(r=255, g=0, b=0, a=255)
    green = sdl2.pixels.SDL_Color(r=0, g=255, b=0, a=255)
    black = sdl2.pixels.SDL_Color(r=0, g=0, b=0, a=255)
    white = sdl2.pixels.SDL_Color(r=255, g=255, b=255, a=255)
    if doBorder:
        sdl2.ext.fill(windowSurf.contents, green)
    else:
        sdl2.ext.fill(
            windowSurf.contents, sdl2.pixels.SDL_Color(r=windowColor[0], g=windowColor[1], b=windowColor[2], a=255)
        )
    window.refresh()

    for i in range(10):
        sdl2.SDL_PumpEvents()  # to show the windows

    sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK)  # uncomment if you want joystick input
    sdl2.SDL_JoystickOpen(0)  # uncomment if you want joystick input
    lostFocus = True
    lostColors = [red, black, red, white]
    lastRefreshTime = time.time()
    while True:
        if lostFocus and doBorder:
            if time.time() > (lastRefreshTime + (2.0 / 60)):
                sdl2.ext.fill(windowSurf.contents, lostColors[0])
                window.refresh()
                lostColors.append(lostColors.pop(0))
                lastRefreshTime = time.time()
        sdl2.SDL_PumpEvents()
        if not qTo.empty():
            message = qTo.get()
            if message == "quit":
                sys.exit()
            elif message == "raise":
                sdl2.SDL_RaiseWindow(window.window)
        for event in sdl2.ext.get_events():
            if event.type == sdl2.SDL_WINDOWEVENT:
                if event.window.windowID == windowID:
                    if event.window.event == sdl2.SDL_WINDOWEVENT_CLOSE:
                        qFrom.put({"type": "key", "time": event.window.timestamp * timeFreq, "value": "escape"})
                        sys.exit()
                    elif event.window.event == sdl2.SDL_WINDOWEVENT_FOCUS_LOST:
                        lostFocus = True
                    elif event.window.event == sdl2.SDL_WINDOWEVENT_FOCUS_GAINED:
                        lostFocus = False
                        if doBorder:
                            sdl2.ext.fill(windowSurf.contents, green)
                            window.refresh()
            else:
                message = {}
                if event.type == sdl2.SDL_KEYDOWN:
                    message["type"] = "key"
                    message["time"] = event.key.timestamp * timeFreq
                    message["value"] = sdl2.SDL_GetKeyName(event.key.keysym.sym).lower()
                    message["keysym"] = event.key.keysym
                    qFrom.put(message)
                elif event.type == sdl2.SDL_JOYAXISMOTION:
                    message["type"] = "axis"
                    message["axis"] = event.jaxis.axis
                    message["time"] = event.jaxis.timestamp * timeFreq
                    message["value"] = event.jaxis.value
                    qFrom.put(message)
                elif event.type == sdl2.SDL_JOYBUTTONDOWN:
                    message["type"] = "button"
                    message["time"] = event.jbutton.timestamp * timeFreq
                    message["value"] = event.jbutton.button
                    qFrom.put(message)
Ejemplo n.º 38
0
def labjackChildFunction(qTo,
                         qFrom,
                         windowSize=[200, 200],
                         windowPosition=[0, 0]):
    import sdl2
    import sdl2.ext
    import sys
    import time
    try:
        import appnope
        appnope.nope()
    except:
        pass

    sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO)
    window = sdl2.ext.Window("labjack",
                             size=windowSize,
                             position=windowPosition,
                             flags=sdl2.SDL_WINDOW_SHOWN)
    windowID = sdl2.SDL_GetWindowID(window.window)
    windowSurf = sdl2.SDL_GetWindowSurface(window.window)
    sdl2.ext.fill(windowSurf.contents,
                  sdl2.pixels.SDL_Color(r=255, g=255, b=255, a=255))
    window.refresh()

    for i in range(10):
        sdl2.SDL_PumpEvents()  #to show the windows

    import u3

    d = u3.U3()
    d.configU3()
    d.getCalibrationData()
    d.configAnalog(u3.FIO0)
    checkForNextZeroTime = False
    checkForTrialNextZeroTime = False

    def exitSafely():
        d.close()
        sys.exit()

    sendTriggers = False
    while True:
        if sendTriggers:
            if not checkForNextZeroTime:
                temp = d.getAIN(0)
                # print temp
                if temp > .5:  #photosensor surpasses criterion
                    d.getFeedback(u3.BitStateWrite(IONumber=8, State=1))
                    nextZeroTime = time.time(
                    ) + .010  #wait 10ms before setting the state back to zero, giving the amp time to pick it up
                    checkForNextZeroTime = True
            else:
                if time.time() >= nextZeroTime:  #time to turn the bit back off
                    d.getFeedback(u3.BitStateWrite(IONumber=8, State=0))
                    checkForNextZeroTime = False
            if checkForTrialNextZeroTime:
                if time.time() >= trialNextZeroTime:
                    d.getFeedback(u3.BitStateWrite(IONumber=9, State=0))
                    checkForTrialNextZeroTime = False
        if not qTo.empty():
            message = qTo.get()
            if message == 'quit':
                exitSafely()
            elif message == 'trialDone':
                sendTriggers = False
                checkForTrialNextZeroTime = False
                checkForNextZeroTime = False
                d.getFeedback(u3.BitStateWrite(
                    IONumber=8, State=0))  #should be zero, but just in case...
                d.getFeedback(u3.BitStateWrite(
                    IONumber=9, State=0))  #should be zero, but just in case...
            elif message == 'trialStart':
                sendTriggers = True
                d.getFeedback(u3.BitStateWrite(IONumber=9, State=1))
                trialNextZeroTime = time.time(
                ) + .010  #wait 10ms before setting the state back to zero, giving the amp time to pick it up
                checkForTrialNextZeroTime = True
        sdl2.SDL_PumpEvents()
        for event in sdl2.ext.get_events():
            if event.type == sdl2.SDL_WINDOWEVENT:
                if (event.window.event == sdl2.SDL_WINDOWEVENT_CLOSE):
                    exitSafely()
Ejemplo n.º 39
0
def main():
    """Launch plover."""
    description = "Run the plover stenotype engine. This is a graphical application."
    parser = argparse.ArgumentParser(description=description)
    parser.add_argument('--version',
                        action='version',
                        version='%s %s' %
                        (__software_name__.capitalize(), __version__))
    parser.add_argument(
        '-s',
        '--script',
        default=None,
        nargs=argparse.REMAINDER,
        help='use another plugin console script as main entrypoint, '
        'passing in the rest of the command line arguments, '
        'print list of available scripts when no argument is given')
    parser.add_argument('-l',
                        '--log-level',
                        choices=['debug', 'info', 'warning', 'error'],
                        default=None,
                        help='set log level')
    parser.add_argument('-g', '--gui', default=None, help='set gui')
    args = parser.parse_args(args=sys.argv[1:])
    if args.log_level is not None:
        log.set_level(args.log_level.upper())
    log.setup_platform_handler()

    log.info('Plover %s', __version__)
    log.info('configuration directory: %s', CONFIG_DIR)

    if PLATFORM == 'mac':
        # Fixes PyQt issue on macOS Big Sur.
        os.environ['QT_MAC_WANTS_LAYER'] = '1'

    registry.update()

    if args.gui is None:
        gui_priority = {
            'qt': 1,
            'none': -1,
        }
        gui_list = sorted(registry.list_plugins('gui'),
                          reverse=True,
                          key=lambda gui: gui_priority.get(gui.name, 0))
        gui = gui_list[0].obj
    else:
        gui = registry.get_plugin('gui', args.gui).obj

    try:
        if args.script is not None:
            if args.script:
                # Create a mapping of available console script,
                # with the following priorities (highest first):
                # - {project_name}-{version}:{script_name}
                # - {project_name}:{script_name}
                # - {script_name}
                console_scripts = {}
                for e in sorted(
                        pkg_resources.iter_entry_points('console_scripts'),
                        key=lambda e: (e.dist, e.name)):
                    for key in (
                            '%s-%s:%s' %
                        (e.dist.project_name, e.dist.version, e.name),
                            '%s:%s' % (e.dist.project_name, e.name),
                            e.name,
                    ):
                        console_scripts[key] = e
                entrypoint = console_scripts.get(args.script[0])
                if entrypoint is None:
                    log.error('no such script: %s', args.script[0])
                    code = 1
                else:
                    sys.argv = args.script
                    try:
                        code = entrypoint.load()()
                    except SystemExit as e:
                        code = e.code
                if code is None:
                    code = 0
            else:
                print('available script(s):')
                dist = None
                for e in sorted(
                        pkg_resources.iter_entry_points('console_scripts'),
                        key=lambda e: (str(e.dist), e.name)):
                    if dist != e.dist:
                        dist = e.dist
                        print('%s:' % dist)
                    print('- %s' % e.name)
                code = 0
            os._exit(code)

        # Ensure only one instance of Plover is running at a time.
        with Controller() as controller:
            if controller.is_owner:
                # Not other instance, regular startup.
                if PLATFORM == 'mac':
                    import appnope
                    appnope.nope()
                init_config_dir()
                # This must be done after calling init_config_dir, so
                # Plover's configuration directory actually exists.
                log.setup_logfile()
                config = Config(CONFIG_FILE)
                code = gui.main(config, controller)
            else:
                log.info(
                    'another instance is running, sending `focus` command')
                # Other instance? Try focusing the main window.
                try:
                    controller.send_command('focus')
                except ConnectionRefusedError:
                    log.error('connection to existing instance failed, '
                              'force cleaning before restart')
                    # Assume the previous instance died, leaving
                    # a stray socket, try cleaning it...
                    if not controller.force_cleanup():
                        raise
                    # ...and restart.
                    code = -1
                else:
                    code = 0
    except:
        gui.show_error('Unexpected error', traceback.format_exc())
        code = 2
    if code == -1:
        # Restart.
        args = sys.argv[:]
        if args[0].endswith('.py') or args[0].endswith('.pyc'):
            # We're running from source.
            spec = sys.modules['__main__'].__spec__
            assert sys.argv[0] == spec.origin
            args[0:1] = [sys.executable, '-m', spec.name]
        # Execute atexit handlers.
        atexit._run_exitfuncs()
        if PLATFORM == 'win':
            # Workaround https://bugs.python.org/issue19066
            subprocess.Popen(args, cwd=os.getcwd())
            code = 0
        else:
            os.execv(args[0], args)
    os._exit(code)
	# from PIL import ImageOps
	#import aggdraw #for drawing
	import math #for rounding
	import sys #for quitting
	import os #for os.nice and checking if folders/files exist
	import random #for shuffling and random sampling
	import time #for timing
	import shutil #for copying files
	import OpenGL.GL as gl
	try:
		os.nice(-20)
	except:
		pass#print('Can\'t nice')
	try:
		import appnope
		appnope.nope()
	except:
		pass
	import fileForker
	byteify = lambda x, enc: x.encode(enc)

	########
	# Initialize the labjack
	########
	labjack = u3.U3()
	labjack.configU3()

	########
	# Initialize audio and define a class for playing sounds
	########
	sdl2.SDL_Init(sdl2.SDL_INIT_AUDIO)
Ejemplo n.º 41
0
def main():
    """Launch plover."""
    description = "Run the plover stenotype engine. This is a graphical application."
    parser = argparse.ArgumentParser(description=description)
    parser.add_argument('--version',
                        action='version',
                        version='%s %s' %
                        (__software_name__.capitalize(), __version__))
    parser.add_argument(
        '-s',
        '--script',
        default=None,
        nargs=argparse.REMAINDER,
        help='use another plugin console script as main entrypoint, '
        'passing in the rest of the command line arguments, '
        'print list of available scripts when no argument is given')
    parser.add_argument('-l',
                        '--log-level',
                        choices=['debug', 'info', 'warning', 'error'],
                        default=None,
                        help='set log level')
    parser.add_argument('-g', '--gui', default=None, help='set gui')
    args = parser.parse_args(args=sys.argv[1:])
    if args.log_level is not None:
        log.set_level(args.log_level.upper())
    log.setup_platform_handler()

    log.info('Plover %s', __version__)
    log.info('configuration directory: %s', CONFIG_DIR)
    log.info('plugins directory: %s', PLUGINS_DIR)

    registry.update()

    if args.gui is None:
        gui_priority = {
            'qt': 1,
            'none': -1,
        }
        gui_list = sorted(registry.list_plugins('gui'),
                          reverse=True,
                          key=lambda gui: gui_priority.get(gui.name, 0))
        gui = gui_list[0].obj
    else:
        gui = registry.get_plugin('gui', args.gui).obj

    try:
        if args.script is not None:
            if args.script:
                # Create a mapping of available console script,
                # with the following priorities (highest first):
                # - {project_name}-{version}:{script_name}
                # - {project_name}:{script_name}
                # - {script_name}
                console_scripts = {}
                for e in sorted(
                        pkg_resources.iter_entry_points('console_scripts'),
                        key=lambda e: (e.dist, e.name)):
                    for key in (
                            '%s-%s:%s' %
                        (e.dist.project_name, e.dist.version, e.name),
                            '%s:%s' % (e.dist.project_name, e.name),
                            e.name,
                    ):
                        console_scripts[key] = e
                entrypoint = console_scripts.get(args.script[0])
                if entrypoint is None:
                    log.error('no such script: %s', args.script[0])
                    code = 1
                else:
                    sys.argv = args.script
                    try:
                        code = entrypoint.load()()
                    except SystemExit as e:
                        code = e.code
                if code is None:
                    code = 0
            else:
                print('available script(s):')
                dist = None
                for e in sorted(
                        pkg_resources.iter_entry_points('console_scripts'),
                        key=lambda e: (str(e.dist), e.name)):
                    if dist != e.dist:
                        dist = e.dist
                        print('%s:' % dist)
                    print('- %s' % e.name)
                code = 0
            os._exit(code)

        # Ensure only one instance of Plover is running at a time.
        with plover.oslayer.processlock.PloverLock():
            if sys.platform.startswith('darwin'):
                appnope.nope()
            init_config_dir()
            # This must be done after calling init_config_dir, so
            # Plover's configuration directory actually exists.
            log.setup_logfile()
            config = Config()
            config.target_file = CONFIG_FILE
            code = gui.main(config)
            with open(config.target_file, 'wb') as f:
                config.save(f)
    except plover.oslayer.processlock.LockNotAcquiredException:
        gui.show_error('Error',
                       'Another instance of Plover is already running.')
        code = 1
    except:
        gui.show_error('Unexpected error', traceback.format_exc())
        code = 2
    if code == -1:
        # Restart.
        args = sys.argv[:]
        if args[0].endswith('.py') or args[0].endswith('.pyc'):
            # We're running from source.
            assert args[0] == __file__
            args[0:1] = [sys.executable, '-m', __spec__.name]
        # Execute atexit handlers.
        atexit._run_exitfuncs()
        if sys.platform.startswith('win32'):
            # Workaround https://bugs.python.org/issue19066
            subprocess.Popen(args, cwd=os.getcwd())
            code = 0
        else:
            os.execv(args[0], args)
    os._exit(code)