root/lib/cyborghood-messenger/terminal_cli.rb @ a1df93fe
205a27cc | Marc Dequènes (Duck) | #--
|
|
# CyborgHood, a distributed system management software.
|
|||
# Copyright (c) 2009-2011 Marc Dequènes (Duck) <Duck@DuckCorp.org>
|
|||
#
|
|||
# This program is free software: you can redistribute it and/or modify
|
|||
# it under the terms of the GNU General Public License as published by
|
|||
# the Free Software Foundation, either version 3 of the License, or
|
|||
# (at your option) any later version.
|
|||
#
|
|||
# This program is distributed in the hope that it will be useful,
|
|||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|||
# GNU General Public License for more details.
|
|||
#
|
|||
# You should have received a copy of the GNU General Public License
|
|||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|||
#++
|
|||
require 'readline'
|
|||
require 'shellwords'
|
|||
module CyborgHood
|
|||
module MessengerLand
|
|||
class TerminalCLI
|
|||
add_deferred_translations 'messenger'
|
|||
def initialize
|
|||
# save state of the terminal
|
|||
@stty_save = `stty -g`.chomp
|
|||
@thread = nil
|
|||
end
|
|||
def when_finished(&cb)
|
|||
@finished_cb = cb
|
|||
end
|
|||
def when_command_received(&cb)
|
|||
@cmd_recv_cb = cb
|
|||
end
|
|||
def run
|
|||
if @thread
|
|||
@thread.wakeup
|
|||
return
|
|||
end
|
|||
@thread = Thread.new do
|
|||
# TODO: handle completion
|
|||
while line = Readline.readline('> ', true)
|
|||
# remove empty lines, comments, or dups from history
|
|||
if line =~ /^\s*(#.*)?$/ or Readline::HISTORY.to_a[-2] == line
|
|||
Readline::HISTORY.pop
|
|||
end
|
|||
begin
|
|||
raw_cmd_parts = line.shellsplit
|
|||
rescue
|
|||
STDERR.puts "Syntax error in command."
|
|||
next
|
|||
end
|
|||
# TODO: handle files arguments (sym as ref)
|
|||
cmd = raw_cmd_parts
|
|||
refs = {}
|
|||
if @cmd_recv_cb
|
|||
EM.schedule do
|
|||
@cmd_recv_cb.call(cmd, refs) do |*reply|
|
|||
ok, messages = reply
|
|||
if ok
|
|||
messages.each{|msg| puts msg }
|
|||
else
|
|||
puts _("Internal error")
|
|||
end
|
|||
self.run
|
|||
end
|
|||
end
|
|||
end
|
|||
Thread.stop
|
|||
end
|
|||
# finished
|
|||
puts # newline to skip leftover prompt
|
|||
logger.debug "CLI: user exited"
|
|||
EM.schedule(@finished_cb) if @finished_cb
|
|||
end
|
|||
end
|
|||
def pause
|
|||
@thread.stop
|
|||
end
|
|||
def stop
|
|||
@thread.kill
|
|||
@thread = nil
|
|||
# restore state of the terminal
|
|||
system('stty', @stty_save)
|
|||
end
|
|||
end
|
|||
end # MessengerLand
|
|||
end
|