#!ruby -Ks
#-- console.rb .. a sample for DosCmd.so
Thread.critical = true
Thread.abort_on_exception = true
require "phi" 
require "DosCmd"  # DosCmd.so in this directory

module Win32_ex
  module_function
  require "Win32API"
  
  EM_GETSEL              = 0x00B0;
  EM_LINEINDEX           = 0x00BB;
  EM_LINEFROMCHAR        = 0x00C9;

  SendMessage = Win32API.new( 'user32' , 'SendMessage' , %w(N N N P) , "N" )

  def send_message( handle , msg , wp ,lp )
    SendMessage.Call( handle , msg , wp , lp )
  end
end

module Phi
  class Memo
    # nifty:FDELPHI/MES/16/681
    def row_col_str
      tmp = self.sel_start
      row =       Win32_ex.send_message( handle , Win32_ex::EM_LINEFROMCHAR , tmp , 0 )
      col = tmp - Win32_ex.send_message( handle , Win32_ex::EM_LINEINDEX    , -1, 0 );
      str = (lines.count > row) ? lines[row] : ""
      [row,col,str]
    end
    def current_line
      row_col_str[2]
    end
  end
end

########


form = Phi::Form.new :form , "Console by DosCommand"

	##	All is OK!

memo  = Phi::Memo.new   form
memo.lines.text =<<MMMM
ruby_ap pause_test.rb
apollo -q pause_test.rb
apollo -Q pause_test.rb
ruby pause_test.rb
#{ENV['ComSpec']} /c dir
grep -i "Win32" *.*
-------
MMMM

btn   = Phi::Button.new form , :btn , "end"
panel = Phi::Panel.new  form
panel.height = 20

panel.align = Phi::AL_BOTTOM
btn.align   = Phi::AL_BOTTOM
memo.align  = Phi::AL_CLIENT

cmd  = Phi::DosCommand.new(form)
cmd.output_lines = memo.lines

#-- たぶんこれが必要。 before DosCmd.dpr  ver. 0.1.4
##cmd.creation_flag = 9           # コンソールの即時表示に必要。fDETACHED_PROCESS
##cmd.show_window = Phi::SW_SHOW  # フォームを表示するのに必要

cmd.on_terminate = proc{p "on_terminate"}
cnt = 0
#cmd.on_new_line = proc{ cnt += 1 ; form.caption = "on_new_line(#{cnt})"}
p cmd.exit_code

def cmd.command_line=( s )
  super s
end

btn.on_click = proc{ 
  if cmd.active?
    cmd.stop 
  else
    cmd.command_line = memo.current_line
    cmd.execute
  end
}

form.on_close = proc{ cmd.stop }

timer = Phi::Timer.new
timer.on_timer = proc{
  stat = "#{cmd.thread_status} #{cmd.since_last_output} #{cmd.since_beginning} #{cmd.prompting}"
  
  if cmd.active?
    panel.caption = "status .. Running #{cmd.command_line} #{stat}"
    btn.caption = "stop .. '#{cmd.command_line}'"
  else
    panel.caption = "status .. Terminated #{stat}"
    btn.caption = "run .. '#{memo.current_line}'"
  end
}

memo.on_key_press = proc{|sender,key|
  if cmd.active?
    panel.caption = "send #{key.chr}"
    cmd.send_line( "#{key.chr}" , (key==13))
    key = 0
  else
    if key == 13
      cmd.command_line = memo.current_line
      cmd.execute
      key = 0
    end
  end
  key
}

memo.on_change = proc{
  if cmd.active?
    unless cmd.line_beginned
      memo.sel_start -= 1
    end
  end
}

form.show
Phi.mainloop

