// Copyright 2013 Intel Corporation
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
//   list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

/// @file
/// @brief Wrappers for Xlib functions
///
/// Each wrapper catches any Xlib error emitted by the wrapped function. The
/// wrapper's signature matches the wrapped.
///
/// All Xlib error generated by Waffle must be caught by Waffle. Otherwise, the
/// Xlib error handler installed by the user will catch the error and may
/// handle it in a way Waffle doesn't like. Or, even worse, the default Xlib
/// error handler will catch it, which exits the process.

#pragma once

#include <X11/Xlib-xcb.h>

#define X11_SAVE_ERROR_HANDLER \
    int (*old_handler)(Display*, XErrorEvent*) = \
        XSetErrorHandler(x11_dummy_error_handler);

#define X11_RESTORE_ERROR_HANDLER \
        XSetErrorHandler(old_handler);

static inline int
x11_dummy_error_handler(Display *dpy, XErrorEvent *err)
{
    return 0;
}

static inline Display*
wrapped_XOpenDisplay(const char *name)
{
    X11_SAVE_ERROR_HANDLER
    Display *dpy = XOpenDisplay(name);
    X11_RESTORE_ERROR_HANDLER
    return dpy;
}

static inline int
wrapped_XCloseDisplay(Display *dpy)
{
    X11_SAVE_ERROR_HANDLER
    int error = XCloseDisplay(dpy);
    X11_RESTORE_ERROR_HANDLER
    return error;
}

static inline xcb_connection_t*
wrapped_XGetXCBConnection(Display *dpy)
{
    X11_SAVE_ERROR_HANDLER
    xcb_connection_t *conn = XGetXCBConnection(dpy);
    X11_RESTORE_ERROR_HANDLER
    return conn;
}
