/*------------------------------------------------------------------------------
 src/lib/djWidget/textWidget.cxx

 Copyright (c) 2004-2006 Darby Johnston.
 All rights reserved.
 Use is subject to license terms.
------------------------------------------------------------------------------*/

//#define DJ_DBG
#include "djTextWidget.h"
#include <FL/Fl.H>
#include <FL/fl_draw.H>
#include <FL/Fl_Input.H>
#include <FL/Fl_Output.H>

namespace dj {

TextWidget::TextWidget(const Str & in) :
  _value(in)
{
  _widget = new Fl_Input(0, 0, 0, 0);
  _widget->textfont(dj::font());
  _widget->textsize(dj::fontSize());
  add(_widget);
  
  sizePolicy(STRETCH, FIXED);

  widgetUpdate();
}

void TextWidget::set(const Str & in)
{
  if (in == _value) return;
  
  DJ_DBG_FNC("dj::TextWidget::set");
  DJ_DBG_PRN("in = " << in);
  
  _value = in;
  _sig.emit(_value);
  widgetUpdate();
}

const Vec2i TextWidget::sizeHint() const
{
  return Vec2i(layoutButtonSize(), labelsize()) + 2 * 2 + 2 * 2;
}

void TextWidget::resize(int x, int y, int w, int h)
{
  Widget::resize(x, y, w, h);
  _widget->resize(x, y, w, h);
}

int TextWidget::handle(int in)
{
  switch (in) {
  
    case FL_UNFOCUS:
      set(_widget->value());
      return 1;
    
    case FL_KEYBOARD:
      switch (Fl::event_key()) {
        case FL_Enter:
        case FL_KP_Enter:
          set(_widget->value());
          _actionSig.emit(true);
          return 1;
      }
      break;
  }
  
  return Widget::handle(in);
}

void TextWidget::widgetUpdate()
{
  _widget->value(_value.toAscii());
  
  const int mark = _value.size();
  _widget->position(mark, mark);
}

TextDisplayWidget::TextDisplayWidget(const Str & in) :
  _value(in)
{
  _widget = new Fl_Output(0, 0, 0, 0);
  _widget->textfont(dj::font());
  _widget->textsize(dj::fontSize());
  add(_widget);
  
  sizePolicy(STRETCH, FIXED);

  widgetUpdate();
}

void TextDisplayWidget::set(const Str & in)
{
  if (in == _value) return;
  
  DJ_DBG_FNC("dj::TextDisplayWidget::set");
  DJ_DBG_PRN("in = " << in);
  
  _value = in;
  widgetUpdate();
}

const Vec2i TextDisplayWidget::sizeHint() const
{
  return Vec2i(layoutButtonSize(), labelsize()) + 2 * 2 + 2 * 2;
}

void TextDisplayWidget::resize(int x, int y, int w, int h)
{
  Widget::resize(x, y, w, h);
  _widget->resize(x, y, w, h);
}

void TextDisplayWidget::widgetUpdate()
{
  _widget->value(_value.toAscii());
  
  const int mark = _value.size();
  _widget->position(mark, mark);
}

}
