//<copyright>
//
// Copyright (c) 1994,95,96
// Institute for Information Processing and Computer Supported New Media (IICM),
// Graz University of Technology, Austria.
//
//</copyright>

//<file>
//
// Name: KbdHandler.C
//
// Purpose:
//
// Created: 3.10.94   Gaisbauer Mansuet Juergen
//
// $Id: kbdhandler.C,v 1.2 1996/03/01 14:22:08 bmarsch Exp $
//
// Description:
//
//</file>
//
// $Log: kbdhandler.C,v $
// Revision 1.2  1996/03/01 14:22:08  bmarsch
// Added instrumentation
//
// Revision 1.1  1996/02/05 15:56:15  bmarsch
// Initial revision
//


#include "kbdhandler.h"

#include <InterViews/style.h>
#include <InterViews/hit.h>
#include <InterViews/event.h>
#include <InterViews/geometry.h>
#ifdef INSTRUMENTED
#include <InterViews/logging.h>
#endif

boolean KeyFunction::event(Event& e)
{
  boolean handled = true;
  switch (e.type()) {
    case Event::key:
      if (action_) {
#ifdef INSTRUMENTED
        Instrumentation::instance()->write_prefix(log_key);
#endif
        action_->execute();
      }
      break;
    default:
      /* ignore */
      break;
  }
  return handled;
}

KeyboardHandler::KeyboardHandler(Glyph *g)
: MonoGlyph(g)
{}

KeyboardHandler::~KeyboardHandler()
{
  removeAllFunctions();
}

void KeyboardHandler::pick(Canvas* c, const Allocation& a, int depth, Hit& h)
{
  const Event* e = h.event();

  if (e->type() == Event::key && 
      (h.right() >= a.left() && h.left() < a.right() &&
       h.top() >= a.bottom() && h.bottom() < a.top()
      )) {
    unsigned int mask = e->keymask();
    unsigned long sym = e->keysym();
    for (KeyFunction* itr = function_list_.getFirst(); itr; itr = function_list_.getNext(itr)) {
      if ((itr->keymask_ == mask) && (itr->keysym_ == sym)) {
        h.target(depth, this, 0, itr);
        return;
      }
    }
  }
  MonoGlyph::pick(c, a, depth, h);
}

void KeyboardHandler::appendFunction(KeyFunction* func)
{
  if (func) {
    Resource::ref(func);
    function_list_.addTail(func);
  }
}

void KeyboardHandler::removeFunction(KeyFunction* func)
{
  if (func) {
    function_list_.remove(func);
    Resource::unref(func);
  }
}

void KeyboardHandler::removeAllFunctions()
{
  KeyFunction* itr;
  while (itr = function_list_.removeHead()) {
    Resource::unref(itr);
  }
}
