/* 
 *  Matchbox Window Manager - A lightweight window manager not for the
 *                            desktop.
 *
 *  Authored By Matthew Allum <mallum@o-hand.com>
 *
 *  Copyright (c) 2002, 2004 OpenedHand Ltd - http://o-hand.com
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2, or (at your option)
 *  any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 */

#include "xerror.h"

static int trapped_error_code = 0;
static int (*old_error_handler) (Display *d, XErrorEvent *e);


int 
handle_xerror(Display *dpy, XErrorEvent *e)
{
    if (e->error_code == BadAccess &&
	e->resourceid == RootWindow(dpy, DefaultScreen(dpy)) ) 
      {
        fprintf(stderr, 
		"root window unavailible (maybe another wm is running?)\n");
        exit(1);
      } 
    else 
      {
        char msg[255];
        XGetErrorText(dpy, e->error_code, msg, sizeof msg);
        fprintf(stderr, "OroboROX: X error warning (%#lx): %s (opcode: %i)\n",
		e->resourceid, msg, e->request_code);
      }

    return 0;
}

int 
ignore_xerror(Display *dpy, XErrorEvent *e)
{
   return 0;
}

static int
trapped_xerror_handler(Display     *display,
	      XErrorEvent *error)
{
   trapped_error_code = error->error_code;
   return 0;
}

void
misc_trap_xerrors(void)
{
  trapped_error_code = 0;
  dbg("**** %s() *****\n", __func__);
  old_error_handler = XSetErrorHandler(trapped_xerror_handler);
}

int
misc_untrap_xerrors(void)
{
  dbg("**** %s() *****\n", __func__);
  XSetErrorHandler(old_error_handler);
  return trapped_error_code;
}

