Example #1
0
    def __init__(self, **kwargs):
        super(IcarusTouchWidget,
              self).__init__(**kwargs)  # don't know if this is necessary?

        # add background image (and add it in the BACKGROUND! --> index modification)
        self.background = Background(
            source=self.app.config.get('Graphics', 'Background'))
        self.float_layout.add_widget(self.background,
                                     index=len(self.float_layout.children))

        # add feedback wall image
        self.feedback_wall = Feedback(source='images/feedbackwall.png',
                                      transparency=0)
        self.float_layout.add_widget(self.feedback_wall)

        # add the keyboard itself
        my_key_width = KEY_WIDTH
        self.keyboard = Keyboard(
            source=self.app.config.get('Graphics', 'Keyboard'),
            pos=(-540, 366),
            size=(
                12 * 5 * my_key_width, 468
            ),  # optimization for small screens (e.g. smartphones): 468 if self.get_parent_window().height > (468 + self.get_parent_window().height * 0.3) else self.get_parent_window().height * 0.7
            border_width=BORDER_WIDTH,
            key_width=my_key_width)
        self.add_widget(self.keyboard)

        # initialize the midi device
        pygame.midi.init()
        self.set_midi_device()

        # initialize the settings_panel (I'm doing this here, otherwise opening it in real-time takes ages...)
        self.my_settings_panel = MySettingsPanel()
Example #2
0
 def build(self):
     self.layout.add_widget(self.control_panel)
     self.layout.add_widget(self.screen)
     self.screen.difficulty.text = self.difficulty
     self.keyboard = Keyboard(self.screen.output, self.key_callback)
     self.layout.add_widget(self.keyboard)
     return self.layout
    def __init__(self, master=None, **kwargs):
        tk.Frame.__init__(self, master, **kwargs)

        master.title("Hangman")
        master.geometry("1000x800")
        master.resizable(False, False)

        self.word = master.word  # get the value from the first screen

        self.score = 7
        self.display = list(len(self.word) * '_')

        # Place the hangman
        # TODO

        # Display the keyboard
        keyboard = Keyboard(self)
        keyboard.pack()

        # Place box for keeping track of word and sample word below
        word_box = tk.Frame(master, height=80, width=600, bd=5, bg='white')
        self.label = tk.Label(word_box, text=self.display)
        self.label.config(font=(None, 25))
        self.label.pack()
        lbl_txt = tk.Label(word_box, text=self.word)
        lbl_txt.pack()
        word_box.place(relx=0.5, y=700, anchor='n')
 def test_part_key_presses(self, inp, res):
     res = res.format(**key)
     kb = Keyboard('US')
     i = random.randint(0, len(res))
     pre_word, shift, caps = kb.part_key_press_string(res[:i])
     post_word, shift, caps = kb.part_key_press_string(res[i:], shift, caps)
     assert inp == pre_word + post_word
Example #5
0
def input_wifi_password():
    global current_screen, screen_type
    current_screen = "wifi_password"
    screen_type = "keyboard"
    print("input_wifi_password")
    kb = Keyboard(oled, kb_callback)
    kb.show()
 def test_word_to_key_press(self, inp, res):
     key = {'c': CAPS_KEY,
            's': SHIFT_KEY}
     KB = Keyboard('US')
     t1 = KB.word_to_key_presses(inp)
     t2 = res.format(**key)
     assert t1 == t2, "{!r} <--> {!r}".format(t1, t2)
 def test_key_prox_keys(self):
     kb = Keyboard('US')
     for inp, res in [('a', 'aqwsxz'),
                      ('t', 'tr456yhgf'),
                      (';', ";lop['/.")]:
         ret = kb.keyboard_prox_key(inp)
         assert set(ret) == set(res)
Example #8
0
 def test_keyboard_dist(self):
     inp_res_map = [(('t', 't'), (0)), (('t', 'T'), (0.8)),
                    (('a', 'S'), (1.8)), (('a', 'w'), (2)),
                    (('w', '$'), (3.8)), (('<', '>'), (1))]
     kb = Keyboard('US')
     for q, r in inp_res_map:
         assert kb.keyboard_dist(*q) == r
Example #9
0
 def test_part_key_presses(self, inp, res):
     res = res.format(**key)
     kb = Keyboard('US')
     i = random.randint(0, len(res))
     pre_word, shift, caps = kb.part_key_press_string(res[:i])
     post_word, shift, caps = kb.part_key_press_string(res[i:], shift, caps)
     assert inp == pre_word + post_word
Example #10
0
 def test_key_press_insert_edits(self, inp, res):
     inp_res_map = [(
         ('{s}pa'.format(**key), [CAPS_KEY, SHIFT_KEY,
                                  'a'], [CAPS_KEY, 't']),
         (
             'pA',
             'Pa',
             'aPa',
             'pa',
             'PA',
             'tpa',  # j=0
             'pA',
             'Pa',
             'Apa',
             'A',
             'a',
             'Ta',  # j=1
             'PA',
             'PA',
             'Paa',
             'P',
             'P',
             'Pt',  # j=2
             'Paa'))]
     kb = Keyboard('US')
     for inp, res in inp_res_map:
         for i, r in enumerate(kb.key_press_insert_edits(*inp)):
             print i, r, res[i]
             assert r == res[i]
Example #11
0
 def test_loc(self):
     inp_res_map = [(('t'), (1, 5, 0)), (('T'), (1, 5, 1)),
                    (('a'), (2, 1, 0)), (('('), (0, 9, 1)),
                    (('M'), (3, 7, 1))]
     kb = Keyboard('US')
     for q, r in inp_res_map:
         assert kb.loc(*q) == r
Example #12
0
    def write_msg(user_id, *messages, keyboard_type=None, logging=True):
        """
        Отправляет сообщения из поля messages пользователю

        :param user_id: id пользователя вконтакте
        :param messages: str
        :param keyboard_type: str принимает параметр 'reg' если нужно отправить клавиатуру для регистрации
        """
        buttons = list()

        if keyboard_type == 'reg':
            buttons.append(Keyboard.get_buttons('negative', 'Отмена'))
        else:
            buttons.append(Keyboard.get_buttons('positive', 'Оценки'))
            buttons.append(
                Keyboard.get_buttons('primary', 'Дз на завтра',
                                     'Дз на сегодня'))
            buttons.append(
                Keyboard.get_buttons('secondary', 'Посчитать', 'Помощь',
                                     "Авторизация"))
            # buttons.append(Keyboard.get_buttons('primary', 'Дз: сегодня'))

        keyboard = Keyboard.get_keyboard(False, buttons)
        for message in messages:
            random_id = random.randint(10, 100000)
            vk_session.messages.send(user_id=user_id,
                                     message=message,
                                     random_id=random_id,
                                     keyboard=keyboard)
            if logging: print("Ответил", message)
Example #13
0
    def __init__(self, master=None, **kwargs):
        tk.Frame.__init__(self, master, **kwargs)

        master.title("Hangman")
        master.geometry("900x550")
        master.resizable(False, False)

        self.word = master.word  # get the value from the first screen
        self.chosen_list = []
        self.score = 7
        self.display = list(len(self.word) * '_')
        self.image = f'images/hangman{self.score}.png'

        # Place the hangman
        hangman_draw = tk.Frame(master, height=580, width=600)
        self.photo = tk.PhotoImage(file=self.image)
        photo_label = tk.Label(hangman_draw, image=self.photo)
        photo_label.pack()

        hangman_draw.place(relx=0.5, y=100, anchor='n')

        # Display the keyboard
        keyboard = Keyboard(self)
        keyboard.pack()

        # Place box for keeping track of word and sample word below
        word_box = tk.Frame(master, height=80, width=600, bd=5)
        self.label = tk.Label(word_box, text=self.display)
        self.label.config(font=(None, 25))
        self.label.pack()
        self.lbl_txt = tk.Label(word_box, text=self.chosen_list)
        self.lbl_txt.pack()
        word_box.place(relx=0.5, y=425, anchor='n')
Example #14
0
    def __init__(self):
        Gtk.DrawingArea.__init__(self)

        self.caret = Gdk.Rectangle()

        self.connect("draw", self.on_draw)
        self.connect("key-press-event", self.on_key_press)
        self.connect("key-release-event", self.on_key_release)
        self.connect("focus-in-event", self.on_focus_in)
        self.connect("focus-out-event", self.on_focus_out)

        self.im_context = Gtk.IMMulticontext()
        self.im_context.set_client_window(self.get_window())
        self.im_context.connect("commit", self.on_commit)
        self.im_context.connect("delete-surrounding",
                                self.on_delete_surrounding)
        self.im_context.connect("retrieve-surrounding",
                                self.on_retrieve_surrounding)
        self.im_context.connect("preedit-changed", self.on_preedit_changed)
        self.im_context.connect("preedit-end", self.on_preedit_end)
        self.im_context.connect("preedit-start", self.on_preedit_start)

        self.set_can_focus(True)

        self.roomazi = Roomazi()
        self.keyboard = Keyboard(self.roomazi)
        self.engine = Engine(self.roomazi)
Example #15
0
 def dispense_and_scan(self, author_selection):
     j = 0
     #f = open(self.dispenserDevices[0], "wb")
     f = open("/dev/ttyUSB0", "wb")
     f.write("020180000380".decode("hex"))
     f.flush()
     f.close()
     #k = Keyboard(self.scannerKeyDev[0])
     k = Keyboard("/dev/input/event0")
     k.flush()
     code = ""
     i = 0
     #return code
     start_time = time.time()
     while i < 8:
         key = k.readKey()
         #print key
         if key is not None:
             code += key
             i += 1
         end_time = time.time() - start_time 
         #self.write_log("end time = "+str(end_time))
         if(end_time > 4):
             self.write_log("reader time out!!")
             break;
     self.write_log("Dispensing from card dispenser " + str(0))
     self.write_log("device = "+str(self.dispenserDevices[0]))
     self.write_log("scanner device = "+str(self.scannerKeyDev[0]))
     return code
Example #16
0
class Nestopia():
    def __init__(self):
        self.workspace = NSWorkspace.sharedWorkspace()
        self.keyboard = Keyboard()

    def show(self):
        for app in self.workspace.runningApplications():
            if app.localizedName() == 'Nestopia':
                app.unhide()
                app.activateWithOptions_(
                    NSApplicationActivateIgnoringOtherApps)
                time.sleep(0.05)

    def pause(self):
        self.keyboard.KeyPress('enter')

    def rotate(self):
        self.keyboard.KeyPress('shift')

    def left(self):
        self.keyboard.KeyPress('left')

    def right(self):
        self.keyboard.KeyPress('right')

    def down(self):
        self.keyboard.KeyPress('down')
Example #17
0
    def full_restart(self):
        """Fully restart the game, clearing all history, etc."""
        # Initialize real and virtual keyboards.
        self.keyboard = Keyboard()
        self.virtual_keyboards = []
        
        # Initialize game objects
        self.players = [Ship(self.keyboard, self.view_size / 2.0)]
        self.bullets = []
        self.rand_state = random.getstate()

        self.asteroids = [Asteroid(self, clear_zone = self.view_size / 2.0,
                                   seed = random.random())
                          for i in range(self.num_asteroids)]
        
        self.DEBUG = DataToggle(source = self.keyboard[sf.Key.NUM0],
                                initVal = False)
                                
#        self.RECORDING = Toggle(source = self.keyboard[sf.Key.T],
#                                initVal = False)

        self.won = False

        # Start the system running
        self.running = DataToggle(
            source = DataOr(self.keyboard[sf.Key.ESCAPE],
                            DataAnd(self.keyboard[sf.Key.Q], 
                                    DataOr(self.keyboard[sf.Key.L_SYSTEM],
                                           self.keyboard[sf.Key.R_SYSTEM]))),
                                  initVal = True)
Example #18
0
    def setup_network_connection(self):
        Keyboard.show(layout=[])

        from subprocess import Popen
        if self.wicd is not None:
            if self.wicd.poll() is None:
                return
        self.wicd = Popen(['xterm', '-maximized', '-e', 'wicd-curses'])
Example #19
0
 def __init__(self, tv=None):
     self._tv = tv
     self._gamepad = None
     self._gamepad_connected = threading.Event()
     self._last_activity_ts = time.time()
     self._locked = False
     self._kbd = Keyboard()
     self._stop = threading.Event()
 def test_other_key_presses_to_word(self, inp, res):
     key = {'c': CAPS_KEY,
            's': SHIFT_KEY}
     KB = Keyboard('US')
     kw = KB.key_presses_to_word('{c}asdf{s}1{c}sdf'.format(**key))
     assert 'ASDFasdf' == KB.key_presses_to_word('{c}asdf{s}a{c}sdf'.format(**key))
     assert 'ASDF!sdf' == KB.key_presses_to_word('{c}asdf{s}1{c}sdf'.format(**key))
     assert KB.key_presses_to_word('{s}apa'.format(**key)) == 'Apa'
Example #21
0
 def volume_down():
     """
     Decrease system volume
     Done by triggering a fake VK_VOLUME_DOWN key event
     :return: void
     """
     Sound.__track()
     Sound.__set_current_volume(Sound.current_volume() - 2)
     Keyboard.key(Keyboard.VK_VOLUME_DOWN)
Example #22
0
 def mute():
     """
     Mute or un-mute the system sounds
     Done by triggering a fake VK_VOLUME_MUTE key event
     :return: void
     """
     Sound.__track()
     Sound.__is_muted = (not Sound.__is_muted)
     Keyboard.key(Keyboard.VK_VOLUME_MUTE)
 def test_loc(self):
     inp_res_map = [(('t'), (1,5,0)),
                   (('T'), (1,5,1)),
                   (('a'), (2,1,0)),
                   (('('), (0,9,1)),
                   (('M'), (3,7,1))]
     kb = Keyboard('US')
     for q, r in inp_res_map:
         assert kb.loc(*q) == r
Example #24
0
 def volume_up():
     """
     Increase system volume
     Done by triggering a fake VK_VOLUME_UP key event
     :return: void
     """
     Key.__track()
     Key.__set_current_volume(Key.current_volume() + 2)
     Keyboard.key(Keyboard.VK_VOLUME_UP)
Example #25
0
 def __init__(self, ratio=1):
     self.RUN = True
     self.TOGGLE = False
     self.vision = Vision(ratio=ratio)
     self.keyboard = Keyboard(sleep=1)
     self.KEYCODES = {1: 18, 2: 19, 3: 20, 4: 21, 5: 23}
     self.potions_box = {"top": 850, "left": 1920, "width": 500, "height": 200}
     self.menu_box = {"top": 300, "left": 1920 + 680, "width": 320, "height": 260}
     self.mouse = Mouse()
Example #26
0
def run():
    for event in longpoll.listen():
        if event.type == VkEventType.MESSAGE_NEW:
            print('\n' + get_name(event.user_id) + ' (id: ' +
                  str(event.user_id) + ')')
            print('Сообщение пришло в: ' +
                  str(datetime.strftime(datetime.now(), "%H:%M:%S")))
            print('Текст сообщения: ' + str(event.text))
            print("---------------------------------\n")
            response = event.text.lower()
            keyboard = Keyboard()
            if event.from_user and event.to_me:
                if found_user(event.user_id) == False:
                    print(event.user_id)
                    print(type(event.user_id))
                    send = {
                        'lang': '',
                        'level': '',
                        'format': '',
                        'discus': ''
                    }
                    steps = {
                        '1': False,
                        '2': False,
                        '3': False,
                        '4': False,
                        '5': False
                    }
                    bot = VkBot(event.user_id, send, steps)
                    add_into_user_bot(event.user_id, send, steps, bot)
                else:
                    if 'vkbot' not in users_bot[event.user_id].keys():
                        user = users_bot[event.user_id]
                        bot = VkBot(event.user_id, user['send'], user['steps'])
                        add_into_user_bot(event.user_id, user['send'],
                                          user['steps'], bot)
                bot_Object = users_bot[event.user_id]['vkbot']
                keyboard = keyboard.create_keyboard(response,
                                                    bot_Object.get_step())
                bb = bot_Object.message(response, keyboard)
                add_into_user_bot(event.user_id, bot_Object.send,
                                  bot_Object.STEPS, bot_Object)
                print(bb)
                print(users_bot)
                print(bot_Object.send)
                print(bot_Object.STEPS)
                add_data_in_json(event.user_id)
                if bb == None:
                    continue
                elif len(bb) == 4:
                    send_message(vk,
                                 bb[0],
                                 bb[1],
                                 message=bb[2],
                                 keyboard=bb[3])
                elif len(bb) == 3:
                    send_message(vk, bb[0], bb[1], message=bb[2])
Example #27
0
 def test_sub_word_table(self, inp, res):
     kb = Keyboard('US')
     res = res.format(**key)
     A = kb.sub_word_table(res)
     print '\n'.join(str(x) for x in A)
     for i in xrange(len(res)):
         pre_w, shift, caps = A[i][0]
         post_w = A[i][2 * shift + caps + 1][0]
         assert pre_w + post_w == inp
Example #28
0
 def volume_up():
     """
     Increase system volume
     Done by triggering a fake VK_VOLUME_UP key event
     :return: void
     """
     Sound.__track()
     Sound.__set_current_volume(Sound.current_volume() + 2)
     Keyboard.key(Keyboard.VK_VOLUME_UP)
Example #29
0
 def volume_down():
     """
     Decrease system volume
     Done by triggering a fake VK_VOLUME_DOWN key event
     :return: void
     """
     Key.__track()
     Key.__set_current_volume(Key.current_volume() - 2)
     Keyboard.key(Keyboard.VK_VOLUME_DOWN)
 def test_sub_word_table(self, inp, res):
     kb = Keyboard('US')
     res = res.format(**key)
     A = kb.sub_word_table(res)
     print '\n'.join(str(x) for x in A)
     for i in xrange(len(res)):
         pre_w, shift, caps = A[i][0]
         post_w = A[i][2*shift + caps + 1][0]
         assert pre_w + post_w == inp
Example #31
0
 def mute():
     """
     Mute or un-mute the system sounds
     Done by triggering a fake VK_VOLUME_MUTE key event
     :return: void
     """
     Key.__track()
     Key.__is_muted = (not Key.__is_muted)
     Keyboard.key(Keyboard.VK_VOLUME_MUTE)
Example #32
0
def typeString(desString):
    desString = desString.replace('type ', '')
    numOfChars = len(desString)
    for i in range(numOfChars):
        keyCode = desString[i].upper()
        if keyCode == ' ':
            keyCode = 'SPACE'
        keyCode = "VK_" + str(keyCode)
        method_to_call = getattr(Keyboard, keyCode)
        Keyboard.key(method_to_call, 0.2)
Example #33
0
 def on_focus(self, instance, value):
     print('instance:', instance)
     if value:
         if instance == self.username:
             self.u_kb = Keyboard("text", instance)
         elif instance == self.password:
             self.p_kb = Keyboard("text", instance)
     else:
         instance.release()
         return False
Example #34
0
class Channel(wx.Panel):
    def __init__(self, parent, writer, doc, log, color=(0, 0, 0)):
        wx.Panel.__init__(self, parent, style=wx.SUNKEN_BORDER)
        self.writer = writer
        self.color = color
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(self.sizer)
        self.doc = doc
        self.corpus = Corpus([doc])
        self.log = log
        self.active = False

        context = self.log.GetValue().split()[-2:]
        suggestions = self.corpus.suggest(context, 20)
        self.keyboard = Keyboard(self, self.doc.name, suggestions, self.log)

        self.sizer.Add(self.keyboard)
        #self.sizer.Add(wx.StaticLine(self, -1, wx.Point(10, 30), wx.Size(200, 30)))
        #self.inspector = Inspector(self, doc)
        #self.inspector.SetBackgroundColour((150,150,150))
        #self.sizer.Add(self.inspector)

    def suggest(self):
        context = self.log.GetValue().split()[-2:]
        return self.corpus.suggest(context, 20)

    def weighted_choice(self, choices):
        total = sum(w for (c, w) in choices)
        r = random.uniform(0, total)
        upto = 0
        for c, w in choices:
            if upto + w >= r:
                return c
            upto += w
        assert False, "Shouldn't get here"

    def refresh(self):
        context = self.log.before().split()[-2:]
        suggestions = self.corpus.suggest(context, 20)
        #print self.weighted_choice(suggestions)
        self.keyboard.Hide()
        self.keyboard = Keyboard(self, self.doc.name, suggestions, self.log)
        if self.active:
            self.keyboard.SetForegroundColour(self.color)
            self.keyboard.header.SetForegroundColour(self.color)
            #if sum(self.color) > 500:
            #	self.keyboard.header.SetForegroundColour("Black")
            #else:
            #	self.keyboard.header.SetForegroundColour("White")
            self.keyboard.Layout()
        else:
            #self.keyboard.SetForegroundColour((80,80,80))
            self.keyboard.header.SetBackgroundColour((0, 0, 0))
        self.sizer.Prepend(self.keyboard)
        self.Layout()
 def test_keyboard_dist(self):
     inp_res_map = [(('t', 't'), (0)),
                    (('t', 'T'), (0.8)),
                    (('a', 'S'), (1.8)),
                    (('a', 'w'), (2)),
                    (('w', '$'), (3.8)),
                    (('<', '>'), (1))
                ]
     kb = Keyboard('US')
     for q, r in inp_res_map:
         assert kb.keyboard_dist(*q) == r
Example #36
0
    def __init__(self):
        super().__init__()

        self.keyboard = Keyboard()
        self.screen = Screen()

        self.poller = Timer(-1)

        self.poll_ref = self.poll
        self.schedule_poll_ref = self.schedule_poll
        self.screen_write_ref = self.screen.write
Example #37
0
 def __init__(self):
     pygame.mixer.init(22050, -16, 2, 64)
     pygame.init()
     self.keyboard = Keyboard(VISABLE_FEEDBACK=Keyboard.VISABLE_NO,
                              WORD_CORRECTION=Keyboard.CORRECT_WORD)
     self.frame_id = 0
     self.save_folder = save_folder = 'data-baseline/' + sys.argv[1] + '/'
     if not os.path.exists(save_folder):
         os.makedirs(save_folder)
     else:
         print('\033[1;31;40m[Warning]\033[0m Folder exists')
Example #38
0
 def __init__(self, config, original_speed, fps, no_ui):
     self.config = config
     self.original_speed = original_speed
     self.fps = fps
     self.no_ui = no_ui
     self.ram = RAM()
     self.keyboard = Keyboard(self.ram)
     self.z80 = Z80(self.ram)
     self.cmd = CMD(self.ram)
     self.entry_addr = self.cmd.load(config["cmd"])
     self.ram.backup()
     self.reset()
Example #39
0
 def __init__(self):
     super(Window, self).__init__()
     self.player1 = Keyboard()
     self.player2 = Keyboard()
     # self.x = 128*3
     # self.y = 120*3
     # self.dx = 1*3
     # self.dy = 1*3
     self.x = 128
     self.y = 120
     self.dx = 1
     self.dy = 1
Example #40
0
def main():
    sio = serial.Serial('COM10', baudrate=9600)
    kb = Keyboard(sio)
    m = Mouse(sio)
    while True:
        m.click()
        m.release()
        kb.press(KEY_RETURN)
        kb.release(KEY_RETURN)
        kb.press(KEY_RETURN)
        kb.release(KEY_RETURN)
        time.sleep(0.8)
 def test_key_press_insert_edits(self, inp, res):
     inp_res_map = [(('{s}pa'.format(**key), [CAPS_KEY, SHIFT_KEY, 'a'], [CAPS_KEY, 't']),
                     ('pA', 'Pa', 'aPa', 'pa', 'PA', 'tpa', # j=0
                      'pA', 'Pa', 'Apa', 'A', 'a', 'Ta',   # j=1
                      'PA', 'PA', 'Paa', 'P', 'P', 'Pt',   # j=2
                      'Paa'))
     ]
     kb = Keyboard('US')
     for inp, res in inp_res_map:
         for i,r in enumerate(kb.key_press_insert_edits(*inp)):
             print i,r,res[i]
             assert r == res[i]
Example #42
0
def test_keypress():
    keyboard = Keyboard("NO")
    keyboard.press_key("n")
    assert len(keyboard.pressed_keys) == 1
    assert keyboard.last_pressed() == "n"
    assert keyboard.currently_pressed() == ["n"]
    keyboard.release_key("n")
    assert keyboard.currently_pressed() == []
    assert len(keyboard.pressed_keys) == 0
Example #43
0
    def __init__(self, connector):
        PyQGLViewer.QGLViewer.__init__(self)
        self.U, self.V = np.meshgrid(np.arange(0, 640, SAMPLE_STRIDE),
                                     np.arange(0, 480, SAMPLE_STRIDE))

        self.points = np.zeros((3, 1))
        self.connector = connector
        self.keyboards = [Keyboard(Keyboard.TYPE_FORWARD, 4, 1, 1, 0.001, 0,"keyboard1.npy" , connector), \
            Keyboard(Keyboard.TYPE_REVERSE, 4, 1, 1, 0.001, -8, "keyboard2.npy", connector), \
            Keyboard(Keyboard.TYPE_SELECT, 1, 2, 2, 0.01, -16, "keyboard3.npy", connector),\
            Keyboard(Keyboard.TYPE_DIRECTION_TOGGLE,1,2,2,0.01,8, "keyboard4.npy", connector) ]
        self.num_keyboard = 4
        self.keyboard = self.keyboards[0]
Example #44
0
class Gui:
    def __init__(self, navdb):
        splash.show()
        self.keyb = Keyboard()                                # processes input from keyboard & mouse
        self.scr  = Screen()                                  # screen output object

    def update(self, sim):
        self.keyb.update(sim, sim.stack, self.scr, sim.traf)  # Check for keys & mouse
        self.scr.update(sim, sim.traf)                        # GUI update

    def reset(self):
        self.scr.objdel()                                     # Delete user defined objects

    def close(self):
        pg.quit()
Example #45
0
File: run.py Project: msarch/py
def main():
    win = Window(fullscreen=True, visible=False)
    camera = Camera(win.width, win.height, (0, 0), 100)
    renderer = Renderer()
    maze = Maze()
    maze.create(50, 30, 300)
    keyboard = Keyboard()
    keyboard.key_handlers[key.ESCAPE] = win.close
    keyboard.key_handlers.update(camera.key_handlers)
    clock.schedule(maze.update)
    win.on_draw = lambda: renderer.on_draw(maze, camera, win.width, win.height)
    win.on_key_press = keyboard.on_key_press
    keyboard.print_handlers()
    win.set_visible()
    app.run()
Example #46
0
 def __init__(self, **kwargs):
     super(IcarusTouchWidget, self).__init__(**kwargs) # don't know if this is necessary?
     
     # add background image (and add it in the BACKGROUND! --> index modification)
     self.background = Background(source=self.app.config.get('Graphics', 'Background'))
     self.float_layout.add_widget(self.background, index=len(self.float_layout.children))
     
     # add feedback wall image
     self.feedback_wall = Feedback(
         source='images/feedbackwall.png',
         transparency=0)
     self.float_layout.add_widget(self.feedback_wall)
     
     # add the keyboard itself
     my_key_width = KEY_WIDTH
     self.keyboard = Keyboard(
         source=self.app.config.get('Graphics', 'Keyboard'),
         pos=(-540, 230), # 366
         size=(12*5*my_key_width, 468), # optimization for small screens (e.g. smartphones): 468 if self.get_parent_window().height > (468 + self.get_parent_window().height * 0.3) else self.get_parent_window().height * 0.7
         border_width=BORDER_WIDTH,
         key_width=my_key_width)
     self.add_widget(self.keyboard)
     
     # initialize the midi device
     pygame.midi.init()
     self.set_midi_device()
     
     # initialize the settings_panel (I'm doing this here, otherwise opening it in real-time takes ages...)
     self.my_settings_panel = MySettingsPanel()
Example #47
0
 def prepare(self):
     """
     Prepare incoming request for handler
     """
     self.keyboard = Keyboard()
     logger.debug("KEYBOARD - Request\n%s", self.request.body)
     super(KeyboardHandler, self).prepare()
Example #48
0
    def setup(self, terminals, payment):
        self.terminals = terminals
        self.payment = payment

        self.ui.setTime.clicked.connect(self.set_time)
        self.ui.showKeyboard.clicked.connect(lambda: Keyboard.show())

        self.ui.setDBIP.clicked.connect(self.set_db_ip)
        self.ui.testDisplay.clicked.connect(self.test_display)
Example #49
0
 def is_triggered(self, obj):
     directions = []
     
     for direction in obj.steering :
         if(Keyboard.is_down(obj.steering[direction])) :
             directions.append(direction)
     if Direction.FORWARD in directions or Direction.BACKWARD in directions :
         self.additionalInfo = directions
         return True
     
     return False        
Example #50
0
class ScoreBuilder(MidiOutStream):
    def __init__(self):
        MidiOutStream.__init__(self)
        self._last_time = 0
        self.keyboard = Keyboard()
        self._last_status = None
        self.score = []

    def note_on(self, channel=0, note=0x40, velocity=0x40):
        # print ("note_on: %s" % note)
        self.keyboard.note_on(note)

    def note_off(self, channel=0, note=0x40, velocity=0x40):
        # print ("note_off:    %s" % note)
        self.keyboard.note_off(note)

    def update_time(self, new_time=0, relative=1):
        # print ("new_time:         %s" % new_time)

        MidiOutStream.update_time(self, new_time, relative)
        if self._absolute_time != self._last_time:
            diff = self._absolute_time - self._last_time

            # print keyboard.format(self.keyboard.snapshot())
            self.score.append(self.keyboard.snapshot())

            self._last_status = [continued(x) for x in self.keyboard.snapshot()]
            for tick in range((diff / eighth_note) - 1):
                # print keyboard.format(self._last_status)
                self.score.append(self._last_status)

            self._last_time = self._absolute_time
Example #51
0
    def is_triggered(self, obj):
        
        directions = []
        
        for direction in obj.steering :
            if(Keyboard.is_down(obj.steering[direction])) :
                directions.append(direction)

        finalDirection = self.map_directions(directions)
        if finalDirection != None :
            self.additionalInfo = finalDirection
            return True
        
        return False
Example #52
0
def main():
    app = QtGui.QApplication(sys.argv)

    controller = Leap.Controller()
    controller.set_policy_flags(Leap.Controller.POLICY_BACKGROUND_FRAMES)

    kb = Keyboard()
    #kb.pressKey((0.97, 0, 0.1))
    kb.pressKey((0.03, 0, 0.1))

    timer = QtCore.QTimer()
    timer.start(33) # 30 cb per sec

    timer.timeout.connect(functools.partial(timer_cb, kb))

    listener = KeyListener(kb)
    controller.add_listener(listener)
    signal.signal(signal.SIGINT, functools.partial(sigint_handler, controller, listener, kb))

    retcode = app.exec_()

    controller.remove_listener(listener)
    sys.exit(retcode)
Example #53
0
 def is_triggered(self, obj):
     
     directions = []
     
     for direction in obj.steering :
         if(Keyboard.is_down(obj.steering[direction])) :
             directions.append(direction)
     
     if Direction.LEFT in directions or Direction.RIGHT in directions or\
             (directions.__len__() == 0 and obj.previous_actions_empty()) or\
            (directions.__len__() == 0 and obj.was_invoked_previously(BasicRotatingCharacter.ROTATE_STOP_ACTION)) :
         self.additionalInfo = directions
         return True
     
     return False
Example #54
0
class KeyboardHandler(JsonHandler):
    """
    Handle requests
    """
    def prepare(self):
        """
        Prepare incoming request for handler
        """
        self.keyboard = Keyboard()
        logger.debug("KEYBOARD - Request\n%s", self.request.body)
        super(KeyboardHandler, self).prepare()

    @tornado.web.asynchronous
    def post(self, *args, **kwargs):
        # 1 - Find operation
        try:
            operation = self.json_data['operation']
            name = self.json_data['name']
        except Exception as e:
            logger.debug("KEYBOARD VIEW - Error\n%s", e)
            self.write_error(500, message=e)
            self.finish()

        # 2 - Execute operation
        method = getattr(self, operation)
        result = method(name)

    def lock(self, name):
        """
        Lock keyboard
        """
        self.keyboard.lock(name)

        self.response = {}
        self.write_json()
        self.finish()
Example #55
0
 def __init__(self, parent=None):
     super(Widget, self).__init__(parent, Qt.FramelessWindowHint)
     self.setAttribute(Qt.WA_TranslucentBackground)
     self.setWindowFlags(self.windowFlags() | Qt.Tool)
     self.resize(300, 30)
     self.cmd = []
     self.lastCmd = ''
     self.cmds = [
         '!yx', '!quit', 'dt', 'dh', 'cmd', 'av', 'put',
         'rm', 'mt', 'bs', 'ba', 'te',
     ]
     self.cmds += [f.split('.')[0] for f in os.listdir(hotkeys)]
     print 'cmds: '
     print self.cmds
     self.keyboard = Keyboard()
     self.keyboard.on('ctrl ;', self.toggle_active)
     self.keyboard.on('print', self.screenshot)
Example #56
0
 def is_triggered(self, obj):
     
     directions = []
     
     for direction in obj.steering :
         if(Keyboard.is_down(obj.steering[direction])) :
             directions.append(direction)
     if directions.__len__() != 0 :
         return False
     
     if obj.previous_actions_empty() or not obj.was_invoked_previously(BasicMovingCharacter.STOP_ACTION):
         self.additionalInfo = Side.FRONT
         return True
     else :
         return False
     
     return False
Example #57
0
File: game.py Project: d00d171/game
    def start_game(self):
        
        while 1 :
            if self.toSetGameScreen != None :
                self.currGameScreen = self.toSetGameScreen
                self.toSetGameScreen = None
                
            if self.currGameScreen == None :
                raise Exception("currGameScreen for game is not set")
            
            for event in pygame.event.get() :
                if event.type == pygame.QUIT: 
                    FileDirHelper.delete_dir(self.GAME_DIRECTORY + Default.TMP_FOLDER)
                    sys.exit()
                    
            Keyboard.get_pressed()
            
            if Keyboard.is_down(pygame.K_LCTRL) and Keyboard.is_down(pygame.K_d) :
                DebugHelper.run_debugger()
            
            
            if Keyboard.is_down(pygame.K_LCTRL) and Keyboard.is_down(pygame.K_s) :
                MainMenuHelper.save_game(self)

                Keyboard.get_pressed()
            
            for gameObject in self.currGameScreen.activeObjects.values() :
                gameObject.analyze_state()
            for gameObject in self.currGameScreen.activeObjects.values() :
                gameObject.interpret_state()
                
            self.currGameScreen.refreshScreen()
            
            
            #obj1 = Game.currGameScreen.activeObjects[2]
            #obj2 = Game.currGameScreen.activeObjects[4]
            #DebugHelper.draw_borders(Game.currGameScreen.surface, obj1)
            #DebugHelper.draw_borders(Game.currGameScreen.surface, obj2)
               
Example #58
0
File: wm.py Project: kopchik/swm
    def __init__(self, display=None, desktops=None, loop=None):
        self.log = Log("WM")
        # INIT SOME BASIC STUFF
        self.hook = Hook()
        self.windows = {}  # mapping between window id and Window
        self.win2desk = {}

        if not display:
            display = os.environ.get("DISPLAY")

        try:
            self._conn = xcffib.connect(display=display)
        except xcffib.ConnectionException:
            sys.exit("cannot connect to %s" % display)

        self.atoms = AtomVault(self._conn)
        self.desktops = desktops or [Desktop()]
        self.cur_desktop = self.desktops[0]
        self.cur_desktop.show()

        # CREATE ROOT WINDOW
        xcb_setup = self._conn.get_setup()
        xcb_screens = [i for i in xcb_setup.roots]
        self.xcb_default_screen = xcb_screens[self._conn.pref_screen]
        root_wid = self.xcb_default_screen.root
        self.root = Window(self, wid=root_wid, atoms=self.atoms, mapped=True)
        self.windows[root_wid] = self.root
#        for desktop in self.desktops:
#            desktop.windows.append(self.root)

        self.root.set_attr(
            eventmask=(
                  EventMask.StructureNotify
                | EventMask.SubstructureNotify
                | EventMask.FocusChange
                # | EventMask.SubstructureRedirect
                | EventMask.EnterWindow
                # | EventMask.LeaveWindow
                # | EventMask.PropertyChange
                | EventMask.OwnerGrabButton
            )
        )

        # INFORM X WHICH FEATURES WE SUPPORT
        self.root.props[self.atoms._NET_SUPPORTED] = [self.atoms[a] for a in SUPPORTED_ATOMS]

        # PRETEND TO BE A WINDOW MANAGER
        supporting_wm_check_window = self.create_window(-1, -1, 1, 1)
        supporting_wm_check_window.props['_NET_WM_NAME'] = "SWM"
        self.root.props['_NET_SUPPORTING_WM_CHECK'] = supporting_wm_check_window.wid
        self.root.props['_NET_NUMBER_OF_DESKTOPS'] = len(self.desktops)
        self.root.props['_NET_CURRENT_DESKTOP'] = 0

        # TODO: set cursor

        # EVENTS THAT HAVE LITTLE USE FOR US...
        self.ignoreEvents = {
            "KeyRelease",
            "ReparentNotify",
            # "CreateNotify",
            # DWM handles this to help "broken focusing windows".
            # "MapNotify",
            "ConfigureNotify",
            "LeaveNotify",
            "FocusOut",
            "FocusIn",
            "NoExposure",
        }
        # KEYBOARD
        self.kbd = Keyboard(xcb_setup, self._conn)
        self.mouse = Mouse(conn=self._conn, root=self.root)

        # FLUSH XCB BUFFER
        self.xsync()    # apply settings
        # the event loop is not yet there, but we might have some pending
        # events...
        self._xpoll()
        # TODO: self.grabMouse

        # NOW IT'S TIME TO GET PHYSICAL SCREEN CONFIGURATION
        self.xrandr = Xrandr(root=self.root, conn=self._conn)

        # TODO: self.update_net_desktops()

        # SETUP EVENT LOOP
        if not loop:
            loop = asyncio.new_event_loop()
        self._eventloop = loop
        self._eventloop.add_signal_handler(signal.SIGINT, self.stop)
        self._eventloop.add_signal_handler(signal.SIGTERM, self.stop)
        self._eventloop.add_signal_handler(signal.SIGCHLD, self.on_sigchld)
        self._eventloop.set_exception_handler(
            lambda loop, ctx: self.log.error(
                "Got an exception in {}: {}".format(loop, ctx))
        )
        fd = self._conn.get_file_descriptor()
        self._eventloop.add_reader(fd, self._xpoll)

        # HANDLE STANDARD EVENTS
        self.hook.register("MapRequest", self.on_map_request)
        self.hook.register("MapNotify", self.on_map_notify)
        self.hook.register("UnmapNotify", self.on_window_unmap)
        self.hook.register("KeyPress", self.on_key_press)
        # self.hook.register("KeyRelease", self.on_key_release)
        # self.hook.register("CreateNotify", self.on_window_create)
        self.hook.register("PropertyNotify", self.on_property_notify)
        self.hook.register("ClientMessage", self.on_client_message)
        self.hook.register("DestroyNotify", self.on_window_destroy)
        self.hook.register("EnterNotify", self.on_window_enter)
        self.hook.register("ConfigureRequest", self.on_configure_window)
        self.hook.register("MotionNotify", self.on_mouse_event)
        self.hook.register("ButtonPress", self.on_mouse_event)
        self.hook.register("ButtonRelease", self.on_mouse_event)
Example #59
0
File: wm.py Project: kopchik/swm
class WM:
    """
        Provides basic building blocks to make a window manager.
        It hides many dirty details about XCB. It was intended
        to provide minimum functionality, the rest supposed to
        be implemented by user in configuration file.
    """
    root = None   # type: Window
    atoms = None  # type: AtomVault

    def __init__(self, display=None, desktops=None, loop=None):
        self.log = Log("WM")
        # INIT SOME BASIC STUFF
        self.hook = Hook()
        self.windows = {}  # mapping between window id and Window
        self.win2desk = {}

        if not display:
            display = os.environ.get("DISPLAY")

        try:
            self._conn = xcffib.connect(display=display)
        except xcffib.ConnectionException:
            sys.exit("cannot connect to %s" % display)

        self.atoms = AtomVault(self._conn)
        self.desktops = desktops or [Desktop()]
        self.cur_desktop = self.desktops[0]
        self.cur_desktop.show()

        # CREATE ROOT WINDOW
        xcb_setup = self._conn.get_setup()
        xcb_screens = [i for i in xcb_setup.roots]
        self.xcb_default_screen = xcb_screens[self._conn.pref_screen]
        root_wid = self.xcb_default_screen.root
        self.root = Window(self, wid=root_wid, atoms=self.atoms, mapped=True)
        self.windows[root_wid] = self.root
#        for desktop in self.desktops:
#            desktop.windows.append(self.root)

        self.root.set_attr(
            eventmask=(
                  EventMask.StructureNotify
                | EventMask.SubstructureNotify
                | EventMask.FocusChange
                # | EventMask.SubstructureRedirect
                | EventMask.EnterWindow
                # | EventMask.LeaveWindow
                # | EventMask.PropertyChange
                | EventMask.OwnerGrabButton
            )
        )

        # INFORM X WHICH FEATURES WE SUPPORT
        self.root.props[self.atoms._NET_SUPPORTED] = [self.atoms[a] for a in SUPPORTED_ATOMS]

        # PRETEND TO BE A WINDOW MANAGER
        supporting_wm_check_window = self.create_window(-1, -1, 1, 1)
        supporting_wm_check_window.props['_NET_WM_NAME'] = "SWM"
        self.root.props['_NET_SUPPORTING_WM_CHECK'] = supporting_wm_check_window.wid
        self.root.props['_NET_NUMBER_OF_DESKTOPS'] = len(self.desktops)
        self.root.props['_NET_CURRENT_DESKTOP'] = 0

        # TODO: set cursor

        # EVENTS THAT HAVE LITTLE USE FOR US...
        self.ignoreEvents = {
            "KeyRelease",
            "ReparentNotify",
            # "CreateNotify",
            # DWM handles this to help "broken focusing windows".
            # "MapNotify",
            "ConfigureNotify",
            "LeaveNotify",
            "FocusOut",
            "FocusIn",
            "NoExposure",
        }
        # KEYBOARD
        self.kbd = Keyboard(xcb_setup, self._conn)
        self.mouse = Mouse(conn=self._conn, root=self.root)

        # FLUSH XCB BUFFER
        self.xsync()    # apply settings
        # the event loop is not yet there, but we might have some pending
        # events...
        self._xpoll()
        # TODO: self.grabMouse

        # NOW IT'S TIME TO GET PHYSICAL SCREEN CONFIGURATION
        self.xrandr = Xrandr(root=self.root, conn=self._conn)

        # TODO: self.update_net_desktops()

        # SETUP EVENT LOOP
        if not loop:
            loop = asyncio.new_event_loop()
        self._eventloop = loop
        self._eventloop.add_signal_handler(signal.SIGINT, self.stop)
        self._eventloop.add_signal_handler(signal.SIGTERM, self.stop)
        self._eventloop.add_signal_handler(signal.SIGCHLD, self.on_sigchld)
        self._eventloop.set_exception_handler(
            lambda loop, ctx: self.log.error(
                "Got an exception in {}: {}".format(loop, ctx))
        )
        fd = self._conn.get_file_descriptor()
        self._eventloop.add_reader(fd, self._xpoll)

        # HANDLE STANDARD EVENTS
        self.hook.register("MapRequest", self.on_map_request)
        self.hook.register("MapNotify", self.on_map_notify)
        self.hook.register("UnmapNotify", self.on_window_unmap)
        self.hook.register("KeyPress", self.on_key_press)
        # self.hook.register("KeyRelease", self.on_key_release)
        # self.hook.register("CreateNotify", self.on_window_create)
        self.hook.register("PropertyNotify", self.on_property_notify)
        self.hook.register("ClientMessage", self.on_client_message)
        self.hook.register("DestroyNotify", self.on_window_destroy)
        self.hook.register("EnterNotify", self.on_window_enter)
        self.hook.register("ConfigureRequest", self.on_configure_window)
        self.hook.register("MotionNotify", self.on_mouse_event)
        self.hook.register("ButtonPress", self.on_mouse_event)
        self.hook.register("ButtonRelease", self.on_mouse_event)

    def on_property_notify(self, evname, xcb_event):
        # TODO: messy ugly code
        wid = xcb_event.window
        atom = self.atoms.get_name(xcb_event.atom)
        # window = self.windows.get(wid, Window(wm=self, wid=wid, mapped=True))
        self.log.error("PropertyNotify: %s" % atom)
        run_("xprop -id %s %s" % (wid, atom))

    # TODO: dirty code, relocate to config
    def on_client_message(self, evname, xcb_event):
        self.log.error(dir(xcb_event))
        data = xcb_event.data
        resp_type = self.atoms.get_name(xcb_event.response_type)
        type = self.atoms.get_name(xcb_event.type)
        wid = xcb_event.window
        self.log.error("client message: resp_type={resp_type} window={wid} type={type} data={data}"  \
                       .format(**locals()))
        # 'bufsize', 'data', 'format', 'pack', 'response_type', 'sequence', 'synthetic', 'type', 'window']

        if type == '_NET_ACTIVE_WINDOW':
            window = self.windows[wid]
            window.rise()
            self.focus_on(window)

    def on_sigchld(self):
        """ Rip orphans. """
        while True:
            try:
                pid, status = os.waitpid(-1, os.WNOHANG)
                if (pid, status) == (0, 0):
                    # no child to rip
                    break
                self.log.notice("ripped child PID=%s" % pid)
            except ChildProcessError:
                break

    def on_map_request(self, evname, xcb_event):
        """ Map request is a request to draw the window on screen. """
        wid = xcb_event.window
        if wid not in self.windows:
            window = self.on_new_window(wid)
        else:
            window = self.windows[wid]
            self.log.on_map_request.debug("map request for %s" % window)
        window.show()
        if window.above_all:
            window.rise()
        if window.can_focus:
            window.focus()

    def on_new_window(self, wid):
        """ Registers new window. """
        window = Window(wm=self, wid=wid, atoms=self.atoms, mapped=True)
        # call configuration hood first
        # to setup attributes like 'sticky'
        self.hook.fire("new_window", window)
        self.log.on_new_window.debug(
            "new window is ready: %s" % window)
        self.windows[wid] = window
        self.win2desk[window] = self.cur_desktop
        if window.sticky:
            for desktop in self.desktops:
                desktop.add(window)
        else:
            self.cur_desktop.windows.append(window)
        return window

    def on_map_notify(self, evname, xcb_event):
        wid = xcb_event.window
        if wid not in self.windows:
            window = self.on_new_window(wid)
        else:
            window = self.windows[wid]
        window.mapped = True

        if window.above_all:
            window.rise()
        # if window.can_focus:
        #     window.focus()

        self.log.on_map_notify.debug("map notify for %s" % window)

    def on_window_unmap(self, evname, xcb_event):
        wid = xcb_event.window
        if wid not in self.windows:
            return
        window = self.windows[wid]
        window.mapped = False
        self.hook.fire("window_unmap", window)

    def on_window_destroy(self, evname, xcb_event):
        wid = xcb_event.window
        if wid not in self.windows:
            return

        window = self.windows[wid]
        assert isinstance(window, Window), "it's not a window: %s (%s)" % (
            window, type(window))

        for desktop in self.desktops:
            try:
                desktop.windows.remove(window)
                self.log.debug("%s removed from %s" % (self, desktop))
            except ValueError:
                pass
        del self.windows[wid]
        if window in self.win2desk:
            del self.win2desk[window]

    def on_window_enter(self, evname, xcb_event):
        wid = xcb_event.event
        if wid not in self.windows:
            # self.log.on_window_enter.error("no window with wid=%s" % wid)
            self.hook.fire("unknown_window", wid)
            return
        window = self.windows[wid]
        # self.log.on_window_enter("window_enter: %s %s" % (wid, window))
        self.hook.fire("window_enter", window)

    def grab_key(self, modifiers, key, owner_events=False, window=None):
        """ Intercept this key when it is pressed. If owner_events=False then
            the window in focus will not receive it. This is useful from WM hotkeys.
        """
        # TODO: check if key already grabbed?
        # Here is how X works with keys:
        # key => keysym => keycode
        # where `key' is something like 'a', 'b' or 'Enter',
        # `keysum' is what should be written on they key cap (physical keyboard)
        # and `keycode' is a number reported by the keyboard when the key is pressed.
        # Modifiers are keys like Shift, Alt, Win and some other buttons.
        self.log.grab_key.debug("intercept keys: %s %s" % (modifiers, key))

        if window is None:
            window = self.root

        keycode = self.kbd.key_to_code(key)
        modmask = get_modmask(modifiers)  # TODO: move to Keyboard
        event = ("on_key_press", modmask, keycode)
        pointer_mode = xproto.GrabMode.Async
        keyboard_mode = xproto.GrabMode.Async
        self._conn.core.GrabKey(
            owner_events,
            window.wid,
            modmask,
            keycode,
            pointer_mode,
            keyboard_mode
        )
        self.flush()  # TODO: do we need this?
        return event

    def on_key_press(self, evname, xcb_event):
        # TODO: ignore capslock, scrolllock and other modifiers?
        modmap = xcb_event.state
        keycode = xcb_event.detail
        event = ("on_key_press", modmap, keycode)
        self.hook.fire(event)

    def on_key_release(self, evname, xcb_event):
        modmap = xcb_event.state
        keycode = xcb_event.detail
        event = ("on_key_release", modmap, keycode)
        self.hook.fire(event)

    def grab_mouse(self, modifiers, button, owner_events=False, window=None):
        # http://www.x.org/archive/X11R7.7/doc/man/man3/xcb_grab_button.3.xhtml
        wid = (window or self.root).wid
        event_mask = xcffib.xproto.EventMask.ButtonPress |    \
            xcffib.xproto.EventMask.ButtonRelease |  \
            xcffib.xproto.EventMask.Button1Motion
        modmask = get_modmask(modifiers)
        pointer_mode = xproto.GrabMode.Async      # I don't know what it is
        keyboard_mode = xproto.GrabMode.Async     # do not block other keyboard events
        confine_to = xcffib.xproto.Atom._None     # do not restrict cursor movements
        cursor = xcffib.xproto.Atom._None         # do not change cursor
        event = ("on_mouse", modmask, button)     # event to be used in hooks

        self._conn.core.GrabButton(
            owner_events,
            wid,
            event_mask,
            pointer_mode,
            keyboard_mode,
            confine_to,
            cursor,
            button,
            modmask,
        )
        self.flush()  # TODO: do we need this?
        return event

    def hotkey(self, keys, cmd):
        """ Setup hook to launch a command on specific hotkeys. """
        @self.hook(self.grab_key(*keys))
        def cb(event):
            run_(cmd)

    def focus_on(self, window, warp=False):
        """ Focuses on given window. """
        self.cur_desktop.focus_on(window, warp)
        self.root.set_prop('_NET_ACTIVE_WINDOW', window.wid)

    def switch_to(self, desktop: Desktop):
        """ Switches to another desktop. """
        if isinstance(desktop, int):
            desktop = self.desktops[desktop]
        if self.cur_desktop == desktop:
            self.log.notice("attempt to switch to the same desktop")
            return
        self.log.debug("switching from {} to {}".format(
            self.cur_desktop, desktop))
        self.cur_desktop.hide()
        self.cur_desktop = desktop
        self.cur_desktop.show()
        # TODO: move this code to Desktop.show()
        self.root.props[self.atom._NET_CURRENT_DESKTOP] = desktop.id

    def relocate_to(self, window: Window, to_desktop: Desktop):
        """ Relocates window to a specific desktop. """
        if window.sticky:
            self.log.debug(
                "%s is meant to be on all desktops, cannot relocate to specific one" % window)
            return

        from_desktop = self.cur_desktop

        if from_desktop == to_desktop:
            self.log.debug(
                "no need to relocate %s because remains on the same desktop" % window)
            return

        from_desktop.remove(window)
        to_desktop.add(window)

    def on_mouse_event(self, evname, xcb_event):
        """evname is one of ButtonPress, ButtonRelease or MotionNotify."""
        # l = [(attr, getattr(xcb_event, attr)) for attr in sorted(dir(xcb_event)) if not attr.startswith('_')]
        # print(evname)
        # print(l)
        modmask = xcb_event.state & 0xff  # TODO: is the mask correct?
        if evname == 'MotionNotify':
            button = 1  # TODO
        else:
            button = xcb_event.detail

        event = ('on_mouse', modmask, button)
        # print(event)
        self.hook.fire(event, evname, xcb_event)

    def on_configure_window(self, _, event):
        # This code is so trivial that I just took it from fpwm as is :)
        values = []
        if event.value_mask & ConfigWindow.X:
            values.append(event.x)
        if event.value_mask & ConfigWindow.Y:
            values.append(event.y)
        if event.value_mask & ConfigWindow.Width:
            values.append(event.width)
        if event.value_mask & ConfigWindow.Height:
            values.append(event.height)
        if event.value_mask & ConfigWindow.BorderWidth:
            values.append(event.border_width)
        if event.value_mask & ConfigWindow.Sibling:
            values.append(event.sibling)
        if event.value_mask & ConfigWindow.StackMode:
            values.append(event.stack_mode)
        self._conn.core.ConfigureWindow(event.window, event.value_mask, values)

    def create_window(self, x, y, width, height):
        """ Create a window. Right now only used for initialization, see __init__. """
        wid = self._conn.generate_id()
        self._conn.core.CreateWindow(
            self.xcb_default_screen.root_depth,
            wid,
            self.xcb_default_screen.root,
            x, y, width, height, 0,
            WindowClass.InputOutput,
            self.xcb_default_screen.root_visual,
            CW.BackPixel | CW.EventMask,
            [
                self.xcb_default_screen.black_pixel,
                EventMask.StructureNotify | EventMask.Exposure
            ]
        )
        return Window(self, wid=wid, atoms=self.atoms)

    def scan(self, focus=True):
        """ Gets all windows in the system. """
        self.log.debug("performing scan of all mapped windows")
        q = self._conn.core.QueryTree(self.root.wid).reply()
        for wid in q.children:
            # attrs=self._conn.core.GetWindowAttributes(wid).reply()
            # print(attrs, type(attrs))
            # if attrs.map_state == xproto.MapState.Unmapped:
            #    self.log.scan.debug(
            #        "window %s is not mapped, skipping" % wid)  # TODO
            #    continue
            if wid not in self.windows:
                self.on_new_window(wid)
        self.log.scan.info("the following windows are active: %s" %
                           sorted(self.windows.values()))

        if focus:
            windows = sorted(self.windows.values())
            windows = list(filter(lambda w: w != self.root and not w.skip, windows))
            if windows:
                # on empty desktop there is nothing to focus on
                self.cur_desktop.focus_on(windows[-1], warp=True)

    def finalize(self):
        """ This code is run when event loop is terminated. """
        pass  # currently nothing to do here

    def flush(self):
        """ Force pending X request to be sent.
            By default XCB aggressevly buffers for performance reasons. """
        return self._conn.flush()

    def xsync(self):
        """ Flush XCB queue and wait till it is processed by X server. """
        # The idea here is that pushing an innocuous request through the queue
        # and waiting for a response "syncs" the connection, since requests are
        # serviced in order.
        self._conn.core.GetInputFocus().reply()

    def stop(self, xserver_dead=False):
        """ Stop WM to quit. """
        self.hook.fire("on_exit")
        # display all hidden windows
        try:
            if not xserver_dead:
                for window in self.windows.values():
                    window.show()
                self.xsync()
        except Exception as err:
            self.log.stop.error("error on stop: %s" % err)
        self.log.stop.debug("stopping event loop")
        self._eventloop.stop()

    def replace(self, execv_args):
        self.log.notice("replacing current process with %s" % (execv_args,))
        self.stop()
        import os
        os.execv(*execv_args)

    def loop(self):
        """ DITTO """
        self.scan()
        try:
            self._eventloop.run_forever()
        finally:
            self.finalize()

    def _xpoll(self):
        """ Fetch incomming events (if any) and call hooks. """

        # OK, kids, today I'll teach you how to write reliable enterprise
        # software! You just catch all the exceptions in the top-level loop
        # and ignore them. No, I'm kidding, these exceptions are no use
        # for us because we don't care if a window cannot be drawn or something.
        # We actually only need to handle just a few events and ignore the rest.
        # Exceptions happen because of the async nature of X.

        while True:
            try:
                xcb_event = self._conn.poll_for_event()
                if not xcb_event:
                    break
                evname = xcb_event.__class__.__name__
                if evname.endswith("Event"):
                    evname = evname[:-5]
                if evname in self.ignoreEvents:
                    self.log._xpoll.info("ignoring %s" % xcb_event)
                    continue
                self.log._xpoll.critical("got %s %s" % (evname, xcb_event))
                self.hook.fire(evname, xcb_event)
                self.flush()  # xcb doesn't flush implicitly
            except (WindowError, AccessError, DrawableError):
                self.log.debug("(minor exception)")
            except Exception as e:
                self.log._xpoll.error(traceback.format_exc())
                error_code = self._conn.has_error()
                if error_code:
                    error_string = XCB_CONN_ERRORS[error_code]
                    self.log.critical("Shutting down due to X connection error %s (%s)" %
                                      (error_string, error_code))
                    self.stop(xserver_dead=True)
                    break