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

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

#include "djMenuWidget.h"
#include <FL/Fl.H>

namespace dj {

class _MenuItem {
public:

  _MenuItem();
  _MenuItem(
    const Str & label, int shortcut,
    Fl_Callback * callback, void * data,
    int flags = 0
  );
  ~_MenuItem();
  
  char * _ascii;
  int _shortcut;
  Fl_Callback * _callback;
  void * _data;
  int _flags;
};

_MenuItem::_MenuItem() :
  _ascii(0), _shortcut(0),
  _callback(0), _data(0),
  _flags(0)
{}

_MenuItem::_MenuItem(
  const Str & label, int shortcut,
  Fl_Callback * callback, void * data,
  int flags
) :
  _ascii(0), _shortcut(shortcut),
  _callback(callback), _data(data),
  _flags(flags)
{
  _ascii = toAscii(label);
}

_MenuItem::~_MenuItem()
{
  if (_ascii) delete [] _ascii;
}

MenuItems::~MenuItems()
{
  del();
}
  
int MenuItems::add(
  const Str & label, int shortcut,
  Fl_Callback * callback, void * data,
  int flags
) {
  _itemList += new _MenuItem(
    label, shortcut,
    callback, data,
    flags
  );
  return _itemList.size() - 1;
}

void MenuItems::end()
{
  _itemList += new _MenuItem;
}
  
void MenuItems::del()
{
  for (ListIt<_MenuItem *> it = _itemList; it.isValid(); ++it)
    delete it();
  _itemList.del();
}
  
void MenuItems::set(Fl_Menu_ * in)
{
  // XXX FLTK menus are ill.
  //
  in->clear();
  if (! _itemList.size()) return;
  Fl_Menu_Item * fl = new Fl_Menu_Item [_itemList.size()];
  for (ListIt<_MenuItem *> it = _itemList; it.isValid(); ++it) {
    fl[it.count()].text = it()->_ascii;
    fl[it.count()].shortcut_ = it()->_shortcut;
    fl[it.count()].callback_ = it()->_callback;
    fl[it.count()].user_data_ = it()->_data;
    fl[it.count()].flags = it()->_flags;
    fl[it.count()].labeltype_ = 0;
    fl[it.count()].labelfont_ = 0;
    fl[it.count()].labelsize_ = 0;
    fl[it.count()].labelcolor_ = 0;
  }
  in->copy(fl);
  delete [] fl;
}
  
MenubarWidget::MenubarWidget() :
  Fl_Menu_Bar(0, 0, 0, 0)
{
  box(FL_THIN_UP_BOX);
  textfont(dj::font());
  textsize(dj::fontSize());
  textcolor(FL_FOREGROUND_COLOR);

  sizePolicy(STRETCH, FIXED);
}

const Vec2i MenubarWidget::sizeHint() const
{
  return
    Vec2i(0, labelsize()) +
    layoutWidgetMargin() * 2 +
    Vec2i(Fl::box_dw(box()), Fl::box_dh(box()));
}

void MenubarWidget::resize(int x, int y, int w, int h)
{
  Fl_Menu_Bar::resize(x, y, w, h);
  WidgetBase::resize(x, y, w, h);
}

int MenubarWidget::visible() const { return Fl_Menu_Bar::visible(); }

}
