Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/woip/rb/livesearch.rb
blob: f57ae049ff97d48ceea6ebb8510ddc03a78dc4a1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
require 'rubygems'
require 'curses'
require 'inline'

class TernarySearcher
  RESULTS = 10
  
  inline(:C) do |builder|
    builder.include '"ternary.h"'
    builder.add_compile_flags "-I../c -I. -DDEBUG"
    builder.add_compile_flags "../c/searcher.c"
    
    builder.prefix "
    char resultbuf[#{RESULTS}][MAXLINE];
    int haveresults;
    "
    
    builder.c "int handleResult(char *s) {
      strncpy(resultbuf[haveresults++], s, MAXLINE);
      if(haveresults == #{RESULTS}) return false;
      else return true;
    }"
    
    builder.c 'void __init(char *indexFile) {
      load_root(indexFile);
    }'
    
    builder.c 'void __prefixSearch(char *s, int n) {
      haveresults = 0;
      root_search(s, handleResult);
    }'
  end
  
  def initialize(index)
    __init(index)
  end
  
  def prefixSearch(str, n)
    @results = []
    __prefixSearch(str, n)
  end
end

class Searcher
  def initialize
    @needle = ""
    @xap = XapianSearcher.new(ARGV.first)
  end
  
  def refresh
    Curses.clear
    Curses.setpos(0, 0)
    Curses.addstr(@needle)
    draw_matches
    Curses.refresh
  end
  
  def draw_matches
    line = 1
    @matches.each do |match|
      match.draw(line += 1)
    end
  end
  
  def search
    @matches = @xap.matches(@needle).map do |match|
      Match.new(match)
    end
  end
  
  def run
    Curses.init_screen
    Curses.noecho
    Curses.stdscr.keypad(true)
    
    loop do
      char = Curses.getch
      
      if char == 127 # Backspace
        @needle = @needle[0..-2] unless @needle.empty?
      else
        @needle += char.chr
      end
      search
      refresh
    end        
  ensure
    Curses.close_screen
  end
end

class Match
  def initialize(str)
    @string = str
  end
  
  def draw(line)
    Curses.setpos(line, 0)
    Curses.addstr(@string)
  end
end

if $0 == __FILE__
  puts "running..."
  Searcher.new.run
end