Last active
December 16, 2015 01:19
-
-
Save supki/5354231 to your computer and use it in GitHub Desktop.
ncurses-based list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# -*- coding: utf-8 -*- | |
require 'curses' | |
# Prepare curses and cleanup after application is finished | |
def with_curses | |
Curses.noecho # Do not print input keys | |
Curses.curs_set 0 # Remove cursor | |
Curses.init_screen | |
Curses.start_color # Enable colors | |
# Load color settings for list elements | |
Curses.init_pair(1, Curses::COLOR_BLACK, Curses::COLOR_YELLOW) # Highlighted element | |
Curses.init_pair(2, Curses::COLOR_YELLOW, Curses::COLOR_BLACK) # Ordinary element | |
begin | |
yield | |
ensure | |
Curses.close_screen | |
end | |
end | |
class CursedList | |
attr_reader :elems | |
def initialize elems = [] | |
@elems = elems.map { |x| x.to_s.rjust Curses.cols } | |
@current = 0 | |
@top = 0 | |
display | |
end | |
def display | |
h = Curses.lines | |
@top &&= [0, @current - h / 2].max if @current + h / 2 - 1 < @elems.size | |
@bottom = [@elems.size - 1, @top + h - 1].min | |
@elems[@top..@bottom].each_with_index do |elem, index| | |
Curses.setpos(index, 0) | |
Curses.attron(Curses.color_pair(if index + @top == @current then 1 else 2 end)) | |
Curses.addstr(elem) | |
end | |
@forced = false | |
end | |
def move direction | |
case direction | |
when :up then @current -= 1 unless @current <= 0 | |
when :down then @current += 1 unless @current >= @elems.size - 1 | |
end | |
display | |
end | |
def append elem | |
@elems << elem | |
@top += 1 if @top != 0 | |
display | |
end | |
end | |
class CursedList | |
def open | |
append(@elems.max.to_i.succ.to_s.rjust(Curses.cols)) | |
end | |
def download | |
end | |
end | |
with_curses do | |
xs = CursedList.new | |
loop do | |
case Curses.getch | |
when ?q then break | |
when ?k then xs.move(:up) | |
when ?j then xs.move(:down) | |
when ?o then xs.open | |
when ?d then xs.download | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment