More work on the connection class.
[kaya/ydirson.git] / lib / ics / connection.rb
blobb65fbf8bc7021db6cc9f6d86e3db300867f3e43d
1 require 'qtutils'
3 module ICS
5
6 # A connection to an ICS server
7
8 class Connection < Qt::Object
9   attr_accessor :debug
11   signals :hostFound, :established,
12   'receivedLine(QString, int)',
13   'receivedText(QString, int)'
15   def initialize(host, port)
16     super nil
18     @create_socket = lambda do 
19       puts "connecting to #{host}:#{port}"
20       s = Qt::TcpSocket.new(self)
21       connect(s, SIGNAL(:hostFound), self, SIGNAL(:hostFound))
22       s.connect(s, SIGNAL(:connected), self, SIGNAL(:established))
23       s.on(:readyRead) { process_line }
24       s.connect_to_host(host, port)
25       s
26     end
27   end
29   def process_line
30     puts "processing line"
31     unless @socket
32       puts "no socket!"
33       return
34     end
35     
36     while @socket.can_read_line
37       line = @socket.read_line.to_s
38       line = @buffer + line.gsub("\r", '')
39       emit receivedLine(line, @buffer.size)
40       @buffer = ''
41     end
43     if (size = @socket.bytes_available) > 0
44       data = @socket.read_all
45       offset = @buffer.size
46       @buffer += data.to_s.gsub("\r", '')
47       emit receivedText(@buffer, offset)
48     end
49     
50   end
52   def start
53     @socket = @create_socket.call
54     @connected = true
55     @buffer = ''
56   end
58   def stop
59   end
61   def send_text(text)
62     puts "> #{text}" if @debug
63     unless @connected
64       @unsent_text += @text + "\n"
65       return
66     end
67     
68     unless @socket
69       puts "no socket!"
70       return
71     end
72     
73     process_line
74     os = Qt::TextStream(@socket)
75     os << text + "\n"
76   end
78   def on_received_line(&blk)
79     connect(self, SIGNAL('receivedLine(QString, int)'), &blk)
80   end
82   def on_received_text(&blk)
83     connect(self, SIGNAL('receivedText(QString, int)'), &blk)
84   end
85 end
87 end