def draw(self, path, start_x, start_y, width, height): # Save cursor curses.putp(curses.tigetstr("sc")) y = start_y # Move to drawing zone self._move_to(start_x, y) # Write intent sys.stdout.write("%s}ic#%d;%d;%s%s" % ( self.display_protocol, width, height, path, self.close_protocol)) # Write Replacement commands ('#') for _ in range(0, height): sys.stdout.write("%s}ib%s%s%s}ie%s" % ( self.display_protocol, self.close_protocol, "#" * width, self.display_protocol, self.close_protocol)) y = y + 1 self._move_to(start_x, y) # Restore cursor curses.putp(curses.tigetstr("rc")) sys.stdout.flush()
def draw(self, path, start_x, start_y, width, height): # Save cursor curses.putp(curses.tigetstr("sc")) y = start_y # Move to drawing zone self._move_to(start_x, y) # Write intent sys.stdout.write( "%s}ic#%d;%d;%s%s" % (self.display_protocol, width, height, path, self.close_protocol)) # Write Replacement commands ('#') for _ in range(0, height): sys.stdout.write( "%s}ib%s%s%s}ie%s" % (self.display_protocol, self.close_protocol, "#" * width, self.display_protocol, self.close_protocol)) y = y + 1 self._move_to(start_x, y) # Restore cursor curses.putp(curses.tigetstr("rc")) sys.stdout.flush()
def printwyx(self, window, coord, arg, color = None, attribute = None): if self.cursescolors == True: try: if color or attribute: attr = 0 if color: attr |= self.color[color] if attribute: attr |= self.attribute[attribute] if coord: window.addstr(coord[0], coord[1], arg, attr) else: window.addstr(arg, attr) elif coord: window.addstr(coord[0], coord[1], arg) else: window.addstr(arg) except curses.error: pass else: coordstr = "" if coord: coordstr = curses.tparm(curses.tigetstr("cup"), coord[0], coord[1]) colorstr = self.attribute['normal'] if color: colorstr += self.color[color] if attribute: colorstr += self.attribute[attribute] clr_eol = curses.tparm(curses.tigetstr("el")) curses.putp(coordstr + colorstr + arg + clr_eol)
def draw(self, path, start_x, start_y, width, height): curses.putp(curses.tigetstr("sc")) sys.stdout.write(curses.tparm(curses.tigetstr("cup"), start_y, start_x)) sys.stdout.write(self._generate_iterm2_input(path, width, height)) curses.putp(curses.tigetstr("rc")) sys.stdout.flush()
def safeexit(): w('exiting in 30 seconds! To exit now, press any key!') t.timeout(30*1000) i=t.getch() curses.putp("\n") curses.nocbreak() curses.endwin() exit()
def temporarily_moved_cursor(to_y, to_x): """Common boilerplate code to move the cursor to a drawing area. Use it as: with temporarily_moved_cursor(dest_y, dest_x): your_func_here()""" curses.putp(curses.tigetstr("sc")) move_cur(to_y, to_x) yield curses.putp(curses.tigetstr("rc")) sys.stdout.flush()
def _placeImage(self, path, x, y, width, height): text = self._escapeSequence(path, width, height) # text = "holy moly" curses.putp(curses.tigetstr("sc")) move = curses.tparm(curses.tigetstr("cup"), y, x) sys.stdout.write(move) sys.stdout.write(text) curses.putp(curses.tigetstr("rc")) sys.stdout.flush()
def _placeImage(self,path,x,y,width,height): text = self._escapeSequence(path,width,height) # text = "holy moly" curses.putp(curses.tigetstr("sc")) move = curses.tparm(curses.tigetstr("cup"), y, x) sys.stdout.write(move) sys.stdout.write(text) curses.putp(curses.tigetstr("rc")) sys.stdout.flush()
def draw(self, path, start_x, start_y, width, height): curses.putp(curses.tigetstr("sc")) tparm = curses.tparm(curses.tigetstr("cup"), start_y, start_x) if sys.version_info[0] < 3: sys.stdout.write(tparm) else: sys.stdout.buffer.write(tparm) # pylint: disable=no-member sys.stdout.write(self._generate_iterm2_input(path, width, height)) curses.putp(curses.tigetstr("rc")) sys.stdout.flush()
def write(self, status=None, timestamp=None, host=None, message=None): message = force_ascii(message) if message else '' if status: return curses.putp(self.status(status + '\r\n') + self.end_line) if not timestamp: return curses.putp(self.heading(message + ":\r\n") + self.end_line) curses.putp( self.timestamp('{0} '.format(timestamp)) + self.host('{0:<10s} '.format(host)) + self.format(message + '\r\n') + self.end_line)
def write(self, status=None, timestamp=None, host=None, message=None): message = force_ascii(message) if message else '' if status: return curses.putp(self.status(status + '\r\n') + self.end_line) if not timestamp: return curses.putp(self.heading(message + ":\r\n") + self.end_line) curses.putp(self.timestamp('{0} '.format(timestamp)) + self.host('{0:<10s} '.format(host)) + self.format(message + '\r\n') + self.end_line)
def slot_changed(self, book, dummy_data): """Slot for orderbook.signal_changed""" self.do_paint() # update the xterm title (this is not handled by curses) if self.gox.config.get_bool("goxtool", "set_xterm_title"): last_candle = self.gox.history.last_candle() if last_candle: title = self.gox.quote2str(last_candle.cls).strip() title += " - goxtool -" title += " bid:" + self.gox.quote2str(book.bid).strip() title += " ask:" + self.gox.quote2str(book.ask).strip() curses.putp("\033]0;%s\007" % title)
def slot_changed(self, book, dummy_data): """Slot for orderbook.signal_changed""" self.do_paint() # update the xterm title (this is not handled by curses) if self.gox.config.get_bool("goxtool", "set_xterm_title"): last_candle = self.gox.history.last_candle() if last_candle: title = goxapi.int2str(last_candle.cls, self.gox.currency).strip() title += " - goxtool -" title += " bid:" + goxapi.int2str(book.bid, self.gox.currency).strip() title += " ask:" + goxapi.int2str(book.ask, self.gox.currency).strip() curses.putp("\033]0;%s\007" % title)
def save_term_mode(*args, **kwargs): # print("BEGIN") isatty = sys.stdin.isatty() if isatty: tty_attrs = termios.tcgetattr(sys.stdin) curses.setupterm() term_rs2 = curses.tigetstr("rs2") try: yield finally: if isatty: termios.tcsetattr(sys.stdin, termios.TCSADRAIN, tty_attrs) if term_rs2: curses.putp(term_rs2)
def slot_changed(self, book, dummy_data): """Slot for orderbook.signal_changed""" self.do_paint() # update the xterm title (this is not handled by curses) if self.exch.config.get_bool("btctool", "set_xterm_title"): last_candle = self.exch.history.last_candle() if last_candle: title = btcapi.int2str(last_candle.cls, self.exch.currency).strip() title += " - btctool -" title += " bid:" + btcapi.int2str(book.bid, self.exch.currency).strip() title += " ask:" + btcapi.int2str(book.ask, self.exch.currency).strip() curses.putp("\033]0;%s\007" % title)
def main(): '''Main function, does high-level setup and kicks off the main loop.''' try: handler = context.SnipeLogHandler(logging.DEBUG) logging.getLogger().addHandler(handler) signal.signal(signal.SIGUSR1, handler.signal_dump) log = logging.getLogger('Snipe') log.warning('snipe starting') logging.captureWarnings(True) warnings.simplefilter('always') warnings.simplefilter('ignore', category=DeprecationWarning) options = parse_options(sys.argv) context_ = context.Context() handler.context = context_ context_.load(options) imbroglio.run(main_task(context_, handler, log)) except imbroglio.Cancelled: pass finally: try: ll = curses.tigetstr('ll') if ll: curses.putp(ll) else: curses.putp(curses.tparm(curses.tigetstr('cup'), 9999, 0)) except curses.error: pass log.warning('snipe ends') print() print('shutting down...', end='', flush=True) if handler.writing: handler.dump() logging.shutdown() print('.', end='', flush=True) print('.', flush=True)
symbol_git_push = '↑' symbol_git_pull = '↓' # Need apt-get install python3.8 gitstatus = subprocess.run(["git", "status", "--porcelain=2", "-b"], capture_output=True) if gitstatus.returncode == 0: stdout = gitstatus.stdout.decode("ascii") branch = re.compile("^# branch\.head (.+)", re.MULTILINE).search(stdout).group(1) ab_m = re.compile("^# branch\.ab \+([0-9]+) \-([0-9]+)", re.MULTILINE).search(stdout) output = cyan + symbol_git_branch.encode() + branch.encode() + " ".encode() if ab_m: ahead = ab_m.group(1) behind = ab_m.group(2) if int(ahead) > 0: output += green + symbol_git_push.encode() + ahead.encode() if int(behind) > 0: output += red + symbol_git_pull.encode() + behind.encode() output += clear curses.putp(output)
def stopwatch( stdscr, alt_format=False, font=DEFAULT_FONT, no_figlet=False, no_seconds=False, quit_after=None, title=None, no_window_title=False, **kwargs ): curses_lock, input_queue, quit_event = setup(stdscr) figlet = Figlet(font=font) if title and not no_figlet: title = figlet.renderText(title) input_thread = Thread( args=(stdscr, input_queue, quit_event, curses_lock), target=input_thread_body, ) input_thread.start() try: sync_start = datetime.now() seconds_elapsed = 0 while quit_after is None or seconds_elapsed < int(quit_after): if alt_format: countdown_text = format_seconds_alt(seconds_elapsed, 0, hide_seconds=no_seconds) else: countdown_text = format_seconds(seconds_elapsed, hide_seconds=no_seconds) with curses_lock: if not no_window_title: curses.putp("\033]2;{0}\007".format(countdown_text).encode()) stdscr.erase() draw_text( stdscr, countdown_text if no_figlet else figlet.renderText(countdown_text), title=title, ) sleep_target = sync_start + timedelta(seconds=seconds_elapsed + 1) now = datetime.now() if sleep_target > now: try: input_action = input_queue.get(True, (sleep_target - now).total_seconds()) except Empty: input_action = None if input_action == INPUT_PAUSE: pause_start = datetime.now() with curses_lock: if not no_window_title: curses.putp("\033]2;{0}\007".format(countdown_text).encode()) stdscr.erase() draw_text( stdscr, countdown_text if no_figlet else figlet.renderText(countdown_text), color=3, title=title, ) input_action = input_queue.get() if input_action == INPUT_PAUSE: sync_start += (datetime.now() - pause_start) if input_action == INPUT_EXIT: # no elif here! input_action may have changed break elif input_action == INPUT_RESET: sync_start = datetime.now() seconds_elapsed = 0 seconds_elapsed = int((datetime.now() - sync_start).total_seconds()) finally: with curses_lock: if not no_window_title: curses.putp("\033]2;\007".encode()) quit_event.set() input_thread.join() raise CursesReturnValue((datetime.now() - sync_start).total_seconds())
def module_funcs(stdscr): "Test module-level functions" for func in [curses.baudrate, curses.beep, curses.can_change_color, curses.cbreak, curses.def_prog_mode, curses.doupdate, curses.filter, curses.flash, curses.flushinp, curses.has_colors, curses.has_ic, curses.has_il, curses.isendwin, curses.killchar, curses.longname, curses.nocbreak, curses.noecho, curses.nonl, curses.noqiflush, curses.noraw, curses.reset_prog_mode, curses.termattrs, curses.termname, curses.erasechar, curses.getsyx]: func() # Functions that actually need arguments if curses.tigetstr("cnorm"): curses.curs_set(1) curses.delay_output(1) curses.echo() ; curses.echo(1) f = tempfile.TemporaryFile() stdscr.putwin(f) f.seek(0) curses.getwin(f) f.close() curses.halfdelay(1) curses.intrflush(1) curses.meta(1) curses.napms(100) curses.newpad(50,50) win = curses.newwin(5,5) win = curses.newwin(5,5, 1,1) curses.nl() ; curses.nl(1) curses.putp('abc') curses.qiflush() curses.raw() ; curses.raw(1) curses.setsyx(5,5) curses.tigetflag('hc') curses.tigetnum('co') curses.tigetstr('cr') curses.tparm('cr') curses.typeahead(sys.__stdin__.fileno()) curses.unctrl('a') curses.ungetch('a') curses.use_env(1) # Functions only available on a few platforms if curses.has_colors(): curses.start_color() curses.init_pair(2, 1,1) curses.color_content(1) curses.color_pair(2) curses.pair_content(curses.COLOR_PAIRS - 1) curses.pair_number(0) if hasattr(curses, 'use_default_colors'): curses.use_default_colors() if hasattr(curses, 'keyname'): curses.keyname(13) if hasattr(curses, 'has_key'): curses.has_key(13) if hasattr(curses, 'getmouse'): (availmask, oldmask) = curses.mousemask(curses.BUTTON1_PRESSED) # availmask indicates that mouse stuff not available. if availmask != 0: curses.mouseinterval(10) # just verify these don't cause errors m = curses.getmouse() curses.ungetmouse(*m)
def gotoyx(self, coord): if self.cursescolors == False: curses.putp(curses.tparm(curses.tigetstr("cup"), coord[0], coord[1]))
def countdown( stdscr, alt_format=False, font=DEFAULT_FONT, blink=False, critical=3, quit_after=None, text=None, timespec=None, title=None, voice=None, no_seconds=False, no_text_magic=True, no_figlet=False, no_window_title=False, **kwargs ): try: sync_start, target = parse_timestr(timespec) except ValueError: click.echo("Unable to parse TIME value '{}'".format(timespec)) exit(64) curses_lock, input_queue, quit_event = setup(stdscr) figlet = Figlet(font=font) if title and not no_figlet: title = figlet.renderText(title) input_thread = Thread( args=(stdscr, input_queue, quit_event, curses_lock), target=input_thread_body, ) input_thread.start() seconds_total = seconds_left = int(ceil((target - datetime.now()).total_seconds())) try: while seconds_left > 0 or blink or text: if alt_format: countdown_text = format_seconds_alt( seconds_left, seconds_total, hide_seconds=no_seconds) else: countdown_text = format_seconds(seconds_left, hide_seconds=no_seconds) if seconds_left > 0: with curses_lock: if not no_window_title: curses.putp("\033]2;{0}\007".format(countdown_text).encode()) stdscr.erase() draw_text( stdscr, countdown_text if no_figlet else figlet.renderText(countdown_text), color=1 if seconds_left <= critical else 0, title=title, ) if seconds_left <= 10 and voice: Popen(["/usr/bin/say", "-v", voice, str(seconds_left)]) # We want to sleep until this point of time has been # reached: sleep_target = sync_start + timedelta(seconds=1) # If sync_start has microsecond=0, it might happen that we # need to skip one frame (the very first one). This occurs # when the program has been startet at, say, # "2014-05-29 20:27:57.930651". Now suppose rendering the # frame took about 0.2 seconds. The real time now is # "2014-05-29 20:27:58.130000" and sleep_target is # "2014-05-29 20:27:58.000000" which is in the past! We're # already too late. We could either skip that frame # completely or we can draw it right now. I chose to do the # latter: Only sleep if haven't already missed our target. now = datetime.now() if sleep_target > now and seconds_left > 0: try: input_action = input_queue.get(True, (sleep_target - now).total_seconds()) except Empty: input_action = None if input_action == INPUT_PAUSE: pause_start = datetime.now() with curses_lock: stdscr.erase() draw_text( stdscr, countdown_text if no_figlet else figlet.renderText(countdown_text), color=3, ) input_action = input_queue.get() if input_action == INPUT_PAUSE: sync_start += (datetime.now() - pause_start) target += (datetime.now() - pause_start) if input_action == INPUT_EXIT: # no elif here! input_action may have changed break elif input_action == INPUT_RESET: sync_start, target = parse_timestr(timespec) seconds_left = int(ceil((target - datetime.now()).total_seconds())) continue sync_start = sleep_target seconds_left = int(ceil((target - datetime.now()).total_seconds())) if seconds_left <= 0: # we could write this entire block outside the parent while # but that would leave us unable to reset everything with curses_lock: curses.beep() if text and not no_text_magic: text = normalize_text(text) if text and not no_figlet: text = figlet.renderText(text) if blink or text: base_color = 1 if blink else 0 blink_reset = False flip = True slept = 0 extra_sleep = 0 while True: with curses_lock: curses.putp("\033]2;{0}\007".format("/" if flip else "\\").encode()) if text: draw_text(stdscr, text, color=base_color if flip else 4) else: draw_text(stdscr, "", color=base_color if flip else 4) if blink: flip = not flip try: sleep_start = datetime.now() input_action = input_queue.get(True, 0.5 + extra_sleep) except Empty: input_action = None finally: extra_sleep = 0 sleep_end = datetime.now() if input_action == INPUT_PAUSE: pause_start = datetime.now() input_action = input_queue.get() extra_sleep = (sleep_end - sleep_start).total_seconds() if input_action == INPUT_EXIT: # no elif here! input_action may have changed return elif input_action == INPUT_RESET: sync_start, target = parse_timestr(timespec) seconds_left = int(ceil((target - datetime.now()).total_seconds())) blink_reset = True break slept += (sleep_end - sleep_start).total_seconds() if quit_after and slept >= float(quit_after): return if blink_reset: continue finally: with curses_lock: if not no_window_title: curses.putp("\033]2;\007".encode()) quit_event.set() input_thread.join()
#
def colorWheel(argv): # # Set up the parser # parser = argparse.ArgumentParser(prog="colorWheel.py", description='produce a faster or slower color wheel', epilog='Glinsterlichten Project, 2016, @kellertuer') parser.add_argument('-f','--framerate', default=24, type=int, metavar='F', help='framerate used in the animation ') parser.add_argument('-r','--radialspeed', default=1, type=float, metavar='s', help='number of degrees per frame') parser.add_argument('-k','--keypressincrement', default=1, type=float, metavar='k', help='increment speed of keypresses') parser.add_argument('-s','--saturation', default=255, type=int, metavar='s', help='dim saturation in HSV model [0..255]') parser.add_argument('-v','--value', default=255, type=int, metavar='s', help='dim brightness (value) in HSV mode [0..255l') parser.add_argument('-x', default=8, type=int, metavar='X', help='number of horizontal board pixels') parser.add_argument('-y', default=16, type=int, metavar='X', help='number of vertical board pixels') args = parser.parse_args(argv) hue = np.zeros( (args.x,args.y) ) for x in range(args.x): for y in range(args.y): hue[x,y] = math.atan2(x-args.x/2,y-args.y/2)/(2*np.pi) # keep saturation and hue img = np.zeros( (args.x,args.y,3) ) # init stdscr = curses.initscr() curses.halfdelay(1) # How many tenths of a second are waited, from 1 to 255 # Iinit Library # c = glc.InitOPC() rs = args.radialspeed val = args.value sat = args.saturation angle = 0; while True: try: angle += rs if (angle > 360) or (angle <0): angle = angle% 360 for x in range(args.x): for y in range(args.y): r,g,b = colorsys.hsv_to_rgb( (hue[x,y]+angle/360.0)%1, sat/255.0,val/255.0) img[x,y,:] = np.round([r*255,g*255,b*255]) c.put_pixels(glc.image2pixels(img)) time.sleep(1/args.framerate) k = stdscr.getch() if k == ord('i'): rs -=args.keypressincrement rs = np.max( (args.keypressincrement,rs) ) curses.putp('Speed:'+str(rs)) if k == ord('o'): rs +=args.keypressincrement curses.putp('Speed:'+str(rs)) if k == ord('k'): val -=args.keypressincrement val = np.max( (val,0) ) curses.putp('Val:'+str(val)) if k == ord('l'): val +=args.keypressincrement val = np.min( (val,255) ) curses.putp('Val:'+str(val)) if k == ord('n'): sat -=args.keypressincrement sat = np.max( (sat,0) ) curses.putp('Sat:'+str(sat)) if k == ord('m'): sat +=args.keypressincrement sat = np.min( (sat,255) ) curses.putp('Sat:'+str(sat)) except KeyboardInterrupt: break # after while: destruct curses.flash() glc.destOPC(c,img) curses.endwin()