David Bushong
Résumé
Picture Gallery
Software Tidbits
Links
Contact Me

Software Tidbits

/*
** $Id$
**
** xbuffer -- manipulates and views the contents of the X cut buffer
*/
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {
    int p, bufsize, i;
    Display *display;
    char *buffer, *tmp, *prog;

    /** store the calling program name **/
    if ((prog = strrchr(argv[0], '/')) == NULL) prog = argv[0];
    else prog++;

    /** try to open the display; fail quietly **/
    if ((display = XOpenDisplay(NULL)) == NULL) exit(1);

    /** if "-h", spit out the usage **/
    if (argc > 1 && argv[1][0] == '-' && argv[1][1] == 'h')  {
	fprintf(stderr, 
	    "usage:  %s [ - | text to go in buffer ]\n"
	    "      -: if only a '-' is supplied, contents of stdin are placed\n"
	    "         in X cut buffer\n"
	    "   text: if arguments are given, the X cut buffer is set to them\n"
	    "         (spaces added, with a trailing newline)\n"
	    " no arg: if no arguments are given, the contents of the X cut\n"
	    "         buffer are printed to stdout\n", prog);
    }

    /** if no arguments, dump out the buffer **/
    if (argc == 1) {
	printf("%s", XFetchBytes(display, &bufsize));
	exit(0);
    }


    /** if just '-', read stdin **/
    if (argc == 2 && argv[1][0] == '-' && argv[1][1] == '\0') {
	bufsize = 32; p = 0;
	buffer = (char*) malloc(bufsize);

	while ((buffer[p++] = getchar()) != EOF) {
	    if (p == bufsize) {
		bufsize *= 2;
		buffer = (char*) realloc(buffer, bufsize);
	    }
	}

	XStoreBytes(display, buffer, p-1);
	XFlush(display);
	exit(0);
    }

    /** else, combined the arg list (ugh) **/
    bufsize = 32; p = 0;
    buffer = (char*) malloc(bufsize);

    for (i = 1; i < argc; i++) {
	while (p + strlen(argv[i]) + 1 >= bufsize) {
	    bufsize *= 2;
	    buffer = (char*) realloc(buffer, bufsize);
	}
	strcpy(buffer+p, argv[i]);
	p += strlen(argv[i]) + 1;
	buffer[p-1] = ' ';
    }
    buffer[p-1] = '\n';

    XStoreBytes(display, buffer, p);
    XFlush(display);
    exit(0);
}