/**************************************************************************
*
* Tint2 : common windows function
*
* Copyright (C) 2007 Pål Staurland (staura@gmail.com)
* Modified (C) 2008 thierry lorthiois (lorthiois@bbsoft.fr) from Omega distribution
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* 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.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
**************************************************************************/

#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <sys/types.h>

#include <Imlib2.h>
#include <cairo.h>
#include <cairo-xlib.h>

#include <X11/extensions/XShm.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#include "common.h"
#include "window.h"
#include "server.h"
#include "panel.h"
#include "taskbar.h"

void activate_window(Window win)
{
    send_event32(win, server.atom [_NET_ACTIVE_WINDOW], 2, CurrentTime, 0);
}

void change_window_desktop(Window win, int desktop)
{
    send_event32(win, server.atom [_NET_WM_DESKTOP], desktop, 2, 0);
}

void close_window(Window win)
{
    send_event32(win, server.atom [_NET_CLOSE_WINDOW], 0, 2, 0);
}

void toggle_window_shade(Window win)
{
    send_event32(win, server.atom [_NET_WM_STATE], 2, server.atom [_NET_WM_STATE_SHADED], 0);
}

void toggle_window_maximized(Window win)
{
    send_event32(win, server.atom [_NET_WM_STATE], 2, server.atom [_NET_WM_STATE_MAXIMIZED_VERT], 0);
    send_event32(win, server.atom [_NET_WM_STATE], 2, server.atom [_NET_WM_STATE_MAXIMIZED_HORZ], 0);
}

gboolean window_is_hidden(Window win)
{
    Window window;
    int count;

    Atom *at = get_property(win, server.atom [_NET_WM_STATE], XA_ATOM, &count);
    for (int i = 0; i < count; i++)
    {
        if (at[i] == server.atom [_NET_WM_STATE_SKIP_TASKBAR]) {
            XFree(at);
            return TRUE;
        }
        // do not add transient_for windows if the transient window is already in the taskbar
        window = win;
        while (XGetTransientForHint(server.display, window, &window))
            if (get_task_buttons(window)) {
                XFree(at);
                return TRUE;
            }
    }
    XFree(at);

    at = get_property(win, server.atom [_NET_WM_WINDOW_TYPE], XA_ATOM, &count);
    for (int i = 0; i < count; i++)
        if (at[i] == server.atom [_NET_WM_WINDOW_TYPE_DOCK] || at[i] == server.atom [_NET_WM_WINDOW_TYPE_DESKTOP] ||
            at[i] == server.atom [_NET_WM_WINDOW_TYPE_TOOLBAR] || at[i] == server.atom [_NET_WM_WINDOW_TYPE_MENU] ||
            at[i] == server.atom [_NET_WM_WINDOW_TYPE_SPLASH])
        {
            XFree(at);
            return TRUE;
        }
    XFree(at);

    for (int i = 0; i < num_panels; i++)
        if (panels[i].main_win == win)
            return TRUE;

    // specification
    // Windows with neither _NET_WM_WINDOW_TYPE nor WM_TRANSIENT_FOR set
    // MUST be taken as top-level window.
    return FALSE;
}

int get_window_desktop(Window win)
{
    int desktop = get_property32(win, server.atom [_NET_WM_DESKTOP], XA_CARDINAL);
    if (desktop == ALL_DESKTOPS)
        return desktop;
    if (!server.viewports)
        return CLAMP(desktop, 0, server.num_desktops - 1);

    int x, y, w, h;
    get_window_coordinates(win, &x, &y, &w, &h);

    desktop = get_current_desktop();
    // Window coordinates are relative to the current viewport, make them absolute
    x += server.viewports[desktop].x;
    y += server.viewports[desktop].y;

    if (x < 0 || y < 0) {
        long *x_screen_size = get_property(server.root_win, server.atom [_NET_DESKTOP_GEOMETRY], XA_CARDINAL, NULL);
        if (!x_screen_size)
            return 0;
        int x_screen_width = x_screen_size[0];
        int x_screen_height = x_screen_size[1];
        XFree(x_screen_size);

        // Wrap
        if (x < 0)
            x += x_screen_width;
        if (y < 0)
            y += x_screen_height;
    }

    int best_match = -1;
    int match_right = 0;
    int match_bottom = 0;
    // There is an ambiguity when a window is right on the edge between viewports.
    // In that case, prefer the viewports which is on the right and bottom of the window's top-left corner.
    for (int i = 0; i < server.num_desktops; i++) {
        if (x >= server.viewports[i].x && x <= (server.viewports[i].x + server.viewports[i].width) &&
            y >= server.viewports[i].y && y <= (server.viewports[i].y + server.viewports[i].height)) {
            int current_right = x < (server.viewports[i].x + server.viewports[i].width);
            int current_bottom = y < (server.viewports[i].y + server.viewports[i].height);
            if (best_match < 0 || (!match_right && current_right) || (!match_bottom && current_bottom)) {
                best_match = i;
            }
        }
    }

    if (best_match < 0)
        best_match = 0;
    // fprintf(stderr, "tint2: window %lx %s : viewport %d, (%d, %d)\n", win, get_task(win) ? get_task(win)->title :
    // "??",
    // best_match+1, x, y);
    return best_match;
}

#define swap(a, b) do { __typeof__(a) _tmp = (a); (a) = (b); (b) = _tmp; } while(0)

int get_interval_overlap(int a1, int a2, int b1, int b2)
{
    if (a1 > b1) {
        swap(a1, b1);
        swap(a2, b2);
    }
    if (b1 <= a2)
        return a2 - b1;
    return 0;
}

int get_window_monitor(Window win)
{
    int x, y, w, h;
    get_window_coordinates(win, &x, &y, &w, &h);

    int best_match = 0;
    int best_area = -1;
    for (int i = 0; i < server.num_monitors; i++) {
        // Another false warning: possibly uninitialized w and h
        int commonx = get_interval_overlap(x, x + w, server.monitors[i].x, server.monitors[i].x + server.monitors[i].width);
        int commony = get_interval_overlap(y, y + h, server.monitors[i].y, server.monitors[i].y + server.monitors[i].height);
        int area = commonx * commony;
        if (0)
            printf("Monitor %d (%dx%d+%dx%d): win (%dx%d+%dx%d) area %dx%d=%d\n",
                   i, server.monitors[i].x, server.monitors[i].y, server.monitors[i].width, server.monitors[i].height,
                   x, y, w, h,
                   commonx, commony, area);
        if (area > best_area) {
            best_area = area;
            best_match = i;
        }
    }
    return best_match;
}

gboolean get_window_coordinates(Window win, int *x, int *y, int *w, int *h)
{
    int dummy_int;
    unsigned ww, wh, bw, bh;
    Window src;
    if (!XTranslateCoordinates(server.display, win, server.root_win, 0, 0, x, y, &src) ||
        !XGetGeometry(server.display, win, &src, &dummy_int, &dummy_int, &ww, &wh, &bw, &bh))
        return FALSE;
    *w = ww + bw;
    *h = wh + bw;
    return TRUE;
}

gboolean window_is_iconified(Window win)
{
    // EWMH specification : minimization of windows use _NET_WM_STATE_HIDDEN.
    // WM_STATE is not accurate for shaded window and in multi_desktop mode.
    int count;
    Atom *at = get_property(win, server.atom [_NET_WM_STATE], XA_ATOM, &count);
    for (int i = 0; i < count; i++)
        if (at[i] == server.atom [_NET_WM_STATE_HIDDEN]) {
            XFree(at);
            return TRUE;
        }
    XFree(at);
    return FALSE;
}

gboolean window_is_urgent(Window win)
{
    int count;

    Atom *at = get_property(win, server.atom [_NET_WM_STATE], XA_ATOM, &count);
    for (int i = 0; i < count; i++)
        if (at[i] == server.atom [_NET_WM_STATE_DEMANDS_ATTENTION]) {
            XFree(at);
            return TRUE;
        }
    XFree(at);
    return FALSE;
}

gboolean window_is_skip_taskbar(Window win)
{
    int count;

    Atom *at = get_property(win, server.atom [_NET_WM_STATE], XA_ATOM, &count);
    for (int i = 0; i < count; i++) {
        if (at[i] == server.atom [_NET_WM_STATE_SKIP_TASKBAR]) {
            XFree(at);
            return TRUE;
        }
    }
    XFree(at);
    return FALSE;
}

Window get_active_window()
{
    return get_property32(server.root_win, server.atom [_NET_ACTIVE_WINDOW], XA_WINDOW);
}

gboolean window_is_active(Window win)
{
    return (win == get_property32(server.root_win, server.atom [_NET_ACTIVE_WINDOW], XA_WINDOW));
}

int get_icon_count(gulong *data, int num)
{
    int count, pos, w, h;

    count = 0;
    pos = 0;
    while (pos + 2 < num) {
        w = data[pos++];
        h = data[pos++];
        pos += w * h;
        if (pos > num || w <= 0 || h <= 0)
            break;
        count++;
    }

    return count;
}

gulong *get_best_icon(gulong *data, int icon_count, int num, int *iw, int *ih, int best_icon_size)
{
    if (icon_count < 1 || num < 1)
        return NULL;

    int width[icon_count], height[icon_count], pos, i, w, h;
    gulong *icon_data[icon_count];

    /* List up icons */
    pos = 0;
    i = icon_count;
    while (i--) {
        w = data[pos++];
        h = data[pos++];
        if (pos + w * h > num)
            break;

        width[i] = w;
        height[i] = h;
        icon_data[i] = &data[pos];

        pos += w * h;
    }

    /* Try to find exact size */
    int icon_num = -1;
    for (i = 0; i < icon_count; i++) {
        if (width[i] == best_icon_size) {
            icon_num = i;
            break;
        }
    }

    /* Take the biggest or whatever */
    if (icon_num < 0) {
        int highest = 0;
        for (i = 0; i < icon_count; i++) {
            if (width[i] > highest) {
                icon_num = i;
                highest = width[i];
            }
        }
    }

    *iw = width[icon_num];
    *ih = height[icon_num];
    return icon_data[icon_num];
}

// Thanks zcodes!
char *get_window_name(Window win)
{
    char *name = NULL;
    XTextProperty text_property;
    Status status = XGetWMName(server.display, win, &text_property);
    if (!status || !text_property.value || !text_property.nitems)
        goto e0;

    char **name_list;
    int count;
    status = Xutf8TextPropertyToTextList(server.display, &text_property, &name_list, &count);
    if (status < Success || !count)
        goto e1;

    if (!name_list[0])
        goto e2;

    name = strdup( name_list[0]);
e2: XFreeStringList( name_list);
e1: XFree( text_property.value);
e0: if (!name)
        strdup_static( name, "");
    return name;
}

void smooth_thumbnail(cairo_surface_t *image_surface)
// On-place 2x2 square blur with center at top-left
{
    u_int32_t *data = (u_int32_t *)cairo_image_surface_get_data(image_surface);
    const size_t tw = cairo_image_surface_get_width(image_surface);
    const size_t th = cairo_image_surface_get_height(image_surface);
    const size_t rmask = 0xff0000;
    const size_t gmask = 0xff00;
    const size_t bmask = 0xff;
    for (size_t i = 0;
         i < tw * (th - 1) - 1 && i < tw * th;
         i++)
    {
        u_int32_t c1 = data[i];
        u_int32_t c2 = data[i + 1];
        u_int32_t c3 = data[i + tw];
        u_int32_t c4 = data[i + tw + 1];
        u_int32_t b = ((c1 & bmask) * 5 + (c2 & bmask) + (c3 & bmask) + (c4 & bmask)) / 8;
        u_int32_t g = ((c1 & gmask) * 5 + (c2 & gmask) + (c3 & gmask) + (c4 & gmask)) / 8;
        // Pollution in ascending bit direction is impossible for this operation, good case to save some cycles
        u_int32_t r = (c1 * 5 + c2 + c3 + c4) / 8;
        data[i] = (r & rmask) | (g & gmask) | (b & bmask);
    }
}

// This is measured to be slightly faster.
#define GetPixel(ximg, x, y) ((u_int32_t *)&(ximg->data[y * ximg->bytes_per_line]))[x]
//#define GetPixel XGetPixel

cairo_surface_t *get_window_thumbnail_ximage(Window win, size_t size, gboolean use_shm)
{
    cairo_surface_t *result = NULL;
    XWindowAttributes wa;
    if (!XGetWindowAttributes(server.display, win, &wa) ||
        wa.width <= 0 || wa.height <= 0)
    {
        if (debug_thumbnails) {
            fprintf(stderr, "tint2: could not get thumbnail, invalid geometry %d x %d\n",
                    wa.width, wa.height);
        }
        goto e0;
    }

    if (wa.map_state != IsViewable) {
        if (debug_thumbnails) {
            fprintf(stderr, "tint2: could not get thumbnail, window not viewable\n");
        }
        goto e0;
    }

    if (window_is_iconified(win)) {
        if (debug_thumbnails) {
            fprintf(stderr, "tint2: could not get thumbnail, minimized window\n");
        }
        goto e0;
    }

    if (debug_thumbnails) {
        fprintf(stderr, "tint2: getting thumbnail for window with size %d x %d\n",
                wa.width, wa.height);
    }

    size_t  w = (size_t)wa.width,
            h = (size_t)wa.height,
            tw = size,
            th = size * h / w,
            fw, ox;
    if (th > tw * 0.618) {
        th = (size_t)(tw * 0.618);
        fw = th * w / h;
        ox = (tw - fw) / 2;
    } else {
        fw = tw;
        ox = 0;
    }
    if (debug_thumbnails) {
        fprintf(stderr,
                "tint2: thumbnail size %zu x %zu, "
                "proportional width %zu, offset %zu\n",
                tw, th, fw, ox);
    }
    if (!w || !h || !tw || !th || !fw) {
        if (debug_thumbnails) {
            fprintf(stderr, "tint2: could not get thumbnail, invalid thumbnail size: "
                    "%zu x %zu => %zu x %zu, %zu\n",
                    w, h, tw, th, fw);
        }
        goto e0;
    }

    XShmSegmentInfo shminfo;
    XImage *ximg;
    if (use_shm)
        ximg = XShmCreateImage(server.display,
                               wa.visual,
                               (unsigned)wa.depth,
                               ZPixmap,
                               NULL,
                               &shminfo,
                               (unsigned)w,
                               (unsigned)h);
    else
        ximg = XGetImage(   server.display, win,
                            0, 0, (unsigned)w, (unsigned)h,
                            AllPlanes, ZPixmap );
    if (!ximg) {
        fprintf(stderr, RED "tint2: !ximg" RESET "\n");
        goto e0;
    }
    if (ximg->bits_per_pixel != 24 && ximg->bits_per_pixel != 32) {
        fprintf(stderr, RED "tint2: unusual bits_per_pixel" RESET "\n");
        goto e1;
    }
    if (use_shm) {
        shminfo.shmid = shmget(IPC_PRIVATE, (size_t)(ximg->bytes_per_line * ximg->height), IPC_CREAT | 0777);
        if (shminfo.shmid < 0) {
            fprintf(stderr, RED "tint2: !shmget" RESET "\n");
            goto e1;
        }
        shminfo.shmaddr = ximg->data = (char *)shmat(shminfo.shmid, 0, 0);
        if (shminfo.shmaddr == (void*)-1) {
            fprintf(stderr, RED "tint2: !shmat" RESET "\n");
            goto e2;
        }
        shminfo.readOnly = False;
        if (!XShmAttach(server.display, &shminfo)) {
            fprintf(stderr, RED "tint2: !xshmattach" RESET "\n");
            goto e3;
        }
        if (!XShmGetImage(server.display, win, ximg, 0, 0, AllPlanes)) {
            fprintf(stderr, RED "tint2: !xshmgetimage" RESET "\n");
            goto e4;
        }
    }

    if (debug_thumbnails) {
        fprintf(stderr,
                "tint2: creating cairo surface with size %zu x %zu = %zu px\n",
                tw, th, tw * th);
    }

    result = cairo_image_surface_create(CAIRO_FORMAT_RGB24, (int)tw, (int)th);
    u_int32_t *data = (u_int32_t *)cairo_image_surface_get_data(result);
    memset(data, 0, tw * th);

    // Fixed-point precision
    // Kernel:
    // 0 0 0 1 0 0 0 0
    // 0 0 0 0 0 0 1 0
    // 0 0 0 0 0 0 0 0
    // 0 0 0 0 0 0 0 0
    // 0 0 1 0 1 0 0 1
    // 0 0 0 0 0 0 0 0
    // 0 1 0 0 0 0 0 0
    // 0 0 0 0 0 1 0 0
    const size_t prec = 1 << 16;
    const size_t xstep = w * prec / fw;
    const size_t ystep = h * prec / th;
    size_t offset_y[] = {0, 0, 1, 4, 4, 4, 6, 7};
    size_t offset_x[] = {0, 3, 6, 2, 4, 7, 1, 6};
    for (int i=1; i<=7; i++) {
        offset_y [i] *= (w * prec / fw) / 8;
        offset_x [i] *= (h * prec / th) / 8;
    }
    u_int32_t rmask = (u_int32_t)ximg->red_mask;
    u_int32_t gmask = (u_int32_t)ximg->green_mask;
    u_int32_t bmask = (u_int32_t)ximg->blue_mask;
    for (size_t yt = 0, y = 0; yt < th; yt++, y += ystep) {
        for (size_t xt = 0, x = 0; xt < fw; xt++, x += xstep) {
            size_t j = yt * tw + ox + xt;
            if (j < tw * th)
            {
                u_int32_t c[8];
                for (int i=1; i<=7; i++)
                    c[i] = (u_int32_t)GetPixel(ximg, (int)((x + offset_x[i]) / prec), (int)((y + offset_y[i]) / prec));

                u_int32_t b = ((c[1] & bmask) + (c[2] & bmask) + (c[3] & bmask) + (c[4] & bmask) + (c[5] & bmask) * 2
                            +  (c[6] & bmask) + (c[7] & bmask)) / 8;
                u_int32_t g = ((c[1] & gmask) + (c[2] & gmask) + (c[3] & gmask) + (c[4] & gmask) + (c[5] & gmask) * 2
                            +  (c[6] & gmask) + (c[7] & gmask)) / 8;
                u_int32_t r = ((c[1] & rmask) + (c[2] & rmask) + (c[3] & rmask) + (c[4] & rmask) + (c[5] & rmask) * 2
                            +  (c[6] & rmask) + (c[7] & rmask)) / 8;
                data[j] = (r & rmask) | (g & gmask) | (b & bmask);
            }
        }
    }
    // Convert to argb32
    if (rmask & 0xff0000) {
        // argb32 or rgb24 => Nothing to do
    } else if (rmask & 0xff) {
        // bgr24
        for (size_t i = 0; i < tw * th; i++) {
            u_int32_t r = (data[i] & rmask) << 16;
            u_int32_t g = (data[i] & gmask);
            u_int32_t b = (data[i] & bmask) >> 16;
            data[i] = (r & 0xff0000) | (g & 0x00ff00) | (b & 0x0000ff);
        }
    } else if (rmask & 0xff00) {
        // bgra32
        for (size_t i = 0; i < tw * th; i++) {
            u_int32_t r = (data[i] & rmask) << 8;
            u_int32_t g = (data[i] & gmask) >> 8;
            u_int32_t b = (data[i] & bmask) >> 24;
            data[i] = (r & 0xff0000) | (g & 0x00ff00) | (b & 0x0000ff);
        }
    }

    // 2nd pass
    smooth_thumbnail(result);
    cairo_surface_mark_dirty(result);

    if (ximg) {
        XDestroyImage(ximg);
        ximg = NULL;
    }
e4: if (use_shm)
        XShmDetach(server.display, &shminfo);
e3: if (use_shm)
        shmdt(shminfo.shmaddr);
e2: if (use_shm)
        shmctl(shminfo.shmid, IPC_RMID, NULL);
e1: if (ximg)
        XDestroyImage(ximg);
e0: return result;
}

gboolean cairo_surface_is_blank(cairo_surface_t *image_surface)
{
    uint32_t *pixels = (uint32_t *)cairo_image_surface_get_data(image_surface);
    int size = cairo_image_surface_get_width(image_surface) * cairo_image_surface_get_height(image_surface);
    for (int i = 0; i < size; i++)
        if (pixels[i] & 0xffFFff)
            return FALSE;
    return TRUE;
}

gboolean thumb_use_shm = FALSE;

cairo_surface_t *get_window_thumbnail(Window win, int size)
{
    cairo_surface_t *image_surface = NULL;
    for (int use_shm = thumb_use_shm && server.has_shm && server.composite_manager; ; use_shm = FALSE)
    {
        image_surface = get_window_thumbnail_ximage(win, (size_t)size, use_shm);
        if (image_surface && cairo_surface_is_blank(image_surface))
        {
            cairo_surface_destroy(image_surface);
            image_surface = NULL;
        }
        if (debug_thumbnails)
        {
            const char *method = use_shm ? "XShmGetImage" : "XGetImage";
            if (!image_surface)
                fprintf(stderr, YELLOW "tint2: %s failed, trying slower method" RESET "\n", method);
            else {
                fprintf(stderr, "tint2: captured window using %s\n", method);
                break;
            }
        }
        if (!use_shm) break;
    }

    return image_surface;
}
