Screenshot:
Source:
/* cc -Wall -O5 -L/usr/X11R6/lib fonts.c -o fonts -lX11 */
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
Display *display;
Window window;
GC gc;
unsigned long black_color;
unsigned long white_color;
int screen;
int width = 500;
int height = 100;
XFontStruct *font;
if(!(display = XOpenDisplay(NULL))) {
fprintf(stderr, "%s: Unable to open display: %s\n",
argv[0], XDisplayName(NULL));
return -1;
}
screen = DefaultScreen(display);
black_color = BlackPixel(display, screen);
white_color = WhitePixel(display, screen);
window = XCreateSimpleWindow(display,
DefaultRootWindow(display),
50, 50, width, height, 0,
black_color,
white_color);
/* Window title */
{
char* title = "Fonts";
XTextProperty title_property;
if(XStringListToTextProperty(&title, 1, &title_property) == 0) {
fprintf(stderr,
"%s: creation of the title text property failed\n", argv[0]);
return -1;
}
XSetWMProperties(display, window, &title_property, &title_property,
argv, argc, NULL, NULL, NULL);
}
XSelectInput(display, window, ExposureMask|StructureNotifyMask|
KeyPressMask);
XMapWindow(display, window);
/* Load font */
{
char font_name[] = "-*-times-medium-r-normal--25-*";
if ((font = XLoadQueryFont(display, font_name))==NULL) {
fprintf( stderr, "%s: Cannot open %s font\n",
argv[0], font_name);
return -1;
}
}
gc = XCreateGC(display, window, 0, NULL);
/* specify font */
XSetFont(display, gc, font->fid);
XSetForeground(display, gc, black_color);
for(;;) {
XEvent event;
char key_string[100];
char text[] = "I am just a text.";
static int text_width = -1; /* We compute it only once. */
XNextEvent(display, &event);
switch(event.type) {
case Expose:
/* Unless this is the last contiguous expose,
* don't draw the window */
if(event.xexpose.count != 0)
break;
if(text_width == -1) {
text_width = XTextWidth(font, text, sizeof(text));
}
/* Hint: text_height = font->ascent+font->descent; */
/* Draw text */
XDrawString(display, window, gc,
(width - text_width)>>1,
(height+font->ascent-font->descent)>>1,
text,
sizeof(text));
/* Draw a frame around text. */
XDrawRectangle(display, window, gc,
(width - text_width)>>1,
(height-font->ascent-font->descent)>>1,
text_width,
font->ascent+font->descent);
break;
case KeyPress:
if(XLookupString((XKeyEvent*)(&event),
key_string, 100, NULL, NULL)) {
/* catch ESCAPE */
if((int)(key_string[0]) == 033) {
XUnloadFont(display, font->fid);
XFreeGC(display, gc);
XCloseDisplay(display);
return 0;
}
}
break;
case ConfigureNotify:
width = event.xconfigure.width;
height = event.xconfigure.height;
break;
}
}
/* Never reached */
return 0;
}