class CmdLine < TkEntry

  def initialize (parent, action)
    @action= action
    @cmdline = TkVariable.new
    opts= TkDefaults::GUI['CmdLine'].update('textvariable'=> @cmdline )
    super(parent, opts )
    bind('KeyPress-Return', proc { do_callback })
    bind('Up', proc {|e| do_history(e) })
    bind('Down', proc {|e| do_history(e) })
#bind('Prior', proc {|e| @display.yview('scroll',-1,'pages') })
#bind('Next', proc {|e| @display.yview('scroll',1,'pages') })
    @history = []
    @hist_index=0
  end

  def do_history (e)
    case e.keysym
    when 'Up'
      @hist_index -= 1 if  @hist_index > 0
      @cmdline.value= @history[@hist_index]
    when 'Down'
      @hist_index += 1 if @hist_index <  @history.length 
      if @hist_index ==  @history.length
        @cmdline.value= ''
      else
        @cmdline.value= @history[@hist_index] 
      end
    end
    self.cursor= 'end'
  end

  def do_callback 
    return if @cmdline.value.empty?

#p  @cmdline.value

    @history.push( @cmdline.value)
    @action.call(@cmdline.value) 
    @cmdline.value=''
    @hist_index= @history.length 
  end

  def set_cmd (line)
    @cmdline.value= line + '  '
     # BUG: inverts the last two chars
    cursor= 'end'
  end
end


class Dialog < TkFrame

  attr_reader  :display, :modified

  def initialize (parent, name= '')
    super(parent,TkDefaults::GUI['Dialog.frame.main.'+ name])


    frame= TkFrame.new(self,TkDefaults::GUI['Dialog.frame.'+ name]).pack('fill'=> 'both','expand'=>'yes')
    @display=TkText.new(frame,TkDefaults::GUI['Dialog.text.'+ name] ).pack(
                                                                           'side' => 'left','expand'=>'yes','fill'=>'both')
    opts= TkDefaults::GUI['Dialog.scrollbar.'+ name].update('command' => proc { |*args| @display.yview *args} )
    @scrollbar=TkScrollbar.new(frame,opts).pack( 
                                                'side' => 'left',
                                                'fill' => 'y')
    @display.yscrollcommand(proc { |*args| @scrollbar.set( *args) })
    @display.bind('KeyPress', proc { @modified=true })

    Defaults.config_console_tags( @display)



  end


  def putline(line,*tags)

    line.gsub(/\\\\/,'\\\\\\\\')
    state=@display.cget('state')
    @display.configure('state'=>'normal') if state == 'disabled'
    @display.insert('end',line,*tags)	
    @display.configure('state'=>'disabled') if state == 'disabled'
    @display.see('end')
  end

  def clear
    state=@display.cget('state')
    @display.configure('state'=>'normal') if state == 'disabled'
    @display.delete(1.0,'end')
    @display.configure('state'=>'disabled') if state == 'disabled'
    @modified= false

  end

  def get_text
    @display.get(1.0,'end').chop
  end


end


