t_tkcmd.c 19.4 KB
Newer Older
Miller Puckette's avatar
Miller Puckette committed
1
2
3
4
/* Copyright (c) 1997-1999 Miller Puckette.
* For information on usage and redistribution, and for a DISCLAIMER OF ALL
* WARRANTIES, see the file, "LICENSE.txt," in this distribution.  */

Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
5
6
#include "config.h"

Miller Puckette's avatar
Miller Puckette committed
7
8
9
10
11
12
13
14
15
16
17
#ifndef MSW     /* in unix this only works first; in MSW it only works last. */
#include "tk.h"
#endif

#include "t_tk.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <sys/types.h>

Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
18
#ifdef HAVE_UNISTD_H
Miller Puckette's avatar
Miller Puckette committed
19
#include <unistd.h>
20
21
#else // if isatty exists outside unistd, please add another #ifdef
static int isatty(int fd) {return 0;}
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
22
23
24
#endif

#ifndef MSW
Miller Puckette's avatar
Miller Puckette committed
25
26
27
28
29
30
31
32
33
34
35
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#ifdef HAVE_BSTRING_H
#include <bstring.h>
#endif
#include <sys/time.h>
#include <errno.h>
#include <fcntl.h>
#endif
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
36
37
38
39
40

#ifdef HAVE_IO_H
#include <io.h>
#endif

Miller Puckette's avatar
Miller Puckette committed
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
#ifdef MSW
#include <winsock.h>
#endif

/* These pragmas are only used for MSVC, not MinGW or Cygwin <hans@at.or.at> */
#ifdef _MSC_VER
#pragma warning( disable : 4305 )  /* uncast const double to float */
#pragma warning( disable : 4244 )  /* uncast double to float */
#pragma warning( disable : 4101 )  /* unused local variables */
#endif

#ifdef MSW
#include "tk.h"
#endif

#ifdef __APPLE__
#define STARTGUI
#endif

#ifdef __linux__
#define STARTGUI
#endif

#define FIRSTPORTNUM 5600

void tcl_mess(char *s);
static Tcl_Interp *tk_pdinterp;
static int pd_portno = 0;
69
static int stderr_isatty;
Miller Puckette's avatar
Miller Puckette committed
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


/***************** the socket setup code ********************/

/* If this is reset by pdgui_setsock(), it's the port number Pd will try to
connect to; but if zero, that means we should set it and start Pd ourselves. */


        /* some installations of linux don't know about "localhost" so give
        the loopback address; NT, on the other hand, can't understand the
        hostname "127.0.0.1". */
char hostname[100] =
#ifdef __linux__
    "127.0.0.1";
#else
    "localhost";
#endif

void pdgui_setsock(int port)
{
    pd_portno = port;
}

    /* why is this here??? probably never used (see t_main.c). */
void pdgui_sethost(char *name)
{
    strncpy(hostname, name, 100);
    hostname[99] = 0;
}

static void pdgui_sockerror(char *s)
{
#ifdef MSW
    int err = WSAGetLastError();
#endif
#ifndef MSW
    int err = errno;
#endif

    fprintf(stderr, "%s: %s (%d)\n", s, strerror(err), err);
    tcl_mess("exit\n");
    exit(1);
}

static int sockfd;

/* The "pd_readsocket" command, which polls the socket. */

#define CHUNKSIZE 20000 /* chunks to allocate memory for reading socket */
Ivica Ico Bukvic's avatar
Ivica Ico Bukvic committed
119
#define READSIZE 1000  /* size of read to issue */
Miller Puckette's avatar
Miller Puckette committed
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

static char *pd_tkbuf = 0;      /* buffer for reading */
static int pd_tkbufsize = 0;    /* current buffer size */
static int pd_buftail = 0;      /* number of bytes already in buffer */
static int pd_bufhead = 0;    /* index of first byte to read */

    /* mask argument unused but is here to follow tcl's prototype. */
static void pd_readsocket(ClientData cd, int mask)
{
    fd_set readset, writeset, exceptset;
    struct timeval timout;

    timout.tv_sec = 0;
    timout.tv_usec = 0;
    FD_ZERO(&writeset);
    FD_ZERO(&readset);
    FD_ZERO(&exceptset);
    FD_SET(sockfd, &readset);
    FD_SET(sockfd, &exceptset);
    if (!pd_tkbuf)
    {
        if (!(pd_tkbuf = malloc(CHUNKSIZE)))
        {
            fprintf(stderr, "pd-gui: out of memory\n");
            tcl_mess("exit\n");
        }
        pd_tkbufsize = CHUNKSIZE;
    }
    if (pd_buftail + READSIZE + 1 > pd_tkbufsize)
    {   
        int newsize = pd_tkbufsize + CHUNKSIZE;
        char *newbuf = realloc(pd_tkbuf, newsize);
        if (!newbuf)
        {
            fprintf(stderr, "pd-gui: out of memory\n");
            tcl_mess("exit\n");
        }
        pd_tkbuf = newbuf;
        pd_tkbufsize = newsize;     
    }
    if (select(sockfd+1, &readset, &writeset, &exceptset, &timout) < 0)
        perror("select");
    if (FD_ISSET(sockfd, &exceptset) || FD_ISSET(sockfd, &readset))
    {
        int ret;
        ret = recv(sockfd, pd_tkbuf + pd_buftail, READSIZE, 0);
        if (ret < 0)
            pdgui_sockerror("socket receive error");
        else if (ret == 0)
        {
            /* fprintf(stderr, "read %d\n", SOCKSIZE - pd_buftail); */
            fprintf(stderr, "pd_gui: pd process exited\n");
            tcl_mess("exit\n");
        }
        else
        {
            pd_buftail += ret;
            while (1)
            {
                char lastc = 0, *gotcr = 0, *bp = pd_tkbuf + pd_bufhead,
                    *ep = pd_tkbuf + pd_buftail;
                int brace = 0;
                    /* search for locations that terminate a complete TK
                    command.  These are carriage returns which are not inside
                    any braces.  Braces can be escaped with backslashes (but
                    backslashes themselves can't.) */
                while (bp < ep)
                {
                    char c = *bp;
                    if (c == '}' && brace)
                        brace--;
                    else if (c == '{')
                        brace++;
                    else if (!brace && c == '\n' && lastc != '\\')
                    {
                        gotcr = bp;
                        break;
                    }
                    lastc = c;
                    bp++;
                }
                    /* if gotcr is set there is at least one complete TK
                    command in the buffer, and gotcr terminates the first one.
                    Because sending the command to tcl may cause this code to
                    be reentered, we first copy the command and take it out of
                    the buffer, then execute the command.
                    Execute it and slide any
                    extra bytes to beginning of the buffer. */
                if (gotcr)
                {
                    int bytesincmd = (gotcr - (pd_tkbuf+pd_bufhead)) + 1;
                    char smallcmdbuf[1000], *realcmdbuf;
                    if (gotcr - (pd_tkbuf+pd_bufhead) < 998)
                        realcmdbuf = smallcmdbuf;
                    else realcmdbuf = malloc(bytesincmd+1);
                    if (realcmdbuf)
                    {
                        strncpy(realcmdbuf, pd_tkbuf+pd_bufhead, bytesincmd);
                        realcmdbuf[bytesincmd] = 0;
                    }
                    pd_bufhead += bytesincmd;
                    if (realcmdbuf)
                    {
                        tcl_mess(realcmdbuf);
                        if (realcmdbuf != smallcmdbuf)
                            free(realcmdbuf);
                    }
                    if (pd_buftail < pd_bufhead)
                        fprintf(stderr, "tkcmd bug\n");
                }
                else break;
            }
            if (pd_bufhead)
            {
                if (pd_buftail > pd_bufhead)
                    memmove(pd_tkbuf, pd_tkbuf + pd_bufhead,
                        pd_buftail-pd_bufhead);
                pd_buftail  -= pd_bufhead;
                pd_bufhead = 0;
            }
        }
    }
}

#ifdef MSW
    /* if we're in Gatesland, we add a tcl command to poll the
    socket for data.  */
static int pd_pollsocketCmd(ClientData cd, Tcl_Interp *interp,
    int argc, char **argv)
{
    pd_readsocket(cd, 0);
    return (TCL_OK);
}
#endif

static void pd_sockerror(char *s)
{
#ifdef MSW
    int err = WSAGetLastError();
    if (err == 10054) return;
    else if (err == 10044)
    {
        fprintf(stderr,
            "Warning: you might not have TCP/IP \"networking\" turned on\n");
        fprintf(stderr, "which is needed for Pd to talk to its GUI layer.\n");
    }
#else
    int err = errno;
#endif
    fprintf(stderr, "%s: %s (%d)\n", s, strerror(err), err);
}

static void pdgui_connecttosocket(void)
{
    struct sockaddr_in server;
    struct hostent *hp;
#ifndef MSW
    int retry = 10;
#else
    int retry = 1;
#endif
#ifdef MSW
    short version = MAKEWORD(2, 0);
    WSADATA nobby;

    if (WSAStartup(version, &nobby)) pdgui_sockerror("setup");
#endif

    /* create a socket */
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) pdgui_sockerror("socket");

    /* connect socket using hostname provided in command line */
    server.sin_family = AF_INET;

    hp = gethostbyname(hostname);

    if (hp == 0)
    {
        fprintf(stderr,
            "localhost not found (inet protocol not installed?)\n");
        exit(1);
    }
    memcpy((char *)&server.sin_addr, (char *)hp->h_addr, hp->h_length);

    /* assign client port number */
    server.sin_port = htons((unsigned short)pd_portno);

        /* try to connect */
    while (1)
    {
        if (connect(sockfd, (struct sockaddr *) &server, sizeof (server)) >= 0)
            goto gotit;
        retry--;
        if (retry <= 0)
            break;
          /* In unix there's a race condition; the child won't be
          able to connect before the parent (pd) has shed its
          setuid-ness.  In case this is the problem, sleep and
          retry. */
        else
        {
#ifndef MSW
            fd_set readset, writeset, exceptset;
            struct timeval timout;

            timout.tv_sec = 0;
            timout.tv_usec = 100000;
            FD_ZERO(&writeset);
            FD_ZERO(&readset);
            FD_ZERO(&exceptset);
            fprintf(stderr, "retrying connect...\n");
            if (select(1, &readset, &writeset, &exceptset, &timout) < 0)
                perror("select");
#endif /* !MSW */
        }
    }
    pdgui_sockerror("connecting stream socket");
gotit: ;
#ifndef MSW
        /* normally we ask TK to call us back; but in MSW we have to poll. */
    Tk_CreateFileHandler(sockfd, TK_READABLE | TK_EXCEPTION,
        pd_readsocket, 0);
#endif /* !MSW */
}

#ifdef STARTGUI

Miller Puckette's avatar
Miller Puckette committed
348
/* #define DEBUGCONNECT */
Miller Puckette's avatar
Miller Puckette committed
349
350
351
352
353
354
355
356
357
358
359
360

#ifdef DEBUGCONNECT
static FILE *debugfd;
#endif


static void pd_startfromgui( void)
{
    pid_t childpid;
    char cmdbuf[1000], pdbuf[1000], *lastchar;
    const char *arg0;
    struct sockaddr_in server;
Mathieu L Bouchard's avatar
Mathieu L Bouchard committed
361
    int len = sizeof(server);
Miller Puckette's avatar
Miller Puckette committed
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
    int ntry = 0, portno = FIRSTPORTNUM;
    int xsock = -1;
#ifdef MSW
    short version = MAKEWORD(2, 0);
    WSADATA nobby;
    char scriptbuf[1000], wishbuf[1000], portbuf[80];
    int spawnret;
    char intarg;
#else
    int intarg;
#endif

    arg0 = Tcl_GetVar(tk_pdinterp, "argv0", 0);
    if (!arg0)
    {
        fprintf(stderr, "Pd-gui: can't get arg 0\n");
        return;
    }
    lastchar = strrchr(arg0, '/');
    if (lastchar)
        snprintf(pdbuf, lastchar - arg0 + 1, "%s", arg0);
    else strcpy(pdbuf, ".");
384
    strcat(pdbuf, "/../bin/pd-l2ork");
Miller Puckette's avatar
Miller Puckette committed
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
#ifdef DEBUGCONNECT     
    fprintf(stderr, "pdbuf is %s\n", pdbuf);
#endif

#ifdef MSW
    if (WSAStartup(version, &nobby))
        pd_sockerror("WSAstartup");
#endif

    /* create a socket */
    xsock = socket(AF_INET, SOCK_STREAM, 0);
    if (xsock < 0) pd_sockerror("socket");
    intarg = 1;
    if (setsockopt(xsock, IPPROTO_TCP, TCP_NODELAY,
        &intarg, sizeof(intarg)) < 0)
            fprintf(stderr, "setsockopt (TCP_NODELAY) failed\n");

    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;

    /* assign server port number */
    server.sin_port =  htons((unsigned short)portno);

        /* name the socket */
    while (bind(xsock, (struct sockaddr *)&server, sizeof(server)) < 0)
    {
#ifdef MSW
        int err = WSAGetLastError();
#else
        int err = errno;
#endif
        if ((ntry++ > 20) || (err != EADDRINUSE))
        {
            perror("bind");
            fprintf(stderr,
                "couldn't open GUI-to-pd network connection\n");
            return;
        }
        portno++;
        server.sin_port = htons((unsigned short)(portno));
    }

#ifdef DEBUGCONNECT     
    fprintf(debugfd, "port %d\n", portno);
        fflush(debugfd);
#endif

Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
432
#ifdef HAVE_UNISTD_H
433
    sprintf(cmdbuf, "\"%s\" -guiport %d\n", pdbuf, portno);
Miller Puckette's avatar
Miller Puckette committed
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
    childpid = fork();
    if (childpid < 0)
    {
        if (errno) perror("sys_startgui");
        else fprintf(stderr, "sys_startgui failed\n");
        return;
    }
    else if (!childpid)                 /* we're the child */
    {
#ifdef DEBUGCONNECT     
        fprintf(debugfd, "%s", cmdbuf);
        fflush(debugfd);
#endif
        execl("/bin/sh", "sh", "-c", cmdbuf, (char*)0);
        perror("pd: exec");
        _exit(1);
    }
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
451
#endif /* HAVE_UNISTD_H */
Miller Puckette's avatar
Miller Puckette committed
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

#ifdef MSW       

#error not yet used.... sys_bashfilename() not filled in here

    strcpy(cmdbuf, pdcmd);
    strcat(cmdbuf, "/pd.exe");
    sys_bashfilename(scriptbuf, scriptbuf);

    sprintf(portbuf, "%d", portno);

    spawnret = _spawnl(P_NOWAIT, cmdbuf, "pd.exe", "-port", portbuf, 0);
    if (spawnret < 0)
    {
        perror("spawnl");
        fprintf(stderr, "%s: couldn't start\n", cmdbuf);
        return;
    }

#endif /* MSW */

#ifdef DEBUGCONNECT
        fprintf(stderr, "Waiting for connection request... \n");
#endif
    if (listen(xsock, 5) < 0) pd_sockerror("listen");
    sockfd = accept(xsock, (struct sockaddr *) &server, (unsigned int *)&len);
    if (sockfd < 0) pd_sockerror("accept");
#ifdef DEBUGCONNECT
        fprintf(stderr, "... connected\n");
#endif

#ifndef MSW
        /* normally we ask TK to call us back; but in MSW we have to poll. */
    Tk_CreateFileHandler(sockfd, TK_READABLE | TK_EXCEPTION,
        pd_readsocket, 0);
#endif /* !MSW */
}

#endif /* STARTGUI */

static void pdgui_setupsocket(void)
{
#ifdef MSW
        pdgui_connecttosocket();
#else
    if (pd_portno)
        pdgui_connecttosocket();
    else pd_startfromgui() ;
#endif
}

/**************************** commands ************************/
static char *pdgui_path;

/* The "pd" command, which cats its args together and throws the result
* at the Pd interpreter.
*/
509
#define MAXWRITE 8192
Miller Puckette's avatar
Miller Puckette committed
510
511
512

static int pdCmd(ClientData cd, Tcl_Interp *interp, int argc,  char **argv)
{
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
513
514
    Tcl_DString dstring; /* used to convert the Tcl string to the OS encoding */
    char *dstring_char;
515
    /*if (argc == 2)
Miller Puckette's avatar
Miller Puckette committed
516
517
    {
        int n = strlen(argv[1]);
518
        // NULL as first arg means use the current system encoding
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
519
520
        dstring_char = Tcl_UtfToExternalDString(NULL, argv[1], -1, &dstring);
        if (send(sockfd, dstring_char, n, 0) < n)
Miller Puckette's avatar
Miller Puckette committed
521
522
523
524
525
526
        {
            perror("stdout");
            tcl_mess("exit\n");
        }
    }
    else
527
    {*/
Miller Puckette's avatar
Miller Puckette committed
528
529
530
531
532
533
534
        int i;
        char buf[MAXWRITE];
        buf[0] = 0;
        for (i = 1; i < argc; i++)
        {
            if (strlen(argv[i]) + strlen(buf) + 2 > MAXWRITE)
            {
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
535
536
                Tcl_SetObjResult(interp, 
                                 Tcl_NewStringObj("pd: arg list too long", -1));
Miller Puckette's avatar
Miller Puckette committed
537
538
                return (TCL_ERROR);     
            }
539
            strcat(buf, " ");
Miller Puckette's avatar
Miller Puckette committed
540
541
            strcat(buf, argv[i]);
        }
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
542
543
544
        /* NULL as first arg means use the current system encoding */
        dstring_char = Tcl_UtfToExternalDString(NULL, buf, -1, &dstring);
        if (send(sockfd, dstring_char, strlen(dstring_char), 0) < 0)
Miller Puckette's avatar
Miller Puckette committed
545
546
547
548
        {
            perror("stdout");
            tcl_mess("exit\n");
        }
549
550
    //}
    //fprintf(stderr, "dstring_char = <%s>\n", dstring_char);
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
551
    Tcl_DStringFree(&dstring);
Miller Puckette's avatar
Miller Puckette committed
552
553
554
555
556
    return (TCL_OK);
}

/***********  "c" level access to tk functions. ******************/

557
558
#define DEBUG_TCL

Miller Puckette's avatar
Miller Puckette committed
559
560
561
void tcl_mess(char *s)
{
    int result;
Ivica Bukvic's avatar
Ivica Bukvic committed
562

563
#ifdef DEBUG_TCL
564
565
    char *catch_s = s;
    //char catch_s[strlen(s)+666]; sprintf(catch_s, "set errorInfo \"\"; if {[catch {%s}]} {puts \"\\033\\[0;1;33m$errorInfo\\033\\[0m\"}", s);
566
#else
Mathieu L Bouchard's avatar
Mathieu L Bouchard committed
567
    char catch_s[strlen(s)+11];
568
    sprintf(catch_s, "catch { %s }", s);
569
#endif
Ivica Bukvic's avatar
Ivica Bukvic committed
570

571
    Tcl_Obj *messageObjPtr = Tcl_NewStringObj(catch_s,-1);
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
572
573
574
    Tcl_IncrRefCount(messageObjPtr);
    result = Tcl_EvalObjEx(tk_pdinterp, messageObjPtr, TCL_EVAL_GLOBAL);
    Tcl_DecrRefCount(messageObjPtr);
Miller Puckette's avatar
Miller Puckette committed
575
576
    if (result != TCL_OK)
    {
577
578
579
580
581
582
583
        if (tk_pdinterp) {
            const char *t = Tcl_GetStringResult(tk_pdinterp);
            if (stderr_isatty)
                printf("in sys_gui \e[0;1;33m%s\e[31m%s\e[0m\n", s, t);
            else
                printf("in sys_gui %s%s\n", s, t);
        } else printf("no error\n");
Miller Puckette's avatar
Miller Puckette committed
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
    }
}

    /* in linux, we load the tk code from here (in MSW and MACOS, this
    is done by passing the name of the file as a startup argument to
    the wish shell.) */
#if !defined(MSW) && !defined(__APPLE__)
void pdgui_doevalfile(Tcl_Interp *interp, char *s)
{
    char buf[GUISTRING];
    sprintf(buf, "set pd_guidir \"%s\"\n", pdgui_path);
    tcl_mess(buf);
    strcpy(buf, pdgui_path);
    strcat(buf, "/bin/");
    strcat(buf, s);
    if (Tcl_EvalFile(interp, buf) != TCL_OK)
    {
        char buf2[1000];
602
603
        const char *trace = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
        printf("error in file %s: %s\n", buf, trace);
Miller Puckette's avatar
Miller Puckette committed
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
        sprintf(buf2, "puts [concat tcl: %s: can't open script]\n",
            buf);
        tcl_mess(buf2);
    }
}

void pdgui_evalfile(char *s)
{
    pdgui_doevalfile(tk_pdinterp, s);
}
#endif

void pdgui_startup(Tcl_Interp *interp)
{
        /* save pointer to the main interpreter */
    tk_pdinterp = interp;

        /* add our own TK commands */
    Tcl_CreateCommand(interp, "pd",  (Tcl_CmdProc*)pdCmd, (ClientData)NULL, 
623
        (Tcl_CmdDeleteProc *)NULL);
624
625
    //Tcl_CreateCommand(interp, "pdsend",  (Tcl_CmdProc*)pdCmd, (ClientData)NULL, 
    //    (Tcl_CmdDeleteProc *)NULL); 
Miller Puckette's avatar
Miller Puckette committed
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
#ifdef MSW
    Tcl_CreateCommand(interp, "pd_pollsocket",(Tcl_CmdProc*)  pd_pollsocketCmd,
        (ClientData)NULL, (Tcl_CmdDeleteProc *)NULL);
#endif
    pdgui_setupsocket();
        /* read in the startup file */
#if !defined(MSW) && !defined(__APPLE__)
    pdgui_evalfile("pd.tk");
#endif
}

#ifndef MSW
void pdgui_setname(char *s)
{
    char *t;
    char *str;
    int n;
    if (t = strrchr(s, '/')) str = s, n = (t-s) + 1;
    else str = "./", n = 2;
    if (n > GUISTRING-100) n = GUISTRING-100;
    pdgui_path = malloc(n+9);

    strncpy(pdgui_path, str, n);
    while (strlen(pdgui_path) > 0 && pdgui_path[strlen(pdgui_path)-1] == '/')
        pdgui_path[strlen(pdgui_path)-1] = 0;
    if (t = strrchr(pdgui_path, '/'))
        *t = 0;
}
#endif

    /* this is called when an off-the-shelf "wish" has to "load" this module
    at runtime.  In Linux, this module is linked in and Pdtcl_Init() is not
    called; instead, the code in t_main.c calls pdgui_setsock() and
    pdgui_startup(). */ 

int Pdtcl_Init(Tcl_Interp *interp)
{
663
    stderr_isatty = isatty(2);
Miller Puckette's avatar
Miller Puckette committed
664
    const char *argv = Tcl_GetVar(interp, "argv", 0);
665
666
667
    int portno = 0, i;
    if (argv)
    {
Miller Puckette's avatar
Miller Puckette committed
668
669
670
671
672
            /* search for arg of form "-guiport %d"; if so we're the
            child. For some reason, the second version is too stringent
            a test on MSW so the first, incorrect one, is conditionally
            used. */
#ifdef MSW
673
        for (i = 0; i < (int)strlen(argv) - 1; i++)
674
675
676
677
678
            if (argv[i] >= '0' && argv[i] <= '9')
        {
            portno = atoi(argv+i);
            break;
        }
Miller Puckette's avatar
Miller Puckette committed
679
680
681
682
683
684
685
686
687
#else
        for (i = 0; i < (int)strlen(argv) - 3; i++)
            if (argv[i] == ' ' &&
                argv[i+1] >= '0' && argv[i+1] <= '9')
        {
            portno = atoi(argv+i+1);
            break;
        }
#endif
688
689
    }
    if (portno)
Miller Puckette's avatar
Miller Puckette committed
690
691
        pdgui_setsock(portno);
#ifdef DEBUGCONNECT
Miller Puckette's avatar
Miller Puckette committed
692
    debugfd = fopen("/tmp/bratwurst", "w");
Miller Puckette's avatar
Miller Puckette committed
693
694
695
696
697
698
699
700
701
    fprintf(debugfd, "turning stderr back on\n");
    fflush(debugfd);
    dup2(fileno(debugfd), 2);
    fprintf(stderr, "duped to stderr?\n");
    fprintf(stderr, "portno %d\n", pd_portno);
    fprintf(stderr, "argv %s\n", argv);
#endif
    tk_pdinterp = interp;
    pdgui_startup(interp);
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
702
    Tcl_SetObjResult (interp, Tcl_NewStringObj ("loaded pdtcl_init", -1));
Miller Puckette's avatar
Miller Puckette committed
703
704
705
706
707
708
709
710
711
712
713

    return (TCL_OK);
}

#if 0
int Pdtcl_SafeInit(Tcl_Interp *interp) {
    fprintf(stderr, "Pdtcl_Safeinit 51\n");
        return (TCL_OK);
}
#endif