#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <X11/Xlib.h>
#include <X11/Xft/Xft.h>

Display *d;
Window w;

char *fontname = "Times-24";
int x = 200;
int y = 200;

static void usage(void)
{
   fprintf(stderr, "usage: xtxft [-f font] [-x xoff] [-y yoff] text\n");
   exit(1);
}

int main(int argc, char **argv)
{
   XEvent evt;
   XSetWindowAttributes attr;
   char c, *str;
   XftFont *font;
   XftDraw *draw;
   XRenderColor colortmp;
   XftColor color_fg;

   while ((c = getopt(argc, argv, ":f:x:y:")) != -1) {
       switch (c) {
           case 'f':
               fontname = (char *)malloc(strlen(optarg) + 1);
               strcpy(fontname, optarg);
               break;
           case 'x':
               x = atoi(optarg);
               break;
           case 'y':
               y = atoi(optarg);
               break;
           case '?':
           case ':':
           default:
               usage();
       }
   }

   if ((argc - optind) < 1)
       usage();

   str = (char *)malloc(strlen(argv[optind]) + 1);
   strcpy(str, argv[optind]);

   d = XOpenDisplay(NULL);

   w = XCreateSimpleWindow(d, DefaultRootWindow(d), 0, 0,
           1024, 768, 0, BlackPixel(d, 0), WhitePixel(d, 0));

   if (! w) {
       printf("Error creating window!\n");
       exit(1);
   }

   attr.event_mask = KeyPressMask;
   XChangeWindowAttributes(d, w, CWEventMask, &attr);
   XStoreName(d, w, "XText");

   XMapWindow(d, w);
   XMoveWindow(d, w, 0, 0);

   font = XftFontOpenName(d, DefaultScreen(d), fontname);

   draw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));

   colortmp.red = 0;
   colortmp.green = 0;
   colortmp.blue = 0;
   colortmp.alpha = 0xffff;
   XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0),
           &colortmp, &color_fg);

   XftDrawString8(draw, &color_fg, font, x, y, str, strlen(str));

   while(1) {
       while(XPending(d)) {
           XNextEvent(d, &evt);
           if (evt.type == KeyPress)
               goto end;
       }
       usleep(1000);
   }

end:
   XDestroyWindow(d, w);
   XCloseDisplay(d);
   return 0;
}