#include <stdio.h>
#include <unistd.h>
#include <X11/Xlib.h>


int main(int argc, char *argv[])
{
    Display *dpy;
    int scrnbr;
    Window root_window;
    Window first_window;
    XGCValues Values_GC_first_window;
    GC GC_first_window;
    XEvent e;
    XEvent mouse_mouvement;

    if((dpy = XOpenDisplay(":0.0")) == NULL)
    {
        printf("Failed to open display\n");
        return -1;
    }
    scrnbr = DefaultScreen(dpy);
    root_window = RootWindow(dpy, scrnbr);

    first_window = XCreateSimpleWindow(dpy, root_window, 0,0, 800, 600, 10, BlackPixel(dpy, scrnbr), WhitePixel(dpy, scrnbr));
    GC_first_window = XCreateGC(dpy, first_window, 0, &Values_GC_first_window);

    XSelectInput(dpy, first_window, KeyPressMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask);


    XMapWindow(dpy, first_window);

    int press = 0;
    int A_pos[2];
    int B_pos[2];
    // boucle
    for(;;)
    {
        if(XCheckWindowEvent(dpy, first_window, KeyPressMask, &e))
        {
            break;
        }
        if(XCheckWindowEvent(dpy, first_window, ButtonPressMask, &e))
        {
            press++;
            if(press == 1)
            {
                A_pos[0] = e.xbutton.x;
                A_pos[1] = e.xbutton.y;
                XSync(dpy, 1);
            }else if(press == 2)
            {
                B_pos[0] = e.xbutton.x;
                B_pos[1] = e.xbutton.y;

                XDrawLine(dpy, first_window, GC_first_window, A_pos[0], A_pos[1], B_pos[0], B_pos[1]);
                press = 0;
                XSync(dpy, 1);
            }
        }
    }


    XDestroyWindow(dpy, first_window);
    XCloseDisplay(dpy);
    return 0;
}
