1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
|
/* plugin.c */
/*
The protocol runs over two pipes, connected to the plugin's
stdin and stdout:
Upon startup, the plugin prints an identification message of
the following form:
200 text
This line, like every line, is terminated by a single newline
character, *not* a CRLF sequence.
A result code starting with the digit '2' indicates successful
startup. Any other result code is taken as a failure; in particular,
a non-digit suggests that this is not a plugin at all!
Communication takes place in a command-reply fashion. The command
consists of a single line of no more that 1024 characters, starting
with a command verb and optionally followed by parameters. Commands
are case sensitive. These commands are implemented here:
SAVE filename Save data in file
LOAD filename Load data from file
EXEC string Execute the string, which should be interpretable
by the plugin
HELP List available commands
NOOP Do nothing
WIN Print the window id of window to be captured
QUIT Quit
PRNT Produce Postscript representation of the plugin
The reply consists of a numeric result code, the character
' ' followed by text:
200 text Command completed successfully
400 text Command failed
500 text Command unknown
The plugin *must reply* even if the command cannot be executed.
Otherwise there will be an annoying timeout when the main
program waits for the reply.
This implementation does *not* handle multi-line replies and will
likely choke on them. I'm just testing.
*/
/*
The typical use of the plugin library will be like this:
1. plugin_start: The plugin is loaded into the buffer but not displayed.
The application runs and displays its toplevel window outside Siag.
The toplevel window is found.
The geometry is saved.
The window is unmapped.
The window ID is saved.
2. In activate_window, every plugin in the buffer is checked to see
if it needs to be displayed.
3. plugin_show: A new widget is created in the grid, using the
geometry information retrieved before.
The plugin toplevel is reparented into the widget and then mapped.
4. plugin_hide: The toplevel window is unmapped and the widget
destroyed.
5. plugin_stop: plugin is hidden, QUIT is sent and pipes are closed.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>
#include <X11/Shell.h>
#include <X11/cursorfont.h>
#include <X11/xpm.h>
#include "../common/cmalloc.h"
#include "plugin.h"
#define REPARENT_LOOPS 50
#define PLUGIN_MAX 30
/*#define DEBUG*/
char **plugin_patterns;
static struct {
int pfd[2], qfd[2];
int taken;
int visible;
pid_t pid;
Window victim;
Position x, y;
Dimension width, height, border, depth;
Widget parent, core; /* keeper of new parent window */
} plugin[PLUGIN_MAX];
static int nplugin = 0;
static struct {
char *desc, *ext, *cmd;
} *handler;
static int nhandler = 0;
static Widget topLevel = None;
static Cursor sane_cursor;
/* write a line to the plugin */
static int plugin_write(int ph, char *b)
{
int retval = write(plugin[ph].pfd[1], b, strlen(b));
#ifdef DEBUG
if (retval >= 0) fprintf(stderr, "plugin_write(%d, %s)\n", ph, b);
#endif
return retval;
}
/* read a line from the plugin, return number of chars read */
static int plugin_read(int ph, char *b)
{
fd_set rfds;
struct timeval tv;
int retval, n;
FD_ZERO(&rfds);
FD_SET(plugin[ph].qfd[0], &rfds);
tv.tv_sec = 60;
tv.tv_usec = 0;
retval = select(plugin[ph].qfd[0]+1, &rfds, NULL, NULL, &tv);
if (!retval) return 0;
#if 1
for (n = 0; n < 1024; n++) {
if (!read(plugin[ph].qfd[0], b+n, 1)) break;
if (b[n] == '\n') {
n++;
break;
}
}
#else
n = read(plugin[ph].qfd[0], b, 1024);
#endif
b[n] = '\0';
#ifdef DEBUG
fprintf(stderr, "plugin_read(%d, %s)\n", ph, b);
#endif
return n;
}
static char **parse_cmd(char *cmd, char *fn, char *name)
{
int i = 0;
char **argv = (char **)cmalloc(10*sizeof(char *));
char *cmd_copy = cstrdup(cmd);
char *p;
for (p = strtok(cmd_copy, " \n"); p && i < 9; p = strtok(NULL, " \n")) {
if (p[0] == '%') {
switch (p[1]) {
case 's':
argv[i++] = cstrdup(fn);
break;
case 'W':
argv[i++] = cstrdup(name);
break;
case '%':
argv[i++] = p+1;
break;
default:
;
}
} else {
argv[i++] = p;
}
}
argv[i] = NULL;
return argv;
}
void chomp(char *p)
{
if ((p = strchr(p, '\n'))) *p = '\0';
}
static int plugin_handler_find(char *ext)
{
int i;
for (i = 0; i < nhandler; i++)
if (!strcmp(ext, handler[i].ext)) return i;
return -1;
}
/*
Run a plugin without displaying it.
fn: File name of file to be loaded. The extension is used to
choose from available plugins. All the plumbing for
communicating with the plugin is set up.
Returns a plugin handle for success of -1 for failure.
*/
int plugin_start(char *fn)
{
int x, y;
unsigned int width, height, border, depth;
Window victim, root;
int ph, i;
char *cmd;
char *ext = strrchr(fn, '.');
if (!ext) ext = fn;
else ext++;
i = plugin_handler_find(ext);
if (i == -1) return -1; /* no handler found */
for (ph = 0; ph < nplugin; ph++)
if (!plugin[ph].taken) break;
if (ph == nplugin) nplugin++;
if (nplugin >= PLUGIN_MAX) return -1; /* too many */
cmd = handler[i].cmd;
plugin[ph].taken = 1;
if (pipe(plugin[ph].pfd) == -1) return -1;
if (pipe(plugin[ph].qfd) == -1) return -1;
plugin[ph].pid = fork();
if (plugin[ph].pid == -1) { /* error */
nplugin--;
return -1;
} else if (plugin[ph].pid == 0) { /* child */
char **argv;
close(plugin[ph].pfd[1]);
dup2(plugin[ph].pfd[0], 0);
close(plugin[ph].pfd[0]);
close(plugin[ph].qfd[0]);
dup2(plugin[ph].qfd[1], 1);
close(plugin[ph].qfd[1]);
/* run the plugin */
argv = parse_cmd(cmd, fn, "SiAg_PlUgIn");
execvp(argv[0], argv);
exit(EXIT_FAILURE);
} else { /* parent */
char r[1024];
close(plugin[ph].pfd[0]);
close(plugin[ph].qfd[1]);
if (plugin_read(ph, r) < 6 || r[0] != '2') {
return -1;
}
plugin_write(ph, "WIN\n");
if (plugin_read(ph, r) < 6 || r[0] != '2') {
return -1;
}
victim = strtol(r+4, NULL, 16);
if (victim == None) {
plugin[ph].taken = 0;
return -1;
}
XGetGeometry(XtDisplay(topLevel), victim, &root,
&x, &y, &width, &height, &border, &depth);
plugin[ph].width = width+2*border;
plugin[ph].height = height+2*border;
plugin[ph].border = border;
plugin[ph].depth = depth;
plugin[ph].victim = victim;
plugin[ph].visible = 1;
plugin[ph].parent = None;
plugin[ph].core = None;
plugin[ph].x = 0; /* unused */
plugin[ph].y = 0;
plugin_hide(ph);
}
return ph;
}
/*
Kill a plugin. Close the pipes, close the window, kill the process.
ph: Plugin handle.
Returns 0 for success or non-0 for failure.
*/
int plugin_stop(int ph)
{
char b[1024];
plugin_hide(ph);
plugin_write(ph, "QUIT\n");
plugin_read(ph, b);
close(plugin[ph].pfd[1]);
close(plugin[ph].qfd[0]);
kill(plugin[ph].pid, SIGINT);
plugin[ph].taken = 0;
return 0;
}
/*
Tell the plugin to load a file.
ph: Plugin handle
fn: File name
Returns 0 for success or non-0 for failure.
*/
int plugin_load(int ph, char *fn)
{
char cmd[1024];
sprintf(cmd, "LOAD %s\n", fn);
plugin_write(ph, cmd);
plugin_read(ph, cmd); /* ignore the response for now */
return 0;
}
/*
Tell the plugin to save to a file.
ph: plugin handle
fn: File name
Returns 0 for success or non-0 for failure.
*/
int plugin_save(int ph, char *fn)
{
char cmd[1024];
sprintf(cmd, "SAVE %s\n", fn);
plugin_write(ph, cmd);
plugin_read(ph, cmd); /* ignore the response for now */
return 0;
}
/*
Ask the plugin what commands it understands.
ph: plugin handle
Returns a one-line string with the available commands.
Caller must free.
*/
char *plugin_help(int ph)
{
char cmd[1024];
plugin_write(ph, "HELP\n");
cmd[0] = '\0';
plugin_read(ph, cmd);
return cstrdup(cmd);
}
int plugin_find_by_widget(Widget w)
{
int ph;
for (ph = 0; ph < nplugin; ph++)
if (plugin[ph].core == w) return ph;
return -1;
}
int plugin_find_by_window(Window w)
{
int ph;
for (ph = 0; ph < nplugin; ph++)
if (plugin[ph].victim == w) return ph;
return -1;
}
/* a callback to tell the app about the change */
static void (*handle_plugin_exit)(int) = NULL;
static void handle_destroy(Widget w, XtPointer p, XEvent *event, Boolean *b)
{
if (event->type == DestroyNotify) {
XDestroyWindowEvent dwevent = event->xdestroywindow;
int ph = plugin_find_by_window(dwevent.window);
if (ph >= 0) {
plugin[ph].taken = 0;
if (plugin[ph].core != None)
XtDestroyWidget(plugin[ph].core);
if (handle_plugin_exit)
(*handle_plugin_exit)(ph);
}
}
}
/*
Display the plugin, i.e. map the window and reparent if necessary.
win: window pointer
ph: plugin handle
Return 0 for success or non-0 for failure.
*/
int plugin_show(int ph, Widget grid)
{
Display *display = XtDisplay(grid);
Window w = plugin[ph].victim;
Window to;
int i;
Cardinal n;
Window root, parent, *child;
plugin[ph].parent = grid;
if (plugin[ph].visible) plugin_hide(ph);
plugin[ph].visible = 1;
/* we don't need to tell Table where to put the widget,
because it will be picked up from plugin_coordinates */
plugin[ph].core = XtVaCreateManagedWidget("plugin",
compositeWidgetClass, grid,
XtNwidth, plugin[ph].width,
XtNheight, plugin[ph].height,
XtNborderWidth, 0,
(char *)0);
to = XtWindow(plugin[ph].core);
XSync(display, False);
for (i = 0; i < REPARENT_LOOPS; i++) {
XReparentWindow(display, w, to, 0, 0);
XQueryTree(display, w, &root, &parent, &child, &n);
XSync(display, False);
#if 0
if (parent == to) {
break;
}
#endif
}
XMapWindow(display, w);
XSync(display, False);
XtAddEventHandler(plugin[ph].core,
SubstructureNotifyMask, False,
handle_destroy, (XtPointer)XtWindow(plugin[ph].core));
/* XSelectInput(display, w,
SubstructureNotifyMask |
FocusChangeMask |
LeaveWindowMask |
EnterWindowMask |
KeyPressMask |
KeyReleaseMask |
PropertyChangeMask |
ColormapChangeMask);
*/
XDefineCursor(display, w, sane_cursor);
return 0;
}
/*
Hide the plugin, i.e. unmap the window.
ph: Plugin handle
Returns 0 for success or non-0 for failure.
*/
int plugin_hide(int ph)
{
int i;
XWMHints *hints;
Display *display = XtDisplay(topLevel);
Screen *screen = XtScreen(topLevel);
Window w = plugin[ph].victim;
XSync(display, False);
XWithdrawWindow(display, w, XScreenNumberOfScreen(screen));
XSync(display, False);
hints = XGetWMHints(display, w);
hints->flags |= WindowGroupHint;
hints->window_group = RootWindowOfScreen(screen);
XSetWMHints(display, w, hints);
#if 1 /* testing */
for (i = 0; i < REPARENT_LOOPS; i++) {
Window root, parent, *child;
Cardinal n;
XQueryTree(display, w, &root, &parent, &child, &n);
#if 0
if (parent == root) break;
#endif
XReparentWindow(display, w, root, 0, 0);
XSync(display, False);
}
#endif
if (plugin[ph].core != None) {
XtDestroyWidget(plugin[ph].core);
plugin[ph].core = None;
}
return 0;
}
/*
Clever little hack to print anything, including plugins that don't know
how to print themselves. Works the following way:
1. Create override widget of the right size.
2. Reparent plugin to override widget.
3. Send expose event to plugin.
4. Copy override widget to pixmap.
5. Reparent plugin back to main application.
6. Destroy override widget.
7. Print the widget as in image plugin.
*/
typedef struct {
char *chars;
XColor xcolor;
} colors;
static void prnt(Pixmap pixmap, FILE *fp)
{
unsigned int width, height, depth = 8;
unsigned int ncolors, cpp;
int x, y, col;
char *title = "Plugged in image";
time_t t;
char **data, *key, *color;
XpmAttributes xa;
int i, n;
colors *cm;
xa.valuemask = 0;
/* figure out a thing or two */
n = XpmCreateDataFromPixmap(XtDisplay(topLevel), &data,
pixmap, None, &xa);
if (n != XpmSuccess) {
printf("503 XpmCreateDataFromPixmap returns %d\n", n);
return;
}
sscanf(data[0], "%d %d %d %d", &width, &height, &ncolors, &cpp);
cm = (colors *)cmalloc(ncolors*sizeof(colors));
for (i = 0; i < ncolors; i++) {
cm[i].chars = (char *)cmalloc(cpp);
memcpy(cm[i].chars, data[i+1], cpp);
key = strtok(data[i+1]+cpp, " \t"); /* skip past chars */
color = strtok(NULL, " \t");
while (key && color && strcmp(key, "c")) {
key = strtok(NULL, " \t");
color = strtok(NULL, " \t");
};
if (!color) {
printf("504 No such color\n");
return;
}
XParseColor(XtDisplay(topLevel),
XDefaultColormapOfScreen(XtScreen(topLevel)),
color, &cm[i].xcolor);
}
/* print postscript preblurb */
fprintf(fp, "%%!PS-Adobe-2.0 EPSF-2.0\n");
fprintf(fp, "%%%%Creator: Image plugin for Siag Office\n");
fprintf(fp, "%%%%Title: %s\n", title);
fprintf(fp, "%%%%Pages: 1\n");
fprintf(fp, "%%%%BoundingBox: %d %d %d %d\n", 0, 0, width, height);
t = time(NULL);
fprintf(fp, "%%%%CreationDate: %s\n", ctime(&t));
fprintf(fp, "%%%%EndComments\n");
fprintf(fp, "%%%%EndProlog\n");
fprintf(fp, "%%%%Page: 1 1\n\n\n");
fprintf(fp, "gsave\n\n");
fprintf(fp, "/inch {72 mul} def\n");
fprintf(fp, "%d %d scale\n", width, height);
fprintf(fp, "/line %d string def\n", 3*width);
fprintf(fp, "%d %d %d\n", width, height, depth);
fprintf(fp, "[ %d %d %d %d %d %d ]\n", width, 0, 0, -height, 0, height);
fprintf(fp, "{currentfile line readhexstring pop}\n");
fprintf(fp, "false 3 colorimage\n");
/* print all the pixels */
col = 0;
for (y = 0; y < height; y++) {
char *line = data[y+ncolors+1];
for (x = 0; x < width; x++) {
char *pix = line+cpp*x;
for (i = 0; i < ncolors; i++)
if (!memcmp(cm[i].chars, pix, cpp)) break;
if (i == ncolors) i = 0;
fprintf(fp, "%02hx%02hx%02hx",
(cm[i].xcolor.red / 256) & 255,
(cm[i].xcolor.green / 256) & 255,
(cm[i].xcolor.blue / 256) & 255);
col += 6;
if (col >= 72) {
fprintf(fp, "\n");
col = 0;
}
}
}
if (col) fprintf(fp, "\n");
/* print postscript postblurb */
fprintf(fp, "%%\n\n");
fprintf(fp, "grestore\n");
fprintf(fp, "%%%%Trailer\n");
for (i = 0; i < ncolors; i++) cfree(cm[i].chars);
cfree(cm);
cfree(data);
}
static int print_anyway(int ph, FILE *fp)
{
Widget ow;
unsigned long width = plugin[ph].width;
unsigned long height = plugin[ph].height;
int i;
ow = XtVaCreatePopupShell("plugin_print",
overrideShellWidgetClass, topLevel,
XtNx, 0, XtNy, 0,
XtNwidth, width, XtNheight, height,
(char *)0);
XtPopup(ow, XtGrabNone);
XSync(XtDisplay(ow), False);
for (i = 0; i < 1 /*REPARENT_LOOPS*/; i++) {
XReparentWindow(XtDisplay(topLevel), plugin[ph].victim,
XtWindow(ow), 0, 0);
XSync(XtDisplay(topLevel), False);
XClearWindow(XtDisplay(topLevel), plugin[ph].victim);
XSync(XtDisplay(topLevel), False);
}
/* print */
prnt(plugin[ph].victim /*pixmap*/, fp);
/* finished printing */
for (i = 0; i < 1 /*REPARENT_LOOPS*/; i++) {
XReparentWindow(XtDisplay(topLevel), plugin[ph].victim,
XtWindow(plugin[ph].core), 0, 0);
XSync(XtDisplay(topLevel), False);
}
XtDestroyWidget(ow);
return 0;
}
/*
Tell the plugin to print its window into the file.
ph: Plugin handle
Returns 0 for success or non-0 for failure, such as an i/o error.
*/
#define TRAILER "%%Trailer"
int plugin_print(int ph, FILE *fp)
{
char b[1024];
plugin_write(ph, "PRNT\n");
if (!plugin_read(ph, b)) {
fprintf(stderr, "Nothing from plugin\n");
return 1;
}
if (strlen(b) < 5 || b[0] != '2') {
return print_anyway(ph, fp);
}
while (plugin_read(ph, b)) {
fputs(b, fp);
if (!strncmp(b, TRAILER, strlen(TRAILER))) return 0;
}
return 1; /* didn't find trailer */
}
/*
Register a plugin handler.
desc: a plaintext description of the plugin
ext: magic extension to be handled by this plugin
cmd: command to run the plugin
Returns 0 for success, non-0 for failure.
*/
int plugin_register(char *desc, char *ext, char *cmd)
{
char b[1024];
int n = plugin_handler_find(ext);
if (n == -1) { /* allocate room for new plugin */
n = nhandler++;
handler = crealloc(handler, nhandler*sizeof *handler);
plugin_patterns = crealloc(plugin_patterns,
(nhandler+1)*sizeof *plugin_patterns);
plugin_patterns[nhandler] = NULL;
} else { /* reuse old position */
cfree(handler[n].desc);
cfree(handler[n].ext);
cfree(handler[n].cmd);
cfree(plugin_patterns[n]);
}
handler[n].desc = cstrdup(desc);
handler[n].ext = cstrdup(ext);
handler[n].cmd = cstrdup(cmd);
sprintf(b, "%s (*.%s)", desc, ext);
plugin_patterns[n] = cstrdup(b);
return 0;
}
void plugin_init(Widget w, void (*handle_exit)(int))
{
topLevel = w;
handle_plugin_exit = handle_exit;
sane_cursor = XCreateFontCursor(XtDisplay(w), XC_top_left_arrow);
}
int plugin_size_get(int ph, unsigned long *width, unsigned long *height)
{
if (ph < 0 || ph >= nplugin) return -1;
*width = plugin[ph].width;
*height = plugin[ph].height;
return 0;
}
|