示例#1
0
    def __init__(self):

        self.player_buttons = Buttons()
        self.player2_buttons = Buttons()
        self.type = "buttons"
        self.__player_count = 2
        self.save_game_path = ""
示例#2
0
def main():
    global epaper
    global shutting_down
    global details_to_display

    epaper = EPaper(debug_mode=DEBUG_MODE)

    atexit.register(shutdown_hook)
    signal.signal(signal.SIGTERM, signal_hook)

    buttons = None
    if not DEBUG_MODE and (os.environ.get("EPAPER_BUTTONS_ENABLED", "true")
                           == "true"):
        from buttons import Buttons
        buttons = Buttons([
            int(os.environ.get("EPAPER_GPIO_PIN_FOR_KEY1", "5")),
            int(os.environ.get("EPAPER_GPIO_PIN_FOR_KEY2", "6")),
            int(os.environ.get("EPAPER_GPIO_PIN_FOR_KEY3", "13")),
            int(os.environ.get("EPAPER_GPIO_PIN_FOR_KEY4", "19"))
        ], lambda key: action_button(key, epaper))

    notifier = sdnotify.SystemdNotifier()
    notifier.notify("READY=1")

    while True:
        if shutting_down:
            logging.info("App is shutting down.....")
            break

        notifier.notify("WATCHDOG=1")

        if details_to_display is not None:
            logging.info(
                "Going to refresh the main screen with details view...")
            details_to_display()
            details_to_display = None
            buttons.set_not_busy()
            for i in range(10):
                time.sleep(0.5)
                if details_to_display is not None:
                    logging.info("Got button pressed while in details!")
                    break
            if details_to_display is not None:
                continue
            logging.info("Ok, enough - going back to standard view")
            refresh_main_screen(epaper, force=True)
        else:
            logging.info("Going to refresh the main screen...")
            refresh_main_screen(epaper)

        for i in range(300 if buttons is not None else 1
                       ):  # lower the CPU usage when no buttons handled
            if shutting_down:
                logging.info("App is shutting down...")
                break
            if details_to_display is not None:
                logging.info("Got button pressed!")
                break
            time.sleep(1 if buttons is not None else 300)
示例#3
0
 def __init__(self, floors=12, height=2.65, velocity=3.0, doors_delay=3.0):
     self.floors = floors
     self.current_floor = 1
     self.time_to_next_floor = float(height) / velocity
     self.doors_delay = doors_delay
     self.current_state = State.idle
     self.cabin_buttons = Buttons()
     self.call_buttons = Buttons()
     self.command = asyncio.Event()
    def __init__(self):
        super().__init__()

        self.handlers = [
            {
                'condition':
                lambda vk, event, user: hasattr(event, 'payload'),
                'admin':
                lambda vk, event, user: self.send_buttons(
                    vk, event, user, 'стучись разрабу, где-то ошибка', self.
                    main_menu_buttons['admin']),
                'main':
                lambda vk, event, user: self.send_buttons(
                    vk, event, user,
                    'ты молодой, шутливый, тебе все легко. это не то. '
                    'это не Чикатило и даже не архивы спецслужб. сюда лучше не лезть',
                    self.main_menu_buttons['main'])
            },
            {
                'condition':
                lambda vk, event, user: event.text.lower() == 'exception',
                'admin': lambda vk, event, user: self.throw_exception()
            },
            {
                'condition':
                lambda vk, event, user: event.text.lower() in [
                    Buttons.get_label(Buttons.to_main), *[
                        Buttons.get_label(button)
                        for line in self.main_menu_buttons['main']
                        for button in line
                    ]
                ],
                'main':
                lambda vk, event, user: vk.send(event.user_id,
                                                'чел, используй кнопки')
            },
            {
                'condition':
                lambda vk, event, user: event.text.lower() in button_labels,
                'admin':
                lambda vk, event, user: vk.send(event.user_id,
                                                'чел, используй кнопки')
            },
            {
                'condition':
                lambda vk, event, user: event.text.lower() != '',
                'main':
                lambda vk, event, user: vk.send(event.user_id, [
                    'что ты несешь-то вообще?', 'ну что ты такое говоришь?',
                    'выбрав кнопки в панели, или написав слово "кнопки", ты попадешь в основное меню.'
                ])
            },
        ]
 def setUp(self):
     self.buttons = Buttons()
     self.start_button_listener = MagicMock()
     self.stop_button_listener = MagicMock()
     self.ev3_buttons = MagicMock()
     self.buttons.ev3_buttons = self.ev3_buttons
     self.ev3_buttons.up = False
     self.ev3_buttons.down = False
     self.ev3_buttons.left = False
     self.ev3_buttons.right = False
     self.ev3_buttons.backspace = False
     self.buttons.start()
示例#6
0
    def __init__(self, modes):
        GPIO.setmode(
            GPIO.BCM)  #set up to use gpio port numbers (instead of pin #s)

        self.buttons = Buttons()
        self.optos = Optos()
        self.lights = Lights()
        self.outlets = Outlets()
        self.sounds = Sounds()
        self.clock = Countdown(12)

        self.modes = modes
        self.last_time = time.localtime()
示例#7
0
    def check_payload(event, key):
        if type(key) is dict:  # is button
            key = Buttons.get_key(key)
        elif type(key) is list:
            keys = [
                Buttons.get_key(single_key)
                if type(key) is dict else single_key for single_key in key
            ]
            return hasattr(event, 'payload') and literal_eval(
                event.payload).get('command') in keys

        return hasattr(event, 'payload') and literal_eval(
            event.payload).get('command') == key
示例#8
0
 def initialize(self):
     self.listbox = Gtk.ListBox()
     self.currentitem = Gtk.Entry()
     self.currentitem.set_hexpand(True)
     self.panel = Gtk.HBox()
     self.scrolledwindow = Gtk.ScrolledWindow()
     self.scrolledwindow.add(self.listbox)
     self.listbox.set_vexpand(True)
     self.buttons = Buttons(['Add', 'Delete', 'Update'], [self.on_add, self.on_delete, self.on_update])
     self.buttons.set_vexpand(False)
     self.panel.pack_start(self.currentitem, True, True, 3)
     self.panel.pack_start(self.buttons, False, False, 3)
     self.pack_start(self.scrolledwindow, True, True, 3)
     self.pack_start(self.panel, False, True, 3)
示例#9
0
    def __init__(self):
        # инициализация переменных
        self.any_button = False
        self.button_n = {}
        for k in range(1, 5):
            self.button_n.update({k: False})

        # инициализация GPIO
        GPIO.setwarnings(False)
        GPIO.setmode(GPIO.BCM)

        # инициализация устройств
        self.display = Display()
        self.buttons = Buttons(self)
        self.t = Temp()
示例#10
0
文件: pygameview.py 项目: eckamm/kgl
    def on_display_resize(self, event):
        """
        * also used when switching Levels
        * also used when changing a Level's grid size
        """
        disp_surf = self.dm.screen
        disp_w, disp_h = disp_surf.get_size()

        # The board is where the current level is shown
        # in the top left.
        self.board_surface = disp_surf.subsurface(
            pygame.Rect((0,0), (disp_w/2, disp_h*7/8)))
        self.board_view = BoardView(self.board_surface, self.lm, self.tm, self.em)

        # "buttons" is the collection of buttons across the bottom.
        self.buttons_surface = disp_surf.subsurface(
            pygame.Rect((0, disp_h*7/8), (disp_w, disp_h/8)))
        self.buttons = Buttons(self.buttons_surface, self.em)
        self.buttons.calc_rects()

        # "tao" means "tiles and objects"
        # It's the selection control for tiles and objects
        # in the top right.
        self.tao_surface = disp_surf.subsurface(
            pygame.Rect((disp_w/2, 0), (disp_w/2, disp_h*7/8)))
        self.tao = TAO(self.tao_surface, self.tm, self.em)
示例#11
0
def run_game():
    pygame.init()
    settings = Settings()
    os.environ["SDL_VIDEO_WINDOW_POS"] = "%d, %d" % (settings.screen_left,
                                                     settings.screen_top)
    screen = pygame.display.set_mode(
        (settings.screen_width, settings.screen_height))
    pygame.display.set_caption('外星人入侵')
    ship = Ship(screen, settings.ship_speed_factor)
    bullets = Group()
    aliens = Group()
    gf.creat_aliens(aliens, screen, settings)
    status = GameStatus(settings)
    game_info = GameInfo(screen, ship, settings, 0, len(aliens), status)
    buttons = Buttons(screen)
    pop_msg = ScreenPopMsg(screen)

    while True:
        gf.check_events(screen, ship, aliens, settings, bullets, buttons,
                        status, game_info)
        gf.check_game_status(status)
        if status.game_alive == 2:
            gf.check_game_hit(ship, aliens, bullets, status,
                              settings.screen_height, game_info)
            ship.update()
            gf.update_bullets(bullets)
            gf.update_aliens(aliens, bullets, screen, settings,
                             status.game_alive)
            game_info.prep_statusbar(len(bullets), len(aliens))
            gf.check_fire(bullets, aliens, settings, status, game_info)

        gf.update_screen(settings, screen, ship, game_info, bullets, aliens,
                         buttons, status, pop_msg)
示例#12
0
def send_defect(update: Update, context: CallbackContext) -> None:
    user_data = context.user_data
    defect = user_data.get(con.DEFECT)
    token = user_data.get(con.ACCESS_TOKEN)
    payload = {
        "created_by": user_data.get(con.SENDER_ID),
        "title": defect.get(con.DEFECT_TITLE),
        "description": defect.get(con.DEFECT_DESCRIPTION),
        "room": defect.get(con.DEFECT_ROOM) 
    }
    photo_file = open(defect.get(con.DEFECT_PHOTO), 'rb')
    files = {
        "attachment": photo_file
    }
    response = Request.post_defect(payload, files, token)
    photo_file.close()

    _remove_defect_cache(context)

    text = ("Дефект успішно додано!" if response.ok 
                else "Сталась помилка на сервері")
    
    
    query = update.callback_query
    keyboard = Buttons.back_to_menu()

    query.answer()
    query.edit_message_text(text=text, reply_markup=keyboard)
示例#13
0
    def process_new_message(self, event):
        try:
            user = self.db.session.query(User).filter(
                User.user_id == event.user_id).first()
            if not user:
                user = self.db.add(User(event.user_id))
            else:
                self.db.update(user,
                               {User.last_interaction_date: datetime.today()})

            if event.user_id in Config.admin_ids or \
                    Settings.bot and not user.banned:
                handlers = self.handlers
                if user.path == Buttons.get_key(Buttons.call_admin):
                    handlers = self.special_handlers

                coincidence = next(
                    (rule for rule in handlers
                     if rule['condition'](self.vk, event, user) and (
                         'main' in rule or 'admin' in rule
                         and event.user_id in Config.admin_ids)))
                if coincidence:
                    if 'admin' in coincidence and event.user_id in Config.admin_ids:
                        coincidence['admin'](self.vk, event, user)
                    elif 'main' in coincidence:
                        coincidence['main'](self.vk, event, user)
        except StopIteration:
            return None
        except Exception as e:
            self.write_error_message(event.user_id)
            self.write_log(self.vk, event.message_id, e)
            self.db.session.rollback()
    def init_components(self):
        self.searchbar = Search()
        self.searchbar.set_on_search(self.on_search)
        self.buttonbar = Buttons(['Generate', 'Previous', 'Next'], [self.generate, self.on_previous, self.on_next])
        self.the_box = Gtk.VBox()
        self.name = Gtk.Entry()
        self.version = Gtk.Entry()
        self.url = Gtk.Entry()
        self.description = Gtk.TextView()
        self.tarball = Gtk.Entry()
        self.commands = Gtk.TextView()
        self.commands_buffer = self.commands.get_buffer()
        self.dependencies = Gtk.HBox()
        self.required = DependencyList(self)
        self.recommended = DependencyList(self)
        self.optional = DependencyList(self)
        self.section = Gtk.Entry()
        self.downloadUrls = DependencyList(self)
        

        self.labels = list()
        for label_text in ['Name', 'Section', 'URL', 'Version', 'Download URLs', 'Commands', 'Dependencies']:
            label = Gtk.Label.new(label_text)
            label.set_xalign(0.0)
            self.labels.append(label)

        self.scrolledwindow1 = Gtk.ScrolledWindow()

        self.panel1 = Gtk.VBox()
        self.panel2 = Gtk.VBox()
        self.panel3 = Gtk.HBox()
        self.panel4 = Gtk.VBox()
        self.panel5 = Gtk.VBox()
        self.panel6 = Gtk.HBox()
示例#15
0
 def __init__(self):
     self.disp = TFT.ILI9341(DC,
                             rst=RST,
                             spi=SPI.SpiDev(SPI_PORT,
                                            SPI_DEVICE,
                                            max_speed_hz=64000000))
     self.disp.begin()
     self.disp.clear()
     self.draw = self.disp.draw()
     self.board = Board(self.draw, (BOARD_WIDTH, BOARD_HEIGHT), CELL_SIZE,
                        (MARGIN_X, MARGIN_Y))
     self.block = blocks.new_block((BOARD_WIDTH / 2, 1))
     self.display_next_block()
     self.draw_container()
     self.last_update = timestamp()
     self.update_delay = REFRESH_PERIOD
     self.score = 0
     self.update_score(0)
     self.disp.display()
     self.buttons = Buttons({
         21: self.rotate,
         26: self.move_left,
         19: self.move_right,
         16: self.drop
     })
     self.running = False
示例#16
0
 def __init__(self, display):
     self.display = display
     self.view = View(self.display)
     self.album_index = 0
     self.album_selected_index = 0
     self.media_index = 0
     self.media_position = 0.0
     self.media_duration = 0.0
     self.lastUpdate = 0.0
     self.keyDownTime = time.time()
     self.albumMode = True
     home = expanduser("~")
     self.rootFolder = "/home/pi/media"  #os.path.join(home, "media")
     self.busy = False
     self.lastChannel = -1
     if 'arm' in platform.machine():
         self.buttons = Buttons()
示例#17
0
 def get_status(self):
     if self.banned:
         return 'Забанен'
     elif self.apologies_count > 0:
         return 'Извиняется'
     elif self.path == Buttons.get_key(Buttons.call_admin):
         return 'Активно разговаривает с админом'
     return 'Активен'
示例#18
0
class DependencyList(Gtk.VBox):
    def __init__(self, parent_window):
        Gtk.VBox.__init__(self)
        self.initialize()
        self.items = list()
        self.parent_window = parent_window

    def initialize(self):
        self.listbox = Gtk.ListBox()
        self.currentitem = Gtk.Entry()
        self.currentitem.set_hexpand(True)
        self.panel = Gtk.HBox()
        self.scrolledwindow = Gtk.ScrolledWindow()
        self.scrolledwindow.add(self.listbox)
        self.listbox.set_vexpand(True)
        self.buttons = Buttons(['Add', 'Delete', 'Update'], [self.on_add, self.on_delete, self.on_update])
        self.buttons.set_vexpand(False)
        self.panel.pack_start(self.currentitem, True, True, 3)
        self.panel.pack_start(self.buttons, False, False, 3)
        self.pack_start(self.scrolledwindow, True, True, 3)
        self.pack_start(self.panel, False, True, 3)

    def set_data(self, dependency_list):
        self.clear()
        self.items = dependency_list
        for item in self.items:
            self.listbox.add(ListBoxRowWithData(item))
        self.show_all()
    
    def clear(self):
        children = self.listbox.get_children()
        for child in children:
            self.listbox.remove(child)

    def get_data(self):
        return self.items

    def on_add(self, source):
        pass
    
    def on_delete(self, source):
        pass
    
    def on_update(self, source):
        pass
示例#19
0
def defect_title(update: Update, context: CallbackContext) -> int:
    text = "Введіть назву пошкодження"
    keyboard = Buttons.cancel()

    query = update.callback_query
    query.answer()
    query.edit_message_text(text=text, reply_markup=keyboard)
    
    return con.DEFECT_DESCRIPTION
示例#20
0
def main():
    lcd = LCD()
    zeilen = ["", "", "", ""]
    zeilen[0] = datetime.datetime.now().strftime("%d.%b.%y %H:%M")
    t = int(datetime.datetime.now().strftime("%H"))
    aktuelle_begruessung = begruessung(stundengrenzen, t)
    zeilen[3] = aktuelle_begruessung
    lcd_show_text(lcd, zeilen)
    time.sleep(2)
    radio_view = StationView(lcd)
    btns = Buttons([10, 15, 17, 27, 24, 9])
    radio_view.active = True
    try:
        while (True):
            time.sleep(0.05)
            radio_view.run_updates(btns.get_signals())
    except KeyboardInterrupt:
        exit
示例#21
0
def open_defects_start_date(update: Update, context: CallbackContext) -> int:
    text = "Введіть початкову дату в форматі день.місяць.рік (01.01.2021)"
    keyboard = Buttons.cancel()

    query = update.callback_query
    query.answer()
    query.edit_message_text(text=text, reply_markup=keyboard)

    return con.END_DATE
示例#22
0
def open_defects_send_date(update: Update, context: CallbackContext) -> int:
    end_date = update.message.text
    context.user_data[con.DATE].update({con.END_DATE: end_date})

    text = "Надіслати"
    keyboard = Buttons.done_or_cancel()

    update.message.reply_text(text=text, reply_markup=keyboard)
    return con.SEND_DATE
示例#23
0
 def start(self, conf):
     while not self.sta_if.isconnected():
         sleep_ms(250)
     for client in conf["clients"]:
         addr_info = socket.getaddrinfo(client, 4444)
         self.addrs[client] = addr_info[0][-1]
     _thread.start_new_thread(self.thread_func, ())
     self.screen.softbtn(["On", "Ready"])
     btns = Buttons(self.screen, [(12, self.btn_cb)])
示例#24
0
文件: drums.py 项目: uvgroovy/bm-2015
    def __init__(self):
        print 'Starting up drums!'
        self._buttons = Buttons()
        self._led = LEDS()
        self._sequenceQueue = []
        self._play = False
        self._last_key_time = datetime.now()

        self._led.test()
示例#25
0
def defect_photo(update: Update, context: CallbackContext) -> int:
    room = update.message.text
    context.user_data[con.DEFECT].update({con.DEFECT_ROOM: room})

    text = "Завантажте фото"
    keyboard = Buttons.cancel()

    update.message.reply_text(text=text, reply_markup=keyboard)

    return con.DEFECT_DONE
示例#26
0
def defect_room(update: Update, context: CallbackContext) -> int:
    description = update.message.text
    context.user_data[con.DEFECT].update({con.DEFECT_DESCRIPTION: description})

    text = "Введіть кімнату"
    keyboard = Buttons.cancel()

    update.message.reply_text(text=text, reply_markup=keyboard)

    return con.DEFECT_PHOTO
示例#27
0
class Elevator(object):
    def __init__(self, floors=12, height=2.65, velocity=3.0, doors_delay=3.0):
        self.floors = floors
        self.current_floor = 1
        self.time_to_next_floor = float(height) / velocity
        self.doors_delay = doors_delay
        self.current_state = State.idle
        self.cabin_buttons = Buttons()
        self.call_buttons = Buttons()
        self.command = asyncio.Event()

    def floor_is_valid(self, floor):
        return 1 <= floor <= self.floors

    def on_call_button(self, floor):
        if self.floor_is_valid(floor):
            log("Called from floor {}".format(floor))
            self.call_buttons.add(floor)
            self.command.set()
        else:
            log("Invalid floor: {}".format(floor))

    def on_cabin_button(self, floor):
        if self.floor_is_valid(floor):
            log("Cabin button {} pressed".format(floor))
            self.cabin_buttons.add(floor)
            self.command.set()
        else:
            log("Invalid floor: {}".format(floor))

    async def handle_commands(self, command_queue):
        while True:
            command = await command_queue.get()
            command.handle(self)

    async def run(self):
        log("Starting operations")
        try:
            while True:
                self.current_state = await self.current_state.run(self)
        except asyncio.CancelledError:
            log("Stopped operations")
            asyncio.get_event_loop().stop()
示例#28
0
def defect_description(update: Update, context: CallbackContext) -> int:
    title = update.message.text
    context.user_data[con.DEFECT] = {con.DEFECT_TITLE: title}
    
    text = "Введіть опис пошкодження"
    keyboard = Buttons.cancel()
    
    update.message.reply_text(text=text, reply_markup=keyboard)

    return con.DEFECT_ROOM
示例#29
0
def open_defects_end_date(update: Update, context: CallbackContext) -> int:
    start_date = update.message.text
    context.user_data[con.DATE] = {con.START_DATE: start_date}

    text = "Введіть кінцеву дату в форматі день.місяць.рік (01.01.2021)"
    keyboard = Buttons.cancel()

    update.message.reply_text(text=text, reply_markup=keyboard)

    return con.FIND_BY_DATE
示例#30
0
class Command:
    def __init__(self):

        self.player_buttons = Buttons()
        self.player2_buttons = Buttons()
        self.type = "buttons"
        self.__player_count = 2
        self.save_game_path = ""

    def object_to_dict(self):

        command_dict = {}

        command_dict['p1'] = self.player_buttons.object_to_dict()
        command_dict['p2'] = self.player2_buttons.object_to_dict()
        command_dict['type'] = self.type
        command_dict['player_count'] = self.__player_count
        command_dict['savegamepath'] = self.save_game_path

        return command_dict
示例#31
0
 def get_essay_button(self, vk, event, user):
     if self.db.session.query(Essay).filter(
             Essay.user_id == event.user_id,
             Essay.processed_text == None).first():
         vk.send(event.user_id, self.reject_message)
     else:
         self.db.update(user, {User.path: Buttons.get_key(Buttons.essay)})
         vk.send(
             event.user_id,
             'давай свой текст, прочту его за тебя и в кратце расскажу в чем суть',
             [[Buttons.to_main]])
示例#32
0
    def dict_to_object(self, player_dict):

        self.player_id = player_dict['character']
        self.health = player_dict['health']
        self.x_coord = player_dict['x']
        self.y_coord = player_dict['y']
        self.is_jumping = player_dict['jumping']
        self.is_crouching = player_dict['crouching']
        self.player_buttons = Buttons(player_dict['buttons'])
        self.is_player_in_move = player_dict['in_move']
        self.move_id = player_dict['move']
示例#33
0
    def __init__(self):
        pygame.init()

        self.imgs = Images()
        self.canvas = Canvas()
        self.netw = Network()
        self.fonts = Fonts()
        self.events = PCEvents()
        self.buttons = Buttons()

        self.screen = pygame.display.set_mode(SCREEN_SIZE)
示例#34
0
class LabArm():
    def __init__(self):
        pygame.init()

        self.imgs = Images()
        self.canvas = Canvas()
        self.netw = Network()
        self.fonts = Fonts()
        self.events = PCEvents()
        self.buttons = Buttons()

        self.screen = pygame.display.set_mode(SCREEN_SIZE)

    def run(self):
        while True:
            self.events.handle(self.screen, self.netw)
            self.canvas.draw(self.screen)
            self.buttons.draw(self.screen)
            self.fonts.draw(self.screen)
            self.netw.draw(self.screen)
            pygame.display.flip()
示例#35
0
文件: drums.py 项目: uvgroovy/bm-2015
class Drums(object):
    def __init__(self):
        print 'Starting up drums!'
        self._buttons = Buttons()
        self._led = LEDS()
        self._sequenceQueue = []
        self._play = False
        self._last_key_time = datetime.now()

        self._led.test()

    def run(self):
        while True:
            now = datetime.now()
            if not self._buttons.has_keys() and (now - self._last_key_time).total_seconds() > STOP_PLAYING_THRESHOLD:
                print 'sequence ended. going to sleep (kinda!)'
                self._play = False

            if self._buttons.has_keys():
                if not self._play:
                    print 'start playing!'

                self._play = True
                self._last_key_time = now
                self._process_key(self._buttons.get_key())

            if not self._play:
                time.sleep(1)
                continue

            time.sleep(0.05)


    def _process_key(self, key):
        print 'processing key %s' % key
        self._led.set_color_for_button(key, 0xFF)
示例#36
0
文件: starter.py 项目: bahniks/PaPyer
    def createWidgets(self):
        self.selectLabel = ttk.Label(self, text = "Select:")
        self.selectLabel.grid(column = 0, row = 0, padx = 10, pady = 5)
        self.select = Select(self, textvariable = self.selectVar)
        self.select.grid(column = 1, row = 0, sticky = (E, W))

        self.searchLabel = ttk.Label(self, text = "Search:")
        self.searchLabel.grid(column = 2, row = 0, padx = 10, pady = 5)
        self.search = Search(self, textvariable = self.searchVar)
        self.search.grid(column = 3, row = 0, sticky = (E, W))

        self.filestorage = FileStorage(self)
        self.filetree = FileTree(self)
        self.filetree.grid(column = 0, row = 1, rowspan = 4, sticky = (N, S, E, W), columnspan = 4)

        self.scrollbar = ttk.Scrollbar(self, orient = VERTICAL, command = self.filetree.yview)
        self.scrollbar.grid(column = 4, row = 1, rowspan = 4, sticky = (N, S, E))
        self.filetree.configure(yscrollcommand = self.scrollbar.set)

        self.tags = Tags(self)
        self.tags.grid(column = 5, row = 2, sticky = (E, W), padx = 5)

        self.tagsLab = ttk.Label(text = "Tags")
        self.tagsLab.grid(column = 5, row = 1, padx = 5, pady = 2)

        self.notes = Notes(self)
        self.notes.grid(column = 5, row = 4, sticky = (N, S, E, W), padx = 5)

        self.notesLab = ttk.Label(text = "Notes")
        self.notesLab.grid(column = 5, row = 3, padx = 5, pady = 2)

        self.scrollNotes = ttk.Scrollbar(self, orient = VERTICAL, command = self.notes.yview)
        self.scrollNotes.grid(column = 6, row = 4, sticky = (N, S, W))
        self.notes.configure(yscrollcommand = self.scrollNotes.set)

        self.buttons = Buttons(self)
        self.buttons.grid(row = 5, column = 0, columnspan = 5, pady = 5, sticky = (E, W))

        self.statusBar = StatusBar(self)
        self.statusBar.grid(row = 6, column = 0, columnspan = 5, padx = 5, pady = 5, sticky = (E, W))        
示例#37
0
 def __init__(self):
     canv = Canvas()
     btn = Buttons()
     self.cam = canv.get_cam_rect()
     self.btn0 = btn.get_button0()
     self.btn1 = btn.get_button1()
     self.btn2 = btn.get_button2()
     self.btn3 = btn.get_button3()
     self.abrir = btn.get_button4()
     self.fechar = btn.get_button5()
     self.disc = btn.get_disconect()
     self.font = pygame.font.SysFont("timesnewroman", 18)
     self.disc_text = self.font.render(
         "Desconectado do servidor.", True, BLACK)
     self.conn_text = self.font.render(
         "Deseja conectar?", True, BLACK)
     self.disconnect_text = self.font.render(
         "Desconectar", True, BLACK)
     self.button0 = self.font.render("Pos Inicial", True, BLACK)
     self.button1 = self.font.render("Tubo Ensaio", True, BLACK)
     self.button2 = self.font.render("Becker AO", True, BLACK)
     self.button3 = self.font.render("Becker AC", True, BLACK)
     self.button4 = self.font.render("Elem Gelo", True, BLACK)
     self.button5 = self.font.render("Filtro", True, BLACK)
示例#38
0
文件: starter.py 项目: bahniks/PaPyer
class GUI(Tk):
    "represents GUI"
    def __init__(self):
        super().__init__()
   
        self.option_add("*tearOff", FALSE)
        self.initialized = False
        self.title("Papyer")
        
        x, y = 1500, 500
        self.minsize(x, y)
        placeWindow(self, x, y)
        
        self.options = Options(self)
        self["menu"] = TopMenu(self)        

        self.protocol("WM_DELETE_WINDOW", self.closeFun)

        self.base = os.getcwd()

        self.selectVar = StringVar()
        self.searchVar = StringVar()

        self.createWidgets()

        self.columnconfigure(1, weight = 1)
        self.columnconfigure(3, weight = 1)
        self.columnconfigure(5, weight = 1)
        self.rowconfigure(4, weight = 1)

        self.bind("<Control-d>", lambda e: self.filetree.keepDuplicates())
        self.bind("<Control-a>", lambda e: self.filetree.selectAll())
        
        self.mainloop()



    def refresh(self):
        # do in a smarter way - check changes in the files
        self.filestorage.save()
        self.filetree.saveSettings()
        selected = self.filetree.selection()
        self.createWidgets()
        self.filetree.selection_set(selected)


    def createWidgets(self):
        self.selectLabel = ttk.Label(self, text = "Select:")
        self.selectLabel.grid(column = 0, row = 0, padx = 10, pady = 5)
        self.select = Select(self, textvariable = self.selectVar)
        self.select.grid(column = 1, row = 0, sticky = (E, W))

        self.searchLabel = ttk.Label(self, text = "Search:")
        self.searchLabel.grid(column = 2, row = 0, padx = 10, pady = 5)
        self.search = Search(self, textvariable = self.searchVar)
        self.search.grid(column = 3, row = 0, sticky = (E, W))

        self.filestorage = FileStorage(self)
        self.filetree = FileTree(self)
        self.filetree.grid(column = 0, row = 1, rowspan = 4, sticky = (N, S, E, W), columnspan = 4)

        self.scrollbar = ttk.Scrollbar(self, orient = VERTICAL, command = self.filetree.yview)
        self.scrollbar.grid(column = 4, row = 1, rowspan = 4, sticky = (N, S, E))
        self.filetree.configure(yscrollcommand = self.scrollbar.set)

        self.tags = Tags(self)
        self.tags.grid(column = 5, row = 2, sticky = (E, W), padx = 5)

        self.tagsLab = ttk.Label(text = "Tags")
        self.tagsLab.grid(column = 5, row = 1, padx = 5, pady = 2)

        self.notes = Notes(self)
        self.notes.grid(column = 5, row = 4, sticky = (N, S, E, W), padx = 5)

        self.notesLab = ttk.Label(text = "Notes")
        self.notesLab.grid(column = 5, row = 3, padx = 5, pady = 2)

        self.scrollNotes = ttk.Scrollbar(self, orient = VERTICAL, command = self.notes.yview)
        self.scrollNotes.grid(column = 6, row = 4, sticky = (N, S, W))
        self.notes.configure(yscrollcommand = self.scrollNotes.set)

        self.buttons = Buttons(self)
        self.buttons.grid(row = 5, column = 0, columnspan = 5, pady = 5, sticky = (E, W))

        self.statusBar = StatusBar(self)
        self.statusBar.grid(row = 6, column = 0, columnspan = 5, padx = 5, pady = 5, sticky = (E, W))        
        

    def closeFun(self):
        "ask for saving files on exit"
        self.filetree.saveSettings()
        self.filestorage.save()
        self.options.save()
        self.destroy()
示例#39
0
def main(args):
    monkeypatch_google_protobuf_text_format()

    # Initialize debuglink transport
    if args.debuglink:
        print "Starting debug connection on '%s'" % args.debuglink_path
        print "Debug connection is for unit tests only. NEVER use debug connection with real wallet!"
        debug_transport = get_transport(args.debuglink_transport, args.debuglink_path)
    else:
        debug_transport = get_transport('fake', None)

    # Initialize main transport
    transport = get_transport(args.transport, args.path)

    # Load persisted data. Create new wallet if file doesn't exist
    print "Loading wallet..."
    storage = Storage(args.wallet, bootloader_mode=args.bootloader_mode)
    # storage.struct.settings.label = 'Slushova penezenka'
    print storage.struct

    # Initialize hardware (screen, buttons)
    but = Buttons(hw=args.shield, stdin=not args.shield, pygame=not args.shield)
    buff = DisplayBuffer(DISPLAY_WIDTH, DISPLAY_HEIGHT)
    display = Display(buff, spi=args.shield, virtual=not args.shield)
    display.init()

    # Initialize layout driver
    layout = Layout(buff, display)

    # Process exponential backoff if there was unsuccesfull PIN attempts
    if storage.get_pin_delay():
        delay = storage.get_pin_delay()
        print "Waiting %s seconds until boot up" % delay
        layout.show_pin_backoff_progress(delay)

    # Startup state machine and switch it to default state
    machine = StateMachine(storage, layout)

    display.refresh()

    # Main cycle
    while True:
        try:
            # Read button states
            button = but.read()
        except KeyboardInterrupt:
            # User requested to close the app
            break

        # Set is_active=True if device does something
        # False = device will sleep for a moment to prevent CPU load
        # Set button=None to use event only for rendering
        # and hide it against state machine
        (is_active, button) = layout.update(button)

        # Handle debug link connection
        msg = debug_transport.read()
        if msg is not None:
            print "Received debuglink", msg.__class__.__name__, msg
            if isinstance(msg, proto.DebugLinkDecision):
                # Press the button
                button = msg.yes_no
            else:
                resp = machine.process_debug_message(msg)
                if resp is not None:
                    print "Sending debuglink", resp.__class__.__name__, resp
                    debug_transport.write(resp)
                    is_active = True

        if button is not None:
            print "Button", button
            is_active = True

            resp = machine.press_button(button)
            if resp is not None:
                print "Sending", resp
                transport.write(resp)

        # Handle main connection
        msg = transport.read()
        if msg is not None:
            print "Received", msg.__class__.__name__, msg
            resp = machine.process_message(msg)
            if resp is not None:
                print "Sending", resp.__class__.__name__, resp
                transport.write(resp)
                is_active = True

        if not is_active:
            # Nothing to do, sleep for a moment
            time.sleep(0.05)

    # Close transports
    transport.close()
    debug_transport.close()
示例#40
0
class PyBlaster:
    """Daemon for PiBlaster project"""

    def __init__(self):
        """Whole project is run from this constructor
        """

        # +++++++++++++++ Init +++++++++++++++ #

        self.keep_run = 0  # used in run for daemon loop, reset by SIGTERM

        self.log = Log(self)
        self.settings = Settings(self)
        self.led = LED(self)
        self.dbhandle = DBHandle(self)
        self.mixer = AlsaMixer(self)
        self.usb = UsbManager(self)
        self.rfcomm = RFCommServer(self)
        self.cmd = EvalCmd(self)
        self.listmngr = PlayListManager(self)
        self.play = Play(self)
        self.lirc = LircThread(self)
        self.buttons = Buttons(self)
        self.keep_run = 1
        self.ret_code = 0  # return code to command line (10 = shutdown)

        self.led.reset_leds()

        # invoke arg parser and parse config or create new config if not found
        self.settings.parse()

        # check if we can load database, create otherwise
        self.dbhandle.dbconnect()

        # restore alsa mixer settings
        self.mixer.restore_mixer()

        # load connected usb before bluetooth
        self.usb.check_new_usb()

        # initialize sound mixer
        self.play.init_mixer()

        # load latest playlist from database
        self.listmngr.load_active_playlist()

        # open cmd fifo to read commands
        self.cmd.open_fifo()

        # fire up bluetooth service
        self.rfcomm.start_server_thread()

        # start lirc thread
        self.lirc.start()

        # fire up one thread per each button
        self.buttons.start()

        # +++++++++++++++ Daemoninze +++++++++++++++ #

        self.check_pidfile()
        self.daemonize()
        self.create_pidfile()

        self.led.show_init_done()

        # +++++++++++++++ Daemon loop +++++++++++++++ #

        self.run()

        # +++++++++++++++ Finalize +++++++++++++++ #

        self.listmngr.save_active()
        self.led.cleanup()
        self.delete_pidfile()

    def run(self):
        """Daemon loop"""

        # Expensive operations like new usb drive check
        # should not be run every loop run.
        poll_count = 0

        # -e flag is set, run only init and exit directly.
        self.keep_run = 0 if self.settings.exitafterinit else 1

        reset_poll_count = self.settings.keep_alive_count * 30 * 4

        # # # # # # DAEMON LOOP ENTRY # # # # # #

        while self.keep_run:

            poll_count += 1

            # Check cmd fifo for new commands.
            if poll_count % 10 == 0:
                # each 300 ms is enough
                self.cmd.read_fifo()

            # Check button events
            if self.buttons.has_button_events():
                self.buttons.read_buttons()

            # Check bluetooth channel for new messages/connections.
            self.rfcomm.check_incomming_commands()

            # Check if lirc thread has command in queue
            if self.lirc.queue_not_empty():
                ircmd = self.lirc.read_command()
                if ircmd is not None:
                    self.cmd.evalcmd(ircmd, "lirc")

            # Check if song has ended
            if poll_count % 4 == 0:
                # every 120 ms
                self.play.check_pygame_events()

            time.sleep(self.settings.polltime / 1000.)  # 30ms default in
                                                        # config

            if poll_count % self.settings.keep_alive_count == 0:
                self.led.set_led_green(1)

            if (poll_count - self.settings.flash_count) % \
                    self.settings.keep_alive_count == 0:
                self.led.set_led_green(0)

            # Check for new USB drives.
            if poll_count % 30 == 0:
                # If new usb device found, new usbdev instance will be created,
                # including dir and mp3 entries.
                # If usb device got lost, all its entries will be removed.
                # To check every ~900ms is enough
                self.usb.check_new_usb()

            # Multiple of all poll counts reached:
            # may reset poll count at reset_poll_count.
            if poll_count >= reset_poll_count:
                poll_count = 0

            # end daemon loop #

        # # # # # # DAEMON LOOP EXIT # # # # # #

        # join remaining threads
        self.mixer.save_mixer()
        self.lirc.join()
        self.buttons.join()
        self.rfcomm.join()

        self.log.write(log.MESSAGE, "---- closed regularly ----")

    # end run() #

    def daemonize(self):
        """Fork process and disable print in log object"""

        signal.signal(signal.SIGTERM, self.term_handler)
        signal.signal(signal.SIGINT, self.term_handler)

        if not self.settings.daemonize:
            self.log.init_log()
            return

        self.log.write(log.DEBUG1, "daemonizing")

        try:
            pid = os.fork()
        except OSError:
            self.log.write(log.EMERGENCY, "Failed to fork daemon")
            raise

        if pid == 0:
            os.setsid()
            try:
                pid = os.fork()
            except OSError:
                self.log.write(log.EMERGENCY, "Failed to fork daemon")
                raise

            if pid == 0:
                os.chdir("/tmp")
                os.umask(0)
            else:
                os._exit(0)
        else:
            os._exit(0)

        self.settings.is_daemonized = True
        self.log.init_log()
        self.log.write(log.MESSAGE, "daemonized.")

    # end daemonize() #

    def term_handler(self, *args):
        """ Signal handler to stop daemon loop"""
        self.keep_run = 0

    def check_pidfile(self):
        """Check if daemon already running, throw if pid file found"""

        if os.path.exists(self.settings.pidfile):
            self.log.write(log.EMERGENCY, "Found pid file for pyblaster, "
                           "another process running?")
            raise Exception("pid file found")

    def create_pidfile(self):
        """Write getpid() to file after daemonize()"""

        try:
            fpid = open(self.settings.pidfile, "w")
        except IOError:
            self.log.write(log.EMERGENCY, "failed to create pidfile %s" %
                           self.settings.pidfile)
            raise

        fpid.write("%s\n" % os.getpid())

    def delete_pidfile(self):
        """Try to remove pid file after daemon should exit"""

        if os.path.exists(self.settings.pidfile):
            try:
                os.remove(self.settings.pidfile)
            except OSError:
                self.log.write(log.EMERGENCY, "failed to remove pidfile %s" %
                               self.settings.pidfile)
                raise

    def kill_other_pyblaster(self):
        """Check if pid found in pid file and try to kill this (old) process"""

        if not os.path.exists(self.settings.pidfile):
            return

        try:
            f = open(self.settings.pidfile, "r")
        except IOError:
            self.log.write(log.EMERGENCY, "failed to read pidfile %s" %
                           self.settings.pidfile)
            raise

        pid = int(f.readline().strip())

        print("Trying to kill old process with pid %s..." % pid)

        try:
            os.kill(pid, signal.SIGTERM)
        except OSError:
            self.log.write(log.EMERGENCY,
                           "failed to kill process with pid %s" % pid)
            raise

        exit(0)
示例#41
0
    def __init__(self):
        """Whole project is run from this constructor
        """

        # +++++++++++++++ Init +++++++++++++++ #

        self.keep_run = 0  # used in run for daemon loop, reset by SIGTERM

        self.log = Log(self)
        self.settings = Settings(self)
        self.led = LED(self)
        self.dbhandle = DBHandle(self)
        self.mixer = AlsaMixer(self)
        self.usb = UsbManager(self)
        self.rfcomm = RFCommServer(self)
        self.cmd = EvalCmd(self)
        self.listmngr = PlayListManager(self)
        self.play = Play(self)
        self.lirc = LircThread(self)
        self.buttons = Buttons(self)
        self.keep_run = 1
        self.ret_code = 0  # return code to command line (10 = shutdown)

        self.led.reset_leds()

        # invoke arg parser and parse config or create new config if not found
        self.settings.parse()

        # check if we can load database, create otherwise
        self.dbhandle.dbconnect()

        # restore alsa mixer settings
        self.mixer.restore_mixer()

        # load connected usb before bluetooth
        self.usb.check_new_usb()

        # initialize sound mixer
        self.play.init_mixer()

        # load latest playlist from database
        self.listmngr.load_active_playlist()

        # open cmd fifo to read commands
        self.cmd.open_fifo()

        # fire up bluetooth service
        self.rfcomm.start_server_thread()

        # start lirc thread
        self.lirc.start()

        # fire up one thread per each button
        self.buttons.start()

        # +++++++++++++++ Daemoninze +++++++++++++++ #

        self.check_pidfile()
        self.daemonize()
        self.create_pidfile()

        self.led.show_init_done()

        # +++++++++++++++ Daemon loop +++++++++++++++ #

        self.run()

        # +++++++++++++++ Finalize +++++++++++++++ #

        self.listmngr.save_active()
        self.led.cleanup()
        self.delete_pidfile()
示例#42
0
文件: leveleditor.py 项目: eckamm/kgl
    def run(self):
        g = self.g
        tick = 30
        clock = pygame.time.Clock()
        running = True

        level_key = sorted(self._levels.keys())[0]

        disp_w, disp_h = self.g.surface.get_size()

        board_surface = self.g.surface.subsurface(
            pygame.Rect((0,0), (disp_w/2, disp_h*7/8)))

        buttons_surface = self.g.surface.subsurface(
            pygame.Rect((0, disp_h*7/8), (disp_w, disp_h/8)))

        tao_surface = self.g.surface.subsurface(
            pygame.Rect((disp_w/2, 0), (disp_w/2, disp_h*7/8)))

        buttons = Buttons(self.g, buttons_surface)

        bg_colors = mk_color_set()
        frame_cnt = 0
        while running:

            if True: # debug
                # Pulse the background to see what's being redrawn.
                self.g.surface.fill(
                    bg_colors[frame_cnt%len(bg_colors)])

            if g.android:
                if g.android.check_pause():
                    g.android.wait_for_resume()

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        running = False

                if event.type in (pygame.MOUSEBUTTONDOWN, pygame.MOUSEBUTTONUP):

                    if buttons.collidepoint(event.pos):
                        action = buttons.mouse_event(event, buttons_surface)
                        if action is not None:
                            if action.lower() == "abort":
                                running = False
                            elif action == "+":
                                level.change_size(1)
                            elif action == "-":
                                level.change_size(-1)

                    if level.collidepoint(event.pos, board_surface):
                        action = level.mouse_event(event, board_surface)



            level = self._levels[level_key]
            level.draw(board_surface)

            buttons.draw()
     
            pygame.display.flip()
            frame_cnt += 1
            clock.tick(tick)
示例#43
0
def main(args):
    # Initialize main transport
    transport = get_transport(args.transport, args.path)

    # Initialize hardware (screen, buttons)
    but = Buttons(hw=args.shield, stdin=not args.shield, pygame=not args.shield)
    buff = DisplayBuffer(DISPLAY_WIDTH, DISPLAY_HEIGHT)
    display = Display(buff, spi=args.shield, virtual=not args.shield)
    display.init()

    # Initialize layout driver
    layout = Layout(buff)

    # Startup state machine and switch it to default state
    machine = StateMachine(args.keyfile, layout)

    display.refresh()

    # Main cycle
    while True:
        # Set True if device does something
        # False = device will sleep for a moment
        is_active = False

        try:
            # Read button states
            button = but.read()
        except KeyboardInterrupt:
            # User requested to close the app
            break

        if button is not None:
            print "Button", button
            is_active = True

            resp = machine.press_button(button)
            if resp is not None:
                print "Sending", resp
                transport.write(resp)

        # Handle main connection
        msg = transport.read()
        if msg is not None:
            print "Received", msg.__class__.__name__  # , msg
            resp = machine.process_message(msg)
            if resp is not None:
                print "Sending", resp.__class__.__name__, resp
                transport.write(resp)
                is_active = True

        # Display scrolling
        is_active |= layout.update()

        if layout.need_refresh:
            # Update display
            display.refresh()

        if not is_active:
            # Nothing to do, sleep for a moment
            time.sleep(0.1)

    # Close transports
    transport.close()
示例#44
0
def main(args):
    # Initialize debuglink transport
    if args.debuglink:
        print "Starting debug connection on '%s'" % args.debuglink_path
        print "Debug connection is for unit tests only. NEVER use debug connection with real wallet!"
        debug_transport = get_transport(args.debuglink_transport, args.debuglink_path)
    else:
        debug_transport = get_transport('fake', None)

    # Initialize main transport
    transport = get_transport(args.transport, args.path)

    # Load persisted data. Create new wallet if file doesn't exist
    print "Loading wallet..."
    wallet = Wallet(args.wallet)
    print wallet.struct

    # Initialize hardware (screen, buttons)
    but = Buttons(hw=args.shield, stdin=not args.shield, pygame=not args.shield)
    buff = DisplayBuffer(DISPLAY_WIDTH, DISPLAY_HEIGHT)
    display = Display(buff, spi=args.shield, virtual=not args.shield)
    display.init()

    # Initialize layout driver
    layout = Layout(buff)

    # Startup state machine and switch it to default state
    machine = StateMachine(wallet, layout)

    #tx1 = proto.TxOutput(address='1BRMLAB7nryYgFGrG8x9SYaokb8r2ZwAsX', amount=112000000)
    #tx2 = proto.TxOutput(address='1MarekMKDKRb6PEeHeVuiCGayk9avyBGBB', amount=12340123400)
    #layout.show_transactions([tx1, tx2 ], False)

    display.refresh()

    # Main cycle
    while True:
	#d=datetime.now()
	#layout.show_message([d.strftime("%d %B %Y %H:%M:%S")],question=False)
        # Set True if device does something
        # False = device will sleep for a moment
        is_active = False

        try:
            # Read button states
            button = but.read()
        except KeyboardInterrupt:
            # User requested to close the app
            break

        # Handle debug link connection
        msg = debug_transport.read()
        if msg is not None:
            print "Received debuglink", msg.__class__.__name__, msg
            if isinstance(msg, proto.DebugLinkDecision):
                # Press the button
                button = msg.yes_no
            else:
                resp = machine.process_message(msg)
                if resp is not None:
                    print "Sending debuglink", resp.__class__.__name__, resp
                    debug_transport.write(resp)
                    is_active = True

            '''
            elif isinstance(msg, proto.DebugLinkGetState):
                # Report device state
                resp = machine.get_state(msg)
                print "Sending debuglink", resp.__class__.__name__, resp
                debug_transport.write(resp)
            else:
                raise Exception("Got unexpected object %s" % msg.__class__.__name__)
            '''

        if button is not None:
            print "Button", button
            is_active = True

            resp = machine.press_button(button)
            if resp is not None:
                print "Sending", resp
                transport.write(resp)

        '''
        if button == True:
            layout.show_transactions([tx1, tx2 ], False)
            layout.show_question_dummy()

        if button == False:
            layout.show_logo(logo)
        '''

        # Handle main connection
        msg = transport.read()
        if msg is not None:
            print "Received", msg.__class__.__name__, msg
            resp = machine.process_message(msg)
            if resp is not None:
                print "Sending", resp.__class__.__name__, resp
                transport.write(resp)
                is_active = True

        # Display scrolling
        is_active |= layout.update()

        if layout.need_refresh:
            # Update display
            display.refresh()

        if not is_active:
            # Nothing to do, sleep for a moment
            time.sleep(0.1)

    # Save wallet file
    wallet.save()

    # Close transports
    transport.close()
    debug_transport.close()
示例#45
0
文件: gui.py 项目: cmrshieh/ukbdc_gui
		self.label.config(text = tip)

	def clear_tip(self):
		self.label.config(text = self.last_status)

	def clear(self):
		self.label.config(text = "")
		self.last_status = ""


tree = ET.parse("gh60.xml")
keyboard = tree.getroot()
w = int(keyboard.attrib['width'])
h = int(keyboard.attrib['height'])
num_keys = int(keyboard.attrib['num_keys'])
buttons = Buttons(num_keys, w, h)
for key in keyboard:
	no = int(key.attrib['id'])
	buttons.add_button(no,
			int(key.attrib['width']), int(key.attrib['height']),
			int(key.attrib['x']), int(key.attrib['y']))

root = Tk()

#app = ScancodeEntry(root, lambda: 0)
#app.pack()
#root.mainloop()

#exit()

app = MainWindow(root, buttons)
示例#46
0
文件: pygameview.py 项目: eckamm/kgl
class PygameView:
    def __init__(self, event_manager, 
                       display_manager,
                       tile_manager,
                       level_manager):
        self.em = event_manager
        self.connections = [
            self.em.register(DisplayResizeEvent, self.on_display_resize),
            self.em.register(LevelKeyChangeEvent, self.on_display_resize),
            self.em.register(LevelSizeChangeEvent, self.on_display_resize),
            self.em.register(TickEvent, self.on_tick),
        ]
        self.dm = display_manager
        self.tm = tile_manager
        self.lm = level_manager

        self.board_surface = None
        self.board_view = None

        self.buttons_surface = None
        self.tao_surface = None

        self.buttons = None
        self.tao = None



    def on_display_resize(self, event):
        """
        * also used when switching Levels
        * also used when changing a Level's grid size
        """
        disp_surf = self.dm.screen
        disp_w, disp_h = disp_surf.get_size()

        # The board is where the current level is shown
        # in the top left.
        self.board_surface = disp_surf.subsurface(
            pygame.Rect((0,0), (disp_w/2, disp_h*7/8)))
        self.board_view = BoardView(self.board_surface, self.lm, self.tm, self.em)

        # "buttons" is the collection of buttons across the bottom.
        self.buttons_surface = disp_surf.subsurface(
            pygame.Rect((0, disp_h*7/8), (disp_w, disp_h/8)))
        self.buttons = Buttons(self.buttons_surface, self.em)
        self.buttons.calc_rects()

        # "tao" means "tiles and objects"
        # It's the selection control for tiles and objects
        # in the top right.
        self.tao_surface = disp_surf.subsurface(
            pygame.Rect((disp_w/2, 0), (disp_w/2, disp_h*7/8)))
        self.tao = TAO(self.tao_surface, self.tm, self.em)


    def on_tick(self, event):
        #LOGGER.info("[[render]]")

        screen = self.dm.screen

        screen.fill((0, 0, 0))

        tm = self.tm

        self.board_view.draw_edit_grid()
        self.board_view.draw()

        self.buttons.draw()
        self.tao.draw()

        pygame.display.update()