source: pymolproxy/trunk/pymolproxy.c @ 4641

Last change on this file since 4641 was 4627, checked in by ldelgass, 10 years ago

fix comment

File size: 63.4 KB
Line 
1
2/*
3 * ----------------------------------------------------------------------
4 * proxypymol2.c
5 *
6 *      This module creates the Tcl interface to the pymol server.  It acts as
7 *      a go-between establishing communication between a molvisviewer widget
8 *      and the pymol server. The communication protocol from the molvisviewer
9 *      widget is the Tcl language.  Commands are then relayed to the pymol
10 *      server.  Responses from the pymol server are translated into Tcl
11 *      commands and send to the molvisviewer widget. For example, resulting
12 *      image rendered offscreen is returned as ppm-formatted image data.
13 *
14 *  Copyright (c) 2004-2012  HUBzero Foundation, LLC
15 *
16 *  See the file "license.terms" for information on usage and
17 *  redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
18 * ======================================================================
19 */
20
21/*
22 * Notes:   The proxy should not maintain any state information from the
23 *          client, other that what it needs for event (rotate, pan, zoom,
24 *          atom scale, bond thickness, etc.) compression.  This is because
25 *          the connection is periodically broken (timeout, error, etc.).
26 *          It's the responsibility of the client (molvisviewer) to restore
27 *          the settings of the previous view.  The proxy is just a relay
28 *          between the client and the pymol server.
29 */
30/*
31 *   +--------------+          +------------+          +----------+
32 *   |              | (stdin)  |            |  (stdin) |          |
33 *   |              |--------->|            |--------->|          |
34 *   | molvisviewer |          | pymolproxy |          | pymol    |
35 *   |  (client)    |          |            |          | (server) |(stderr)
36 *   |              | (stdout) |            | (stdout) |          |-------> file
37 *   |              |<---------|            |<---------|          |
38 *   +--------------+          +------------+          +----------+
39 *
40 * We're using a simple 2 thread setup: one for read client requests and
41 * relaying them to the pymol server, another reading pymol server output,
42 * and sending images by to the client.  The reason is because the client
43 * blocks on writes.  While it is sending requests or data, the proxy
44 * must be available to accept it.  Likewise, the proxy buffers images in a
45 * linked list when the client isn't ready to receive them.
46 *
47 * Reader thread:
48 * The communication between the pymol server and proxy is asynchronous. 
49 * The proxy translates commands from the client and sends them to the
50 * server without waiting for a response.  It watches the server's
51 * stdout in a separate thread snooping for image data. 
52 *
53 * Writer thread:
54 * The communication between the client and the proxy is also asynchronous. 
55 * The client commands are read when they become available on the socket. 
56 * The proxy writes images to the client when it can, otherwise it stores
57 * them in a list in memory.  This should prevent deadlocks from occuring:
58 * the client sends a request, while the proxy is writing an image.
59 */
60
61#include <assert.h>
62#include <ctype.h>
63#include <errno.h>
64#include <fcntl.h>
65#include <getopt.h>
66#include <poll.h>
67#include <stdio.h>
68#include <stdlib.h>
69#include <string.h>
70#include <sys/stat.h>
71#include <sys/time.h>
72#include <sys/times.h>
73#include <sys/types.h>
74#include <sys/wait.h>
75#include <time.h>
76#include <syslog.h>
77#include <unistd.h>
78#include <tcl.h>
79#include <pthread.h>
80#include <md5.h>
81
82#define PYMOLPROXY_VERSION "1.1.0"
83
84#undef INLINE
85#ifdef __GNUC__
86#  define INLINE __inline__
87#else
88#  define INLINE
89#endif
90
91#define FALSE 0
92#define TRUE  1
93
94static int debug = FALSE;
95static FILE *frecord;
96static int recording = FALSE;
97static int pymolIsAlive = TRUE;
98static int statsFile = -1;
99
100#define WANT_DEBUG      0
101#define READ_DEBUG      0
102#define WRITE_DEBUG     0
103#define EXEC_DEBUG      0
104
105#define FORCE_UPDATE            (1<<0)
106#define CAN_UPDATE              (1<<1)
107#define INVALIDATE_CACHE        (1<<3)
108#define ATOM_SCALE_PENDING      (1<<4)
109#define STICK_RADIUS_PENDING    (1<<5)
110#define ROTATE_PENDING          (1<<6)
111#define PAN_PENDING             (1<<7)
112#define ZOOM_PENDING            (1<<8)
113#define UPDATE_PENDING          (1<<9)
114#define VIEWPORT_PENDING        (1<<10)
115
116#define IO_TIMEOUT (30000)
117#define CLIENT_READ             STDIN_FILENO
118#define CLIENT_WRITE            STDOUT_FILENO
119
120#ifndef LOGDIR
121#define LOGDIR          "/tmp"
122#endif  /* LOGDIR */
123
124#define CVT2SECS(x)  ((double)(x).tv_sec) + ((double)(x).tv_usec * 1.0e-6)
125
126typedef struct {
127    pid_t pid;                          /* Child process. */
128    size_t numFrames;                   /* # of frames sent to client. */
129    size_t numBytes;                    /* # of bytes for all frames. */
130    size_t numCommands;                 /* # of commands executed */
131    double cmdTime;                     /* Elapsed time spend executing
132                                         * commands. */
133    struct timeval start;               /* Start of elapsed time. */
134} Stats;
135
136static Stats stats;
137
138typedef struct Image {
139    struct Image *nextPtr;              /* Next image in chain of images. The
140                                         * list is ordered by the most
141                                         * recently received image from the
142                                         * pymol server to the least. */
143    struct Image *prevPtr;              /* Previous image in chain of
144                                         * images. The list is ordered by the
145                                         * most recently received image from
146                                         * the pymol server to the least. */
147    int id;
148    ssize_t numWritten;                 /* Number of bytes of image data
149                                         * already delivered.*/
150    size_t bytesLeft;                   /* Number of bytes of image data left
151                                         * to delivered to the client. */
152    unsigned char data[1];              /* Start of image data. We allocate
153                                         * the size of the Image structure
154                                         * plus the size of the image data. */
155} Image;
156
157#define BUFFER_SIZE             4096
158
159typedef struct {
160    Image *headPtr, *tailPtr;           /* List of images to be delivered to
161                                         * the client.  The most recent images
162                                         * are in the front of the list. */
163} ImageList;
164
165typedef struct {
166    const char *ident;
167    unsigned char *bytes;
168    size_t fill;
169    size_t mark;
170    size_t newline;
171    size_t bufferSize;
172    int lastStatus;
173    int fd;
174} ReadBuffer;
175
176#define BUFFER_OK                0
177#define BUFFER_ERROR            -1
178#define BUFFER_CONTINUE         -2
179#define BUFFER_EOF              -3
180
181typedef struct {
182    Tcl_Interp *interp;
183    unsigned int flags;                 /* Various flags. */
184    int sin, sout;                      /* Server file descriptors. */
185    int cin, cout;                      /* Client file descriptors. */
186    ReadBuffer client;                  /* Read buffer for client input. */
187    ReadBuffer server;                  /* Read buffer for server output. */
188    int frame;
189    int rockOffset;
190    int cacheId;
191    int error;
192    int status;
193    int width, height;                  /* Size of viewport. */
194    float xAngle, yAngle, zAngle;       /* Euler angles of pending
195                                         * rotation.  */
196    float sphereScale;                  /* Atom scale of pending re-scale. */
197    float stickRadius;                  /* Bond thickness of pending
198                                         * re-scale. */
199    float zoom;
200    float xPan, yPan;
201    pid_t pid;
202} PymolProxy;
203
204#if WANT_DEBUG
205#define DEBUG(...)      if (debug) PrintToLog(__VA_ARGS__)
206#else
207#define DEBUG(...)
208#endif
209
210#define ERROR(...)      SysLog(LOG_ERR, __FILE__, __LINE__, __VA_ARGS__)
211#define TRACE(...)      SysLog(LOG_DEBUG, __FILE__, __LINE__, __VA_ARGS__)
212#define WARN(...)       SysLog(LOG_WARNING, __FILE__, __LINE__, __VA_ARGS__)
213#define INFO(...)       SysLog(LOG_INFO, __FILE__, __LINE__, __VA_ARGS__)
214
215static const char *syslogLevels[] = {
216    "emergency",                        /* System is unusable */
217    "alert",                            /* Action must be taken immediately */
218    "critical",                         /* Critical conditions */
219    "error",                            /* Error conditions */
220    "warning",                          /* Warning conditions */
221    "notice",                           /* Normal but significant condition */
222    "info",                             /* Informational */
223    "debug",                            /* Debug-level messages */
224};
225
226#if WANT_DEBUG
227static void
228PrintToLog TCL_VARARGS_DEF(const char *, arg1)
229{
230    const char *format;
231    va_list args;
232   
233    format = TCL_VARARGS_START(const char *, arg1, args);
234    fprintf(stderr, "pymolproxy: ");
235    vfprintf(stderr, format, args);
236    fprintf(stderr, "\n");
237    fflush(stderr);
238}
239#endif
240
241void
242SysLog(int priority, const char *path, int lineNum, const char* fmt, ...)
243{
244#define MSG_LEN (2047)
245    char message[MSG_LEN+1];
246    const char *s;
247    int length;
248    va_list lst;
249
250    va_start(lst, fmt);
251    s = strrchr(path, '/');
252    if (s == NULL) {
253        s = path;
254    } else {
255        s++;
256    }
257    length = snprintf(message, MSG_LEN, "pymolproxy (%d) %s: %s:%d ",
258        getpid(), syslogLevels[priority],  s, lineNum);
259    length += vsnprintf(message + length, MSG_LEN - length, fmt, lst);
260    message[MSG_LEN] = '\0';
261    if (debug) {
262        DEBUG("%s\n", message);
263    } else {
264        syslog(priority, message, length);
265    }
266}
267
268static void
269Record TCL_VARARGS_DEF(const char *, arg1)
270{
271    const char *format;
272    va_list args;
273   
274    format = TCL_VARARGS_START(const char *, arg1, args);
275    vfprintf(frecord, format, args);
276    fflush(frecord);
277}
278
279static int
280SendToPymol(PymolProxy *proxyPtr, const char *format, ...)
281{
282    va_list ap;
283    char buffer[BUFSIZ];
284    int result;
285    ssize_t numWritten;
286    size_t length;
287
288    if (proxyPtr->error) {
289        return TCL_ERROR;
290    }
291   
292    va_start(ap, format);
293    result = vsnprintf(buffer, BUFSIZ-1, format, ap);
294    va_end(ap);
295   
296#ifdef EXEC_DEBUG
297    DEBUG("to-pymol>(%s) code=%d", buffer, result);
298#endif
299    if (recording) {
300        Record("%s\n", buffer);
301    }
302   
303    /* Write the command out to the server. */
304    length = strlen(buffer);
305    numWritten = write(proxyPtr->sin, buffer, length);
306    if (numWritten != length) {
307        ERROR("short write to pymol (wrote=%d, should have been %d): %s",
308              numWritten, length, strerror(errno));
309    }
310    proxyPtr->status = result;
311    return  proxyPtr->status;
312}
313
314
315
316/* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
317/*
318 * Copyright (C) 2011, Purdue Research Foundation
319 *
320 * Author: George A. Howlett <gah@purdue.edu>
321 */
322
323static void
324FlushReadBuffer(ReadBuffer *bp)
325{
326    bp->fill = bp->mark = 0;
327    bp->newline = 0;
328}
329
330/**
331 * \param[in] fd File descriptor to read
332 * \param[in] bufferSize Block size to use in internal buffer
333 */
334
335static void
336InitReadBuffer(ReadBuffer *bp, const char *id, int fd, size_t bufferSize)
337{
338    bp->ident = id;
339    bp->bufferSize = bufferSize;
340    bp->fd = fd;
341    bp->lastStatus = BUFFER_OK;
342    bp->bytes = malloc(bufferSize);
343    FlushReadBuffer(bp);
344}
345
346/**
347 * \brief Checks if a new line is currently in the buffer.
348 *
349 * \return the index of the character past the new line.
350 */
351static size_t
352NextLine(ReadBuffer *bp)
353{
354    /* Check for a newline in the current buffer. */
355
356    if (bp->newline > 0) {
357        return bp->newline;
358    } else {
359        unsigned char *p;
360        size_t newline;
361
362        p = (unsigned char *)memchr(bp->bytes + bp->mark, '\n',
363                                    bp->fill - bp->mark);
364        if (p == NULL) {
365            newline = 0;
366        } else {
367            newline = (p - bp->bytes + 1);
368        }
369        bp->newline = newline;
370        return newline;
371    }
372}
373
374/** 
375 * \brief Fills the buffer with available data.
376 *
377 * Any existing data in the buffer is moved to the front of the buffer,
378 * then the channel is read to fill the rest of the buffer.
379 *
380 * \return If an error occur when reading the channel, then ERROR is
381 * returned. ENDFILE is returned on EOF.  If the buffer can't be filled,
382 * then CONTINUE is returned.
383 */
384static int
385FillReadBuffer(ReadBuffer *bp)
386{
387    ssize_t numRead;
388    size_t bytesLeft;
389
390#if READ_DEBUG
391    DEBUG("Enter FillReadBuffer for %s: mark=%lu fill=%lu",
392          bp->ident, bp->mark, bp->fill);
393#endif
394    if (bp->mark >= bp->fill) {
395        FlushReadBuffer(bp);    /* Fully consumed buffer */
396    }
397    if (bp->mark > 0) {
398        /* Some data has been consumed. Move the unconsumed data to the front
399         * of the buffer. */
400#if READ_DEBUG
401        DEBUG("memmove %lu bytes", bp->fill - bp->mark);
402#endif
403        memmove(bp->bytes, bp->bytes + bp->mark,
404                bp->fill - bp->mark);
405        bp->fill -= bp->mark;
406        bp->mark = 0;
407    }
408
409    bytesLeft = bp->bufferSize - bp->fill;
410#if READ_DEBUG
411    DEBUG("going to read %lu bytes", bytesLeft);
412#endif
413    numRead = read(bp->fd, bp->bytes + bp->fill, bytesLeft);
414    if (numRead == 0) {
415        /* EOF */
416#if READ_DEBUG
417        DEBUG("EOF found reading %s buffer (fill=%d): ",
418              bp->ident, bp->fill);
419#endif
420        return BUFFER_EOF;
421    }
422    if (numRead < 0) {
423        if (errno != EAGAIN) {
424            ERROR("error reading %s buffer: %s", bp->ident, strerror(errno));
425            return BUFFER_ERROR;
426        }
427#if READ_DEBUG
428        DEBUG("Short read for buffer");
429#endif
430        return BUFFER_CONTINUE;
431    }
432    bp->fill += numRead;
433#if READ_DEBUG
434    DEBUG("Read %lu bytes", numRead);
435#endif
436    return ((size_t)numRead == bytesLeft) ? BUFFER_OK : BUFFER_CONTINUE;
437}
438
439/**
440 * \brief Read the requested number of bytes from the buffer.
441
442 * Fails if the requested number of bytes are not immediately
443 * available. Never should be short.
444 */
445static int
446ReadFollowingData(ReadBuffer *bp, unsigned char *out, size_t numBytes)
447{
448#if READ_DEBUG
449    DEBUG("Enter ReadFollowingData %s", bp->ident);
450#endif
451    while (numBytes > 0) {
452        size_t bytesLeft;
453
454        bytesLeft = bp->fill - bp->mark;
455        if (bytesLeft > 0) {
456            int size;
457
458            /* Pull bytes out of the buffer, updating the mark. */
459            size = (bytesLeft >  numBytes) ? numBytes : bytesLeft;
460            memcpy(out, bp->bytes + bp->mark, size);
461            bp->mark += size;
462            numBytes -= size;
463            out += size;
464        }
465        if (numBytes == 0) {
466            /* Received requested # bytes. */
467            return BUFFER_OK;
468        }
469        /* Didn't get enough bytes, need to read some more. */
470        bp->lastStatus = FillReadBuffer(bp);
471        if ((bp->lastStatus == BUFFER_ERROR) ||
472            (bp->lastStatus == BUFFER_EOF)) {
473            return bp->lastStatus;
474        }
475    }
476    return BUFFER_OK;
477}
478
479/**
480 * \brief Returns the next available line (terminated by a newline)
481 *
482 * If insufficient data is in the buffer, then the channel is
483 * read for more data.  If reading the channel results in a
484 * short read, CONTINUE is returned and *numBytesPtr is set to 0.
485 */
486static int
487GetLine(ReadBuffer *bp, size_t *numBytesPtr, const char **bytesPtr)
488{
489#if READ_DEBUG
490    DEBUG("Enter GetLine");
491#endif
492    *numBytesPtr = 0;
493    *bytesPtr = NULL;
494
495    bp->lastStatus = BUFFER_OK;
496    for (;;) {
497        size_t newline;
498
499        newline = NextLine(bp);
500        if (newline > 0) {
501            /* Start of the line. */
502            *bytesPtr = (const char *)(bp->bytes + bp->mark);
503            /* Number of bytes in the line. */
504            *numBytesPtr = newline - bp->mark;
505            bp->mark = newline;
506            bp->newline = 0;
507            return BUFFER_OK;
508        }
509        /* Couldn't find a newline, so it may be that we need to read some
510         * more. Check first that last read wasn't a short read. */
511        if (bp->lastStatus == BUFFER_CONTINUE) {
512            /* No complete line just yet. */
513            return BUFFER_CONTINUE;
514        }
515        /* Try to add more data to the buffer. */
516        bp->lastStatus = FillReadBuffer(bp);
517        if (bp->lastStatus == BUFFER_ERROR ||
518            bp->lastStatus == BUFFER_EOF) {
519            return bp->lastStatus;
520        }
521        /* OK or CONTINUE */
522    }
523    return BUFFER_CONTINUE;
524}
525
526static int
527IsLineAvailable(ReadBuffer *bp)
528{
529    return (NextLine(bp) > 0);
530}
531
532static int
533WaitForNextLine(ReadBuffer *bp, struct timeval *tvPtr)
534{
535    fd_set readFds;
536    int n;
537
538    if (IsLineAvailable(bp)) {
539        return 1;
540    }
541    FD_ZERO(&readFds);
542    FD_SET(bp->fd, &readFds);
543    n = select(bp->fd+1, &readFds, NULL, NULL, tvPtr);
544    return (n > 0);
545}
546
547INLINE static void
548clear_error(PymolProxy *proxyPtr)
549{
550    proxyPtr->error = 0;
551    proxyPtr->status = TCL_OK;
552}
553
554#ifndef STATSDIR
555#define STATSDIR        "/var/tmp/visservers"
556#endif  /*STATSDIR*/
557
558static int
559GetStatsFile(const char *string)
560{
561    Tcl_DString ds;
562    int i;
563    char fileName[33];
564    const char *path;
565    int length;
566    char pidstr[200];
567    md5_state_t state;
568    md5_byte_t digest[16];
569
570    if ((string == NULL) || (statsFile >= 0)) {
571        return statsFile;
572    }
573    /* By itself the client's key/value pairs aren't unique.  Add in the
574     * process id of this render server. */
575    Tcl_DStringInit(&ds);
576    Tcl_DStringAppend(&ds, string, -1);
577    Tcl_DStringAppendElement(&ds, "pid");
578    sprintf(pidstr, "%d", getpid());
579    Tcl_DStringAppendElement(&ds, pidstr);
580
581    /* Create a md5 hash of the key/value pairs and use it as the file name. */
582    string = Tcl_DStringValue(&ds);
583    length = strlen(string);
584    md5_init(&state);
585    md5_append(&state, (const md5_byte_t *)string, length);
586    md5_finish(&state, digest);
587    for (i = 0; i < 16; i++) {
588        sprintf(fileName + i * 2, "%02x", digest[i]);
589    }
590    Tcl_DStringSetLength(&ds, 0);
591    Tcl_DStringAppend(&ds, STATSDIR, -1);
592    Tcl_DStringAppend(&ds, "/", 1);
593    Tcl_DStringAppend(&ds, fileName, 32);
594    path = Tcl_DStringValue(&ds);
595
596    statsFile = open(path, O_EXCL | O_CREAT | O_WRONLY, 0600);
597    Tcl_DStringFree(&ds);
598    if (statsFile < 0) {
599        ERROR("can't open \"%s\": %s", fileName, strerror(errno));
600        return -1;
601    }
602    return statsFile;
603}
604
605static int
606WriteToStatsFile(int f, const char *s, size_t length)
607{
608
609    if (f >= 0) {
610        ssize_t numWritten;
611
612        numWritten = write(f, s, length);
613        if (numWritten == (ssize_t)length) {
614            close(dup(f));
615        }
616    }
617    return 0;
618}
619
620static int
621ServerStats(int code)
622{
623    double start, finish;
624    char buf[BUFSIZ];
625    Tcl_DString ds;
626    int result;
627    int f;
628
629    {
630        struct timeval tv;
631
632        /* Get ending time.  */
633        gettimeofday(&tv, NULL);
634        finish = CVT2SECS(tv);
635        tv = stats.start;
636        start = CVT2SECS(tv);
637    }
638    /*
639     * Session information:
640     *   - Name of render server
641     *   - Process ID
642     *   - Hostname where server is running
643     *   - Start date of session
644     *   - Start date of session in seconds
645     *   - Number of frames returned
646     *   - Number of bytes total returned (in frames)
647     *   - Number of commands received
648     *   - Total elapsed time of all commands
649     *   - Total elapsed time of session
650     *   - Exit code of vizserver
651     *   - User time
652     *   - System time
653     *   - User time of children
654     *   - System time of children
655     */
656
657    Tcl_DStringInit(&ds);
658   
659    Tcl_DStringAppendElement(&ds, "render_stop");
660    /* renderer */
661    Tcl_DStringAppendElement(&ds, "renderer");
662    Tcl_DStringAppendElement(&ds, "pymol");
663    /* pid */
664    Tcl_DStringAppendElement(&ds, "pid");
665    sprintf(buf, "%d", getpid());
666    Tcl_DStringAppendElement(&ds, buf);
667    /* host */
668    Tcl_DStringAppendElement(&ds, "host");
669    gethostname(buf, BUFSIZ-1);
670    buf[BUFSIZ-1] = '\0';
671    Tcl_DStringAppendElement(&ds, buf);
672    /* date */
673    Tcl_DStringAppendElement(&ds, "date");
674    strcpy(buf, ctime(&stats.start.tv_sec));
675    buf[strlen(buf) - 1] = '\0';
676    Tcl_DStringAppendElement(&ds, buf);
677    /* date_secs */
678    Tcl_DStringAppendElement(&ds, "date_secs");
679    sprintf(buf, "%ld", stats.start.tv_sec);
680    Tcl_DStringAppendElement(&ds, buf);
681    /* num_frames */
682    Tcl_DStringAppendElement(&ds, "num_frames");
683    sprintf(buf, "%lu", (unsigned long int)stats.numFrames);
684    Tcl_DStringAppendElement(&ds, buf);
685    /* frame_bytes */
686    Tcl_DStringAppendElement(&ds, "frame_bytes");
687    sprintf(buf, "%lu", (unsigned long int)stats.numBytes);
688    Tcl_DStringAppendElement(&ds, buf);
689    /* num_commands */
690    Tcl_DStringAppendElement(&ds, "num_commands");
691    sprintf(buf, "%lu", (unsigned long int)stats.numCommands);
692    Tcl_DStringAppendElement(&ds, buf);
693    /* cmd_time */
694    Tcl_DStringAppendElement(&ds, "cmd_time");
695    sprintf(buf, "%g", stats.cmdTime);
696    Tcl_DStringAppendElement(&ds, buf);
697    /* session_time */
698    Tcl_DStringAppendElement(&ds, "session_time");
699    sprintf(buf, "%g", finish - start);
700    Tcl_DStringAppendElement(&ds, buf);
701    /* status */
702    Tcl_DStringAppendElement(&ds, "status");
703    sprintf(buf, "%d", code);
704    Tcl_DStringAppendElement(&ds, buf);
705    {
706        long clocksPerSec = sysconf(_SC_CLK_TCK);
707        double clockRes = 1.0 / clocksPerSec;
708        struct tms tms;
709
710        memset(&tms, 0, sizeof(tms));
711        times(&tms);
712        /* utime */
713        Tcl_DStringAppendElement(&ds, "utime");
714        sprintf(buf, "%g", tms.tms_utime * clockRes);
715        Tcl_DStringAppendElement(&ds, buf);
716        /* stime */
717        Tcl_DStringAppendElement(&ds, "stime");
718        sprintf(buf, "%g", tms.tms_stime * clockRes);
719        Tcl_DStringAppendElement(&ds, buf);
720        /* cutime */
721        Tcl_DStringAppendElement(&ds, "cutime");
722        sprintf(buf, "%g", tms.tms_cutime * clockRes);
723        Tcl_DStringAppendElement(&ds, buf);
724        /* cstime */
725        Tcl_DStringAppendElement(&ds, "cstime");
726        sprintf(buf, "%g", tms.tms_cstime * clockRes);
727        Tcl_DStringAppendElement(&ds, buf);
728    }
729    Tcl_DStringAppend(&ds, "\n", -1);
730    f = GetStatsFile(NULL);
731    result = WriteToStatsFile(f, Tcl_DStringValue(&ds), Tcl_DStringLength(&ds));
732    Tcl_DStringFree(&ds);
733    close(f);
734    return result;
735}
736
737
738static int
739CartoonCmd(ClientData clientData, Tcl_Interp *interp, int argc,
740           const char *argv[])
741{
742    PymolProxy *p = clientData;
743    int bool, defer, push, i;
744    const char *model;
745
746    clear_error(p);
747    defer = push = FALSE;
748    model = "all";
749    bool = FALSE;
750    for(i = 1; i < argc; i++) {
751        if (strcmp(argv[i],"-defer") == 0) {
752            defer = TRUE;
753        } else if (strcmp(argv[i],"-push") == 0) {
754            push = TRUE;
755        } else if (strcmp(argv[i],"-model") == 0) {
756            if (++i < argc) {
757                model = argv[i];
758            }
759        } else {
760            if (Tcl_GetBoolean(interp, argv[i], &bool) != TCL_OK) {
761                return TCL_ERROR;
762            }
763        }
764    }
765    p->flags |= INVALIDATE_CACHE;       /* cartoon */
766    if (!defer || push) {
767        p->flags |= UPDATE_PENDING;
768    }
769    if (push) {
770        p->flags |= FORCE_UPDATE;
771    }
772    if (bool) {
773        SendToPymol(p, "show cartoon,%s\n", model);
774    } else {
775        SendToPymol(p, "hide cartoon,%s\n", model);
776    }
777    return p->status;
778}
779
780static int
781CartoonTraceCmd(ClientData clientData, Tcl_Interp *interp, int argc,
782                const char *argv[])
783{
784    PymolProxy *p = clientData;
785    int bool, defer, push, i;
786    const char *model;
787
788    clear_error(p);
789    defer = push = bool = FALSE;
790    model = "all";
791    for(i = 1; i < argc; i++) {
792        if (strcmp(argv[i],"-defer") == 0) {
793            defer = TRUE;
794        } else if (strcmp(argv[i],"-push") == 0) {
795            push = TRUE;
796        } else if (strcmp(argv[i],"-model") == 0) {
797            if (++i < argc) {
798                model = argv[i];
799            }
800        } else {
801            if (Tcl_GetBoolean(interp, argv[i], &bool) != TCL_OK) {
802                return TCL_ERROR;
803            }
804        }
805    }
806    p->flags |= INVALIDATE_CACHE; /* cartoon_trace  */
807    if (!defer || push) {
808        p->flags |= UPDATE_PENDING;
809    }
810    if (push) {
811        p->flags |= FORCE_UPDATE;
812    }
813    SendToPymol(p, "set cartoon_trace,%d,%s\n", bool, model);
814    return p->status;
815}
816
817static int
818DisableCmd(ClientData clientData, Tcl_Interp *interp, int argc,
819           const char *argv[])
820{
821    PymolProxy *p = clientData;
822    const char *model = "all";
823    int i, defer, push;
824
825    clear_error(p);
826    defer = push = FALSE;
827    for(i = 1; i < argc; i++) {
828        if (strcmp(argv[i], "-defer") == 0 )
829            defer = 1;
830        else if (strcmp(argv[i], "-push") == 0 )
831            push = 1;
832        else
833            model = argv[i];
834    }
835
836    p->flags |= INVALIDATE_CACHE;       /* disable */
837    if (!defer || push) {
838        p->flags |= UPDATE_PENDING;
839    }
840    if (push) {
841        p->flags |= FORCE_UPDATE;
842    }
843    SendToPymol(p, "disable %s\n", model);
844    return p->status;
845}
846
847
848static int
849EnableCmd(ClientData clientData, Tcl_Interp *interp, int argc,
850          const char *argv[])
851{
852    PymolProxy *p = clientData;
853    const char *model;
854    int i, defer, push;
855
856    clear_error(p);
857    push = defer = FALSE;
858    model = "all";
859    for(i = 1; i < argc; i++) {
860        if (strcmp(argv[i],"-defer") == 0) {
861            defer = TRUE;
862        } else if (strcmp(argv[i], "-push") == 0) {
863            push = TRUE;
864        } else {
865            model = argv[i];
866        }
867    }
868    p->flags |= INVALIDATE_CACHE; /* enable */
869    if (!defer || push) {
870        p->flags |= UPDATE_PENDING;
871    }
872    if (push) {
873        p->flags |= FORCE_UPDATE;
874    }
875    SendToPymol(p, "enable %s\n", model);
876    return p->status;
877}
878
879static int
880FrameCmd(ClientData clientData, Tcl_Interp *interp, int argc,
881         const char *argv[])
882{
883    PymolProxy *p = clientData;
884    int i, push, defer, frame;
885
886    clear_error(p);
887    frame = 0;
888    push = defer = FALSE;
889    for(i = 1; i < argc; i++) {
890        if (strcmp(argv[i],"-defer") == 0) {
891            defer = TRUE;
892        } else if (strcmp(argv[i],"-push") == 0) {
893            push = TRUE;
894        } else {
895            frame = atoi(argv[i]);
896        }
897    }
898    if (!defer || push) {
899        p->flags |= UPDATE_PENDING;
900    }
901    if (push) {
902        p->flags |= FORCE_UPDATE;
903    }
904    p->frame = frame;
905
906    /* Does not invalidate cache? */
907
908    SendToPymol(p,"frame %d\n", frame);
909    return p->status;
910}
911
912/*
913 * ClientInfoCmd --
914 *
915 *       
916 *      clientinfo path list
917 */
918static int
919ClientInfoCmd(ClientData clientData, Tcl_Interp *interp, int argc,
920              const char *argv[])
921{
922    Tcl_DString ds;
923    int result;
924    int i, numElems;
925    const char **elems;
926    char buf[BUFSIZ];
927    static int first = 1;
928    int f;
929
930    if (argc != 2) {
931        Tcl_AppendResult(interp, "wrong # of arguments: should be \"", argv[0],
932                " list\"", (char *)NULL);
933        return TCL_ERROR;
934    }
935    /* Use the initial client key value pairs as the parts for a generating
936     * a unique file name. */
937    f = GetStatsFile(argv[1]);
938    if (f < 0) {
939        Tcl_AppendResult(interp, "can't open stats file: ",
940                         Tcl_PosixError(interp), (char *)NULL);
941        return TCL_ERROR;
942    }
943    Tcl_DStringInit(&ds);
944    if (first) {
945        first = 0;
946        Tcl_DStringAppendElement(&ds, "render_start");
947        /* renderer */
948        Tcl_DStringAppendElement(&ds, "renderer");
949        Tcl_DStringAppendElement(&ds, "pymol");
950        /* pid */
951        Tcl_DStringAppendElement(&ds, "pid");
952        sprintf(buf, "%d", getpid());
953        Tcl_DStringAppendElement(&ds, buf);
954        /* host */
955        Tcl_DStringAppendElement(&ds, "host");
956        gethostname(buf, BUFSIZ-1);
957        buf[BUFSIZ-1] = '\0';
958        Tcl_DStringAppendElement(&ds, buf);
959    } else {
960        Tcl_DStringAppendElement(&ds, "render_info");
961    }
962    /* date */
963    Tcl_DStringAppendElement(&ds, "date");
964    strcpy(buf, ctime(&stats.start.tv_sec));
965    buf[strlen(buf) - 1] = '\0';
966    Tcl_DStringAppendElement(&ds, buf);
967    /* date_secs */
968    Tcl_DStringAppendElement(&ds, "date_secs");
969    sprintf(buf, "%ld", stats.start.tv_sec);
970    Tcl_DStringAppendElement(&ds, buf);
971
972    /* Client arguments. */
973    if (Tcl_SplitList(interp, argv[1], &numElems, &elems) != TCL_OK) {
974        return TCL_ERROR;
975    }
976    for (i = 0; i < numElems; i++) {
977        Tcl_DStringAppendElement(&ds, elems[i]);
978    }
979    free(elems);
980    Tcl_DStringAppend(&ds, "\n", 1);
981    result = WriteToStatsFile(f, Tcl_DStringValue(&ds), Tcl_DStringLength(&ds));
982    Tcl_DStringFree(&ds);
983    return result;
984}
985
986static int
987LabelCmd(ClientData clientData, Tcl_Interp *interp, int argc,
988         const char *argv[])
989{
990    PymolProxy *p = clientData;
991    int i, push, defer, bool, size;
992    const char *model;
993
994    clear_error(p);
995    model = "all";
996    size = 14;
997    bool = TRUE;
998    push = defer = FALSE;
999    for(i = 1; i < argc; i++) {
1000        if (strcmp(argv[i],"-defer") == 0) {
1001            defer = TRUE;
1002        } else if (strcmp(argv[i],"-push") == 0) {
1003            push = TRUE;
1004        } else if (strcmp(argv[i],"-model") == 0) {
1005            if (++i < argc) {
1006                model = argv[i];
1007            }
1008        } else if (strcmp(argv[i],"-size") == 0) {
1009            if (++i < argc) {
1010                size = atoi(argv[i]);
1011            }
1012        } else if (Tcl_GetBoolean(interp, argv[i], &bool) != TCL_OK) {
1013            return TCL_ERROR;
1014        }
1015    }
1016    p->flags |= INVALIDATE_CACHE;       /* label */
1017    if (!defer || push) {
1018        p->flags |= UPDATE_PENDING;
1019    }
1020    if (push) {
1021        p->flags |= FORCE_UPDATE;
1022    }
1023    SendToPymol(p, "set label_color,white,%s\nset label_size,%d,%s\n",
1024            model, size, model);
1025    if (bool) {
1026        SendToPymol(p, "label %s,\"%%s%%s\" %% (ID,name)\n", model);
1027    } else {
1028        SendToPymol(p, "label %s\n", model);
1029    }
1030    return p->status;
1031}
1032
1033/*
1034 * LoadPDBCmd --
1035 *
1036 *      Load a PDB into pymol.  We write the pdb data into a temporary file
1037 *      and then let pymol read it and delete it.  There is no good way to
1038 *      load PDB data into pymol without using a file.  The specially created
1039 *      routine "loadandremovepdbfile" in pymol will remove the file after
1040 *      loading it. 
1041 *
1042 */
1043static int
1044LoadPDBCmd(ClientData clientData, Tcl_Interp *interp, int argc,
1045           const char *argv[])
1046{
1047    PymolProxy *p = clientData;
1048    const char *string;
1049    const char *name;
1050    unsigned char *allocated;
1051    int state, defer, push;
1052    size_t numBytes;
1053    int i, j;
1054    int status;
1055
1056    if (p == NULL){
1057        return TCL_ERROR;
1058    }
1059    clear_error(p);
1060    defer = push = FALSE;
1061    for(i = j = 1; i < argc; i++) {
1062        if (strcmp(argv[i],"-defer") == 0) {
1063            defer = TRUE;
1064        } else if (strcmp(argv[i],"-push") == 0) {
1065            push = TRUE;
1066        } else {
1067            if (j < i) {
1068                argv[j] = argv[i];
1069            }
1070            j++;
1071        }
1072    }
1073    argc = j;
1074    if (argc < 4) {
1075        Tcl_AppendResult(interp, "wrong # arguments: should be \"", argv[0],
1076                         " <data>|follows <model> <state> ?<numBytes>?\"",
1077                         (char *)NULL);
1078        return TCL_ERROR;
1079    }
1080    string = argv[1];
1081    name   = argv[2];
1082    if (Tcl_GetInt(interp, argv[3], &state) != TCL_OK) {
1083        return TCL_ERROR;
1084    }
1085    numBytes = 0;
1086    status = BUFFER_ERROR;
1087    if (strcmp(string, "follows") == 0) {
1088        int n;
1089
1090        if (argc != 5) {
1091            Tcl_AppendResult(interp, "wrong # arguments: should be \"", argv[0],
1092                         " follows <model> <state> <numBytes>\"", (char *)NULL);
1093            return TCL_ERROR;
1094        }
1095        if (Tcl_GetInt(interp, argv[4], &n) != TCL_OK) {
1096            return TCL_ERROR;
1097        }
1098        if (n < 0) {
1099            Tcl_AppendResult(interp, "bad value for # bytes \"", argv[4],
1100                         "\"", (char *)NULL);
1101            return TCL_ERROR;
1102        }
1103        numBytes = (size_t)n;
1104    }
1105    if (!defer || push) {
1106        p->flags |= UPDATE_PENDING;
1107    }
1108    if (push) {
1109        p->flags |= FORCE_UPDATE;
1110    }
1111    p->cacheId = state;
1112
1113    /* Does not invalidate cache? */
1114
1115    allocated = NULL;
1116    allocated = malloc(sizeof(char) * numBytes);
1117    if (allocated == NULL) {
1118        Tcl_AppendResult(interp, "can't allocate buffer for pdbdata.",
1119                         (char *)NULL);
1120        return TCL_ERROR;
1121    }
1122    status = ReadFollowingData(&p->client, allocated, numBytes);
1123    if (status != BUFFER_OK) {
1124        Tcl_AppendResult(interp, "can't read pdbdata from client.",
1125                         (char *)NULL);
1126        free(allocated);
1127        return TCL_ERROR;
1128    }
1129    string = (const char *)allocated;
1130    {
1131        int f;
1132        ssize_t numWritten;
1133        char fileName[200];
1134
1135        strcpy(fileName, "/tmp/pdb.XXXXXX");
1136        p->status = TCL_ERROR;
1137        f = mkstemp(fileName);
1138        if (f < 0) {
1139            Tcl_AppendResult(interp, "can't create temporary file \"",
1140                fileName, "\":", Tcl_PosixError(interp), (char *)NULL);
1141            goto error;
1142        }
1143        numWritten = write(f, string, numBytes);
1144        if (numBytes != numWritten) {
1145            Tcl_AppendResult(interp, "can't write PDB data to \"",
1146                fileName, "\": ", Tcl_PosixError(interp), (char *)NULL);
1147            close(f);
1148            goto error;
1149        }
1150        close(f);
1151        SendToPymol(p, "loadandremovepdbfile %s,%s,%d\n", fileName, name,
1152                    state);
1153        p->status = TCL_OK;
1154    }
1155 error:
1156    if (allocated != NULL) {
1157        free(allocated);
1158    }
1159    return p->status;
1160}
1161
1162static int
1163OrthoscopicCmd(ClientData clientData, Tcl_Interp *interp, int argc,
1164              const char *argv[])
1165{
1166    PymolProxy *p = clientData;
1167    int bool, defer, push, i;
1168
1169    clear_error(p);
1170    defer = push = FALSE;
1171    bool = FALSE;
1172    for(i = 1; i < argc; i++) {
1173        if (strcmp(argv[i],"-defer") == 0) {
1174            defer = TRUE;
1175        } else if (strcmp(argv[i],"-push") == 0) {
1176            push = TRUE;
1177        } else {
1178            if (Tcl_GetBoolean(interp, argv[i], &bool) != TCL_OK) {
1179                return TCL_ERROR;
1180            }
1181        }
1182    }
1183    p->flags |= INVALIDATE_CACHE; /* orthoscopic */
1184    if (!defer || push) {
1185        p->flags |= UPDATE_PENDING;
1186    }
1187    if (push) {
1188        p->flags |= FORCE_UPDATE;
1189    }
1190    SendToPymol(p, "set orthoscopic=%d\n", bool);
1191    return p->status;
1192}
1193
1194/*
1195 * PanCmd --
1196 *
1197 *      Issue "move" commands for changes in the x and y coordinates of the
1198 *      camera.  The problem here is that there is no event compression.
1199 *      Consecutive "pan" commands are not compressed into a single
1200 *      directive.  The means that the pymol server will render scenes that
1201 *      are not used by the client.
1202 *
1203 *      Need to 1) defer the "move" commands until we find the next command
1204 *      isn't a "pan". 2) Track the x and y coordinates as they are
1205 *      compressed.
1206 */
1207static int
1208PanCmd(ClientData clientData, Tcl_Interp *interp, int argc, const char *argv[])
1209{
1210    PymolProxy *p = clientData;
1211    double x, y;
1212    int i;
1213    int defer, push;
1214
1215    clear_error(p);
1216    defer = push = FALSE;
1217    for (i = 1; i < argc; i++) {
1218        if (strcmp(argv[i],"-defer") == 0) {
1219            defer = 1;
1220        } else if (strcmp(argv[i],"-push") == 0) {
1221            push = 1;
1222        } else {
1223            break;
1224        }
1225    }
1226    if ((Tcl_GetDouble(interp, argv[i], &x) != TCL_OK) ||
1227        (Tcl_GetDouble(interp, argv[i+1], &y) != TCL_OK)) {
1228        return TCL_ERROR;
1229    }
1230    p->flags |= INVALIDATE_CACHE;       /* pan */
1231    if (!defer || push) {
1232        p->flags |= UPDATE_PENDING;
1233    }
1234    if (push) {
1235        p->flags |= FORCE_UPDATE;
1236    }
1237    if ((x != 0.0f) || (y != 0.0f)) {
1238        p->xPan = x * 0.05;
1239        p->yPan = -y * 0.05;
1240        p->flags |= PAN_PENDING;
1241    }
1242    return p->status;
1243}
1244
1245static int
1246PngCmd(ClientData clientData, Tcl_Interp *interp, int argc, const char *argv[])
1247{
1248    PymolProxy *p = clientData;
1249
1250    clear_error(p);
1251
1252    /* Force pymol to update the current scene. */
1253    SendToPymol(p, "refresh\n");
1254    /* This is a hack. We're encoding the filename to pass extra information
1255     * to the MyPNGWrite routine inside of pymol. Ideally these would be
1256     * parameters of a new "molvispng" command that would be passed all the
1257     * way through to MyPNGWrite.
1258     *
1259     * The extra information is contained in the token we get from the
1260     * molvisviewer client, the frame number, and rock offset. */
1261    SendToPymol(p, "png -:%d:%d:%d\n", p->cacheId, p->frame, p->rockOffset);
1262    return p->status;
1263}
1264
1265
1266static int
1267PpmCmd(ClientData clientData, Tcl_Interp *interp, int argc, const char *argv[])
1268{
1269    PymolProxy *p = clientData;
1270
1271    clear_error(p);
1272
1273    /* Force pymol to update the current scene. */
1274    SendToPymol(p, "refresh\n");
1275    /* This is a hack. We're encoding the filename to pass extra information
1276     * to the MyPNGWrite routine inside of pymol. Ideally these would be
1277     * parameters of a new "molvispng" command that would be passed all the
1278     * way through to MyPNGWrite.
1279     *
1280     * The extra information is contained in the token we get from the
1281     * molvisviewer client, the frame number, and rock offset. */
1282    SendToPymol(p, "png -:%d:%d:%d,format=1\n", p->cacheId, p->frame,
1283            p->rockOffset);
1284    p->flags &= ~(UPDATE_PENDING|FORCE_UPDATE);
1285    return p->status;
1286}
1287
1288
1289static int
1290PrintCmd(ClientData clientData, Tcl_Interp *interp, int argc,
1291         const char *argv[])
1292{
1293    PymolProxy *p = clientData;
1294    int width, height;
1295    const char *token, *bgcolor;
1296
1297    clear_error(p);
1298
1299    if (argc != 5) {
1300        Tcl_AppendResult(interp, "wrong # arguments: should be \"",
1301                         argv[0], " token width height color\"", (char *)NULL);
1302        return TCL_ERROR;
1303    }
1304    token = argv[1];
1305    if (Tcl_GetInt(interp, argv[2], &width) != TCL_OK) {
1306        return TCL_ERROR;
1307    }
1308    if (Tcl_GetInt(interp, argv[3], &height) != TCL_OK) {
1309        return TCL_ERROR;
1310    }
1311    bgcolor = argv[4];
1312    /* Force pymol to update the current scene. */
1313    if (strcmp(bgcolor, "none") == 0) {
1314        SendToPymol(p, "set ray_opaque_background,off\n");
1315        SendToPymol(p, "refresh\n", bgcolor);
1316    } else {
1317        SendToPymol(p, "set ray_opaque_background,on\n");
1318        SendToPymol(p, "bg_color %s\nrefresh\n", bgcolor);
1319    }
1320    /* This is a hack. We're encoding the filename to pass extra information
1321     * to the MyPNGWrite routine inside of pymol. Ideally these would be
1322     * parameters of a new "molvispng" command that would be passed all the
1323     * way through to MyPNGWrite. 
1324     *
1325     * The extra information is contained in the token we get from the
1326     * molvisviewer client, the frame number, and rock offset.
1327     */
1328    SendToPymol(p, "png -:%s:0:0,width=%d,height=%d,ray=1,dpi=300\n",
1329            token, width, height);
1330    SendToPymol(p, "bg_color black\n");
1331    return p->status;
1332}
1333
1334static int
1335RawCmd(ClientData clientData, Tcl_Interp *interp, int argc, const char *argv[])
1336{
1337    PymolProxy *p = clientData;
1338    int arg, defer = 0, push = 0;
1339    const char *cmd;
1340    clear_error(p);
1341
1342    cmd = NULL;
1343    defer = push = FALSE;
1344    for(arg = 1; arg < argc; arg++) {
1345        if (strcmp(argv[arg], "-defer") == 0)
1346            defer = 1;
1347        else if (strcmp(argv[arg], "-push") == 0)
1348            push = 1;
1349        else {
1350            cmd = argv[arg];
1351        }
1352    }
1353
1354    p->flags |= INVALIDATE_CACHE; /* raw */
1355    if (!defer || push) {
1356        p->flags |= UPDATE_PENDING;
1357    }
1358    if (push) {
1359        p->flags |= FORCE_UPDATE;
1360    }
1361    SendToPymol(p,"%s\n", cmd);
1362    return p->status;
1363}
1364
1365static int
1366ResetCmd(ClientData clientData, Tcl_Interp *interp, int argc,
1367         const char *argv[])
1368{
1369    PymolProxy *p = clientData;
1370    int arg, push = 0, defer = 0;
1371
1372    clear_error(p);
1373    defer = push = 0;
1374    for(arg = 1; arg < argc; arg++) {
1375        if ( strcmp(argv[arg],"-defer") == 0 )
1376            defer = 1;
1377        else if (strcmp(argv[arg],"-push") == 0 )
1378            push = 1;
1379    }
1380               
1381    p->flags |= INVALIDATE_CACHE; /* reset */
1382    if (!defer || push) {
1383        p->flags |= UPDATE_PENDING;
1384    }
1385    if (push) {
1386        p->flags |= FORCE_UPDATE;
1387    }
1388    SendToPymol(p, "reset\nzoom complete=1\n");
1389    return p->status;
1390}
1391
1392static int
1393RockCmd(ClientData clientData, Tcl_Interp *interp, int argc,
1394        const char *argv[])
1395{
1396    PymolProxy *p = clientData;
1397    float y = 0.0;
1398    int arg, push, defer;
1399
1400    clear_error(p);
1401
1402    defer = push = FALSE;
1403    for(arg = 1; arg < argc; arg++) {
1404        if ( strcmp(argv[arg],"-defer") == 0 )
1405            defer = 1;
1406        else if (strcmp(argv[arg],"-push") == 0 )
1407            push = 1;
1408        else
1409            y = atof( argv[arg] );
1410    }
1411               
1412    /* Does not invalidate cache. */
1413
1414    if (!defer || push) {
1415        p->flags |= UPDATE_PENDING;
1416    }
1417    if (push) {
1418        p->flags |= FORCE_UPDATE;
1419    }
1420    SendToPymol(p,"turn y, %f\n", y - p->rockOffset);
1421    p->rockOffset = y;
1422    return p->status;
1423}
1424
1425static int
1426RepresentationCmd(ClientData clientData, Tcl_Interp *interp, int argc,
1427                  const char *argv[])
1428{
1429    PymolProxy *p = clientData;
1430    const char *model;
1431    const char *rep;
1432    int defer, push, i;
1433
1434    clear_error(p);
1435    defer = push = FALSE;
1436    model = "all";
1437    rep = NULL;
1438    for (i = 1; i < argc; i++) {
1439        if (strcmp(argv[i],"-defer") == 0 ) {
1440            defer = TRUE;
1441        } else if (strcmp(argv[i],"-push") == 0) {
1442            push = TRUE;
1443        } else if (strcmp(argv[i],"-model") == 0) {
1444            if (++i < argc) {
1445                model = argv[i];
1446            }
1447        } else {
1448            rep = argv[i];
1449        }
1450    }
1451    if (rep == NULL) {
1452        Tcl_AppendResult(interp, "missing representation argument",
1453                         (char *)NULL);
1454        return TCL_ERROR;
1455    }
1456
1457    p->flags |= INVALIDATE_CACHE; /* representation */
1458    if (!defer || push) {
1459        p->flags |= UPDATE_PENDING;
1460    }
1461    if (push) {
1462        p->flags |= FORCE_UPDATE;
1463    }
1464    if (strcmp(rep, "ballnstick") == 0) { /* Ball 'n Stick */
1465        SendToPymol(p,
1466              "set stick_color,white,%s\n"
1467              "show sticks,%s\n"
1468              "show spheres,%s\n"
1469              "hide lines,%s\n"
1470              "hide cartoon,%s\n",
1471              model, model, model, model, model);
1472    } else if (strcmp(rep, "spheres") == 0) { /* spheres */   
1473        SendToPymol(p,
1474              "hide sticks,%s\n"
1475              "show spheres,%s\n"
1476              "hide lines,%s\n"
1477              "hide cartoon,%s\n"
1478              "set sphere_quality,2,%s\n"
1479              "set ambient,.2,%s\n",
1480              model, model, model, model, model, model);
1481    } else if (strcmp(rep, "none") == 0) { /* nothing */   
1482        SendToPymol(p,
1483              "hide sticks,%s\n",
1484              "hide spheres,%s\n"
1485              "hide lines,%s\n"
1486              "hide cartoon,%s\n",
1487              model, model, model, model);
1488    } else if (strcmp(rep, "sticks") == 0) { /* sticks */   
1489        SendToPymol(p,
1490              "set stick_color,white,%s\n"
1491              "show sticks,%s\n"
1492              "hide spheres,%s\n"
1493              "hide lines,%s\n"
1494              "hide cartoon,%s\n",
1495              model, model, model, model, model);
1496    } else if (strcmp(rep, "lines") == 0) { /* lines */   
1497        SendToPymol(p,
1498              "hide sticks,%s\n"
1499              "hide spheres,%s\n"
1500              "show lines,%s\n"
1501              "hide cartoon,%s\n",
1502              model, model, model, model);
1503    } else if (strcmp(rep, "cartoon") == 0) { /* cartoon */   
1504        SendToPymol(p,
1505              "hide sticks,%s\n"
1506              "hide spheres,%s\n"
1507              "hide lines,%s\n"
1508              "show cartoon,%s\n",
1509              model, model, model, model);
1510    }
1511    return p->status;
1512}
1513
1514/*
1515 * RotateCmd --
1516 *
1517 *      Issue "turn" commands for changes in the angle of the camera.  The
1518 *      problem here is that there is no event compression.  Consecutive
1519 *      "rotate" commands are not compressed into a single directive.  The
1520 *      means that the pymol server will render many scene that are not used
1521 *      by the client.
1522 *
1523 *      Need to 1) defer the "turn" commands until we find the next command
1524 *      isn't a "rotate". 2) Track the rotation angles as they are compressed.
1525 */
1526static int
1527RotateCmd(ClientData clientData, Tcl_Interp *interp, int argc,
1528          const char *argv[])
1529{
1530    PymolProxy *p = clientData;
1531    float xAngle, yAngle, zAngle;
1532    int defer, push, arg, varg = 1;
1533
1534    clear_error(p);
1535    defer = push = 0;
1536    xAngle = yAngle = zAngle = 0.0f;
1537    for(arg = 1; arg < argc; arg++) {
1538        if (strcmp(argv[arg],"-defer") == 0) {
1539            defer = 1;
1540        } else if (strcmp(argv[arg],"-push") == 0) {
1541            push = 1;
1542        } else  if (varg == 1) {
1543            double value;
1544            if (Tcl_GetDouble(interp, argv[arg], &value) != TCL_OK) {
1545                return TCL_ERROR;
1546            }
1547            xAngle = (float)value;
1548            varg++;
1549        } else if (varg == 2) {
1550            double value;
1551            if (Tcl_GetDouble(interp, argv[arg], &value) != TCL_OK) {
1552                return TCL_ERROR;
1553            }
1554            yAngle = (float)value;
1555            varg++;
1556        } else if (varg == 3) {
1557            double value;
1558            if (Tcl_GetDouble(interp, argv[arg], &value) != TCL_OK) {
1559                return TCL_ERROR;
1560            }
1561            zAngle = (float)value;
1562            varg++;
1563        }
1564    }
1565    p->flags |= INVALIDATE_CACHE; /* rotate */
1566    if (!defer || push) {
1567        p->flags |= UPDATE_PENDING;
1568    }
1569    if (push) {
1570        p->flags |= FORCE_UPDATE;
1571    }
1572    if ((xAngle != 0.0f) || (yAngle != 0.0f) || (zAngle != 0.0f)) {
1573        p->xAngle += xAngle;
1574        p->yAngle += yAngle;
1575        p->zAngle += zAngle;
1576        p->flags |= ROTATE_PENDING;
1577    }
1578    return p->status;
1579}
1580
1581static int
1582ScreenCmd(ClientData clientData, Tcl_Interp *interp, int argc,
1583          const char *argv[])
1584{
1585    PymolProxy *p = clientData;
1586    int width = -1, height = -1;
1587    int defer, push, i, varg;
1588
1589    clear_error(p);
1590    defer = push = FALSE;
1591    varg = 1;
1592    for(i = 1; i < argc; i++) {
1593        if ( strcmp(argv[i],"-defer") == 0 )
1594            defer = 1;
1595        else if ( strcmp(argv[i], "-push") == 0 )
1596            push = 1;
1597        else if (varg == 1) {
1598            width = atoi(argv[i]);
1599            height = width;
1600            varg++;
1601        }
1602        else if (varg == 2) {
1603            height = atoi(argv[i]);
1604            varg++;
1605        }
1606    }
1607    if ((width < 0) || (height < 0)) {
1608        return TCL_ERROR;
1609    }
1610    p->flags |= INVALIDATE_CACHE; /* viewport */
1611    if (!defer || push) {
1612        p->flags |= UPDATE_PENDING;
1613    }
1614    if (push) {
1615        p->flags |= FORCE_UPDATE;
1616    }
1617    p->width = width;
1618    p->height = height;
1619    p->flags |= VIEWPORT_PENDING;
1620    return p->status;
1621}
1622
1623static int
1624SphereScaleCmd(ClientData clientData, Tcl_Interp *interp, int argc,
1625           const char *argv[])
1626{
1627    int defer = 0, push = 0, i;
1628    double scale;
1629    const char *model = "all";
1630    PymolProxy *p = clientData;
1631
1632    clear_error(p);
1633    scale = 0.25f;
1634    for(i = 1; i < argc; i++) {
1635        if ( strcmp(argv[i],"-defer") == 0 ) {
1636            defer = 1;
1637        } else if (strcmp(argv[i],"-push") == 0) {
1638            push = 1;
1639        } else if (strcmp(argv[i],"-model") == 0) {
1640            if (++i < argc) {
1641                model = argv[i];
1642            }
1643        } else {
1644            if (Tcl_GetDouble(interp, argv[i], &scale) != TCL_OK) {
1645                return TCL_ERROR;
1646            }
1647        }
1648    }
1649    p->flags |= INVALIDATE_CACHE;  /* sphere_scale */
1650    if (!defer || push) {
1651        p->flags |= UPDATE_PENDING;
1652    }
1653    if (push) {
1654        p->flags |= FORCE_UPDATE;
1655    }
1656    if (strcmp(model, "all") == 0) {
1657        p->flags |= ATOM_SCALE_PENDING;
1658        p->sphereScale = scale;
1659    } else {
1660        SendToPymol(p, "set sphere_scale,%f,%s\n", scale, model);
1661    }
1662    return p->status;
1663}
1664
1665static int
1666StickRadiusCmd(ClientData clientData, Tcl_Interp *interp, int argc,
1667               const char *argv[])
1668{
1669    PymolProxy *p = clientData;
1670    int defer = 0, push = 0, i;
1671    double scale;
1672    const char *model = "all";
1673
1674    clear_error(p);
1675    scale = 0.25f;
1676    for(i = 1; i < argc; i++) {
1677        if (strcmp(argv[i],"-defer") == 0 ) {
1678            defer = 1;
1679        } else if (strcmp(argv[i],"-push") == 0) {
1680            push = 1;
1681        } else if (strcmp(argv[i],"-model") == 0) {
1682            if (++i < argc)
1683                model = argv[i];
1684        } else {
1685            if (Tcl_GetDouble(interp, argv[i], &scale) != TCL_OK) {
1686                return TCL_ERROR;
1687            }
1688        }
1689    }
1690    p->flags |= INVALIDATE_CACHE;  /* stick_radius */
1691    if (!defer || push) {
1692        p->flags |= UPDATE_PENDING;
1693    }
1694    if (push) {
1695        p->flags |= FORCE_UPDATE;
1696    }
1697
1698    if (strcmp(model, "all") == 0) {
1699        p->flags |= STICK_RADIUS_PENDING;
1700        p->stickRadius = scale;
1701    } else {
1702        SendToPymol(p, "set stick_radius,%f,%s\n", scale, model);
1703    }
1704    return p->status;
1705}
1706
1707static int
1708TransparencyCmd(ClientData clientData, Tcl_Interp *interp, int argc,
1709                const char *argv[])
1710{
1711    PymolProxy *p = clientData;
1712    const char *model;
1713    float transparency;
1714    int defer, push;
1715    int i;
1716
1717    clear_error(p);
1718    model = "all";
1719    defer = push = FALSE;
1720    transparency = 0.0f;
1721    for(i = 1; i < argc; i++) {
1722        if ( strcmp(argv[i],"-defer") == 0 ) {
1723            defer = 1;
1724        } else if (strcmp(argv[i],"-push") == 0) {
1725            push = 1;
1726        } else if (strcmp(argv[i],"-model") == 0) {
1727            if (++i < argc) {
1728                model = argv[i];
1729            }
1730        } else {
1731            transparency = atof(argv[i]);
1732        }
1733    }
1734    p->flags |= INVALIDATE_CACHE; /* transparency */
1735    if (!defer || push) {
1736        p->flags |= UPDATE_PENDING;
1737    }
1738    if (push) {
1739        p->flags |= FORCE_UPDATE;
1740    }
1741    SendToPymol(p,
1742          "set sphere_transparency,%g,%s\n"
1743          "set stick_transparency,%g,%s\n"
1744          "set cartoon_transparency,%g,%s\n",
1745          transparency, model, transparency, model,
1746          transparency, model);
1747    return p->status;
1748}
1749
1750static int
1751VMouseCmd(ClientData clientData, Tcl_Interp *interp, int argc,
1752          const char *argv[])
1753{
1754    PymolProxy *p = clientData;
1755    int i, defer = 0, push = 0, varg = 1;
1756    int arg1 = 0, arg2 = 0, arg3 = 0, arg4 = 0, arg5 = 0;
1757
1758    clear_error(p);
1759
1760    for(i = 1; i < argc; i++) {
1761        if (strcmp(argv[i], "-defer") == 0)
1762            defer = 1;
1763        else if (strcmp(argv[i], "-push") == 0)
1764            push = 1;
1765        else if (varg == 1) {
1766            arg1 = atoi(argv[i]);
1767            varg++;
1768        } else if (varg == 2) {
1769            arg2 = atoi(argv[i]);
1770            varg++;
1771        } else if (varg == 3) {
1772            arg3 = atoi(argv[i]);
1773            varg++;
1774        } else if (varg == 4) {
1775            arg4 = atoi(argv[i]);
1776            varg++;
1777        } else if (varg == 5) {
1778            arg5 = atoi(argv[i]);
1779            varg++;
1780        }
1781    }
1782
1783    p->flags |= INVALIDATE_CACHE;       /* vmouse */
1784    if (!defer || push) {
1785        p->flags |= UPDATE_PENDING;
1786    }
1787    if (push) {
1788        p->flags |= FORCE_UPDATE;
1789    }
1790    SendToPymol(p, "vmouse %d,%d,%d,%d,%d\n", arg1, arg2, arg3, arg4, arg5);
1791    return p->status;
1792}
1793
1794
1795/*
1796 * ZoomCmd --
1797 *
1798 *      Issue "move" commands for changes in the z-coordinate of the camera.
1799 *      The problem here is that there is no event compression.  Consecutive
1800 *      "zoom" commands are not compressed into a single directive.  The means
1801 *      that the pymol server will render scenes that are not used by the
1802 *      client.
1803 *
1804 *      Need to 1) defer the "move" commands until we find the next command
1805 *      isn't a "zoom". 2) Track the z-coordinate as they are compressed.
1806 */
1807static int
1808ZoomCmd(ClientData clientData, Tcl_Interp *interp, int argc, const char *argv[])
1809{
1810    PymolProxy *p = clientData;
1811    double factor = 0.0;
1812    int defer = 0, push = 0, i, varg = 1;
1813
1814    clear_error(p);
1815
1816    for(i = 1; i < argc; i++) {
1817        if (strcmp(argv[i],"-defer") == 0)
1818            defer = 1;
1819        else if (strcmp(argv[i],"-push") == 0)
1820            push = 1;
1821        else if (varg == 1) {
1822            double value;
1823            if (Tcl_GetDouble(interp, argv[i], &value) != TCL_OK) {
1824                return TCL_ERROR;
1825            }
1826            factor = (float)value;
1827            varg++;
1828        }
1829    }
1830    p->flags |= INVALIDATE_CACHE; /* Zoom */
1831    if (!defer || push) {
1832        p->flags |= UPDATE_PENDING;
1833    }
1834    if (push) {
1835        p->flags |= FORCE_UPDATE;
1836    }
1837    if (factor != 0.0) {
1838        p->zoom = factor;
1839        p->flags |= ZOOM_PENDING;
1840    }
1841    return p->status;
1842}
1843
1844       
1845
1846static int
1847ExecuteCommand(Tcl_Interp *interp, Tcl_DString *dsPtr)
1848{
1849    struct timeval tv;
1850    double start, finish;
1851    int result;
1852
1853    gettimeofday(&tv, NULL);
1854    start = CVT2SECS(tv);
1855
1856#if EXEC_DEBUG
1857    DEBUG("command from client is (%s)", Tcl_DStringValue(dsPtr));
1858#endif
1859    result = Tcl_Eval(interp, Tcl_DStringValue(dsPtr));
1860    if (result != TCL_OK) {
1861#if EXEC_DEBUG
1862        DEBUG("result was %s\n", Tcl_GetString(Tcl_GetObjResult(interp)));
1863#endif
1864    }
1865    gettimeofday(&tv, NULL);
1866    finish = CVT2SECS(tv);
1867
1868    stats.cmdTime += finish - start;
1869    stats.numCommands++;
1870    Tcl_DStringSetLength(dsPtr, 0);
1871    return result;
1872}
1873
1874static void
1875SetViewport(PymolProxy *p)
1876{
1877    if (p->flags & VIEWPORT_PENDING) {
1878        SendToPymol(p, "viewport %d,%d\n", p->width, p->height);
1879        SendToPymol(p, "refresh\n");
1880        p->flags &= ~VIEWPORT_PENDING;
1881    }
1882}
1883
1884static void
1885SetZoom(PymolProxy *p)
1886{
1887    if (p->flags & ZOOM_PENDING) {
1888        SendToPymol(p, "move z,%f\n", p->zoom);
1889        p->flags &= ~ZOOM_PENDING;
1890    }
1891}
1892
1893static void
1894SetPan(PymolProxy *p)
1895{
1896    if (p->flags & PAN_PENDING) {
1897        SendToPymol(p, "move x,%f\nmove y,%f\n", p->xPan, p->yPan);
1898        p->flags &= ~PAN_PENDING;
1899    }
1900}
1901
1902static void
1903SetRotation(PymolProxy *p)
1904{
1905    if (p->flags & ROTATE_PENDING) {
1906        /* Every pymol command line generates a new rendering. Execute all
1907         * three turns as a single command line. */
1908        SendToPymol(p,"turn x,%f\nturn y,%f\nturn z,%f\n", p->xAngle, p->yAngle,
1909                p->zAngle);
1910        p->xAngle = p->yAngle = p->zAngle = 0.0f;
1911        p->flags &= ~ROTATE_PENDING;
1912    }
1913}
1914
1915static void
1916SetSphereScale(PymolProxy *p)
1917{
1918    if (p->flags & ATOM_SCALE_PENDING) {
1919        SendToPymol(p, "set sphere_scale,%f,all\n", p->sphereScale);
1920        p->flags &= ~ATOM_SCALE_PENDING;
1921    }
1922}
1923
1924static void
1925SetStickRadius(PymolProxy *p)
1926{
1927    if (p->flags & STICK_RADIUS_PENDING) {
1928        SendToPymol(p, "set stick_radius,%f,all\n", p->stickRadius);
1929        p->flags &= ~STICK_RADIUS_PENDING;
1930    }
1931}
1932
1933static void
1934UpdateSettings(PymolProxy *p)
1935{
1936    /* Handle all the pending setting changes now. */
1937    if (p->flags & VIEWPORT_PENDING) {
1938        SetViewport(p);
1939    }
1940    if (p->flags & ROTATE_PENDING) {
1941        SetRotation(p);
1942    }
1943    if (p->flags & PAN_PENDING) {
1944        SetPan(p);
1945    }
1946    if (p->flags & ZOOM_PENDING) {
1947        SetZoom(p);
1948    }
1949    if (p->flags & ATOM_SCALE_PENDING) {
1950        SetSphereScale(p);
1951    }
1952    if (p->flags & STICK_RADIUS_PENDING) {
1953        SetStickRadius(p);
1954    }
1955}
1956
1957static Image *
1958NewImage(ImageList *listPtr, size_t dataLength)
1959{
1960    Image *imgPtr;
1961    static int id = 0;
1962
1963    imgPtr = malloc(sizeof(Image) + dataLength);
1964    if (imgPtr == NULL) {
1965        ERROR("can't allocate image of %lu bytes",
1966              (unsigned long)(sizeof(Image) + dataLength));
1967        abort();
1968    }
1969    imgPtr->prevPtr = imgPtr->nextPtr = NULL;
1970    imgPtr->bytesLeft = dataLength;
1971    imgPtr->id = id++;
1972#if WRITE_DEBUG
1973    DEBUG("NewImage: allocating image %d of %d bytes", imgPtr->id, dataLength);
1974#endif
1975    if (listPtr->headPtr != NULL) {
1976        listPtr->headPtr->prevPtr = imgPtr;
1977    }
1978    imgPtr->nextPtr = listPtr->headPtr;
1979    if (listPtr->tailPtr == NULL) {
1980        listPtr->tailPtr = imgPtr;
1981    }
1982    listPtr->headPtr = imgPtr;
1983    imgPtr->numWritten = 0;
1984    return imgPtr;
1985}
1986
1987INLINE static void
1988FreeImage(Image *imgPtr)
1989{
1990    assert(imgPtr != NULL);
1991    free(imgPtr);
1992}
1993
1994
1995static void
1996WriteImages(ImageList *listPtr, int fd)
1997{
1998    Image *imgPtr, *prevPtr;
1999
2000    if (listPtr->tailPtr == NULL) {
2001        ERROR("Should not be here: no image available to write");
2002        return;
2003    }
2004#if WRITE_DEBUG
2005        DEBUG("Entering WriteImages");
2006#endif
2007    for (imgPtr = listPtr->tailPtr; imgPtr != NULL; imgPtr = prevPtr) {
2008        ssize_t bytesLeft;
2009
2010        assert(imgPtr->nextPtr == NULL);
2011        prevPtr = imgPtr->prevPtr;
2012#if WRITE_DEBUG
2013        DEBUG("WriteImages: image %d of %d bytes.", imgPtr->id,
2014              imgPtr->bytesLeft);
2015#endif
2016        for (bytesLeft = imgPtr->bytesLeft; bytesLeft > 0; /*empty*/) {
2017            ssize_t numWritten;
2018#if WRITE_DEBUG
2019            DEBUG("image %d: bytesLeft=%d", imgPtr->id, bytesLeft);
2020#endif
2021            numWritten = write(fd, imgPtr->data + imgPtr->numWritten, bytesLeft);
2022#if WRITE_DEBUG
2023            DEBUG("image %d: wrote %d bytes.", imgPtr->id, numWritten);
2024#endif
2025            if (numWritten < 0) {
2026                ERROR("Error writing fd=%d, %s", fd, strerror(errno));
2027#if WRITE_DEBUG
2028                DEBUG("Abnormal exit WriteImages");
2029#endif
2030                return;
2031            }
2032            bytesLeft -= numWritten;
2033            if (bytesLeft > 0) {
2034#if WRITE_DEBUG
2035                DEBUG("image %d, wrote a short buffer, %d bytes left.",
2036                      imgPtr->id, bytesLeft);
2037#endif
2038                /* Wrote a short buffer, means we would block. */
2039                imgPtr->numWritten += numWritten;
2040                imgPtr->bytesLeft = bytesLeft;
2041#if WRITE_DEBUG
2042                DEBUG("Abnormal exit WriteImages");
2043#endif
2044                return;
2045            }
2046            imgPtr->numWritten += numWritten;
2047        }
2048        /* Check if image is on the head.  */
2049        listPtr->tailPtr = prevPtr;
2050        if (prevPtr != NULL) {
2051            prevPtr->nextPtr = NULL;
2052        }
2053        FreeImage(imgPtr);
2054    }
2055    listPtr->headPtr = NULL;
2056#if WRITE_DEBUG
2057    DEBUG("Exit WriteImages");
2058#endif
2059}
2060
2061
2062static void
2063ChildHandler(int sigNum)
2064{
2065    ERROR("pymol (%d) died unexpectedly", stats.pid);
2066    pymolIsAlive = FALSE;
2067    /*DoExit(1);*/
2068}
2069
2070typedef struct {
2071    const char *name;
2072    Tcl_CmdProc *proc;
2073} CmdProc;
2074
2075static CmdProc cmdProcs[] = {
2076    { "cartoon",        CartoonCmd        },       
2077    { "cartoontrace",   CartoonTraceCmd   }, 
2078    { "clientinfo",     ClientInfoCmd     },
2079    { "disable",        DisableCmd        },       
2080    { "enable",         EnableCmd         },       
2081    { "frame",          FrameCmd          },         
2082    { "label",          LabelCmd          },         
2083    { "loadpdb",        LoadPDBCmd        },       
2084    { "orthoscopic",    OrthoscopicCmd    },   
2085    { "pan",            PanCmd            },           
2086    { "png",            PngCmd            },           
2087    { "ppm",            PpmCmd            },           
2088    { "print",          PrintCmd          },         
2089    { "raw",            RawCmd            },           
2090    { "representation", RepresentationCmd },
2091    { "reset",          ResetCmd          },         
2092    { "rock",           RockCmd           },         
2093    { "rotate",         RotateCmd         },       
2094    { "screen",         ScreenCmd         },       
2095    { "spherescale",    SphereScaleCmd    },   
2096    { "stickradius",    StickRadiusCmd    },   
2097    { "transparency",   TransparencyCmd   }, 
2098    { "viewport",       ScreenCmd         },       
2099    { "vmouse",         VMouseCmd         },       
2100    { "zoom",           ZoomCmd           },         
2101    { NULL,             NULL              }
2102};
2103
2104static int
2105InitProxy(PymolProxy *p, char *const *argv)
2106{
2107    int sin[2], sout[2];                /* Pipes to connect to server. */
2108    pid_t child;
2109    struct timeval end;
2110
2111#if DEBUG
2112    DEBUG("Entering InitProxy\n");
2113#endif
2114    /* Create two pipes for communication with the external application. One
2115     * each for the applications's: stdin and stdout.  */
2116
2117    if (pipe(sin) == -1) {
2118        return -1;
2119    }
2120    if (pipe(sout) == -1) {
2121        close(sin[0]);
2122        close(sin[1]);
2123        return -1;
2124    }
2125
2126    /* Fork the new process.  Connect I/O to the new socket.  */
2127    child = fork();
2128    if (child < 0) {
2129        ERROR("can't fork process: %s\n", strerror(errno));
2130        return -3;
2131    }
2132
2133    if (child == 0) {                   /* Child process */
2134        int f;
2135        char tmpname[200];
2136
2137        /*
2138         * Create a new process group, so we can later kill this process and
2139         * all its children without affecting the process that created this
2140         * one.
2141         */
2142        setpgid(child, 0);
2143       
2144        /* Redirect stdin, stdout, and stderr to pipes before execing */
2145
2146        dup2(sin[0],  0);               /* Server standard input */
2147        dup2(sout[1], 1);               /* Server standard output */
2148
2149        /* Redirect child's stderr to a log file. */
2150        sprintf(tmpname, "%s/PYMOL-%d-stderr.XXXXXX", LOGDIR, getpid());
2151        f = mkstemp(tmpname);
2152        if (f < 0) {
2153            ERROR("can't open file `%s' to capture pymol stderr: %s", tmpname,
2154                  strerror(errno));
2155            exit(1);
2156        }
2157        dup2(f, 2);                     /* Redirect stderr to a log file */
2158       
2159        /* Close all other descriptors  */       
2160        for (f = 3; f < FD_SETSIZE; f++) {
2161            close(f);
2162        }
2163        INFO("attempting to start \"%s\"", argv[0]);
2164        execvp(argv[0], argv);
2165        ERROR("can't exec `%s': %s", argv[0], strerror(errno));
2166        exit(-1);
2167    } else {
2168        pymolIsAlive = TRUE;
2169        signal(SIGCHLD, ChildHandler);
2170    }
2171    stats.pid = child;
2172
2173#if DEBUG
2174    DEBUG("Started %s DISPLAY=%s\n", argv[0], getenv("DISPLAY"));
2175#endif
2176    /* close opposite end of pipe, these now belong to the child process  */
2177    close(sin[0]);
2178    close(sout[1]);
2179
2180    memset(p, 0, sizeof(PymolProxy));
2181    p->sin        = sin[1];
2182    p->sout       = sout[0];
2183    p->cin        = fileno(stdout);
2184    p->cout       = fileno(stdin);
2185    p->flags      = CAN_UPDATE;
2186    p->frame      = 1;
2187    p->pid      = child;
2188    InitReadBuffer(&p->client, "client", CLIENT_READ, 1<<16);
2189    InitReadBuffer(&p->server, "server", p->sout, 1<<18);
2190
2191    /* Create safe interpreter and add pymol-specific commands to it. */
2192    {
2193        Tcl_Interp *interp;
2194        CmdProc *cp;
2195
2196        interp = Tcl_CreateInterp();
2197        Tcl_MakeSafe(interp);
2198
2199        for (cp = cmdProcs; cp->name != NULL; cp++) {
2200#if DEBUG
2201            DEBUG("Adding command %s\n", cp->name);
2202#endif
2203            Tcl_CreateCommand(interp, cp->name, cp->proc, p, NULL);
2204        }
2205        p->interp = interp;
2206    }
2207    gettimeofday(&end, NULL);
2208    stats.start = end;
2209    return 1;
2210}
2211
2212static int
2213FreeProxy(PymolProxy *p)
2214{
2215    int result, status;
2216
2217#if DEBUG
2218    DEBUG("Enter FreeProxy");
2219#endif
2220    close(p->cout);
2221    close(p->sout);
2222    close(p->cin);
2223    close(p->sin);
2224
2225    Tcl_DeleteInterp(p->interp);
2226    ServerStats(0);
2227
2228#if DEBUG
2229    DEBUG("Waiting for pymol server to exit");
2230#endif
2231    alarm(5);
2232    if (waitpid(p->pid, &result, 0) < 0) {
2233        ERROR("error waiting on pymol server to exit: %s", strerror(errno));
2234    }
2235#if DEBUG
2236    DEBUG("attempting to signal (SIGTERM) pymol server.");
2237#endif
2238    kill(-p->pid, SIGTERM);             // Kill process group
2239    alarm(5);
2240   
2241#if DEBUG
2242    DEBUG("Waiting for pymol server to exit after SIGTERM");
2243#endif
2244    if (waitpid(p->pid, &result, 0) < 0) {
2245        if (errno != ECHILD) {
2246            ERROR("error waiting on pymol server to exit after SIGTERM: %s",
2247                  strerror(errno));
2248        }
2249    }
2250    status = -1;
2251    while ((status == -1) && (errno == EINTR)) {
2252#if DEBUG
2253        DEBUG("Attempting to signal (SIGKILL) pymol server.");
2254#endif
2255        kill(-p->pid, SIGKILL);         // Kill process group
2256        alarm(10);
2257#if DEBUG
2258        DEBUG("Waiting for pymol server to exit after SIGKILL");
2259#endif
2260        status = waitpid(p->pid, &result, 0);
2261        alarm(0);
2262    }
2263    INFO("pymol server process ended (result=%d)", result);
2264
2265    if (WIFEXITED(result)) {
2266        result = WEXITSTATUS(result);
2267    }
2268    return result;
2269}
2270
2271
2272static void *
2273ClientToServer(void *clientData)
2274{
2275    PymolProxy *p = clientData;
2276    Tcl_DString command;
2277    struct timeval tv, *tvPtr;
2278
2279#if READ_DEBUG
2280    DEBUG("Reader thread started");
2281#endif
2282    Tcl_DStringInit(&command);
2283    while (pymolIsAlive) {
2284        tvPtr = NULL;
2285#if READ_DEBUG
2286        DEBUG("Start I/O set");
2287#endif
2288        while ((pymolIsAlive) && (WaitForNextLine(&p->client, tvPtr))) {
2289            size_t numBytes;
2290            const char *line;
2291            int status;
2292
2293            status = GetLine(&p->client, &numBytes, &line);
2294            if (status != BUFFER_OK) {
2295                ERROR("can't read client stdout (numBytes=%d): %s\n", numBytes,
2296                      strerror(errno));
2297                goto done;
2298            }
2299            Tcl_DStringAppend(&command, line, numBytes);
2300            if (Tcl_CommandComplete(Tcl_DStringValue(&command))) {
2301                int result;
2302                   
2303                /* May execute more than one command. */
2304                result = ExecuteCommand(p->interp, &command);
2305                if (result == TCL_BREAK) {
2306#if READ_DEBUG
2307                    DEBUG("TCL_BREAK found");
2308#endif
2309                    break;              /* This was caused by a "imgflush"
2310                                         * command. Break out of the read
2311                                         * loop and allow a new image to be
2312                                         * rendered. */
2313                }
2314                if (p->flags & FORCE_UPDATE) {
2315#if READ_DEBUG
2316                    DEBUG("FORCE_UPDATE set");
2317#endif
2318                    break;
2319                }
2320            }
2321            tv.tv_sec = 0L;
2322            tv.tv_usec = 0L;            /* On successive reads, we break
2323                                         * out if no data is available. */
2324            tvPtr = &tv;                       
2325        }
2326#if READ_DEBUG
2327        DEBUG("Finish I/O set");
2328#endif
2329        /* Handle all the pending setting changes now. */
2330        UpdateSettings(p);
2331
2332        /* We might want to refresh the image if we're not currently
2333         * transmitting an image back to the client. The image will be
2334         * refreshed after the image has been completely transmitted. */
2335        if (p->flags & UPDATE_PENDING) {
2336#if READ_DEBUG
2337            DEBUG("calling ppm because of update");
2338#endif
2339            Tcl_Eval(p->interp, "ppm");
2340            p->flags &= ~(UPDATE_PENDING|FORCE_UPDATE);
2341        }
2342    }
2343 done:
2344#if READ_DEBUG
2345    DEBUG("Leaving Reader thread");
2346#endif
2347    return NULL;
2348}
2349
2350static void *
2351ServerToClient(void *clientData)
2352{
2353    ReadBuffer *bp = clientData;
2354    ImageList list;
2355
2356#if WRITE_DEBUG
2357    DEBUG("Writer thread started");
2358#endif
2359    list.headPtr = list.tailPtr = NULL;
2360    while (pymolIsAlive) {
2361        while (WaitForNextLine(bp, NULL)) {
2362            Image *imgPtr;
2363            const char *line;
2364            char header[200];
2365            size_t len;
2366            int numBytes;
2367            size_t hdrLength;
2368            int frameNum, rockOffset;
2369            char cacheId[200];
2370
2371            /* Keep reading lines untils we find a "image follows:" line */
2372            if (GetLine(bp, &len, &line) != BUFFER_OK) {
2373#if WRITE_DEBUG
2374                DEBUG("Leaving Writer thread");
2375#endif
2376                return NULL;
2377            }
2378#if WRITE_DEBUG
2379            DEBUG("Writer: line found is %s\n", line);
2380#endif
2381            if (strncmp(line, "image follows: ", 15) != 0) {
2382                continue;
2383            }
2384            if (sscanf(line, "image follows: %d %s %d %d\n", &numBytes, cacheId,
2385                       &frameNum, &rockOffset) != 4) {
2386                ERROR("can't get # bytes from \"%s\"", line);
2387                DEBUG("Leaving Writer thread");
2388                return NULL;
2389            }
2390#if WRITE_DEBUG
2391            DEBUG("found image line \"%.*s\"", numBytes, line);
2392#endif
2393            sprintf(header, "nv>image %d %s %d %d\n", numBytes, cacheId,
2394                    frameNum, rockOffset);
2395            hdrLength = strlen(header);
2396#if WRITE_DEBUG
2397            DEBUG("Queueing image numBytes=%d cacheId=%s, frameNum=%d, rockOffset=%d size=%d\n", numBytes, cacheId, frameNum, rockOffset, numBytes + hdrLength);
2398#endif
2399            imgPtr = NewImage(&list, numBytes + hdrLength);
2400            memcpy(imgPtr->data, header, hdrLength);
2401            if (ReadFollowingData(bp, imgPtr->data + hdrLength,
2402                        (size_t)numBytes) != BUFFER_OK) {
2403                ERROR("can't read %d bytes for \"image follows\" buffer: %s",
2404                      numBytes, strerror(errno));
2405#if WRITE_DEBUG
2406                DEBUG("Leaving Writer thread");
2407#endif
2408                return NULL;
2409            }
2410            stats.numFrames++;
2411            stats.numBytes += numBytes;
2412            {
2413                struct timeval tv;
2414                fd_set writeFds;
2415
2416                tv.tv_sec = tv.tv_usec = 0L;
2417                FD_ZERO(&writeFds);
2418                FD_SET(CLIENT_WRITE, &writeFds);
2419                if (select(CLIENT_WRITE+1, NULL, &writeFds, NULL, &tv) > 0) {
2420                    WriteImages(&list, CLIENT_WRITE);
2421                }
2422            }
2423        }
2424    }
2425#if WRITE_DEBUG
2426    DEBUG("Leaving Writer thread");
2427#endif
2428    return NULL;
2429}
2430
2431int
2432main(int argc, char **argv)
2433{
2434    PymolProxy proxy;
2435    pthread_t thread1, thread2;
2436    char version[200];
2437    ssize_t numWritten;
2438    size_t numBytes;
2439
2440    frecord = NULL;
2441    if (recording) {
2442        char fileName[200];
2443
2444        sprintf(fileName, "/tmp/pymolproxy%d.py", getpid());
2445        frecord = fopen(fileName, "w");
2446    }
2447    sprintf(version, "PymolProxy %s (build %s)\n", PYMOLPROXY_VERSION, SVN_VERSION);
2448    numBytes = strlen(version);
2449    numWritten = write(CLIENT_WRITE, version, numBytes);
2450    if (numWritten < numBytes) {
2451        ERROR("Short write on version string", strerror(errno));
2452    }
2453    INFO("Starting pymolproxy (threaded version)");
2454
2455    InitProxy(&proxy, argv + 1);
2456    if (pthread_create(&thread1, NULL, &ClientToServer, &proxy) < 0) {
2457        ERROR("Can't create reader thread: %s", strerror(errno));
2458    }
2459    if (pthread_create(&thread2, NULL, &ServerToClient, &proxy.server) < 0) {
2460        ERROR("Can't create writer thread: %s", strerror(errno));
2461    }
2462    if (pthread_join(thread1, NULL) < 0) {
2463        ERROR("Can't join reader thread: %s", strerror(errno));
2464    }
2465    return FreeProxy(&proxy);
2466}
Note: See TracBrowser for help on using the repository browser.