/* buttons.c --- handle button changes and various.  */

#include "d2rd.h"
#include "menus.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "kernel.h"
#include "template.h"
#include "resspr.h"
#include "res.h"

struct display *which_menu;

wimp_menustr *iconbar_menu;
menu window_menu, mag_menu, goto_page, saveas_menu;

char goto_page_buffer[12];

void
handle_buttons (wimp_eventdata *b)
{
  struct display *w;
  wimp_dragstr d;
  wimp_icon ic;
  wimp_mousestr m;
  int i, x, y;

  /* Menu on the iconbar icon.  */

  if (b->but.m.bbits == wimp_BMID && b->but.m.w == -2 && b->but.m.i == iconbar_icon)
    {
      which_menu = 0;
      wimp_create_menu (iconbar_menu, b->but.m.x - 64, 96 + 2 * 45);
      return;
    }

  /* Drag from the saveas menu-window.  */

  if (b->but.m.w == saveas && b->but.m.i == SAVEAS_FILEICON && b->but.m.bbits == wimp_BDRAGLEFT)
    {
      wimpt_noerr (wimp_get_point_info (&m));
      wimpt_noerr (wimp_get_icon_info (saveas, SAVEAS_FILEICON, &ic));
      d.window = saveas;
      d.type = wimp_USER_FIXED;
      x = ic.box.x1 - ic.box.x0;
      y = ABS (ic.box.y1 - ic.box.y0);
      d.box.x0 = m.x - x / 2;
      d.box.y0 = m.y - y / 2;
      d.box.x1 = m.x + x / 2;
      d.box.y1 = m.y + y / 2;
      d.parent.x0 = -4242;
      d.parent.y0 = -4242;
      d.parent.x1 = 4242;
      d.parent.y1 = 4242;
      wimpt_noerr (wimp_drag_box (&d));
      return;
    }

  /* OK clicked in the saveas menu leaf.  */

  if (b->but.m.w == saveas && b->but.m.i == SAVEAS_OKBUTTON)
    {
      if (strchr (saveas_buffer, '.'))
        output_saveas (saveas_buffer);
      else
        fatal ("To save, drag icon to a directory viewer.");
      return;
    }

  for (w = windows; w; w = w->next)
    if (w->w_handle == b->but.m.w)
      break;

  wimp_get_point_info (&menu_pos);

  /* Sink a button event for an unknown window.  */

  if (w == NULL)
    return;

  if (b->but.m.bbits == wimp_BMID)
    {
      /* Pop up the window menu.  Shade the `Next', `Previous' and `Goto
         page' menu items in case the document only has one page.  */

      menu_setflags (window_menu, 1 + MAINMENU_NEXT, 0, w->page->next == NULL || w->page->next->complete == FALSE);
      menu_setflags (window_menu, 1 + MAINMENU_PREVIOUS, 0, w->page == w->file->pages);
      menu_setflags (window_menu, 1 + MAINMENU_GOTO_PAGE, 0, w->file->pages->next == NULL);

      /* Tick the approriate \magstep value.  */

      for (i = 0; i < 7; i++)
        menu_setflags (mag_menu, 1 + i, w->magstep == i, 0);

      /* Tick the 75dpi tweak icon, if active */
      menu_setflags (mag_menu, 8, w->mag_tweak != 1.0, 0);

      sprintf (goto_page_buffer, "%d", w->page->dvi_page);

      wimp_create_menu (menu_syshandle (window_menu), b->but.m.x - 64, b->but.m.y + 16);
      which_menu = w;
    }
}

/* EOF buttons.c */
