Add licence and installation instructions.
[kaya.git] / lib / history.rb
bloba300fa939bc8c499b216203fea9301c62a283a5f
1 # Copyright (c) 2009 Paolo Capriotti <p.capriotti@gmail.com>
2
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 2 of the License, or
6 # (at your option) any later version.
8 require 'observer_utils.rb'
10 class History
11   include Enumerable
12   include Observable
13   
14   attr_reader :current
15   
16   Item = Struct.new(:state, :move, :text)
17   OutOfBound = Class.new(Exception)
19   def initialize(state)
20     @history = [Item.new(state.dup, nil, "Mainline")]
21     @current = 0
22   end
23   
24   def each
25     @history.each {|item| yield item.state, item.move }
26   end
27   
28   def add_move(state, move)
29     item = Item.new(state.dup, move, nil)
30     old_size = @history.size
31     
32     @history = @history[0..@current]
34     @history << item
35     @current = @history.size - 1
36     
37     fire :new_move
38   end
39   
40   def forward
41     raise OutOfBound if @current >= @history.size - 1
42     @current += 1
43     item = @history[@current]
44     
45     fire :current_changed
46     [item.state, item.move]
47   end
48   
49   def back
50     raise OutOfBound if @current <= 0
51     move = @history[@current].move
52     @current -= 1
53     
54     fire :current_changed
55     [@history[@current].state, move]
56   end
57   
58   def go_to(index)
59     if index != @current
60       item = self[index]
61       @current = index
62       fire :current_changed
63       [item.state, item.move]
64     end
65   end
66   
67   def go_to_last
68     go_to(size - 1)
69   end
70   
71   def go_to_first
72     go_to(0)
73   end
74   
75   def state
76     @history[current].state
77   end
78   
79   def move
80     @history[current].move
81   end
82   
83   def size
84     @history.size
85   end
86   
87   def [](index)
88     if index >= @history.size || index < 0
89       raise OutOfBound 
90     end
91     @history[index]
92   end
93 end