#!/usr/bin/env ruby
# the idea came from ftp://ftp.cs.hmc.edu/pub/me/urlview-0.7.tar.gz
require "slang"
include Slang
require "parsearg"
# original urlview's regexp 
# ((((ht|f)tp)|mailto):(//)?[^ >"]*|www.[-a-z0-9.]+)[^ .,;>">]
URLPAT = Regexp.compile(/((http|ftp|mailto):\/\/[:=\.~\/\-_&#A-Za-z0-9]+)/)

def show_usage()
  printf("Usage: %s [-m] [-s] -b browser-name \n", $0)
  printf('
        -b browser-name   specify browser program path
        -m                specify if you want to use mouse
        -s                specify if the browser is a X client
  ')
end

$USAGE='show_usage'
parseArgs(0, "b", "ms", "b:")

$mouse = TRUE if ($OPT_m)
$spawn = TRUE if ($OPT_s)

$browser = $OPT_b

def map_keys
  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("\033[M\040", SL_MOUSE_B0) if $mouse
end

class Urlview < Pager
  def initialize
    # cursor_move=TRUE , with_mini_buffer=TRUE
    super(0, sltt_screen_rows-2, 0, sltt_screen_cols-1)
    set_cursor(TRUE, 0, sltt_screen_rows-3)
    set_mini_buffer(TRUE)
  end

  def build_lines
    @urls = []
    
    while gets
      # use scan in case multiple URLs in a line
      $_.scan(URLPAT) do |mat|
	@urls <<  mat[0]
      end
    end

    @urls.uniq!

    @urls.each do |u|
      add_line(u)
    end
    @scrw.init_lines(@lines_num)
  end

  def draw_bottom
    slsmg_gotorc(@rmax, @cmin)
    reverse_color
    slsmg_printf("Press 'q' to quit. Press 'ENTER' to browse the URL")
    slsmg_erase_eol
    normal_color
  end

  def special_key_actions    
    # CR
    key_actions_add([0xd]) do
      open_url
    end

    if $mouse
      key_actions_add([SL_MOUSE_B0]) do # LEFT buttun
	c, r = sl_get_mouse_rc
	if r < @rmax and r >= @rmin
	  if  @urls[@scrw.line_num + r - 1]
	    @current_row = r
	    open_url
	  end
	end
      end
    end

  end

  def open_url
    num = @scrw.line_num + @current_row - 1
    url = @urls[num]
    if url
      len, str = sl_read_mini(sprintf("URL = %s: OK? (Y/n)", url))
      return if len > 0 and str =~ /^[Nn]/ 
      if $spawn # X browser ... any better idea ?
	cmd = sprintf("nohup %s %s > /dev/null &", $browser, url)
	system(cmd)
      else
	reset_tty
	slsmg_reset_smg
	cmd = sprintf("%s %s", $browser, url)
	system(cmd)
	init_terminal(1, 1)
	map_keys
      end
    end
  end

end

# --------- main 

mouse_on if $mouse
exit unless init_terminal(1, 1)
map_keys

p = Urlview.new

p.main_loop
sl_reset
exit
