#include <stdio.h>
#include <string.h>
#include <X11/Xlib.h>
#include <X11/keysym.h>

static unsigned long color(Display *display, int screen, const char *name,
                           unsigned long fallback)
{
  XColor found, exact;
  return XAllocNamedColor(display, DefaultColormap(display, screen),
                          name, &found, &exact) ? found.pixel : fallback;
}

int main(void)
{
  Display *display;
  Window window;
  int screen;
  GC gc;
  unsigned long border_color, bg, text_color;

  display = XOpenDisplay(NULL);
  if (!display) {
    fprintf(stderr, "Cannot open display!\n");
    return 1;
  }
  screen = DefaultScreen(display);

  bg = color(display, screen, "#eaeeaf", WhitePixel(display, screen));
  border_color = color(display, screen, "#081a38", BlackPixel(display, screen));
  text_color = color(display, screen, "#ff1100", BlackPixel(display, screen));

  window = XCreateSimpleWindow(display, RootWindow(display, screen),
                               100, 100, 250, 150,
                               0, border_color, bg);
  XStoreName(display, window, "Is it on?");
  XSelectInput(display, window, ExposureMask | KeyPressMask);

  Atom wm_delete = XInternAtom(display, "WM_DELETE_WINDOW", False);
  Atom wm_protocols = XInternAtom(display, "WM_PROTOCOLS", False);
  XSetWMProtocols(display, window, &wm_delete, 1);

  gc = XCreateGC(display, window, 0, NULL);
  XSetForeground(display, gc, text_color);

  XMapWindow(display, window);

  const char *text = "Hello, cruel world!";
  int running = 1;

  while (running) {
    XEvent e;
    XNextEvent(display, &e);

    switch (e.type) {
    case Expose:
      XDrawString(display, window, gc, 20, 50, text, (int)strlen(text));
      break;
    case KeyPress:
      if (XLookupKeysym(&e.xkey, 0) == XK_q)
        running = 0;
      break;
    case ClientMessage:
      if (e.xclient.message_type == wm_protocols &&
          e.xclient.format == 32 &&
          (Atom)e.xclient.data.l[0] == wm_delete)
        running = 0;
      break;
    }
  }

  XFreeGC(display, gc);
  XDestroyWindow(display, window);
  XCloseDisplay(display);

  printf("That's all folks!\n");
  return 0;
}
