예제 #1
0
def main(t):
    curses.curs_set(0)
    a, b = curses.mousemask(curses.ALL_MOUSE_EVENTS
                            | curses.REPORT_MOUSE_POSITION)
    t.addstr(2, 0, f"a={a}, b={b}")

    pt = Point()

    curses.delay_output(100)
    mx, my = 0, 0
    while True:
        # draw
        t.addstr(0, 0, f"x={mx}, y={my}")
        a, mx, my, _, mask = curses.getmouse()

        t.addstr(4, 0, f"x={pt.x}, y={pt.y}")

        # input
        windll.user32.GetCursorPos(byref(pt))
        c = t.getch()
        if c == ord('q'):
            break
        if c == curses.KEY_MOUSE:
            t.addstr(1, 0, "MOUSE")
            a, mx, my, _, mask = curses.getmouse()
 def check_on_click(self, key : int):
     key = self.renderer.stdscr.getch()
     if key == curses.KEY_MOUSE:
         self.mousex, self.mousey = curses.getmouse()[1], curses.getmouse()[2]
         if self.mousex >= self.posx:
             if self.mousex <= self.posx + self.xsize:
                 if self.mousey >= self.pos_y:
                     if self.mousey <= self.posy + self.ysize:
                         return True
예제 #3
0
 def handle_input(self, key):
     if key == curses.KEY_LEFT: self.cursor_move(-1, 0)
     elif key == curses.KEY_UP: self.cursor_move(0, -1)
     elif key == curses.KEY_RIGHT: self.cursor_move(1, 0)
     elif key == curses.KEY_DOWN: self.cursor_move(0, 1)
     elif key == curses.KEY_DC: self.handle_generic_input(' ')  # delete
     elif key == curses.KEY_BACKSPACE:
         self.cursor_to_next_char(-1)
         self.handle_generic_input(' ', 0)  # backspace, don't move cursor
     elif key == ord('\t'):
         self.cursor_to_next_word(1)  # tab
     elif key == curses.KEY_BTAB:
         self.cursor_to_next_word(-1)  # shift-tab
     elif key == curses.KEY_HOME:
         self.cursor_home()
     elif key == curses.KEY_END:
         self.cursor_end()
     elif len(input_to_chr(key)) == 1 and input_to_chr(
             key) in string.ascii_letters + string.digits + 'äöüÄÖÜ ':
         self.handle_generic_input(key)
     elif key == curses.KEY_MOUSE:
         _id, x, y, z, bstate = curses.getmouse()
         self.handle_mouse_input(x, y, bstate)
     else:
         log.info("ignored key '{}'".format(key))
         return False  # did not handle key, no need to update screen
     return True
예제 #4
0
def getmouse():
    if not use_mouse():
        return -1, -1, -1, -1, 0
    try:
        return curses.getmouse()
    except curses.error:  # for *BSD
        return -1, -1, -1, -1, 0
예제 #5
0
def main(screen):
	GLBL['screen'] = screen;
	CuInit(screen)

	mw = CuMainWindow(None)
	mw.drawBorder()

	it = 1
	event = 0

	while True:
		mw.getWin().addstr(8, 10, "Iteration:" + str(it))
		it += 1
		mw.getWin().addstr(9, 10, "Event:" + str(event))

		curses.panel.update_panels()
		screen.refresh()

		event = screen.getch()

		if event == curses.ERR: break
		if event == ord("q"): break 
		if event == curses.KEY_MOUSE:
			# _, mx, my, _, _ = curses.getmouse()
			# y, x = screen.getyx()
			mw.getWin().addstr(10, 10, "pippo")
			mw.getWin().addstr(11, 10, str(curses.getmouse()) + "                      ")
		if event == curses.KEY_RESIZE:
			GLBL['maxY'], GLBL['maxX'] = screen.getmaxyx()
			mw.resize(GLBL['maxX'], GLBL['maxY'])
			mw.drawBorder()
			mw.getWin().addstr(13, 10, "---RESIZE---")
예제 #6
0
파일: window.py 프로젝트: beanbeam/scurses
 def read_key(self, flush_first=False):
   if flush_first:
     self.flush_input()
   key = self._window.getch()
   if key == curses.KEY_MOUSE:
     try:
       mouse = curses.getmouse()
       if mouse[4] & curses.BUTTON1_RELEASED:
         key = "MOUSE_1RELEASED"
       elif (mouse[4] & curses.BUTTON2_RELEASED        |
             mouse[4] & curses.BUTTON2_CLICKED         |
             mouse[4] & curses.BUTTON2_DOUBLE_CLICKED  |
             mouse[4] & curses.BUTTON2_TRIPLE_CLICKED  |
            mouse[4] & curses.BUTTON2_PRESSED):
         key = "MOUSE_SCROLL_DOWN"
       elif mouse[4] & curses.BUTTON3_RELEASED:
         key = "MOUSE_3RELEASED"
       elif (mouse[4] & curses.BUTTON4_RELEASED        |
             mouse[4] & curses.BUTTON4_CLICKED         |
             mouse[4] & curses.BUTTON4_DOUBLE_CLICKED  |
             mouse[4] & curses.BUTTON4_TRIPLE_CLICKED  |
             mouse[4] & curses.BUTTON4_PRESSED):
         key = "MOUSE_SCROLL_UP"
       else: key = "MOUSE_UNKNOWN"
       self.mouse_location = (mouse[1], mouse[2])
     except:
       key = "MOUSE_UNKNOWN"
   else:
     curses.ungetch(key)
     key = self._window.getkey()
     if key == "KEY_RESIZE": return "WINDOW_RESIZED"
   return key
예제 #7
0
def on_mouse():
    '''Update selected line / sort'''
    _, x, y, z, bstate =  curses.getmouse()

    # Left button click ?
    if bstate & curses.BUTTON1_CLICKED:
        # Is it title line ?
        if y == 0:
            # Determine sort column based on offset / col width
            x_max = 0
            for col in COLUMNS:
                if not col.width:
                    set_sort_col(col.col_sort)
                elif x < x_max+col.width:
                    set_sort_col(col.col_sort)
                else:
                    x_max += col.width + 1
                    continue
                return 2
        # Is it a cgroup line ?
        elif y <= len(CONFIGURATION['cgroups']):
            if CONFIGURATION['follow']:
                CONFIGURATION['selected_line_name'] = CONFIGURATION['cgroups'][y-1]
            else:
                CONFIGURATION['selected_line_num'] = y-1
            return 2
    return 1
예제 #8
0
def loop():
    try:
        while True:
            key = cw.screen.getch()

            if key == curses.KEY_RESIZE:
                cw.resize()

            if key == curses.KEY_MOUSE:
                _, mx, my, _, _ = curses.getmouse()

                win = cw.getWindow(my,mx)
                if win:
                    win.win.addstr(1,1,"HERE")
                cw.refresh()
                #wy,wx = cw.Map.win.getparyx()
                #cw.Map.win.erase()
                #cw.screen.addstr(my,mx,str(my - wy) + "  " + str(mx - wx))
                #cw.refresh()

            if key==ord('q'):
                break

        cw.quit()
    except:
        cw.quit()
        traceback.print_exc()
예제 #9
0
 def get_cmds(self):
     m = {'cmd': None}
     c = self.stdscr.getch()
     if c == -1:
         m['cmd'] = None
     if c == curses.KEY_LEFT:
         m['cmd'] = "CONFIG_A"
     if c == curses.KEY_RIGHT:
         m['cmd'] = "CONFIG_B"
     # if c == curses.KEY_UP:
     #     m['cmd'] = "LOAD"
     # if c == curses.KEY_DOWN:
     #     m['cmd'] = "SAVE"
     if c == ord('Q'):
         m['cmd'] = 'quit'
     if c == ord('s'):
         m['cmd'] = 'toggle_save'
     # if c == ord('S'):
     #     m['cmd'] = 'save'
     if c == ord(' '):
         m['cmd'] = 'step_beat'
     if c == curses.KEY_MOUSE:
         _m = curses.getmouse()
         m = self.get_mouse_zone(_m)
     return m
예제 #10
0
def input_thread(**kwargs):
    glopnet = kwargs.get('glopnet')
    stop_lock = kwargs.get('stop_lock')
    input_queue = kwargs.get('input_queue')
    curses_lock = kwargs.get('curses_lock')

    assert isinstance(glopnet, Glopnet)

    while True:
        if stop_lock.acquire(blocking=False):
            break

        curses_lock.acquire(
        )  # =============================================================== CURSES LOCK ACQUIRE
        while True:
            ch = glopnet.stdscr.getch()
            if ch == -1:
                break
            elif ch == curses.KEY_MOUSE:
                mouseinfo = (-1, -1, -1, -1, -1)
                try:
                    mouseinfo = curses.getmouse()
                except curses.error:
                    pass
                input_queue.put(Mouse(info=mouseinfo))
            elif ch == curses.KEY_RESIZE:
                glopnet.resize_screen()
            else:
                s = str(curses.keyname(ch))
                input_queue.put(Key(ch, mod=False, s=s))
        curses_lock.release(
        )  # =============================================================== CURSES LOCK RELEASE

        sleep(SPF / 16.0)
예제 #11
0
    def getInput(self, screen):
        c = screen.getch()
        if c != -1:
            if 0 < c < 256:
                if chr(c) in 'qQ':
                    self.exitFlag = True
                    return False
            elif c == curses.KEY_RESIZE:
                if self.activeResize:
                    return False
            elif c == curses.KEY_MOUSE:
                mouseId, mouseX, mouseY, mouseZ, bState = curses.getmouse()

                if bState & KB["left"]['click']:
                    for w in self.subWindows:
                        if w.belongsWindow(mouseX, mouseY):
                            w.click(mouseX - w.x, mouseY - w.y)

                elif bState & KB["wheel"]["up"]:
                    for w in self.subWindows:
                        w.mouseWheel(mouseX, mouseY,
                                     directionUp=True)  # x,y均为0,没法使用,但又非传递不可

                elif bState & KB["wheel"]["down"]:
                    for w in self.subWindows:
                        w.mouseWheel(mouseX, mouseY,
                                     directionUp=False)  # x,y均为0,没法使用,但又非传递不可
        return True
예제 #12
0
 def gather_input(self, win):
     """
     Read and process a part of the available input from stdin, 
     possibly pausing a few ms to wait for additional input.
     Execute all functions enqueued by run_soon() at the end.
     You should call this in a loop.
     """
     curses.halfdelay(7)
     win.nodelay(1)
     while True:
         try:
             key = win.get_wch()
         except curses.error:
             break
         curses.cbreak()
         if key == curses.KEY_MOUSE:
             try:
                 self.input_mouse(*curses.getmouse())
             except curses.error:
                 pass
         else:
             self.input_key(key)
     if self.runqueue:
         rq = self.runqueue
         self.runqueue = []
         for f in rq:
             f()
     return self.key_events != [] or self.mouse_events != []
예제 #13
0
    def _encode_mouse_event(self):
        # convert to escape sequence
        last = next = self.last_bstate
        (id,x,y,z,bstate) = curses.getmouse()
        
        mod = 0
        if bstate & curses.BUTTON_SHIFT:    mod |= 4
        if bstate & curses.BUTTON_ALT:        mod |= 8
        if bstate & curses.BUTTON_CTRL:        mod |= 16
        
        l = []
        def append_button( b ):
            b |= mod
            l.extend([ 27, ord('['), ord('M'), b+32, x+33, y+33 ])
        
        if bstate & curses.BUTTON1_PRESSED and last & 1 == 0:
            append_button( 0 )
            next |= 1
        if bstate & curses.BUTTON2_PRESSED and last & 2 == 0:
            append_button( 1 )
            next |= 2
        if bstate & curses.BUTTON3_PRESSED and last & 4 == 0:
            append_button( 2 )
            next |= 4
        if bstate & curses.BUTTON4_PRESSED and last & 8 == 0:
            append_button( 64 )
            next |= 8
        if bstate & curses.BUTTON1_RELEASED and last & 1:
            append_button( 0 + escape.MOUSE_RELEASE_FLAG )
            next &= ~ 1
        if bstate & curses.BUTTON2_RELEASED and last & 2:
            append_button( 1 + escape.MOUSE_RELEASE_FLAG )
            next &= ~ 2
        if bstate & curses.BUTTON3_RELEASED and last & 4:
            append_button( 2 + escape.MOUSE_RELEASE_FLAG )
            next &= ~ 4
        if bstate & curses.BUTTON4_RELEASED and last & 8:
            append_button( 64 + escape.MOUSE_RELEASE_FLAG )
            next &= ~ 8
        
        if bstate & curses.BUTTON1_DOUBLE_CLICKED:
            append_button( 0 + escape.MOUSE_MULTIPLE_CLICK_FLAG )
        if bstate & curses.BUTTON2_DOUBLE_CLICKED:
            append_button( 1 + escape.MOUSE_MULTIPLE_CLICK_FLAG )
        if bstate & curses.BUTTON3_DOUBLE_CLICKED:
            append_button( 2 + escape.MOUSE_MULTIPLE_CLICK_FLAG )
        if bstate & curses.BUTTON4_DOUBLE_CLICKED:
            append_button( 64 + escape.MOUSE_MULTIPLE_CLICK_FLAG )

        if bstate & curses.BUTTON1_TRIPLE_CLICKED:
            append_button( 0 + escape.MOUSE_MULTIPLE_CLICK_FLAG*2 )
        if bstate & curses.BUTTON2_TRIPLE_CLICKED:
            append_button( 1 + escape.MOUSE_MULTIPLE_CLICK_FLAG*2 )
        if bstate & curses.BUTTON3_TRIPLE_CLICKED:
            append_button( 2 + escape.MOUSE_MULTIPLE_CLICK_FLAG*2 )
        if bstate & curses.BUTTON4_TRIPLE_CLICKED:
            append_button( 64 + escape.MOUSE_MULTIPLE_CLICK_FLAG*2 )

        self.last_bstate = next
        return l
예제 #14
0
def demo_5(win, inp):
    """Cursor movement."""
    ymin,xmin = 0,0
    ymin += 1
    xmin += 1
    ymax,xmax = win.getmaxyx()
    ymax -= 2
    xmax -= 2
    x = 1
    y = 1
    win.erase()
    win.bkgd(' ', pairs[('black','lgray')])
    win.box()
    if inp is not None and inp > -1:
        if inp in SKGROUPS['ARROW']:
            if inp in SKEYS['UP']:
                y = max(y-1,ymin)
            elif inp in SKEYS['DOWN']:
                y = min(y+1, ymax)
            elif inp in SKEYS['LEFT']:
                x = max(x-1, xmin)
            elif inp in SKEYS['RIGHT']:
                x = min(x+1, xmax)
            win.addch(y, x, 'X')
        elif inp in SKEYS['MOUSE']:
            _, mx, my, _, click = curses.getmouse()
            if click in SGL_CLICKS:
                if win.enclose(my,mx):
                    # rev = not rev
                    win.addstr(y, x, str((mx,my,click)))
    win.noutrefresh()
예제 #15
0
  def main(self):
    game = game_of_life(self.BOARD_X, self.BOARD_Y)
    if self.pause:
      self.screen.nodelay(0)
      self.step = 0

    while True:
      try:
        k = self.screen.getch()
        if k==ord(' '):
          self.pause = not self.pause
          if self.pause:
            self.screen.nodelay(0)
            self.step = 0
          else: 
            self.screen.nodelay(1)
            self.step = STEP
        elif k==curses.KEY_MOUSE:
          _, x, y, _, state = curses.getmouse()
          if x%2==0:    #map from visual with spaces in between each spot to board
            x = x/2
            if state==curses.BUTTON1_RELEASED and 0<=x<self.BOARD_X and 0<=y<self.BOARD_Y:
              board[x,y] = not board[x,y]
              self.render(board)
        else:
          time.sleep(self.step)
          board = next(game)
          self.render(board)
  
      except curses.error:
        pass
예제 #16
0
    def _encode_mouse_event(self):
        # convert to escape sequence
        last = next = self.last_bstate
        (id,x,y,z,bstate) = curses.getmouse()

        mod = 0
        if bstate & curses.BUTTON_SHIFT:    mod |= 4
        if bstate & curses.BUTTON_ALT:        mod |= 8
        if bstate & curses.BUTTON_CTRL:        mod |= 16

        l = []
        def append_button( b ):
            b |= mod
            l.extend([ 27, ord('['), ord('M'), b+32, x+33, y+33 ])

        if bstate & curses.BUTTON1_PRESSED and last & 1 == 0:
            append_button( 0 )
            next |= 1
        if bstate & curses.BUTTON2_PRESSED and last & 2 == 0:
            append_button( 1 )
            next |= 2
        if bstate & curses.BUTTON3_PRESSED and last & 4 == 0:
            append_button( 2 )
            next |= 4
        if bstate & curses.BUTTON4_PRESSED and last & 8 == 0:
            append_button( 64 )
            next |= 8
        if bstate & curses.BUTTON1_RELEASED and last & 1:
            append_button( 0 + escape.MOUSE_RELEASE_FLAG )
            next &= ~ 1
        if bstate & curses.BUTTON2_RELEASED and last & 2:
            append_button( 1 + escape.MOUSE_RELEASE_FLAG )
            next &= ~ 2
        if bstate & curses.BUTTON3_RELEASED and last & 4:
            append_button( 2 + escape.MOUSE_RELEASE_FLAG )
            next &= ~ 4
        if bstate & curses.BUTTON4_RELEASED and last & 8:
            append_button( 64 + escape.MOUSE_RELEASE_FLAG )
            next &= ~ 8

        if bstate & curses.BUTTON1_DOUBLE_CLICKED:
            append_button( 0 + escape.MOUSE_MULTIPLE_CLICK_FLAG )
        if bstate & curses.BUTTON2_DOUBLE_CLICKED:
            append_button( 1 + escape.MOUSE_MULTIPLE_CLICK_FLAG )
        if bstate & curses.BUTTON3_DOUBLE_CLICKED:
            append_button( 2 + escape.MOUSE_MULTIPLE_CLICK_FLAG )
        if bstate & curses.BUTTON4_DOUBLE_CLICKED:
            append_button( 64 + escape.MOUSE_MULTIPLE_CLICK_FLAG )

        if bstate & curses.BUTTON1_TRIPLE_CLICKED:
            append_button( 0 + escape.MOUSE_MULTIPLE_CLICK_FLAG*2 )
        if bstate & curses.BUTTON2_TRIPLE_CLICKED:
            append_button( 1 + escape.MOUSE_MULTIPLE_CLICK_FLAG*2 )
        if bstate & curses.BUTTON3_TRIPLE_CLICKED:
            append_button( 2 + escape.MOUSE_MULTIPLE_CLICK_FLAG*2 )
        if bstate & curses.BUTTON4_TRIPLE_CLICKED:
            append_button( 64 + escape.MOUSE_MULTIPLE_CLICK_FLAG*2 )

        self.last_bstate = next
        return l
예제 #17
0
파일: t.py 프로젝트: int3l/explains
def c_main(stdscr: curses._CursesWindow) -> int:
    curses.mousemask(-1)
    curses.mouseinterval(0)

    pressed = False
    x, y = 0, 0

    stdscr.addstr('hello hello world')

    while True:
        stdscr.erase()
        stdscr.addstr('click anywhere!')
        if pressed:
            for y in range(y - 1, y + 2):
                stdscr.addstr(y, x - 1, 'XXX')

        c = stdscr.get_wch()
        if c == 'q':
            return 0
        elif c == curses.KEY_MOUSE:
            _, x, y, _, bstate = curses.getmouse()
            if bstate & curses.BUTTON1_PRESSED:
                pressed = True
            elif bstate & curses.BUTTON1_RELEASED:
                pressed = False
        else:
            raise AssertionError(c)
예제 #18
0
	def _callmouse(self, *args):
		'''Run a mouse's callback. Saves invalid mouse data for next call'''
		chars = [i for i in args[-1] if i != curses.KEY_MOUSE]
		args = args[:-1]
		if chars[0] != -1:
			#control not returned to loop until later
			asyncio.get_event_loop().call_soon(
				partial_apply(self, chars, *args, raise_=False))
		try:
			if self._last_mouse is not None:
				x, y, state = self._last_mouse	#pylint: disable=unpacking-non-sequence
				KeyContainer._last_mouse = None
			else:
				_, x, y, _, state = curses.getmouse()
			error_sig = "..."
			if state not in self._mouse:
				if -1 not in self._mouse:
					KeyContainer._last_mouse = (x, y, state)
					raise KeyException
				error_sig = "..., state"
				args = (*args, state)
				state = -1
			try:
				return self._mouse[state](chars, *args, x, y)
			except TypeError:
				return self._mouse[state](chars, *args)
		except TypeError as exc:
			raise TypeError(self._MOUSE_ERROR.format(error_sig
				, self._mouse[state])) from exc
		except curses.error:
			pass
		raise KeyException
예제 #19
0
파일: core.py 프로젝트: Towdium/PyGraphicsT
        def run():
            # mouse event
            if c == _curses.KEY_MOUSE:
                try:
                    _, x, y, _, state = _curses.getmouse()
                    if not self.interface.on_mouse(x, y, state):
                        _dist(self.mouse_lsnr, lambda l: l(x, y, state))

                except _curses.error:
                    pass

            # resize event
            elif c == _curses.KEY_RESIZE:
                y, x = self._window.getmaxyx()
                self.state = Window.STATE_LAYOUT
                self.interface.on_layout(x, y)
                self._window.clear()
                self.interface.on_canvas(self._canvas(0, 0))
                self.interface.on_draw()
                self.state = Window.STATE_SERVE

            # key event
            else:
                if not self.interface.on_key(c):
                    _dist(self.key_lsnr, lambda w: w(c))
예제 #20
0
    def my_get_event(self):
        """
        Check for any event without waiting.
        """
        # Look for a new event and consume it if there is one.
        key = 0
        while key != -1:
            # Get the next key
            key = self._screen.getch()

            if key == curses.KEY_RESIZE:
                # Handle screen resize
                self._re_sized = True
            elif key == curses.KEY_MOUSE:
                # Translate into a MouseEvent object.
                _, x, y, _, bstate = curses.getmouse()
                buttons = 0
                # Some Linux modes only report clicks, so check for any
                # button down or click events.
                if (bstate & curses.BUTTON1_PRESSED != 0 or
                        bstate & curses.BUTTON1_CLICKED != 0):
                    buttons = MouseEvent.LEFT_CLICK
                elif (bstate & curses.BUTTON3_PRESSED != 0 or
                        bstate & curses.BUTTON3_CLICKED != 0):
                    buttons = MouseEvent.RIGHT_CLICK
                elif bstate & curses.BUTTON1_DOUBLE_CLICKED != 0:
                    buttons = MouseEvent.DOUBLE_CLICK
                buttons = (bstate if type(bstate) == int and buttons == 0 else buttons)
                buttons = 0 if buttons not in [0, 1, 2, 4] else buttons
                return MouseEvent(x, y, buttons)
            elif key != -1:
                # Handle any byte streams first
                logger.debug("Processing key: %x", key)
                if self._unicode_aware and key > 0:
                    if key & 0xC0 == 0xC0:
                        self._bytes_to_return = struct.pack(b"B", key)
                        self._bytes_to_read = bin(key)[2:].index("0") - 1
                        logger.debug("Byte stream: %d bytes left",
                                     self._bytes_to_read)
                        continue
                    elif self._bytes_to_read > 0:
                        self._bytes_to_return += struct.pack(b"B", key)
                        self._bytes_to_read -= 1
                        if self._bytes_to_read > 0:
                            continue
                        else:
                            key = ord(self._bytes_to_return.decode("utf-8"))

                # Handle a genuine key press.
                logger.debug("Returning key: %x", key)
                if key in self._KEY_MAP:
                    return KeyboardEvent(self._KEY_MAP[key])
                elif key != -1:
                    return KeyboardEvent(key)



        # If we get here, we've fully processed the event queue and found
        # nothing interesting.
        return None
예제 #21
0
    def _curses_screen_get_event(self, ):
        """
        Check for an event without waiting. This monkey patch adds support for the mouse
        scroll
        """
        import curses
        # Spin through notifications until we find something we want.
        key = 0
        while key != -1:
            # Get the next key
            key = self.screen._screen.getch()

            if key == curses.KEY_RESIZE:
                # Handle screen resize
                self.screen._re_sized = True
            elif key == curses.KEY_MOUSE:
                # Handle a mouse event
                _, x, y, _, bstate = curses.getmouse()
                buttons = 0
                # Some Linux modes only report clicks, so check for any
                # button down or click events.
                if (bstate & curses.BUTTON1_PRESSED != 0 or
                        bstate & curses.BUTTON1_CLICKED != 0):
                    buttons |= MouseEvent.LEFT_CLICK
                if (bstate & curses.BUTTON3_PRESSED != 0 or
                        bstate & curses.BUTTON3_CLICKED != 0):
                    buttons |= MouseEvent.RIGHT_CLICK
                if bstate & curses.BUTTON1_DOUBLE_CLICKED != 0:
                    buttons |= MouseEvent.DOUBLE_CLICK
                if (bstate & curses.A_LOW != 0 or
                        bstate & curses.A_LOW != 0):
                    # scroll down
                    buttons |= DOMMouseEvent.MOUSE_SCROLL_DOWN
                if (bstate & curses.BUTTON4_PRESSED != 0 or
                        bstate & curses.BUTTON4_CLICKED != 0):
                    # scroll up
                    buttons |= DOMMouseEvent.MOUSE_SCROLL_UP
                return MouseEvent(x, y, buttons)
            elif key != -1:
                # Handle any byte streams first
                if self.screen._unicode_aware and key > 0:
                    if key & 0xC0 == 0xC0:
                        self.screen._bytes_to_return = struct.pack(b"B", key)
                        self.screen._bytes_to_read = bin(key)[2:].index("0") - 1
                        continue
                    elif self.screen._bytes_to_read > 0:
                        self.screen._bytes_to_return += struct.pack(b"B", key)
                        self.screen._bytes_to_read -= 1
                        if self.screen._bytes_to_read > 0:
                            continue
                        else:
                            key = ord(self.screen._bytes_to_return.decode("utf-8"))

                # Handle a genuine key press.
                if key in self.screen._KEY_MAP:
                    return KeyboardEvent(self.screen._KEY_MAP[key])
                elif key != -1:
                    return KeyboardEvent(key)

        return None
예제 #22
0
def on_mouse():
    '''Update selected line / sort'''
    _, x, y, z, bstate = curses.getmouse()

    # Left button click ?
    if bstate & curses.BUTTON1_CLICKED:
        # Is it title line ?
        if y == 0:
            # Determine sort column based on offset / col width
            x_max = 0
            for col in COLUMNS:
                if not col.width:
                    set_sort_col(col.col_sort)
                elif x < x_max + col.width:
                    set_sort_col(col.col_sort)
                else:
                    x_max += col.width + 1
                    continue
                return 2
        # Is it a cgroup line ?
        elif y <= len(CONFIGURATION['cgroups']):
            if CONFIGURATION['follow']:
                CONFIGURATION['selected_line_name'] = CONFIGURATION['cgroups'][
                    y - 1]
            else:
                CONFIGURATION['selected_line_num'] = y - 1
            return 2
    return 1
예제 #23
0
 def get_and_use_mouse_event(self):
     mouse_event = curses.getmouse()
     wg = self.find_mouse_handler(mouse_event)
     if wg:
         self.set_editing(wg)
     else:
         curses.beep()
예제 #24
0
	def getCh(self):
		"""
		Gets a character from input immediately. If there is no character to get, returns -1.
		Also handles mouse events, and updates windows appropriately (returns -1 on mouse events)
		"""
		ch = self.window.getch()
	
		if ch == curses.KEY_MOUSE:
			mouseId, x, y, z, event = curses.getmouse()
			
			if event & curses.BUTTON1_CLICKED == curses.BUTTON1_CLICKED:
				x = x - 1 #Adjust due to being in window
				y = y - 1

				try:
					tile = self.tileArray[y][x]
					info = self.tileData[tile]
					self.writeToWindow(self.bottomWindow, 'Information on space from tile at (%d, %d) : %s' % (y, x, info), True)
				except IndexError:
					self.writeToWindow(self.bottomWindow, 'There is no tile information for this space.', True) 			
				except KeyError:
					self.writeToWindow(self.bottomWindow, 'Tile information for this space could not be found.', True)

			return -1

		if ch > 256 or ch < -1: #With keypad(1) enabled its possible to get non ascii values, ignore them
			return -1

		return ch
예제 #25
0
def main(stdscr):
	curses.curs_set(0)
	curses.mousemask(1)
	curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_RED)
	curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_GREEN)

	stdscr.addstr(0, 0, "Hello!")
	stdscr.addstr(1, 0, "Red")
	stdscr.addstr(2, 0, "Green")

	while 1:
		stdscr.refresh()
		key = stdscr.getch()

		if key == curses.KEY_MOUSE:
			_, x, y, _, _ = curses.getmouse()
			if y == 1 and x in range(3):
				stdscr.attron(curses.color_pair(1))
				stdscr.addstr(0, 0, "Hello!")
				stdscr.attroff(curses.color_pair(1))
			elif y == 2 and x in range(5):
				stdscr.attron(curses.color_pair(2))
				stdscr.addstr(0, 0, "Hello!")
				stdscr.attroff(curses.color_pair(2))
		elif key == 27:
			break
예제 #26
0
def main(screen):
	#screen = curses.initscr() 
	#curses.noecho() 
	curses.curs_set(0) 
	screen.keypad(1) 
	curses.mousemask(curses.ALL_MOUSE_EVENTS | curses.REPORT_MOUSE_POSITION)

	screen.addstr("This is a Sample Curses Script\n\n")
	# printf("\033[?1003h\n"); // Makes the terminal report mouse movement events
	print '\033[?1003h'


	it = 1;
	while True:
	    event = screen.getch()
	    screen.addstr(8, 10, "Iteration:" + str(it))
	    it += 1
	    screen.addstr(9, 10, "Event:" + str(event))
	    if event == curses.ERR: break
	    if event == ord("q"): break 
	    if event == curses.KEY_MOUSE:
	        # _, mx, my, _, _ = curses.getmouse()
	        # y, x = screen.getyx()
	        screen.addstr(10, 10, "pippo")
	        screen.addstr(11, 10, str(curses.getmouse()) + "                      ")
예제 #27
0
def main(stdscr):
    curses.curs_set(0)
    curses.mousemask(1)
    curses.init_pair(1, curses.COLOR_BLUE, curses.COLOR_BLACK)
    curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK)

    stdscr.addstr(0, 0, tittle)
    stdscr.addstr(15, 0, "Red")
    stdscr.addstr(16, 0, "Green")

    while 1:
        stdscr.refresh()
        key = stdscr.getch()

        if key == curses.KEY_MOUSE:
            _, x, y, _, _ = curses.getmouse()
            if y == 15 and x in range(3):
                stdscr.attron(curses.color_pair(1))
                stdscr.addstr(0, 0, tittle)
                stdscr.attroff(curses.color_pair(1))
            elif y == 16 and x in range(5):
                stdscr.attron(curses.color_pair(2))
                stdscr.addstr(0, 0, tittle)
                stdscr.attroff(curses.color_pair(2))
        elif key == 27:
            break
예제 #28
0
파일: back.py 프로젝트: abramclark/fiddle
def main(argv):
    global mines, board

    args = map(int, argv[1:])
    xw = int(args[0]) if args else 20
    yw = int(args[1]) if len(args) > 1 else xw / 2
    mines = int(args[2]) if len(args) > 2 else int(xw * yw / 20)

    board = [' ' * xw for i in range(yw)]
    mines = {(randint(0, xw), randint(0, yw)) : True for i in range(mines)}

    scr = curses.initscr()
    scr.keypad(1)
    curses.curs_set(0)
    curses.noecho()
    curses.mousemask(curses.ALL_MOUSE_EVENTS)

    while True:
        scr.clear()

        k = scr.getch()
        scr.addstr(yw + 2, 0, ': ' + str(k))
        if k == 27:
            break
        elif k == curses.KEY_MOUSE:
            _, x, y, z, bstate = curses.getmouse()
            scr.addstr(y, x, ' '.join(str(v) for v in (z, bstate)))
        elif k == curses.KEY_DC:
            boom(scr)

    scr.clear()
    curses.endwin()
예제 #29
0
파일: window.py 프로젝트: Wayt/tcapsoul
 def __mouse_event(self, s, args):
     b = curses.getmouse()
     if (b[4] == 524288):
         self.tcs.buddysWindow[self.tcs.currentBuddy].scroll(-1)
     elif (b[4] == 134217728):
         self.tcs.buddysWindow[self.tcs.currentBuddy].scroll(1)
     self.tcs.buddysWindow[self.tcs.currentBuddy].refresh()
예제 #30
0
파일: gui.py 프로젝트: gowvijay/PA2
def checkUserInput():
    while 1:
        
        try:
            c = gl.scrn.getch()
            if c == curses.KEY_MOUSE:
                pass
                # handle mouse events -- set x,y to the mouse click location
                device_id, mouse_x, mouse_y, mouse_z, eventType = curses.getmouse()
                gl.error['mouse EVENT'] = (device_id, mouse_x, mouse_y, mouse_z, eventType)
                if eventType == curses.BUTTON1_CLICKED:
                    c = 'v'
                    x, y = mouse_x, mouse_y
                    if gl.bottomWin.enclose(y,x):
                        py, px = gl.bottomWin.getparyx()
                        gl.bottomWin.move(y-py,x)
                        
                        writeOut( chr( gl.bottomWin.inch() ) )
                        #time.sleep(0.5)
                    viewNext()
                    pass
                    #plane.xcurs = mouse_x
                    #plane.ycurs = mouse_y
                    #window.addstr(0, 0, "%s,%s"%(mouse_x,mouse_y))
            else:
                c = chr(c)
            if c == 'q': 
                break
        
            keyboardActions[c]()
        except:
            gl.error['checkUserInput'] = c
            if c == 'v':
                raise
예제 #31
0
파일: p7_drawline.py 프로젝트: FSXAC/Curses
def main(screen):
    curses.curs_set(0)
    curses.mousemask(curses.BUTTON1_PRESSED)

    x1, y1 = None, None

    while True:

        # Get key input
        key = screen.getch()
        # screen.clear()

        if key == curses.KEY_MOUSE:
            _, mouseX, mouseY, _, _ = curses.getmouse()

            screen.addstr(0, 0, '({}, {})'.format(mouseX, mouseY))
            screen.refresh()

            if not x1 and not y1:
                x1, y1 = mouseX, mouseY
            else:
                line(screen, x1, y1, mouseX, mouseY)
                x1, y1 = None, None

        elif key == ord('q'):
            break

        elif key == ord('c'):
            screen.clear()
예제 #32
0
def Main(stdscr):
    args = Arguments(sys.argv)
    mineFieldWidth, mineFieldHeight, numMines, mode = args.parse()
    game = Game(stdscr, mineFieldWidth, mineFieldHeight, numMines)
    game.start() 
    while True:
        event = stdscr.getch()
        my, mx = 0, 0
        if event == curses.KEY_MOUSE:
            _, mx, my, _, bstate = curses.getmouse()
            if bstate & curses.BUTTON1_PRESSED :
                if game.poke(my, mx) == "dead":
                    game.gameLose()
            elif bstate & curses.BUTTON3_PRESSED:
                game.flag(my, mx)
        maxy, maxx = stdscr.getmaxyx()

        if game.checkWin():
            game.gameWin()

        if event == ord("q") or (mx >= maxx - 9 and mx <= maxx - 4 and my == maxy - 2): 
            game.exit() 

        if event == ord("R") or (mx >= 39 and mx <= 47 and my == maxy - 2):   
            game.displayRecord()

        if event == ord("c") or (mx >= 14 and mx <= 21 and my == maxy - 2):   
            game.resume()

        if event == ord("p") or (mx >= 3 and mx <= 9 and my == maxy - 2):   
            game.pause()

        if event == ord("r") or (mx >= 26 and mx <= 34 and my == maxy - 2):   
            game.restart()
예제 #33
0
파일: main_02.py 프로젝트: voxelv/glopnet
def run():
    ch = -1
    count = 0
    event = None

    os.environ['TERM'] = "xterm-1003"

    screen = curses.initscr()
    curses.raw()
    screen.keypad(True)
    curses.noecho()

    screen.clear()
    curses.cbreak()

    curses.mousemask(curses.ALL_MOUSE_EVENTS | curses.REPORT_MOUSE_POSITION)

    while ch != ord('q'):
        count += 1
        # screen.addstr(1, 1, "Has mouse {}".format(curses.has_mouse()))
        screen.addstr(
            2, 1, "Key code: {}; mouse code:{}".format(ch, curses.KEY_MOUSE))
        if ch == curses.KEY_MOUSE:
            event = curses.getmouse()
            screen.addstr(
                3, 3,
                "Mouse Event: x={}, y={}, z={}".format(event[1], event[2],
                                                       event[3]))
            screen.addstr(4, 3, "Mouse device id: {}".format(event[0]))
            screen.addstr(5, 3, "Mouse button mask: {}".format(event[4]))
        screen.addstr(6, 1, "Event number: {}".format(count))
        screen.refresh()
        ch = screen.getch()
    curses.endwin()
예제 #34
0
 def commandLoop(self):
     window = self.inputWindow
     window.focus()
     self.focusedWindow = window
     self.mainLoopTime = 0
     self.mainLoopTimePeak = 0
     start = time.time()
     while not self.exiting:
         self.refresh()
         self.mainLoopTime = time.time() - start
         if self.mainLoopTime > self.mainLoopTimePeak:
             self.mainLoopTimePeak = self.mainLoopTime
         cmdList = []
         mouseEvents = []
         while not len(cmdList):
             for i in range(5):
                 ch = window.cursorWindow.getch()
                 #if ch != -1:
                 #  app.log.info('ch', ch)
                 if ch == curses.ascii.ESC:
                     keySequence = []
                     n = window.cursorWindow.getch()
                     while n != curses.ERR:
                         keySequence.append(n)
                         n = window.cursorWindow.getch()
                     #app.log.info('sequence\n', keySequence)
                     ch = tuple(keySequence)
                     if not ch:
                         # The sequence was empty, just forward the esc.
                         ch = curses.ascii.ESC
                 if ch != curses.ERR:
                     self.ch = ch
                     if ch == curses.KEY_MOUSE:
                         # On Ubuntu, Gnome terminal, curses.getmouse() may only be called
                         # once for each KEY_MOUSE. Subsequent calls will throw an
                         # exception.
                         self.debugMouseEvent = curses.getmouse()
                         mouseEvents.append(
                             (self.debugMouseEvent, time.time()))
                         #app.log.info('mouse event\n', mouseEvents[-1])
                     cmdList.append(ch)
         start = time.time()
         if len(cmdList):
             for cmd in cmdList:
                 if cmd == curses.KEY_RESIZE:
                     if sys.platform == 'darwin':
                         rows, cols = app.curses_util.terminalSize()
                         curses.resizeterm(rows, cols)
                     self.layout()
                     window.controller.onChange()
                     self.refresh()
                     app.log.debug(self.stdscr.getmaxyx(), time.time())
                     continue
                 window.controller.doCommand(cmd)
                 if cmd == curses.KEY_MOUSE:
                     self.handleMouse(mouseEvents[0])
                     mouseEvents = mouseEvents[1:]
                 window = self.focusedWindow
                 window.controller.onChange()
def main(stdscr):
    global DEPTH

    curses.curs_set(0)
    curses.mousemask(1)
    curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_CYAN)  # tiles 1
    curses.init_pair(2, curses.COLOR_BLUE, curses.COLOR_BLUE)  # tiles 2
    curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLUE)  # pieces 1
    curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLUE)  # pieces 2
    curses.init_pair(5, curses.COLOR_GREEN, curses.COLOR_BLUE)  # moves
    curses.init_pair(6, curses.COLOR_WHITE,
                     curses.COLOR_BLUE)  # first action of the movement
    curses.init_pair(7, curses.COLOR_WHITE, curses.COLOR_BLACK)  # borders
    curses.init_pair(8, curses.COLOR_GREEN, curses.COLOR_BLACK)  # you won
    curses.init_pair(9, curses.COLOR_RED, curses.COLOR_BLACK)  # you lost

    board = new_board()
    capture = check_captures(board, 1)
    moves = []

    while 1:
        stdscr.refresh()
        moved = 0

        go = game_over(board)
        if bool(go):
            print_game_over(board, stdscr, go)
        else:
            print_board(board, stdscr)

        key = stdscr.getch()

        if key == curses.KEY_MOUSE:
            _, x, y, _, _ = curses.getmouse()

            clear_moves(board)

            if not go:

                if x < BOARD_LEN * 2 and y < BOARD_LEN and x % 2 == 0:
                    x = int(x / 2)

                    for move in moves:
                        if move[-1] == (y, x):
                            step(board, move)
                            moves.clear()
                            moved = 1

                    if not moved:
                        capture = check_captures(board, 1)
                        moves = possible_moves(board, (y, x), 1, capture)
                        add_moves(board, moves)

                    if moved:
                        minimax(board, DEPTH, float("-inf"), float("+inf"), 0)
                        step(board, MOVE_PC)

        elif key == 27:  # Esc
            break
예제 #36
0
    def __init__(self, screen):
        '''Needs a reference to a screen, grab one from the draw controller via get_screen'''

        curses.mousemask(1)

        self.use_mouse = True
        try:
            curses.getmouse()
        except:
            self.use_mouse = False

        self.screen = screen
        self.callbacks = defaultdict(set)

        if self.use_mouse:
            self.mouse_callbacks = set()
            self.mouse_state = curses.getmouse()
예제 #37
0
파일: ui.py 프로젝트: andresmrm/ranger
 def handle_mouse(self):
     """Handles mouse input"""
     try:
         event = MouseEvent(curses.getmouse())
     except _curses.error:
         return
     if not self.console.visible:
         DisplayableContainer.click(self, event)
예제 #38
0
파일: ui.py 프로젝트: niksfirefly/ranger
 def handle_mouse(self):
     """Handles mouse input"""
     try:
         event = MouseEvent(curses.getmouse())
     except _curses.error:
         return
     if not self.console.visible:
         DisplayableContainer.click(self, event)
예제 #39
0
파일: ui.py 프로젝트: EvanKuhn/evdoc
    def edit(self, terminators=[curses.ascii.ESC]):
        '''
        Collect input keystrokes from the user. When a given terminator character
        is received, stop and return it.
        - Always ignores the Escape character.
        - Always returns a KEY_RESIZE character.
        '''
        while True:
            # Get input
            c = self.getch()

            if c in terminators:
                return c
            if c == curses.KEY_RESIZE:
                return c

            # Take action
            if c == curses.ascii.LF:
                self.scroll_x = 0
                self.addch(c)
                self.update()
            elif c == curses.ascii.TAB:
                pass
            elif curses.ascii.isprint(c):
                self.addch(c)
                self.update()
            elif c == curses.KEY_UP:
                self.move_up()
            elif c == curses.KEY_DOWN:
                self.move_down()
            elif c == curses.KEY_LEFT:
                self.move_left()
            elif c == curses.KEY_RIGHT:
                self.move_right()
            elif c == curses.ascii.DEL:
                self.backspace()
                self.update()
            elif c == curses.KEY_DC:
                self.delete()
                self.update()
            elif c == curses.KEY_MOUSE:
                id, x, y, z, bstate = curses.getmouse()
                self.logger.log("Mouse event: id=%d, x=%d, y=%d, z=%d, bstate=%d" %
                    (id, x, y, z, bstate))

            # Run the on_char callback
            if self.on_char:
                self.on_char(self.on_char_arg)

            # Redraw the window if dirty
            if self.is_dirty():
                self.redraw()

            # Debug output
            win_y, win_x = self.window.getyx()
            doc_y, doc_x = self.document.getyx()
            self.logger.log("doc: (%d, %d)  win: (%d, %d) scroll: (%d, %d) dims: (%d, %d)" %
                (doc_y, doc_x, win_y, win_x, self.scroll_y, self.scroll_x, self.rows, self.cols))
예제 #40
0
def main(scr):
    curses.mousemask(curses.ALL_MOUSE_EVENTS)
    curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_RED)
    
    room = lightUtil.lights(50)
    all = lightUtil.group(room,range(50))
    colors = {'red':127, 'green':127, 'blue':127}
    color_range = range(256)

    win = lightPanel(scr,'room',8,20,10,10)
    fields = ['red', 'green', 'blue']
    win.add_field('red',colors['red'],1)
    win.add_field('green',colors['green'],2)
    win.add_field('blue',colors['blue'],3)

    current_field = 'red'
    win.focus_on(current_field)
    all.setColor((colors['red'], colors['green'], colors['blue']))

    while True:
        c = scr.getkey()
        #scr.addstr(0,0,c)
        if c == 'KEY_UP':
            current_field = cycle_list(fields,current_field,'up')
            win.focus_on(current_field)
        if c == 'KEY_DOWN':
            current_field = cycle_list(fields,current_field,'down')
            win.focus_on(current_field)
        if c == 'KEY_RIGHT':
            colors[current_field] = cycle_list(color_range,
                                               colors[current_field],
                                               'down')
        if c == 'KEY_LEFT':
            colors[current_field] = cycle_list(color_range,
                                               colors[current_field],
                                               'up')
        if c == 'KEY_MOUSE':
            #scr.addstr(0,0,str(curses.getmouse()))
            id, x, y, z, bstate = curses.getmouse()
            for f in win.fields:
                if win.fields[f][0].enclose(y, x):
                    win.focus_on(f)
        if c == '0':
            colors[current_field] = 0
        if c == 'w':
            win.move('up')
        if c == 's':
            win.move('down')
        if c == 'a':
            win.move('left')
        if c == 'd':
            win.move('right')
        if c == 'q':
            break
        all.setColor((colors['red'], colors['green'], colors['blue']))
        win.update_field('red',colors['red'],1)
        win.update_field('green',colors['green'],2)
        win.update_field('blue',colors['blue'],3)
예제 #41
0
def handle_mouse(screen, win, *args, **kwargs):
    data = curses.getmouse()
    win.window.clear()
    win.window.border()
    win.window.addstr(5, 5, str(data))
    if data[-1] == curses.BUTTON1_CLICKED:
        win.window.addstr(7, 6, str(win.is_in_window(data[1], data[2])))
        win.window.addstr(8, 6, str(win.is_in_content(data[1], data[2])))
    win.window.refresh()
예제 #42
0
def main(window):
    curses.mousemask(curses.ALL_MOUSE_EVENTS)
    curses.mouseinterval(0)
    while True:
        char = window.getch()
        if char == curses.KEY_MOUSE:
            window.addstr(repr(curses.getmouse()) + SEPARATOR)
        else:
            window.addstr(str(char) + SEPARATOR)
예제 #43
0
def main(window):
    curses.mousemask(curses.ALL_MOUSE_EVENTS)
    curses.mouseinterval(0)
    while True:
        char = window.getch()
        if char == curses.KEY_MOUSE:
            window.addstr(repr(curses.getmouse()) + SEPARATOR)
        else:
            window.addstr(str(char) + SEPARATOR)
예제 #44
0
 def get_act_position(self):
     event = self.canvas.getch()
     if event == curses.KEY_MOUSE:
         _, click_x, click_y, _, _ = curses.getmouse()
         return click_x - 1, click_y - 1
     if event in (ord("q"), ord("й")):
         return -1
     else:
         return None
예제 #45
0
파일: ui.py 프로젝트: aachik/suplemon
 def get_mouse_state(self):
     """Get the mouse event data."""
     try:
         mouse_state = curses.getmouse()
     except:
         self.app.log(get_error_info())
         return False
     # Translate the coordinates to the editor coordinate system
     return self._translate_mouse_to_editor(mouse_state)
def game_loop(screen):
  while True:
    render_board(screen)
    key_pressed = screen.getch()
    if key_pressed in [ord('q'),27]:
      break
    if key_pressed == curses.KEY_MOUSE:
      _, y, x, __, click_type = curses.getmouse()
      raise Exception(x//tile_size,y//tile_size)
예제 #47
0
 def get_mouse_state(self):
     """Get the mouse event data."""
     try:
         mouse_state = curses.getmouse()
     except:
         self.app.log(get_error_info())
         return False
     # Translate the coordinates to the editor coordinate system
     return self._translate_mouse_to_editor(mouse_state)
예제 #48
0
파일: vd.py 프로젝트: cwbooth5/visidata
    def run(self):
        global sheet
        global windowHeight, windowWidth
        windowHeight, windowWidth = scr.getmaxyx()

        commands = base_commands
        while True:
            if not self.sheets:
                # if no more sheets, exit
                return

            sheet = self.sheets[0]
            if sheet.nRows == 0:
                self.status('no rows')

            try:
                sheet.draw()
            except Exception as e:
                self.exceptionCaught()

            # draw status on last line
            attr = colors[options.c_StatusLine]
            statusstr = options.SheetNameFmt % sheet.name + options.StatusSep.join(self._status)
            self.clipdraw(windowHeight-1, 0, statusstr, attr, windowWidth)
            self._status = []

            scr.move(windowHeight-1, windowWidth-2)
            curses.doupdate()

            ch = scr.getch()
            if ch == curses.KEY_RESIZE:
                windowHeight, windowWidth = scr.getmaxyx()
            elif ch == curses.KEY_MOUSE:
                try:
                    devid, x, y, z, bstate = curses.getmouse()
                    sheet.cursorRowIndex = sheet.topRowIndex+y-1
                except Exception:
                    self.exceptionCaught()
            elif ch in sheet.commands or ch in commands:
                cmdstr = sheet_specific_commands.get((sheet.name, ch)) or sheet.commands.get(ch) or commands.get(ch)
                try:
                    exec(cmdstr)

                    commands = base_commands
                except ChangeCommandSet as e:
                    # prefixes raise ChangeCommandSet exception instead
                    commands = e.commands
                    self.status(e.mode)
                except Exception:
                    commands = base_commands
                    self.exceptionCaught()
                    self.status(cmdstr)
            else:
                self.status('no command for key "%s" (%d) ' % (chr(ch), ch))

            sheet.checkCursor()
예제 #49
0
def noise(window):
    mid, mx, my, mz, mbstate = 0, 0, 0, 0, 0
    ymax, xmax = window.getmaxyx()
    window.timeout(0)  # Nonblocking gets, 0 in ms
    t0 = time()
    tot = 0
    window.addch(ymax-7, 24, curses.ACS_LARROW)
    window.hline(ymax-7, 25, curses.ACS_HLINE, 10)
    window.addstr(ymax-7, 36, "click this box, or press h, or q")
    win2 = curses.newwin(12, 21, ymax-13, 1)
    win2.box()
    win2.keypad(1)
    win2.nodelay(1)
    win2.border()
    win2.leaveok(0)
    win2.scrollok(0)
    win2.bkgd(' ', 0)
    win2_inv = False
    while True:
        t1 = time()
        tot += 1
        ups = tot/(t1-t0)
        x = randint(1, randint(1, xmax - 2))
        y = randint(1, randint(1, ymax - 2 - 12))
        c = ord('#')
        getch = window.getch() 
        if getch == curses.KEY_MOUSE or getch == ord('h'):
            tmid, tmx, tmy, tmz, tmbstate = curses.getmouse()
            if getch == ord('h') or tmbstate == 2 and win2.enclose(tmy, tmx):
                mid, mx, my, mz, mbstate = tmid, tmx, tmy, tmz, tmbstate
                if win2_inv:
                    win2.attroff(curses.A_REVERSE)
                else:
                    win2.attron(curses.A_REVERSE)
                win2_inv = not win2_inv
        elif getch == ord('q'):
            raise SystemExit(None)
        window.addch(y, x, c)
        window.noutrefresh()  # Mark for update

        ylst, xlst = curses.getsyx()
        win2.addstr(12-11, 1, "tot   :%12i" % tot)
        win2.addstr(12-10, 1, "#/s   :%12.3f" % ups)
        win2.addstr(12-9,  1,  "t tot :%12.3f" % (t1-t0))
        win2.addstr(12-8,  1,  "y lst :%12i" % ylst)
        win2.addstr(12-7,  1,  "x lst :%12i" % xlst)
        win2.addstr(12-6,  1,  "m id  :%12i" % mid)
        win2.addstr(12-5,  1,  "m x   :%12i" % mx)
        win2.addstr(12-4,  1,  "m y   :%12i" % my)
        win2.addstr(12-3,  1,  "m z   :%12i" % mz)
        win2.addstr(12-2,  1,  "m st  :%12i" % mbstate)
        win2.noutrefresh()

        #sleep(1/100000.)
        curses.doupdate()  # Perform refreshes
        continue
예제 #50
0
파일: ui.py 프로젝트: Gnewbee/suplemon
    def get_mouse_state(self):
        """Get the mouse event data."""
        try:
            mouse_state = curses.getmouse()
        except:
            self.logger.error("curses.getmouse() failed!", exc_info=True)
            return False

        # Translate the coordinates to the editor coordinate system
        return self._translate_mouse_to_editor(mouse_state)
예제 #51
0
파일: interface.py 프로젝트: Mefoolyhi/Zuma
 def update_win(self):
     """Обновление игрового окна, обработка нажатия"""
     key = self.win.getch()
     if key == curses.KEY_MOUSE:
         _, x, y, _, _ = curses.getmouse()
         line = self.level._frog.shoot(
             x, y, (self.level.field_height, self.level.field_width))[:-1]
         return "shoot", line
     if key == 115:
         return "save"
예제 #52
0
  def renderMenu(self):
    self.status = 'menu'
    self.delWindows()
    self.stdscr.clear()
    self.stdscr.addstr(3,4,'MAIN MENU')
    menuOpt = 1
    while True:
      if menuOpt == 1:
        self.stdscr.addstr(5,5,'New Game', self.highlight)
      else:
        self.stdscr.addstr(5,5,'New Game')
      if menuOpt == 2:
        self.stdscr.addstr(6,7,'Quit', self.highlight)
      else:
        self.stdscr.addstr(6,7,'Quit')
      self.stdscr.refresh()

      c = self.stdscr.getch()
      if c == curses.KEY_UP or c == ord('w') or c == ord('k'):
        menuOpt = max(1, menuOpt-1)
      if c == curses.KEY_DOWN or c == ord('s') or c == ord('j'):
        menuOpt = min(2, menuOpt+1)
      if c == curses.KEY_MOUSE:
        _,_,my,_,bstate = curses.getmouse()
        my = my-2*dim-5
        if 0<my<=2:
          menuOpt = my
          if bstate & curses.BUTTON1_DOUBLE_CLICKED:
            break
      if c == ord('\n'):
        break

    if menuOpt == 1:
      while True:
        self.stdscr.clear()
        self.stdscr.addstr(4,1,'Enter a dimension:')
        c = self.stdscr.getch()
        if ord('1') <= c <= ord('9'):
          self.stdscr.addstr(5,9,chr(c))
          d = self.stdscr.getch()
          if ord('0') <= d <= ord('9'):
            self.stdscr.addstr(5,10,chr(d))
            e = self.stdscr.getch()
            if e == ord('\n') and c == ord('1'):
              dim = 10 + int(chr(d))
              break
          if d == ord('\n'):
            dim = int(chr(c))
            break
      self.stdscr.addstr(6,1,'stuff')
      self.stdscr.refresh()    
      return 'play', dim
    
    if menuOpt == 2:
      return 'quit', None
예제 #53
0
def getBoardClickedCoord(stdscr, boardLeftCorner, boardObj):
    """Note: mouseClick will be a tuple containing (id, xCoord, yCoord, z,
    state) state will only matter with clicks
    This function returns (y, x)""" 
    i = stdscr.getch()

    if i == curses.KEY_MOUSE:
        mouseClick = curses.getmouse()
        return mouseClick[2], mouseClick[1]
    else:
        return None, None
예제 #54
0
 def updateloop(self):
     while True:
         self.redraw()
         self.getch = self.window.getch()
         self.mx, self.my, self.click = None, None, None
         if self.getch:
             if self.getch > -1:
                 if self.getch in SKEYS['MOUSE']:
                     _, self.mx, self.my, _, click = curses.getmouse()
                     for each in self.windows:
                         if each.window.enclose(self.my, self.mx):
                             each.on_click(self.my, self.mx)
예제 #55
0
파일: wnd.py 프로젝트: hihihippp/kaa
    def do_input(self, nonblocking):
        """Get an input from curses"""

        self._panel.top()

        if nonblocking:
            self._cwnd.timeout(0)
        else:
            self._cwnd.timeout(-1)
#            self._cwnd.timeout(self.WAITINPUTFOR)

        no_trailing_char = False  # true if esc key pressed
        try:
            curses.panel.update_panels()
            curses.doupdate()

            c = self._cwnd.get_wch()
            if c == '\x1b':
                self._cwnd.timeout(0)
                try:
                    c2 = self._cwnd.get_wch()
                    # has trailing character.
                    curses.unget_wch(c2)
                except curses.error:
                    # no trailing character.
                    no_trailing_char = True

        except curses.error as e:
            if repr(e.args) != self._lasterror:
                if e.args[0] != 'no input':
                    log.debug('Error in get_wch()', exc_info=True)
                self._lasterror = repr(e.args)
            else:
                self._skipped += 1
                if self._skipped % 500 == 0:
                    log.debug(
                        'Too much input-error skips!: {} times'.format(self._skipped))
            return []

        self._lasterror = ''
        self._skipped = 0

        if c == curses.KEY_MOUSE:
            mouseid, x, y, z, bstate = curses.getmouse()
            keys = [keydef.MouseEvent(self, mouseid, x, y, z, bstate)]
        else:
            keys = [keydef.KeyEvent(self, k, no_trailing_char)
                    for k in keydef.convert_registered_key(c)]

#        for k in keys:
#            _trace('{!r}'.format(k))

        return keys
예제 #56
0
 def user_input(self):
     while not self.main_future.cancelled():
         curses.raw()
         curses.cbreak()
         curses.meta(1)
         event = yield from asyncio.async(self.get_wch())
         if event is None:
             continue
         if event == curses.KEY_MOUSE:
             self.loop.call_soon(partial(self.mouse_event_handler,
                                         *curses.getmouse()))
         else:
             self.loop.call_soon(partial(self.key_event_handler, event))
예제 #57
0
def mainloop(scr):
	curses.mousemask(curses.ALL_MOUSE_EVENTS)#curses.BUTTON1_PRESSED)#curses.ALL_MOUSE_EVENTS)
	while 1:
		scr.keypad(1)
		curses.halfdelay(1)
		ch = scr.getch()
		if ch == "-1": scr.addstr(2, 0, '-1')
		scr.addstr(2, 0, str(ch))
		if ch == curses.KEY_MOUSE:
		    scr.addstr(4,0, "%s" % ' '.join(str(curses.getmouse())))
		    curses.beep()
		#return ch
		scr.refresh()
예제 #58
0
파일: system.py 프로젝트: codelurker/ctd
 def update(self):
     char = self.scrn.getch()
     # was returned as an integer (ASCII); make it a character
     if char != -1:
         if char == curses.KEY_MOUSE:
             #device_id, x, y, z, button = self.system.getmouse()
             ret = curses.getmouse()
             x = ret[1]
             y = ret[2]
             button = ret[4]
             self.evm.Post(MouseClickEvent(button, Vector(x,y)))
         else:
             char = chr(char)
             self.evm.Post(KeyPressEvent(char))
예제 #59
0
파일: main.py 프로젝트: insaneHoshi/seng426
def main():
	global stdscr
	pointList = []
	print "Welcome to my convex hull algorithm implementation using python and curses.  To set points click on the the terminal, to unset points click near a set point.\n"
	print "This application is only stable with linux terminals and python 2.x\n"
	print "Note the resolution is dependent on your Unix terminal, increase it for greater resolution\n"
	
	raw_input("Press Enter to continue...")
	
	stdscr = curses.initscr()
	curses.noecho()
	curses.cbreak()
	stdscr.keypad(1)
	curses.mousemask(1)
	windowYSize = stdscr.getmaxyx()[0]
	stdscr.addstr(windowYSize-1,0,"Press (s) to start the Convex Hull Alg, (r) to reset or (q) to quit")
	while True:
		event = stdscr.getch() 
		if event == ord("q"): break
		elif event == ord("r"): 
			stdscr.clear()
			pointList = []
			stdscr.addstr(windowYSize-1,0,"Press (s) to start the Convex Hull Alg, (r) to reset or (q) to quit")
		elif event == ord("s"):
			stdscr.clear()
			stdscr.addstr(windowYSize-1,0,"Press (s) to start the Convex Hull Alg, (r) to reset or (q) to quit")
			if(len(pointList)>1):
				convexHull = doConvexHull(pointList)
				i = 0
				while i<len(convexHull)-1:
					dline(convexHull[i],convexHull[i+1],".")
					i+=1
					
			for point in pointList:
				plot(point[0],point[1],"o")
			
		if event == curses.KEY_MOUSE:
			_, mx, my, _, _ = curses.getmouse()
			if(my<windowYSize-1):
				testPoint = [mx,my]
				if(testPoint in pointList):
					pointList.remove(testPoint)
					plot(mx,my," ")
				else:
					pointList.append([mx,my])
					plot(mx,my,"o")
	    
	curses.nocbreak(); stdscr.keypad(0); curses.echo()
	curses.endwin()
예제 #60
0
파일: hex.py 프로젝트: quo/hex.py
	def main_loop(self):
		while True:
			self.draw_status()
			self.scroll_to_cursor()
			c = self.scr.getch()
			self.status = self.file.file.name
			if c == curses.KEY_RESIZE:
				self.resize()
			elif c == curses.KEY_MOUSE:
				self.process_mouse(*curses.getmouse())
			else:
				if 0 < c < 128: c = chr(c)
				if c == 'q': return
				self.process_key(c)
			self.pos = max(0, min(self.pos, self.file.size-1))