xlib_playground

Xlib playground for experiments.
Log | Files | Refs

commit a98635208fb450c2469407449585ab92ce009ee3
parent ad350d81ba26c4f4b3fb65d9963314a5a92f13d0
Author: Matsuda Kenji <info@mtkn.jp>
Date:   Thu, 22 Dec 2022 10:32:32 +0900

add new ex

Diffstat:
Aex2/Makefile | 14++++++++++++++
Aex2/ex2.c | 111+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2 files changed, 125 insertions(+), 0 deletions(-)

diff --git a/ex2/Makefile b/ex2/Makefile @@ -0,0 +1,14 @@ +INCS=-I/usr/X11R6/include +CFLAGS=-Wall -Wextra -std=c11 +LIBS=-L/usr/X11R6/lib -lX11 -lXext +IN=*.c +OUT=ex2 + +all: main.c + $(CC) $(INCS) $(CFLAGS) -o $(OUT) $(IN) $(LIBS) + +run: all + ./$(OUT) + +clean: + rm -f $(OUT) diff --git a/ex2/ex2.c b/ex2/ex2.c @@ -0,0 +1,111 @@ +#include <stdio.h> +#include <stdlib.h> +#include <time.h> +#include <unistd.h> +#include <math.h> + +#include <X11/Xlib.h> + +/* macros */ +#define INIT_WIDTH 800 +#define INIT_HEIGHT 600 + + +/* variables */ +Display *display; +Window window; +unsigned int win_width = INIT_WIDTH, win_height = INIT_HEIGHT; +GC gc; +Atom wm_delete_window; + +/* function prototypes */ +void setup(void); +void cleanup(void); + + +void +setup(void) +{ + if ((display = XOpenDisplay(NULL)) == NULL){ + fprintf(stderr, "ERROR: could not open display\n"); + exit(1); + } + window = XCreateSimpleWindow( + display, + XDefaultRootWindow(display), + 0, 0, + win_width, win_height, + 0, 0, + 0); + XStoreName(display, window, "UNKO"); + gc = XCreateGC(display, window, 0, NULL); + + wm_delete_window = XInternAtom(display, + "WM_DELETE_WINDOW", False); + XSetWMProtocols(display, window, &wm_delete_window, 1); + + XSelectInput(display, window, + ExposureMask|KeyPressMask|KeyReleaseMask); + + XSetForeground(display, gc, 0x0000FF); + XMapWindow(display, window); +} + +void +cleanup(void) +{ + XCloseDisplay(display); +} + +int +main(void) +{ + int px, py; + int quit; + struct timespec ts; + XEvent event; + + setup(); + quit = 0; + + while (!quit){ + while(XPending(display) > 0){ + XNextEvent(display, &event); + switch (event.type){ + case KeyPress: { + switch (XLookupKeysym(&event.xkey, 0)){ + case 'q': + quit = 1; + break; + default: + break; + } + } break; + case ClientMessage: { + if ((Atom) event.xclient.data.l[0] == wm_delete_window) { + quit = 1; + } + } break; + default: + break; + } + } + clock_gettime(CLOCK_MONOTONIC, &ts); + px = 200 + (int) (100 * sinf(ts.tv_sec + ts.tv_nsec / 1000.0 / 1000 / 1000)); + py = 200 + (int) (100 * cosf(ts.tv_sec + ts.tv_nsec / 1000.0 / 1000 / 1000)); + XClearArea(display, window, + 0, 0, // position + win_width, win_height, // width and height + False); + XFillRectangle(display, window, gc, + px, py, // position + 100, 100); // width and height + + ts.tv_sec = 0; + ts.tv_nsec = 10 * 1000 * 1000; + nanosleep(&ts, NULL); + } + + cleanup(); + return 0; +}