#!/usr/bin/env ruby
require "kconv"
require "slang"
include Slang

if ENV['LANG'] =~ /sjis/i
  $lang = Kconv::SJIS
else
  $lang = Kconv::EUC
end

class Pager2 < Pager
    def main_loop
      @do_break = FALSE
      while TRUE
	check_winch
	update_display
	sleep(0.01) if (IO::select([ STDIN ]))
	# c = STDIN.getc
	c = slkp_getkey
	# sl_reset;p c;exit
	key_actions_call(c)
	break if @do_break
      end
    end

  def build_lines
    if $file == nil
      fp = $stdin;
    else 
      begin
	fp = open($file, "r")
      rescue
	printf($stderr, "Unable to read %s\n", $file)
	exit
      end
    end

    while fp.gets
      str = Kconv.kconv($_, $lang, Kconv::AUTO)
      add_line(str)
    end
    
    init_lines
  end

 def draw_bottom
   slsmg_gotorc(@rmax, @cmin)
   reverse_color
   if $file
     slsmg_printf("%s ", $file)
   else
     slsmg_printf("<stdin> ")
   end
   slsmg_erase_eol
   normal_color
 end

 def post_winch_hook
   slsmg_cls
   #draw_bottom
   #update_display
 end

end

# --------- main 

if ARGV.length == 1
  $file = ARGV.shift
else
  if ARGV.length != 0 || $stdin.tty?
    printf($stderr, "Usage: %s [FILENAME]\n", $0);
    exit
  end
  $file = nil
end

mouse_on
exit unless init_terminal(1, 1)

def key_map
  slkp_define_keysym("\033>", PAGER_EOB)
  slkp_define_keysym("\033<", PAGER_BOB)
  slkp_define_keysym("q", PAGER_QUIT)
  slkp_define_keysym("b", PAGER_PPAGE)
  slkp_define_keysym(" ", PAGER_NPAGE)
  slkp_define_keysym("k", PAGER_KEY_UP)
  slkp_define_keysym("j", PAGER_KEY_DOWN)
  slkp_define_keysym("\033[M\040", SL_MOUSE_B0)
  slkp_define_keysym("\033[M\041", SL_MOUSE_B1)
  slkp_define_keysym("\033[M\042", SL_MOUSE_B2)
  slkp_define_keysym("/", PAGER_SEARCH_FWD)
  slkp_define_keysym("\033/", PAGER_SEARCH_BWD)
  slkp_define_keysym("n", PAGER_SEARCH_NEXT)
end

$p = Pager2.new(0, sltt_screen_rows-2, 0, sltt_screen_cols-1) # mini buffer
$p.set_mini_buffer(TRUE)
urlpat1 = Regexp.compile(/((?:http|ftp|mailto):(?:\/\/)?[@:=\.~\/\-_&#A-Za-z0-9]+)/)
urlpat2 = Regexp.compile(/([-\/=\.\w]+\@[-\.\w]+)/n)
$p.set_highlight_rex([[SL_BG_LGRAY+SL_RED, urlpat1], [SL_BG_LGRAY+SL_BLUE, urlpat2]])
key_map
#trap("SIGTSTP", "DEFAULT")
#trap("SIGCONT", "DEFAULT")
$p.main_loop
sl_reset
