/*------------------------------------------------------------------------------
 src/bin/djview/magnifyTool.cxx

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

//#define DJ_DBG
#include "magnifyTool.h"
#include "widget.h"
#include <djLabelWidget.h>
#include <djButtonWidget.h>
#include <djNumWidget.h>
#include <djImageWidget.h>

namespace djview {

MagnifyTool::MagnifyTool() :
  DialogBase("Magnify Tool"),
  _value(0),
  _zoom(2),
  _callbacks(true)
{
  // Widgets.
  //
  _widget = new ImageWidget;
  LabelWidget * zoomLabel = new LabelWidget("Zoom:");
  _zoomWidget = new IntWidget;
  Widget * dialogFrameWidget = new Widget;
  dialogFrameWidget->box(FL_THIN_UP_BOX);
  PushButtonWidget * closeWidget = new PushButtonWidget("Clos&e");
  
  // Layout.
  //
  VLayout * windowLayout = new VLayout(this);
  windowLayout->spacing(0);
  windowLayout->margin(0);
  windowLayout->add(_widget);
  windowLayout->stretch(_widget);
  windowLayout->add(dialogFrameWidget);
  HLayout * dialogFrameLayout = new HLayout(dialogFrameWidget);
  dialogFrameLayout->add(zoomLabel);
  dialogFrameLayout->add(_zoomWidget);
  dialogFrameLayout->stretchAdd();
  dialogFrameLayout->add(closeWidget);
  
  // Initialize.
  //
  widgetUpdate();
  size(max(sizeHint(), Vec2i(300, 300)));
  
  // Callbacks.
  //
  _zoomWidget->sig().set(this, zoomCallback);
  closeWidget->sig().set(this, closeCallback);
}

void MagnifyTool::set(const ViewWidget * in)
{
  _value = in;

  // XXX Should copy image data instead.
  //  
  _widget->set(_value->image());
  _widget->viewPositionZoom(
    (_value->viewPosition() - _value->mouse()) *
      ImageWidget::zoomToFloat(_zoom) +
      Vec2i(_widget->w(), _widget->h()) / 2,
    _value->viewZoom() + _zoom
  );
  _widget->redraw();
}

void MagnifyTool::del(const ViewWidget * in)
{
  if (in == _value) {
    _value = 0;
    _widget->set(0);
    _widget->redraw();
  }
}

void MagnifyTool::zoomCallback(int in)
{
  if (! _callbacks) return;
  _zoom = in;
  widgetUpdate();
}

void MagnifyTool::closeCallback(bool)
{
  if (! _callbacks) return;
  hide();
}

void MagnifyTool::widgetUpdate()
{
  _callbacks = false;
    
  _zoomWidget->set(_zoom);

  _callbacks = true;
}

void MagnifyTool::prefs(const Prefs & in)
{
  Prefs prefs(in, "magnifyTool");

  prefs.get("zoom", &_zoom, _zoom);
  
  widgetUpdate();
}

void MagnifyTool::prefs(Prefs * in)
{
  Prefs prefs(in, "magnifyTool");

  prefs.set("zoom", _zoom);
}

}
