def test_010_unbind_callbacks(self):
        event_name = 'newCoolEvent'
        eh = EventHandler(event_name)

        def callback1(*args):
            pass

        self.assertTrue(eh.link(callback1, event_name))
        self.assertTrue(eh.unlink(callback1, event_name))

        # Test already unregistered event
        output = io.StringIO()
        eh = EventHandler(event_name, verbose=True, stream_output=output)
        self.assertFalse(eh.unlink(callback1, event_name))

        self.assertTrue(eh.link(callback1, event_name))
        self.assertFalse(eh.link(callback1, event_name))

        value = output.getvalue()

        self.assertTrue(callback1.__name__ in value)
        self.assertTrue(event_name in value)

        # Test try unregister not exists event
        self.assertFalse(eh.unlink(callback1, 'inexistentEventName'))

        value = output.getvalue()
        print(output)

        for event in eh.event_list:
            self.assertTrue(event in value)
Exemple #2
0
    def handle(self, event):
        EventHandler.handle(self, event)

        controller = self.get_controller()

        if event.type == pygame.QUIT:
            if controller is not None:
                controller.shutdown()
                pygame.quit()

        elif event.type == pygame.KEYDOWN:
            key = pygame.key.get_pressed()

            if key[controls.key_quit]:
                controller.shutdown()
                self.stop()

            elif key[pygame.K_ESCAPE]:
                controller.shutdown()
                self.stop()

            elif pygame.key.get_mods() & pygame.KMOD_ALT:
                if key[pygame.K_s]:
                    controller.get_output().get_btns()["START"].click()

                elif key[pygame.K_i]:
                    controller.get_output().get_btns()["INFO"].click()

                elif key[pygame.K_e]:
                    controller.get_output().get_btns()["EXIT"].click()

        elif event.type == pygame.MOUSEBUTTONUP:
            pos = pygame.mouse.get_pos()

            controller.get_output().click(pos)
    def __init__(self):
        self.logger = logging.getLogger(Config.LOGGING_NAME+".SocketServer")
        EventHandler.addListener("onQuitWebSocketServer", Events.SERVER_SHUTDOWN, self.stop)

        HOST = ('', 1998)

        self.server = socketserver.ThreadingTCPServer(HOST, WebRequestHandler)
        self.logger.info("Binding SocketServer to %s", HOST)
Exemple #4
0
    def terminate():
        if Keyboard.Enabled:
            Keyboard._repeatTimeInitial = -1
            Keyboard._repeatTimeRepeat = -1

            EventHandler.removeEventListener(KeyboardEvent.KEY_DOWN,
                                             Keyboard._onKeyDown)
            EventHandler.removeEventListener(KeyboardEvent.KEY_UP,
                                             Keyboard._onKeyUp)

            Keyboard.Enabled = False
Exemple #5
0
    def initialize():
        if not Keyboard.Enabled:
            Keyboard._repeatTimeInitial = 32
            Keyboard._repeatTimeRepeat = 10

            EventHandler.addEventListener(KeyboardEvent.KEY_DOWN,
                                          Keyboard._onKeyDown)
            EventHandler.addEventListener(KeyboardEvent.KEY_UP,
                                          Keyboard._onKeyUp)

            Keyboard.Enabled = True
Exemple #6
0
 def __init__(self):
     pygame.init()
     self.width = 500
     self.height = 500
     self.window = pygame.display.set_mode((self.width, self.height))
     self.clock = pygame.time.Clock()
     self.map = Map(width=self.width,height=self.height)
     while True:
         self.clock.tick(15)
         self.update()
         self.draw()
         EventHandler.handle_events()
    def test_006_event_registration(self):
        eh = EventHandler()
        event_name = 'onMyCoolEventHappens'
        self.assertFalse(eh.is_event_registered(event_name))
        self.assertTrue(eh.register_event(event_name))
        self.assertTrue(eh.is_event_registered(event_name))

        eh = EventHandler('one', 'two', 'three', verbose=True)
        self.assertTrue(eh.is_event_registered('three'))
        self.assertFalse(eh.register_event('one'))
 def test_007_event_unregistration(self):
     eh = EventHandler()
     event_name = 'onMyCoolEventHappens'
     self.assertFalse(eh.is_event_registered(event_name))
     self.assertTrue(eh.register_event(event_name))
     self.assertTrue(eh.is_event_registered(event_name))
     eh.unregister_event(event_name)
     self.assertFalse(eh.unregister_event('one'))
    def onPacketReceived(self, data):
        packet = data[0]
        sendFunc = data[1]
        def respond(value):
            sendFunc(('{"%s":"%s"}\n' % ("response", value)).encode("UTF-8"))

        if "command" in packet:
            args = packet["command"].split(" ")

            if args[0] == "ping":
                respond("pong")

            elif args[0] == "handshake":
                gen = self.queuemanager.generateID()
                respond("handshook %s"%gen)
                EventHandler.callEvent(Events.CLIENT_CONNECT, gen)

            elif args[0] == "cookieDump":
                self.logger.debug("Cookie dump: %s"%args[1])
                respond("ok")

            elif args[0] == "queue":
                result = self.queuemanager.addToQueue(args[1])
                if result:
                    respond("queued")
                else:
                    respond("error")

            elif args[0] == "getControlTime":
                respond(str(Config.CONTROL_TIME))

            elif args[0] == "getQueuedPeople":
                respond(self.queuemanager.getPlaceInQueue(args[1]))

            elif args[0] == "getETA":
                respond(self.queuemanager.getTimeUntilTurn(args[1]))

            elif args[0] == "isTurn":
                respond(self.queuemanager.isTurn(args[1]))

            elif args[0] == "robot":
                self.handleRobotCommand(args, sendFunc)

            else:
                respond("UNKNOWN COMMAND")

        else:
            respond("Command not found")
 def test_002_initiaization_with_events(self):
     # Test init with args.
     eh = EventHandler('MyEvent')
     self.assertEqual(eh.count_events, 1)
     self.assertFalse(eh.verbose)  # checks verbose is false
     self.assertFalse(eh.tolerate_exceptions)  # checks no exception toleration
     self.assertIsNotNone(eh.stream_output)
    def __init__(self, nombre="Editor", resolucion=(800, 600)):

        self.nombre = nombre
        self.resolucion = resolucion
        self.pantalla = pygame.display.set_mode(self.resolucion)
        self.cont_tiempo = 0

        self.menuayuda = Ayuda(self.resolucion)
        self.mundo = Mundo()
        self.raton = Raton("res/puntero.png")
        self.camara = Camara(self.mundo, self.raton, self.resolucion)
        # de momento menu_nmundo se queda aqui ya veremos si es mejor moverlo a
        # menu como estaba antes
        self.menu_nmundo = NuevoMundo(self.resolucion[0] / 2,
                    self.resolucion[1] / 2, 10, 10, self.raton, self.mundo, self.camara)
        self.menu_carga = MenuCarga(self.resolucion, self.raton, self.mundo, self.camara)
        self.menu = Menu(self.resolucion, self.raton, self.mundo,
                            self.menu_nmundo, self.menu_carga)
        self.chat = Chat(self.resolucion, self.mundo.tiles_suelos1[31][31], self.mundo.capa,
                      self.mundo.modo_entidad, self.camara.pincel.borrar,
                       self.mundo.aut_save, self.mundo)

        self.eventhandler = EventHandler(self)

        self.cambio = False
        self.fullscreen = False
        self.primera_menu = True
        self.primera_camara = True
 def test_001_initialization_args(self):
     # Test init on no args
     eh = EventHandler()
     self.assertEqual(eh.count_events, 0)  # checks there is no events
     self.assertFalse(eh.verbose)  # checks verbose is false
     self.assertFalse(eh.tolerate_exceptions)  # checks no exception toleration
     self.assertIsNotNone(eh.stream_output)
Exemple #13
0
    def __init__(self):
        pygame.init()
        self.window = pygame.display.set_mode((640, 480))
        self.player = Player(x=100, y=100, width=640, height=480)
        self.plupp = Plupp(window_width=640, window_height=480)
        self.clock = pygame.time.Clock()
        self.map = Map()

        while True:
            CollisionHandler.handle_plupp_collisions(player=self.player, plupp=self.plupp)
            CollisionHandler.handle_player_collisions(player=self.player, map=self.map)

            EventHandler.handle_events(player=self.player, plupp=self.plupp)
            self.clock.tick(15)
            self.update()
            self.draw()
Exemple #14
0
class ChatRoom:
    """Simulates a chatroom environment with event handler implementation.

    This is just a documented sample without pretensions. It is not a real class implementation.
    """
    def __init__(self):
        """Initialize the chat room."""
        self.__messages = []  # Stores users messages
        self.__users = {
            'bot': []
        }  # Stores a dictionary with registered usernames

        # Define the event handler and make it public outside the class to let externals subscriptions to events.
        self.event_handler = EventHandler(
            'onNewuser',
            'onMessage')  # Note that events names are cased sensitive.
        # You can set any number of unique events and asing any number of unique callbacks to fire per event.
        # Is not necessary define events names during initialization, also you can register the event names during
        # run time using register_event method.

        # Lets link some internal class methods to those events as callbacks.
        # Limits are available resources.
        self.event_handler.link(self.__on_newuser_join, 'onNewuser')
        self.event_handler.link(self.__on_message, 'onMessage')

    # Now lets define this two methods to dispatch the events
    # Note this methods are not accesible outside class instance
    # This calbback will be called when onNewUser event happens
    def __on_newuser_join(self, user):
        """Shout in the output telling new user has joined chat room, when onNewuser event happens."""
        print(
            f'\n** ChatRoom info ** user {user} has joined the chat ** {len(self.user_list())} user/s **\n'
        )

    # This callback will be called when onMessage event happens
    def __on_message(self, user, msg):
        """Print the user message in the output, when onMessage event happens."""
        print(f'{user} says:\t {msg}')

    # Now let's define the public methods of the chatroom to be used outside the class
    def user_list(self):
        """Return a list of not bot users."""
        return [user for user in self.__users.keys() if user != 'bot']

    def say(self, user, msg=None):
        """Let user (and bots) send a message to the chat room."""
        if not user in self.__users:
            # if user is not registered fire onNewuser event and recibe it inside the class.
            self.__users[user] = []
            self.event_handler.fire('onNewuser', user)
        if not msg:
            return
        if msg != '':
            # Enqueue the message and fire onMessage event to be received internally by __on_message method.
            self.__messages.append((user, msg))
            self.event_handler.fire('onMessage', user, msg)
Exemple #15
0
    def handle(self, event):
        EventHandler.handle(self, event)
        controller = self.get_controller()

        if event.type == pygame.QUIT:
            controller.shutdown()

        if event.type == pygame.KEYDOWN:
            key = pygame.key.get_pressed()

            if key[nav_controls.key_quit]:
                controller.shutdown()

            elif key[nav_controls.key_back]:
                controller.back()

            controller.back()
    def handle(self):
        self.running = True
        EventHandler.addListener("onQuit"+str(current_thread().ident), Events.SERVER_SHUTDOWN, self.shutdown)
        self.logger = logging.getLogger(Config.LOGGING_NAME+".SocketServer.RequestHandler")
        #self.logger.debug("Connection from %s", self.client_address)

        packetStarted = False
        packetContents = ""
        while self.running:
            receivedData = self.request.recv(1)
            if not receivedData: break  # If there is no dataz, then probably the client disconnected.
            try:
                receivedData = receivedData.decode("utf-8")
            except:
                continue

            if not packetStarted:       # If the packetStarted flag has not been set, set it when "{" is received
                if receivedData == "~":
                    packetStarted = True
                    packetContents = packetContents + "{"
            elif packetStarted:         # If the packet has started, append stuff to it until "}" is received
                if receivedData == "~":
                    packetContents = packetContents + "}"
                    packetStarted = False

                    # If the packet is valid, then fire an event - if not report it through logging
                    try:
                        EventHandler.callEvent(Events.PACKET_RECEIVED, (literal_eval(packetContents), self.request.send))
                        packetContents = ""
                        packetContents = ""
                    except ValueError:
                        self.logger.error(packetContents)
                        self.logger.error("Malformed packet! - VALUE ERROR")
                        packetContents = ""
                        break
                    except SyntaxError:
                        self.logger.error(packetContents)
                        self.logger.error("Malformed packet! - SYNTAX ERROR")
                        packetContents = ""
                        break

                else:
                    packetContents = packetContents + receivedData

        self.request.close()
Exemple #17
0
    def __init__(self):
        pygame.init()
        self.window = pygame.display.set_mode((640, 480))
        self.player = Player(x=100, y=100, width=640, height=480)
        self.plupp = Plupp(window_width=640, window_height=480)
        self.clock = pygame.time.Clock()
        self.map = Map()

        while True:
            CollisionHandler.handle_plupp_collisions(player=self.player,
                                                     plupp=self.plupp)
            CollisionHandler.handle_player_collisions(player=self.player,
                                                      map=self.map)

            EventHandler.handle_events(player=self.player, plupp=self.plupp)
            self.clock.tick(15)
            self.update()
            self.draw()
    def handle(self, event):
        EventHandler.handle(self, event)

        if event.type == pygame.QUIT:
            self.get_controller().shutdown()

        elif event.type == pygame.KEYDOWN:
            key = pygame.key.get_pressed()

            if key[nav_controls.key_quit]:
                self.get_controller().shutdown()
            elif key[nav_controls.key_back]:
                self.get_controller().back()

        elif event.type == pygame.MOUSEBUTTONUP:
            pos = pygame.mouse.get_pos()

            self.get_controller().get_output().click(pos)
Exemple #19
0
    def __init__(self):
        """Initialize the chat room."""
        self.__messages = []  # Stores users messages
        self.__users = {
            'bot': []
        }  # Stores a dictionary with registered usernames

        # Define the event handler and make it public outside the class to let externals subscriptions to events.
        self.event_handler = EventHandler(
            'onNewuser',
            'onMessage')  # Note that events names are cased sensitive.
        # You can set any number of unique events and asing any number of unique callbacks to fire per event.
        # Is not necessary define events names during initialization, also you can register the event names during
        # run time using register_event method.

        # Lets link some internal class methods to those events as callbacks.
        # Limits are available resources.
        self.event_handler.link(self.__on_newuser_join, 'onNewuser')
        self.event_handler.link(self.__on_message, 'onMessage')
 def __init__(self,
              bgcolor=pygame.Color('White'),
              size=(400, 400),
              foodspawnrange=(200, 700)):
     pygame.init()
     self.window = pygame.display.set_mode(size)
     self.window.fill(bgcolor)
     pygame.display.set_icon(pygame.image.load('images/favicon.png'))
     pygame.display.set_caption("Snake")
     self.objects = []
     self.clock = Clock()
     self.bgcolor = bgcolor
     self.eventhandler = EventHandler()
     self.run = True
     self.foodspawn = foodspawnrange
     self.nextfood = -randint(*self.foodspawn)
     self.size = size
     self.pause = False
     self.deaths = {}
     self.events = []
 def test_add_event_parse_with_defaults(self):
     results = self.my_service.add_event(self.feed_with_defaults)
     # make_time truncates milliseconds
     # risky if we are on a break of a second
     time = EventHandler.make_time()
     expected = {
         'id': 1,
         'text': "It's empty",
         'category': 'update',
         'person': 'all',
         'time': time
     }
     self.assertDictEqual(results, expected)
 def test_add_event(self):
     results = self.app.post('/feeds/api/v1.0/events',
                             data=self.feed_with_all)
     time = EventHandler.make_time()
     expected = {
         'id': 1,
         'text': 'What a fantastic day #update @john',
         'category': 'update',
         'person': 'john',
         'time': time
     }
     self.assertEqual(results.status, '201 CREATED')
     self.assertDictEqual(json.loads(results.data), {"event": expected})
 def test_add_event_parse_no_defaults(self):
     results = self.my_service.add_event(self.feed_with_all)
     # make_time truncates milliseconds
     # risky if we are on a break of a second
     time = EventHandler.make_time()
     expected = {
         'id': 1,
         'text': 'What a fantastic day #update @john',
         'category': 'update',
         'person': 'john',
         'time': time
     }
     self.assertDictEqual(results, expected)
    def test_005_initialization_file_to_verbose(self):
        with open('test.txt', '+w') as f:
            eh = EventHandler(stream_output=f, verbose=True)
            self.assertEqual('test.txt', eh.stream_output.name)

            instance_id = str(hex(id(eh)))
            f.close()
        with open('test.txt', 'r') as f:
            content = f.read()
            self.assertTrue((instance_id in content))

            f.close()
        os.remove('test.txt')
Exemple #25
0
 def __init__(self):
     super( EventCapture, self ).__init__()
     self.finished = threading.Event()
     
     # Hook to our display.
     self.local_display = display.Display()
     self.record_display = display.Display()
     
     # Set up event handler     
     self.event_handler = EventHandler()
     
     # Check for record extension
     if not self.record_display.has_extension("RECORD"):
         raise Exception("Your X-Server does not have the RECORD extension available/enabled.")
Exemple #26
0
    def _plotit(self):
        rows = 5
        cols = 6
        if not self._legendflag:
            self.fig, (self._heatax, self._matax) = plt.subplots(1, 2)
        else:
            gs = gridspec.GridSpec(rows, cols)

            # self._matax = plt.subplot2grid(   (rows, cols), ( 0, 0), rowspan=rows, colspan=2)
            # self._heatax = plt.subplot2grid(  (rows, cols), ( 0, 4), rowspan=rows, colspan=2)
            # self._legax = plt.subplot2grid(   (rows, cols), ( 0, 2), rowspan=3, colspan=2)
            # self.cont_dir = plt.subplot2grid( (rows, cols), ( 3, 2), colspan=2)

            self._matax   = plt.subplot(gs[ :,  :2])
            self._heatax  = plt.subplot(gs[ :, 4:])
            self._legax   = plt.subplot(gs[ :3, 2:4])
            self.cont_dir = plt.subplot(gs[ -1,  2])

            self.cont_dir.set_title('sort on click by')
            self._plot_legend()
            self._matpatches = []
            self.fig = self._matax.figure
            self.fig.tight_layout()
            self.fig.canvas.set_window_title('binderfinder Matrix {} -- {}'.format(__version__, self.filename))
            self.fig.subplots_adjust(top=0.90)
            # self.fig.suptitle(self.filename)
            plt.figtext(0.07, 0.03, self.filename)

        self._matimg = self._matax.imshow(self._matrix, interpolation='none')
        self._heatimg = self._heatax.imshow(np.zeros(self._matrix.shape[:2]),
                                            interpolation='none', vmin=0, vmax=1, cmap=self._heatmap_color)

        plt.colorbar(mappable=self._heatimg, ax=self._heatax)
        self._update_matrixdata()

        self._set_ticks(self.subnames, self.typnames)

        # self._check_color = RadioButtons(self.cont_rgb, ('R', 'G', 'B', 'mean'), (False, False, True))
        self._check_dir = RadioButtons(self.cont_dir, ('row', 'col', 'both'))
        self._event_handler = EventHandler(self.fig, self, debug=self._debugflag)

        # spacer between stats and data
        self._plot_spacer()

        # remove spines
        for ax in (self._matax, self._heatax):
            # for line in ('top', 'bottom', 'left', 'right'):
            #     ax.spines[l].set_visible(False)
            for spine in ax.spines.values():
                spine.set_visible(False)
Exemple #27
0
def run_module(module_name, args, controller, socks_port, stats):
    """
    Run an exitmap module over all available exit relays.
    """

    logger.info("Running module '%s'." % module_name)
    stats.modules_run += 1

    try:
        module = __import__("modules.%s" % module_name, fromlist=[module_name])
    except ImportError as err:
        logger.error("Failed to load module because: %s" % err)
        return

    # Let module perform one-off setup tasks.

    if hasattr(module, "setup"):
        logger.debug("Calling module's setup() function.")
        module.setup()

    exit_destinations = select_exits(args, module)

    exit_relays = list(exit_destinations.keys())
    random.shuffle(exit_relays)

    count = len(exit_relays)
    stats.total_circuits += count

    if count < 1:
        raise error.ExitSelectionError("Exit selection yielded %d exits "
                                       "but need at least one." % count)

    handler = EventHandler(controller,
                           module,
                           socks_port,
                           stats,
                           exit_destinations=exit_destinations)

    controller.add_event_listener(handler.new_event, EventType.CIRC,
                                  EventType.STREAM)

    duration = count * args.build_delay
    logger.info("Scan is estimated to take around %s." %
                datetime.timedelta(seconds=duration))

    logger.info("Beginning to trigger %d circuit creation(s)." % count)

    iter_exit_relays(exit_relays, controller, stats, args)
Exemple #28
0
    def __init__(self, x, y):
        self.board_size = min(x, y)
        self.piece_size = self.board_size // 8
        self.bg_image = Image.open("./resources/images/chessboard.png")
        self.og_pieces = self.load_piece_images()
        self.pieces = self.og_pieces
        self.board = self.bg_image.copy()
        self.play_board = self.board.copy()

        self.env = ChessEnvironment()

        self.root = tk.Tk(className="Chess")
        self.root.geometry("{}x{}".format(x, y))

        self.eh = EventHandler(self)
        self.root.bind("<Configure>", self.eh.on_configure)
        self.root.bind("<Return>", self.eh.on_confirm)

        self.tk_image = ImageTk.PhotoImage(self.play_board)
        self.board_label = tk.Label(self.root, image=self.tk_image)
        self.board_label.place(relx=0.05, rely=0.05)

        self.game_label = tk.Label(self.root, text="Game playing")
        self.game_label.place(relx=0.05, rely=0.96)

        self.move_var = tk.StringVar()
        self.move_var.set("")
        self.move_var.trace("w", self.eh.check_move)
        self.move_box = tk.Entry(self.root, textvariable=self.move_var)
        self.move_box.place(relx=0.15, rely=0.01)

        self.move_label = tk.Label(self.root, text="NOT a valid move")
        self.move_label.place(relx=0.25, rely=0.01)

        self.random_move_button = tk.Button(
            self.root, text="Random Move", command=self.eh.on_random_move
        )
        self.random_move_button.place(relx=0.35, rely=0.01)

        self.start_button = tk.Button(
            self.root, text="New Game", command=self.eh.on_start
        )
        self.start_button.place(relx=0.05, rely=0.01)

        self.root.mainloop()
        self.on_resize()
    def start(self):
        self.initLogging()

        self.hexapod = Hexapod()
        self.hexapod.start()

        self.queuemanager = QueueManager()

        self.webSocketServer = WebSocketServer()
        self.webSocketServer.start()

        EventHandler.addListener("eacho", Events.PACKET_RECEIVED, self.onPacketReceived)
        EventHandler.addListener("onClientConnect", Events.NEW_CLIENT_CONTROLLER, self.onNewClientController)
        EventHandler.addListener("onClientTimeUp", Events.CLIENT_TIME_UP, self.onClientTimeUp)

        self.loop()
 def shutdown(self):
     EventHandler.callEvent(Events.SERVER_SHUTDOWN, None)
     exit()
    def test_009_bind_callbacks(self):
        event_name = 'newCoolEvent'
        eh = EventHandler(event_name)

        def callback1(*args):
            pass

        self.assertFalse(eh.is_callback_in_event(event_name, callback1))

        output = io.StringIO()
        eh = EventHandler(event_name, verbose=True, stream_output=output)

        with self.assertRaises(EventHandler.Exceptions.EventNotAllowedError) as context:
            # Impossible to link to a not registered callback, will raie error
            eh.link(callback1, 'onNotRegisteredEvent')

        self.assertTrue(eh.link(callback1, event_name))
        self.assertFalse(eh.link(callback1, event_name))

        output = str(output.getvalue())

        self.assertTrue(callback1.__name__ in output)
        self.assertTrue(event_name in output)

        self.assertTrue(eh.is_callback_in_event(event_name, callback1))

        # tries to link not callable event
        self.assertFalse(eh.link('not_callable', event_name))
    def test_008_is_callable(self):
        func = lambda x: print(x)
        not_func = 'This is not callable as method'

        self.assertTrue(EventHandler.is_callable(func))
        self.assertFalse(EventHandler.is_callable(not_func))
Exemple #33
0
class EventCapture(threading.Thread):


    def __init__(self):
        super( EventCapture, self ).__init__()
        self.finished = threading.Event()
        
        # Hook to our display.
        self.local_display = display.Display()
        self.record_display = display.Display()
        
        # Set up event handler     
        self.event_handler = EventHandler()
        
        # Check for record extension
        if not self.record_display.has_extension("RECORD"):
            raise Exception("Your X-Server does not have the RECORD extension available/enabled.")
        
                
    def run(self):
        # Create a recording context
        self.context = self.record_display.record_create_context(
                0,
                [record.AllClients],
                [{
                        'core_requests': (0, 0),
                        'core_replies': (0, 0),
                        'ext_requests': (0, 0, 0, 0),
                        'ext_replies': (0, 0, 0, 0),
                        'delivered_events': (0, 0),
                        'device_events': (X.KeyPress, X.ButtonPress),
                        'errors': (0, 0),
                        'client_started': False,
                        'client_died': False,
                }]
            )

        # Enable the context. Only returns after a call to record_disable_context,
        # while calling the callback function in the meantime
        self.record_display.record_enable_context(self.context, self.__processEvents )
        
        # Free the context
        self.record_display.record_free_context(self.context)
        self.record_display.close()


    def stop(self):
        """ Close everything down """

        self.finished.set()
        self.local_display.record_disable_context(self.context)
        self.local_display.flush()
        self.event_handler.event_queue.put((None, None))
        self.join()
    
    
    def shouldReturn( self, reply ):
        """ Check whether or not we should continue processing """
    
        if reply.category != record.FromServer:
            return True
        elif reply.client_swapped:
            return True
        elif not len(reply.data) or ord(reply.data[0]) < 2:
            return True
        else:
            return False
    
    
    def extractEventAndData( self, data ):
        """ Return the event and data """
    
        event_field = rq.EventField(None)
        return event_field.parse_binary_value(
               data, 
               self.record_display.display, 
               None, 
               None
           )
    
    
    def __processEvents( self, reply ):
        if self.shouldReturn( reply ) is False:
            data = reply.data
            
            while len(data):
                event, data = self.extractEventAndData( data )
                
                if event.type == X.KeyPress:
                    self.event_handler.handleKeyPress('key_code')
                
                elif event.type == X.KeyRelease:
                    self.event_handler.handleKeyRelease('key_code')
                
                elif event.type == X.ButtonPress:
                    logger.info( "button pressed" )
    def test_003_initialization_verbose(self):
        eh = EventHandler(verbose=True)
        self.assertTrue(eh.verbose)

        eh = EventHandler(verbose=False)
        self.assertFalse(eh.verbose)
 def test_015_test__rep(self):
     eh = EventHandler('one', 'two', 'three')
     self.assertEqual(eh.__str__(), eh.__repr__())
 def test_014_test_events_tuple(self):
     eh = EventHandler('one', 'two', 'three')
     self.assertDictEqual(eh.events, {'one': [], 'two': [], 'three': []})
     self.assertTrue(eh.clear_events())
     self.assertDictEqual(eh.events, {})
 def test_013_test_events_tuple(self):
     eh = EventHandler('one', 'two', 'three')
     self.assertDictEqual(eh.events, {'one': [], 'two': [], 'three': []})
Exemple #38
0
class ModuleHandler():
    def __init__(self, bot):
        self.event_handler = EventHandler()
        self.bot = bot
        self.load_modules(True)
    
    def load_modules(self, first_time = False):
        if any(result is False for result in self.fire_event('modulehandler:before_load_modules', (self, self.bot, self.event_handler, first_time))):
            return False
        
        logging.info('Loading module resources')
        module_files = glob.glob(os.path.dirname(__file__) + '/modules/resources/*.py')
        module_names = ['modules.resources.' + os.path.basename(f)[:-3] for f in module_files]
        if not self._load_module_list(module_names, first_time):
            return False
        
        logging.info('Loading modules')
        module_files = glob.glob(os.path.dirname(__file__) + '/modules/*.py')
        module_names = ['modules.' + os.path.basename(f)[:-3] for f in module_files]
        imported_modules = self._load_module_list(module_names, first_time)
        if not imported_modules:
            return False
        
        if any(result is False for result in self.fire_event('modulehandler:before_init_modules', (self, self.bot, self.event_handler, first_time))):
            return False
        
        # we've imported with no problems - break old hooks, and try to add new
        self.event_handler.clear_module_hooks()
        self.event_handler.importing_modules = True
        
        for module in imported_modules:
            try:
                module.init()
            except BaseException as e:
                if first_time:
                    raise
                # if we fail out here, this module will NOT have hooked its events - others may have though, so we don't return so all unbroken modules can init
                error = 'module "%s" unable to init: %s: %s' % (str(module), type(e).__name__, e)
                logging.exception(error)
                print(error)
        
        self.event_handler.importing_modules = False
        
        self.fire_event('modulehandler:after_load_modules', (self, self.bot, self.event_handler, first_time))
        
        return True
    
    def _load_module_list(self, list, first_time):
        loaded_modules = []
        for module in list:
            if module.endswith('__init__'):
                continue
        
            if module in sys.modules:
                module = sys.modules[module]
                importfunc = reload_func
            else:
                importfunc = importlib.import_module
            
            try:
                module = importfunc(module)
                module.bot = self.bot
                module.event_handler = self.event_handler
                loaded_modules.append(module)
            except BaseException as e:
                if first_time:
                    raise
                # if we fail out here, old event hooks remain in place
                error = 'module "%s" unable to import: %s: %s' % (str(module), type(e).__name__, e)
                logging.exception(error)
                print(error)
                return []
        
        return loaded_modules
    
    def fire_event(self, key, parameters):
        return self.event_handler.fire(key, parameters)
    
    def hook_event(self, key, function, priority = 500):
        return self.event_handler.hook(key, function, priority)
    
    def get_event_handlers(self, key):
        return self.event_handler.get_handlers(key)
Exemple #39
0
 def __init__(self, bot):
     self.event_handler = EventHandler()
     self.bot = bot
     self.load_modules(True)
class Editor(object):

    # No te olvides de quitar las rutas hardcodeadas y meterlas
    # en un archivo de configuracion

    def __init__(self, nombre="Editor", resolucion=(800, 600)):

        self.nombre = nombre
        self.resolucion = resolucion
        self.pantalla = pygame.display.set_mode(self.resolucion)
        self.cont_tiempo = 0

        self.menuayuda = Ayuda(self.resolucion)
        self.mundo = Mundo()
        self.raton = Raton("res/puntero.png")
        self.camara = Camara(self.mundo, self.raton, self.resolucion)
        # de momento menu_nmundo se queda aqui ya veremos si es mejor moverlo a
        # menu como estaba antes
        self.menu_nmundo = NuevoMundo(self.resolucion[0] / 2,
                    self.resolucion[1] / 2, 10, 10, self.raton, self.mundo, self.camara)
        self.menu_carga = MenuCarga(self.resolucion, self.raton, self.mundo, self.camara)
        self.menu = Menu(self.resolucion, self.raton, self.mundo,
                            self.menu_nmundo, self.menu_carga)
        self.chat = Chat(self.resolucion, self.mundo.tiles_suelos1[31][31], self.mundo.capa,
                      self.mundo.modo_entidad, self.camara.pincel.borrar,
                       self.mundo.aut_save, self.mundo)

        self.eventhandler = EventHandler(self)

        self.cambio = False
        self.fullscreen = False
        self.primera_menu = True
        self.primera_camara = True

    def iniciar(self):

        pygame.init()
        self.cambio = False
        pygame.display.set_caption(self.nombre)
        self.salir = False
        self.reloj = pygame.time.Clock()

        while self.menu.salir != 1:

            # ticks del reloj
            self.reloj.tick(40)
            # actualizacion eventos de teclado
            self.eventhandler.update()

            # actualizacion del raton (raton + puntero)
            # (puntero es un rect muy pequeno que sigue a raton para darle mas precision)
            self.raton.update()
            # tile seleccionado:
            if not self.mundo.modo_entidad:
                # seleccion de tile del marco del menu
                if self.mundo.capa == 1:
                    self.tile_activo = self.menu.marco_tileset.tile_seleccionado_suelos
                elif self.mundo.capa == 3:
                    self.tile_activo = self.menu.marco_tileset.tile_seleccionado_paredes
                elif self.mundo.capa == 4:
                    self.tile_activo = self.menu.marco_tileset.tile_seleccionado_tejados
            else:
                # seleccion del tile que representa un enemigo
                self.tile_activo = self.menu.marco_tileset.tile_seleccionado_enemigos
            self.tile_activo_paredes = self.menu.marco_tileset.tile_seleccionado_paredes

            self.menu.update()

            # /* anotacion1
            # /** anotacion2

            ########### dibujar sobre la pantalla el menu, actualizacion de chat y mostrarlo
            self.dibuja(self.menu)
            self.muestra_chat()
            self.dibuja(self.chat)
            ###########

            if not self.camara.focused():    # /**
                self.pantalla.blit(self.raton.surface, (self.raton.puntero.x, self.raton.puntero.y))
                if self.primera_camara:
                    self.pantalla.blit(self.camara.render(), (0, 0))
                    self.primera_camara = False
            else:

                self.camara.update(self.tile_activo)
                self.pantalla.blit(self.camara.render(), (0, 0))

                self.primera_camara = True

            # menu para crear nuevo mundo
            if self.menu_nmundo.activo:

                self.menu_activo()

            if self.menu_carga.activo:

                self.menu_carga_activo()

            if self.menuayuda.run:

                self.menu_ayuda()

            # contador para guardar con autosave, esta en milisegundos
            if self.mundo.aut_save:
                self.cont_tiempo = self.cont_tiempo + 1
                if self.cont_tiempo == 8000:
                    self.mundo.grabar("temporal")
                    self.cont_tiempo = 0
                    print "Mapa guardado en temporal.txt"

            pygame.display.update()

    def dibuja(self, ente):

        self.pantalla.blit(ente.surface, (ente.rect.x, ente.rect.y))

    def muestra_chat(self):

        self.chat.update(self.tile_activo, self.mundo.capa,
                 self.camara.mostrar_capa3, self.camara.mostrar_capa4,
                 self.mundo.modo_entidad, self.camara.pincel.borrar,
                 self.mundo.aut_save, self.mundo)
        self.chat.imprime()


    def menu_ayuda(self):

        while self.menuayuda.run:
            self.menuayuda.ejecutar()
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == K_F1:
                        self.menuayuda.run = False
            self.dibuja(self.menuayuda)
            pygame.display.update()
        self.pantalla.blit(self.camara.render(), (0, 0))

    def menu_activo(self):

        while self.menu_nmundo.activo:

            # /***
            eventos = pygame.event.get()
            self.pantalla.fill((0, 0, 0))
            self.reloj.tick(35)
            self.raton.update()
            self.menu_nmundo.update(eventos, self.mundo)
            self.menu_nmundo.render()
            self.dibuja(self.menu_nmundo)
            self.pantalla.blit(self.raton.surface, (self.raton.puntero.x, self.raton.puntero.y))
            self.menu.update()
            pygame.display.update()
        self.pantalla.blit(self.camara.render(), (0, 0))

    def menu_carga_activo(self):

        self.menu_carga.build_menu()
        while self.menu_carga.activo:
            eventos = pygame.event.get()
            self.pantalla.fill((0, 0, 0))
            self.reloj.tick(35)
            self.raton.update()
            self.menu_carga.update(eventos)
            self.dibuja(self.menu_carga)
            self.pantalla.blit(self.raton.surface, (self.raton.puntero.x, self.raton.puntero.y))
            self.menu.update()
            pygame.display.update()
        self.pantalla.blit(self.camara.render(), (0, 0))
    def test_004_initialization_tolerate_execeptions(self):
        eh = EventHandler(tolerate_callbacks_exceptions=True)
        self.assertTrue(eh.tolerate_exceptions)

        eh = EventHandler(tolerate_callbacks_exceptions=False)
        self.assertFalse(eh.tolerate_exceptions)