s_inter.c 50.9 KB
Newer Older
Miller Puckette's avatar
Miller Puckette committed
1 2 3 4 5 6 7
/* 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.  */

/* Pd side of the Pd/Pd-gui interface.  Also, some system interface routines
that didn't really belong anywhere. */

Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
8 9
#include "config.h"

Miller Puckette's avatar
Miller Puckette committed
10 11 12 13
#include "m_pd.h"
#include "s_stuff.h"
#include "m_imp.h"
#include "g_canvas.h"   /* for GUI queueing stuff */
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
14

Jonathan Wilkes's avatar
Jonathan Wilkes committed
15 16 17 18 19 20 21 22 23 24 25
/* Use this if you want to point the guidir at a local copy of the
 * repo while developing. Then recompile and copy the pd-l2ork binary
 * to the system path. After that you can make changes to the gui code
 * in purr-data/pd/nw and test them without having to recompile the
 * pd-l2ork binary.
 * If you do this, make sure you have run tar_em_up.sh first to fetch and
 * extract the nw binary to purr-data/pd/nw/nw
 */

#define GUIDIR "" /* "/home/user/purr-data/pd/nw" */

Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
26
#ifdef HAVE_UNISTD_H
Miller Puckette's avatar
Miller Puckette committed
27
#include <unistd.h>
28 29
#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
30 31 32
#endif

#ifndef _WIN32
Miller Puckette's avatar
Miller Puckette committed
33 34 35 36 37 38 39 40 41
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/mman.h>
#include <sys/resource.h>
#endif
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
42

Miller Puckette's avatar
Miller Puckette committed
43 44 45
#ifdef HAVE_BSTRING_H
#include <bstring.h>
#endif
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
46 47

#ifdef HAVE_IO_H
Miller Puckette's avatar
Miller Puckette committed
48
#include <io.h>
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
49 50 51
#endif 

#ifdef _WIN32
Miller Puckette's avatar
Miller Puckette committed
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
#include <fcntl.h>
#include <process.h>
#include <winsock.h>
#include <windows.h>
# ifdef _MSC_VER
typedef int pid_t;
# endif
typedef int socklen_t;
#define EADDRINUSE WSAEADDRINUSE
#endif

#include <stdarg.h>
#include <signal.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>

#ifdef __APPLE__
#include <sys/types.h>
#include <sys/stat.h>
#include <pthread.h>
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
74
#include <glob.h>
Miller Puckette's avatar
Miller Puckette committed
75 76 77 78 79 80 81 82 83 84 85 86
#else
#include <stdlib.h>
#endif

#define DEBUG_MESSUP 1      /* messages up from pd to pd-gui */
#define DEBUG_MESSDOWN 2    /* messages down from pd-gui to pd */

#ifndef PDBINDIR
#define PDBINDIR "bin/"
#endif

#ifndef WISHAPP
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
87
#define WISHAPP "wish85.exe"
Miller Puckette's avatar
Miller Puckette committed
88 89 90 91 92 93 94 95
#endif

#ifdef __linux__
#define LOCALHOST "127.0.0.1"
#else
#define LOCALHOST "localhost"
#endif

96 97
#define X_SPECIFIER "x%.6lx"

98 99 100 101 102 103
#if PD_FLOATSIZE == 32
#define FLOAT_SPECIFIER "%.6g"
#elif PD_FLOATSIZE == 64
#define FLOAT_SPECIFIER "%.14g"
#endif

104 105
static int stderr_isatty;

106 107 108
/* I don't see any other systems where this header (and backtrace) are
   available. */
#ifdef __linux__
109
#include <execinfo.h>
110
#endif
111

Miller Puckette's avatar
Miller Puckette committed
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
typedef struct _fdpoll
{
    int fdp_fd;
    t_fdpollfn fdp_fn;
    void *fdp_ptr;
} t_fdpoll;

#define INBUFSIZE 4096

struct _socketreceiver
{
    char *sr_inbuf;
    int sr_inhead;
    int sr_intail;
    void *sr_owner;
    int sr_udp;
    t_socketnotifier sr_notifier;
    t_socketreceivefn sr_socketreceivefn;
};

extern char *pd_version;
extern int sys_guisetportnumber;

static int sys_nfdpoll;
static t_fdpoll *sys_fdpoll;
static int sys_maxfd;
static int sys_guisock;

static t_binbuf *inbinbuf;
static t_socketreceiver *sys_socketreceiver;
extern int sys_addhist(int phase);

/* ----------- functions for timing, signals, priorities, etc  --------- */

#ifdef MSW
static LARGE_INTEGER nt_inittime;
static double nt_freq = 0;

static void sys_initntclock(void)
{
    LARGE_INTEGER f1;
    LARGE_INTEGER now;
    QueryPerformanceCounter(&now);
    if (!QueryPerformanceFrequency(&f1))
    {
          fprintf(stderr, "pd: QueryPerformanceFrequency failed\n");
          f1.QuadPart = 1;
    }
    nt_freq = f1.QuadPart;
    nt_inittime = now;
}

#if 0
    /* this is a version you can call if you did the QueryPerformanceCounter
    call yourself.  Necessary for time tagging incoming MIDI at interrupt
    level, for instance; but we're not doing that just now. */

double nt_tixtotime(LARGE_INTEGER *dumbass)
{
    if (nt_freq == 0) sys_initntclock();
    return (((double)(dumbass->QuadPart - nt_inittime.QuadPart)) / nt_freq);
}
#endif
#endif /* MSW */

    /* get "real time" in seconds; take the
    first time we get called as a reference time of zero. */
double sys_getrealtime(void)    
{
#ifndef MSW
    static struct timeval then;
    struct timeval now;
    gettimeofday(&now, 0);
    if (then.tv_sec == 0 && then.tv_usec == 0) then = now;
    return ((now.tv_sec - then.tv_sec) +
        (1./1000000.) * (now.tv_usec - then.tv_usec));
#else
    LARGE_INTEGER now;
    QueryPerformanceCounter(&now);
    if (nt_freq == 0) sys_initntclock();
    return (((double)(now.QuadPart - nt_inittime.QuadPart)) / nt_freq);
#endif
}

extern int sys_nosleep;

static int sys_domicrosleep(int microsec, int pollem)
{
    struct timeval timout;
    int i, didsomething = 0;
    t_fdpoll *fp;
    timout.tv_sec = 0;
    timout.tv_usec = (sys_nosleep ? 0 : microsec);
    if (pollem)
    {
        fd_set readset, writeset, exceptset;
        FD_ZERO(&writeset);
        FD_ZERO(&readset);
        FD_ZERO(&exceptset);
        for (fp = sys_fdpoll, i = sys_nfdpoll; i--; fp++)
            FD_SET(fp->fdp_fd, &readset);
#ifdef MSW
        if (sys_maxfd == 0)
                Sleep(microsec/1000);
        else
#endif
        select(sys_maxfd+1, &readset, &writeset, &exceptset, &timout);
        for (i = 0; i < sys_nfdpoll; i++)
            if (FD_ISSET(sys_fdpoll[i].fdp_fd, &readset))
        {
#ifdef THREAD_LOCKING
            sys_lock();
#endif
            (*sys_fdpoll[i].fdp_fn)(sys_fdpoll[i].fdp_ptr, sys_fdpoll[i].fdp_fd);
#ifdef THREAD_LOCKING
            sys_unlock();
#endif
            didsomething = 1;
        }
        return (didsomething);
    }
    else
    {
#ifdef MSW
        if (sys_maxfd == 0)
              Sleep(microsec/1000);
        else
#endif
        select(0, 0, 0, 0, &timout);
        return (0);
    }
}

void sys_microsleep(int microsec)
{
    sys_domicrosleep(microsec, 1);
}

Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
250
#ifdef HAVE_UNISTD_H
Miller Puckette's avatar
Miller Puckette committed
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
typedef void (*sighandler_t)(int);

static void sys_signal(int signo, sighandler_t sigfun)
{
    struct sigaction action;
    action.sa_flags = 0;
    action.sa_handler = sigfun;
    memset(&action.sa_mask, 0, sizeof(action.sa_mask));
#if 0  /* GG says: don't use that */
    action.sa_restorer = 0;
#endif
    if (sigaction(signo, &action, 0) < 0)
        perror("sigaction");
}

static void sys_exithandler(int n)
{
    static int trouble = 0;
    if (!trouble)
    {
        trouble = 1;
        fprintf(stderr, "Pd: signal %d\n", n);
        sys_bail(1);
    }
    else _exit(1);
}

static void sys_alarmhandler(int n)
{
    fprintf(stderr, "Pd: system call timed out\n");
}

static void sys_huphandler(int n)
{
    struct timeval timout;
    timout.tv_sec = 0;
    timout.tv_usec = 30000;
    select(1, 0, 0, 0, &timout);
}

void sys_setalarm(int microsec)
{
    struct itimerval gonzo;
Miller Puckette's avatar
Miller Puckette committed
294 295
    int sec = (int)(microsec/1000000);
    microsec %= 1000000;
Miller Puckette's avatar
Miller Puckette committed
296
#if 0
Miller Puckette's avatar
Miller Puckette committed
297
    fprintf(stderr, "timer %d:%d\n", sec, microsec);
Miller Puckette's avatar
Miller Puckette committed
298 299 300
#endif
    gonzo.it_interval.tv_sec = 0;
    gonzo.it_interval.tv_usec = 0;
Miller Puckette's avatar
Miller Puckette committed
301
    gonzo.it_value.tv_sec = sec;
Miller Puckette's avatar
Miller Puckette committed
302 303 304 305 306 307 308 309 310
    gonzo.it_value.tv_usec = microsec;
    if (microsec)
        sys_signal(SIGALRM, sys_alarmhandler);
    else sys_signal(SIGALRM, SIG_IGN);
    setitimer(ITIMER_REAL, &gonzo, 0);
}

#endif

311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
void sys_setsignalhandlers(void)
{
#if !defined(_WIN32) && !defined(__CYGWIN__)
    signal(SIGHUP, sys_huphandler);
    signal(SIGINT, sys_exithandler);
    signal(SIGQUIT, sys_exithandler);
    signal(SIGILL, sys_exithandler);
# ifdef SIGIOT
    signal(SIGIOT, sys_exithandler);
# endif
    signal(SIGFPE, SIG_IGN);
    /* signal(SIGILL, sys_exithandler);
    signal(SIGBUS, sys_exithandler);
    signal(SIGSEGV, sys_exithandler); */
    signal(SIGPIPE, SIG_IGN);
    signal(SIGALRM, SIG_IGN);
#if 0  /* GG says: don't use that */
    signal(SIGSTKFLT, sys_exithandler);
#endif
#endif /* NOT _WIN32 && NOT __CYGWIN__ */
}

#if defined(__linux__) || defined(__FreeBSD_kernel__) || defined(__GNU__)

Miller Puckette's avatar
Miller Puckette committed
335 336 337 338 339

#if defined(_POSIX_PRIORITY_SCHEDULING) || defined(_POSIX_MEMLOCK)
#include <sched.h>
#endif

340 341 342 343
#define MODE_NRT 0
#define MODE_RT 1
#define MODE_WATCHDOG 2

Miller Puckette's avatar
Miller Puckette committed
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
void sys_set_priority(int higher) 
{
#ifdef _POSIX_PRIORITY_SCHEDULING
    struct sched_param par;
    int p1 ,p2, p3;
    p1 = sched_get_priority_min(SCHED_FIFO);
    p2 = sched_get_priority_max(SCHED_FIFO);
#ifdef USEAPI_JACK    
    p3 = (higher ? p1 + 7 : p1 + 5);
#else
    p3 = (higher ? p2 - 1 : p2 - 3);
#endif
    par.sched_priority = p3;
    if (sched_setscheduler(0,SCHED_FIFO,&par) != -1)
       fprintf(stderr, "priority %d scheduling enabled.\n", p3);
#endif

#ifdef REALLY_POSIX_MEMLOCK /* this doesn't work on Fedora 4, for example. */
#ifdef _POSIX_MEMLOCK
    /* tb: force memlock to physical memory { */
    {
        struct rlimit mlock_limit;
        mlock_limit.rlim_cur=0;
        mlock_limit.rlim_max=0;
        setrlimit(RLIMIT_MEMLOCK,&mlock_limit);
    }
    /* } tb */
    if (mlockall(MCL_FUTURE) != -1) 
        fprintf(stderr, "memory locking enabled.\n");
#endif
#endif
}

#endif /* __linux__ */

#ifdef IRIX             /* hack by <olaf.matthes@gmx.de> at 2003/09/21 */

#if defined(_POSIX_PRIORITY_SCHEDULING) || defined(_POSIX_MEMLOCK)
#include <sched.h>
#endif

void sys_set_priority(int higher)
{
#ifdef _POSIX_PRIORITY_SCHEDULING
    struct sched_param par;
        /* Bearing the table found in 'man realtime' in mind, I found it a */
        /* good idea to use 192 as the priority setting for Pd. Any thoughts? */
    if (higher)
                par.sched_priority = 250;       /* priority for watchdog */
    else
                par.sched_priority = 192;       /* priority for pd (DSP) */

    if (sched_setscheduler(0, SCHED_FIFO, &par) != -1)
        fprintf(stderr, "priority %d scheduling enabled.\n", par.sched_priority);
#endif

#ifdef _POSIX_MEMLOCK
    if (mlockall(MCL_FUTURE) != -1) 
        fprintf(stderr, "memory locking enabled.\n");
#endif
}
/* end of hack */
#endif /* IRIX */

/* ------------------ receiving incoming messages over sockets ------------- */

void sys_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);
}

void sys_addpollfn(int fd, t_fdpollfn fn, void *ptr)
{
    int nfd = sys_nfdpoll;
    int size = nfd * sizeof(t_fdpoll);
    t_fdpoll *fp;
    sys_fdpoll = (t_fdpoll *)t_resizebytes(sys_fdpoll, size,
        size + sizeof(t_fdpoll));
    fp = sys_fdpoll + nfd;
    fp->fdp_fd = fd;
    fp->fdp_fn = fn;
    fp->fdp_ptr = ptr;
    sys_nfdpoll = nfd + 1;
    if (fd >= sys_maxfd) sys_maxfd = fd + 1;
}

void sys_rmpollfn(int fd)
{
    int nfd = sys_nfdpoll;
    int i, size = nfd * sizeof(t_fdpoll);
    t_fdpoll *fp;
    for (i = nfd, fp = sys_fdpoll; i--; fp++)
    {
        if (fp->fdp_fd == fd)
        {
            while (i--)
            {
                fp[0] = fp[1];
                fp++;
            }
            sys_fdpoll = (t_fdpoll *)t_resizebytes(sys_fdpoll, size,
                size - sizeof(t_fdpoll));
            sys_nfdpoll = nfd - 1;
            return;
        }
    }
    post("warning: %d removed from poll list but not found", fd);
}

t_socketreceiver *socketreceiver_new(void *owner, t_socketnotifier notifier,
    t_socketreceivefn socketreceivefn, int udp)
{
    t_socketreceiver *x = (t_socketreceiver *)getbytes(sizeof(*x));
    x->sr_inhead = x->sr_intail = 0;
    x->sr_owner = owner;
    x->sr_notifier = notifier;
    x->sr_socketreceivefn = socketreceivefn;
    x->sr_udp = udp;
    if (!(x->sr_inbuf = malloc(INBUFSIZE))) bug("t_socketreceiver");;
    return (x);
}

void socketreceiver_free(t_socketreceiver *x)
{
    free(x->sr_inbuf);
    freebytes(x, sizeof(*x));
}

    /* this is in a separately called subroutine so that the buffer isn't
    sitting on the stack while the messages are getting passed. */
static int socketreceiver_doread(t_socketreceiver *x)
{
    char messbuf[INBUFSIZE], *bp = messbuf;
489
    int indx, first = 1;
Miller Puckette's avatar
Miller Puckette committed
490 491 492
    int inhead = x->sr_inhead;
    int intail = x->sr_intail;
    char *inbuf = x->sr_inbuf;
493 494
    for (indx = intail; first || (indx != inhead);
        first = 0, (indx = (indx+1)&(INBUFSIZE-1)))
Miller Puckette's avatar
Miller Puckette committed
495 496 497 498 499 500 501 502 503
    {
            /* if we hit a semi that isn't preceeded by a \, it's a message
            boundary.  LATER we should deal with the possibility that the
            preceeding \ might itself be escaped! */
        char c = *bp++ = inbuf[indx];
        if (c == ';' && (!indx || inbuf[indx-1] != '\\'))
        {
            intail = (indx+1)&(INBUFSIZE-1);
            binbuf_text(inbinbuf, messbuf, bp - messbuf);
504 505
            if (sys_debuglevel & DEBUG_MESSDOWN) {
                if (stderr_isatty)
506
                    fprintf(stderr,"\n<- \e[0;1;36m%.*s\e[0m", bp - messbuf, messbuf);
507
                else
508
                    fprintf(stderr,"\n<- %.*s", bp - messbuf, messbuf);
Miller Puckette's avatar
Miller Puckette committed
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
            }
            x->sr_inhead = inhead;
            x->sr_intail = intail;
            return (1);
        }
    }
    return (0);
}

static void socketreceiver_getudp(t_socketreceiver *x, int fd)
{
    char buf[INBUFSIZE+1];
    int ret = recv(fd, buf, INBUFSIZE, 0);
    if (ret < 0)
    {
        sys_sockerror("recv");
        sys_rmpollfn(fd);
        sys_closesocket(fd);
    }
    else if (ret > 0)
    {
        buf[ret] = 0;
#if 0
        post("%s", buf);
#endif
        if (buf[ret-1] != '\n')
        {
#if 0
            buf[ret] = 0;
            error("dropped bad buffer %s\n", buf);
#endif
        }
        else
        {
            char *semi = strchr(buf, ';');
            if (semi) 
                *semi = 0;
            binbuf_text(inbinbuf, buf, strlen(buf));
            outlet_setstacklim();
            if (x->sr_socketreceivefn)
                (*x->sr_socketreceivefn)(x->sr_owner, inbinbuf);
            else bug("socketreceiver_getudp");
        }
    }
}

void sys_exit(void);

void socketreceiver_read(t_socketreceiver *x, int fd)
{
    if (x->sr_udp)   /* UDP ("datagram") socket protocol */
        socketreceiver_getudp(x, fd);
    else  /* TCP ("streaming") socket protocol */
    {
        int readto =
            (x->sr_inhead >= x->sr_intail ? INBUFSIZE : x->sr_intail-1);
        int ret;

            /* the input buffer might be full.  If so, drop the whole thing */
        if (readto == x->sr_inhead)
        {
            fprintf(stderr, "pd: dropped message from gui\n");
            x->sr_inhead = x->sr_intail = 0;
            readto = INBUFSIZE;
        }
        else
        {
            ret = recv(fd, x->sr_inbuf + x->sr_inhead,
                readto - x->sr_inhead, 0);
            if (ret < 0)
            {
                sys_sockerror("recv");
                if (x == sys_socketreceiver) sys_bail(1);
                else
                {
                    if (x->sr_notifier) (*x->sr_notifier)(x->sr_owner);
                    sys_rmpollfn(fd);
                    sys_closesocket(fd);
                }
            }
            else if (ret == 0)
            {
                if (x == sys_socketreceiver)
                {
                    fprintf(stderr, "pd: exiting\n");
                    sys_exit();
                    return;
                }
                else
                {
                    post("EOF on socket %d\n", fd);
                    if (x->sr_notifier) (*x->sr_notifier)(x->sr_owner);
                    sys_rmpollfn(fd);
                    sys_closesocket(fd);
                }
            }
            else
            {
                x->sr_inhead += ret;
                if (x->sr_inhead >= INBUFSIZE) x->sr_inhead = 0;
                while (socketreceiver_doread(x))
                {
                    outlet_setstacklim();
                    if (x->sr_socketreceivefn)
                        (*x->sr_socketreceivefn)(x->sr_owner, inbinbuf);
                    else binbuf_eval(inbinbuf, 0, 0, 0);
615 616
                    if (x->sr_inhead == x->sr_intail)
                        break;
Miller Puckette's avatar
Miller Puckette committed
617 618 619 620 621 622 623 624
                }
            }
        }
    }
}

void sys_closesocket(int fd)
{
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
625
#ifdef HAVE_UNISTD_H
Miller Puckette's avatar
Miller Puckette committed
626 627 628 629 630 631 632 633 634 635
    close(fd);
#endif
#ifdef MSW
    closesocket(fd);
#endif
}

/* ---------------------- sending messages to the GUI ------------------ */
#define GUI_ALLOCCHUNK 8192
#define GUI_UPDATESLICE 512 /* how much we try to do in one idle period */
636 637
#define GUI_BYTESPERPING 1024 /* how much we send up per ping */
//#define GUI_BYTESPERPING 0x7fffffff /* as per Miller's suggestion to disable the flow control */
Miller Puckette's avatar
Miller Puckette committed
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704

typedef struct _guiqueue
{
    void *gq_client;
    t_glist *gq_glist;
    t_guicallbackfn gq_fn;
    struct _guiqueue *gq_next;
} t_guiqueue;

static t_guiqueue *sys_guiqueuehead;
static char *sys_guibuf;
static int sys_guibufhead;
static int sys_guibuftail;
static int sys_guibufsize;
static int sys_waitingforping;
static int sys_bytessincelastping;

static void sys_trytogetmoreguibuf(int newsize)
{
    char *newbuf = realloc(sys_guibuf, newsize);
#if 0
    static int sizewas;
    if (newsize > 70000 && sizewas < 70000)
    {
        int i;
        for (i = sys_guibuftail; i < sys_guibufhead; i++)
            fputc(sys_guibuf[i], stderr);
    }
    sizewas = newsize;
#endif
#if 0
    fprintf(stderr, "new size %d (head %d, tail %d)\n",
        newsize, sys_guibufhead, sys_guibuftail);
#endif

        /* if realloc fails, make a last-ditch attempt to stay alive by
        synchronously writing out the existing contents.  LATER test
        this by intentionally setting newbuf to zero */
    if (!newbuf)
    {
        int bytestowrite = sys_guibuftail - sys_guibufhead;
        int written = 0;
        while (1)
        {
            int res = send(sys_guisock,
                sys_guibuf + sys_guibuftail + written, bytestowrite, 0);
            if (res < 0)
            {
                perror("pd output pipe");
                sys_bail(1);
            }
            else
            {
                written += res;
                if (written >= bytestowrite)
                    break;
            }
        }
        sys_guibufhead = sys_guibuftail = 0;
    }
    else
    {
        sys_guibufsize = newsize;
        sys_guibuf = newbuf;
    }
}

705
void blargh(void) {
706
#ifndef __linux__
707 708 709 710 711 712 713 714 715 716 717
  fprintf(stderr,"unhandled exception\n");
#else
  int i;
  void *array[25];
  int nSize = backtrace(array, 25);
  char **symbols = backtrace_symbols(array, nSize);
  for (i=0; i<nSize; i++) fprintf(stderr,"%d: %s\n",i,symbols[i]);
  free(symbols);
#endif
}

718 719 720 721
static int lastend = -1;
void sys_vvgui(const char *fmt, va_list ap) {
	va_list aq;
	va_copy(aq,ap);
722
    int msglen;
Miller Puckette's avatar
Miller Puckette committed
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751

    if (sys_nogui)
        return;
    if (!sys_guibuf)
    {
        if (!(sys_guibuf = malloc(GUI_ALLOCCHUNK)))
        {
            fprintf(stderr, "Pd: couldn't allocate GUI buffer\n");
            sys_bail(1);
        }
        sys_guibufsize = GUI_ALLOCCHUNK;
        sys_guibufhead = sys_guibuftail = 0;
    }
    if (sys_guibufhead > sys_guibufsize - (GUI_ALLOCCHUNK/2))
        sys_trytogetmoreguibuf(sys_guibufsize + GUI_ALLOCCHUNK);
    msglen = vsnprintf(sys_guibuf + sys_guibufhead,
        sys_guibufsize - sys_guibufhead, fmt, ap);
    va_end(ap);
    if(msglen < 0) 
    {
        fprintf(stderr, "Pd: buffer space wasn't sufficient for long GUI string\n");
        return;
    }
    if (msglen >= sys_guibufsize - sys_guibufhead)
    {
        int msglen2, newsize = sys_guibufsize + 1 +
            (msglen > GUI_ALLOCCHUNK ? msglen : GUI_ALLOCCHUNK);
        sys_trytogetmoreguibuf(newsize);

752
        va_copy(ap,aq);
Miller Puckette's avatar
Miller Puckette committed
753 754 755 756 757 758 759 760
        msglen2 = vsnprintf(sys_guibuf + sys_guibufhead,
            sys_guibufsize - sys_guibufhead, fmt, ap);
        va_end(ap);
        if (msglen2 != msglen)
            bug("sys_vgui");
        if (msglen >= sys_guibufsize - sys_guibufhead)
            msglen = sys_guibufsize - sys_guibufhead;
    }
761
    if (sys_debuglevel & DEBUG_MESSUP) {
762
        //blargh();
763
        //int begin = lastend=='\n' || lastend=='\r' || lastend==-1;
764
        int begin = lastend=='\x1f' || lastend==-1;
765 766
        if (stderr_isatty)
            fprintf(stderr, "%s\e[0;1;35m%s\e[0m",
767
                begin ? "\n-> " : "", sys_guibuf + sys_guibufhead);
768 769
        else
            fprintf(stderr, "%s%s",
770
                begin ? "\n-> " : "", sys_guibuf + sys_guibufhead);
771
    }
Miller Puckette's avatar
Miller Puckette committed
772 773
    sys_guibufhead += msglen;
    sys_bytessincelastping += msglen;
774
    if (sys_guibufhead>0) lastend=sys_guibuf[sys_guibufhead-1];
Mathieu L Bouchard's avatar
Mathieu L Bouchard committed
775 776
    if (sys_guibufhead>1 && strcmp(sys_guibuf+sys_guibufhead-2,"\\\n")==0)
        lastend=' ';
Miller Puckette's avatar
Miller Puckette committed
777
}
778
#undef sys_vgui
779
#undef sys_gui
780 781 782 783 784
void sys_vgui(const char *fmt, ...) {
    va_list ap;
    va_start(ap, fmt);
    sys_vvgui(fmt,ap);
}
785 786

/* This was used by the old command interface, but is no longer used. */
787 788 789 790 791 792
void sys_vvguid(const char *file, int line, const char *fmt, va_list ap) {
    if ((sys_debuglevel&4) && /*line>=0 &&*/ (lastend=='\n' || lastend=='\r' || lastend==-1)) {
        sys_vgui("AT %s:%d; ",file,line);
    }
    sys_vvgui(fmt,ap);
}
793

794
void sys_gui(const char *s)
Miller Puckette's avatar
Miller Puckette committed
795 796 797 798
{
    sys_vgui("%s", s);
}

799 800 801
static void escape_double_quotes(const char *src) {
    int dq = 0, len = 0;
    const char *s = src;
802
    while(*s)
Jonathan Wilkes's avatar
Jonathan Wilkes committed
803
    {
804
        len++;
805
        if (*s == '\"' || *s == '\\')
806
        {
807
            dq++;
808 809
        }
        s++;
810 811 812 813 814
    }
    if (!dq)
        sys_vgui("\"%s\"", src);
    else
    {
815 816
        char *dest = (char *)t_getbytes((len+dq+1)*sizeof(*dest));
        char *tmp = dest;
817
        s = src;
818
        while(*s)
819
        {
820
            if (*s == '\"' || *s == '\\')
821 822
            {
                *tmp++ = '\\';
823
                *tmp++ = *s;
824
            }
825
            else
826
            {
827
                *tmp++ = *s;
828 829
            }
            s++;
830
        }
831
        *tmp = '\0'; /* null terminate */
832
        sys_vgui("\"%s\"", dest);
833
        t_freebytes(dest, (len+dq+1)*sizeof(*dest));
Jonathan Wilkes's avatar
Jonathan Wilkes committed
834 835 836
    }
}

837 838
void gui_end_vmess(void)
{
839
    sys_gui("\x1f"); /* hack: use unit separator to delimit messages */
840 841
}

Jonathan Wilkes's avatar
Jonathan Wilkes committed
842 843 844 845 846
static int gui_array_head;
static int gui_array_tail;
/* this is a bug fix for the edge case of a message to the gui
   with a single array. This is necessary because I'm using a space
   delimiter between the first and second arg, and commas between
847
   the rest.
Jonathan Wilkes's avatar
Jonathan Wilkes committed
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
   While I think gui_vmess and gui_start_vmess interfaces work well,
   the actual format of the message as sent to the GUI can definitely
   be changed if need be. I threw it together hastily just to get something
   easy to parse in Javascript on the GUI side.
   -jw */
static void set_leading_array(int state) {
    if (state)
    {
        gui_array_head = 1;
        gui_array_tail = 0;
    }
    else
    {
        gui_array_head = 0;
        gui_array_tail = 0;
    }
}

866
/* quick hack to send a parameter list for use as a function call in nw.js */
Jonathan Wilkes's avatar
Jonathan Wilkes committed
867 868 869 870 871 872
void gui_do_vmess(const char *sel, char *fmt, int end, va_list ap)
{
    //va_list ap;
    int nargs = 0;
    char *fp = fmt;
    //va_start(ap, end);
873
    sys_vgui("%s ", sel);
Jonathan Wilkes's avatar
Jonathan Wilkes committed
874 875 876 877 878 879 880 881 882 883 884
    while (*fp)
    {
        // stop-gap-- increase to 20 until we find a way to pass a list or array
        if (nargs >= 20)
        {
            error("sys_gui_vmess: only 10 named parameters allowed");
            break;
        }
        if (nargs > 0) sys_gui(",");
        switch(*fp++)
        {
885
        case 'f': sys_vgui(FLOAT_SPECIFIER, va_arg(ap, double)); break;
886
        case 's': escape_double_quotes(va_arg(ap, const char *)); break;
887
        case 'i': sys_vgui("%d", va_arg(ap, int)); break;
888 889 890
        case 'x': sys_vgui("\"" X_SPECIFIER "\"",
            va_arg(ap, long unsigned int));
            break;
Jonathan Wilkes's avatar
Jonathan Wilkes committed
891 892 893 894 895 896 897
        //case 'p': SETPOINTER(at, va_arg(ap, t_gpointer *)); break;
        default: goto done;
        }
        nargs++;
    }
done:
    va_end(ap);
Jonathan Wilkes's avatar
Jonathan Wilkes committed
898
    if (nargs) set_leading_array(0);
Jonathan Wilkes's avatar
Jonathan Wilkes committed
899
    if (end)
900
        gui_end_vmess();
Jonathan Wilkes's avatar
Jonathan Wilkes committed
901 902 903 904 905 906 907 908 909 910 911 912 913
}

void gui_vmess(const char *sel, char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    gui_do_vmess(sel, fmt, 1, ap);
}

void gui_start_vmess(const char *sel, char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
Jonathan Wilkes's avatar
Jonathan Wilkes committed
914
    set_leading_array(1);
Jonathan Wilkes's avatar
Jonathan Wilkes committed
915 916 917 918 919
    gui_do_vmess(sel, fmt, 0, ap);
}

void gui_start_array(void)
{
920
    if (gui_array_head && !gui_array_tail)
921 922 923
        sys_gui("[");
    else
        sys_gui(",[");
Jonathan Wilkes's avatar
Jonathan Wilkes committed
924
    gui_array_head = 1;
925
    gui_array_tail = 0;
Jonathan Wilkes's avatar
Jonathan Wilkes committed
926 927
}

928
void gui_f(t_float f)
Jonathan Wilkes's avatar
Jonathan Wilkes committed
929
{
930
    if (gui_array_head && !gui_array_tail)
Jonathan Wilkes's avatar
Jonathan Wilkes committed
931
    {
932
        sys_vgui(FLOAT_SPECIFIER, f);
Jonathan Wilkes's avatar
Jonathan Wilkes committed
933 934
    }
    else
935
        sys_vgui("," FLOAT_SPECIFIER, f);
936
    gui_array_head = 0;
937
    gui_array_tail = 0;
Jonathan Wilkes's avatar
Jonathan Wilkes committed
938 939
}

940
void gui_i(int i)
Jonathan Wilkes's avatar
Jonathan Wilkes committed
941
{
942
    if (gui_array_head && !gui_array_tail)
Jonathan Wilkes's avatar
Jonathan Wilkes committed
943 944 945 946 947
    {
        sys_vgui("%d", i);
    }
    else
        sys_vgui(",%d", i);
948
    gui_array_head = 0;
949
    gui_array_tail = 0;
Jonathan Wilkes's avatar
Jonathan Wilkes committed
950 951
}

952
void gui_s(const char *s) 
Jonathan Wilkes's avatar
Jonathan Wilkes committed
953
{
954
    if (gui_array_head && !gui_array_tail)
Jonathan Wilkes's avatar
Jonathan Wilkes committed
955
    {
956
        escape_double_quotes(s);
Jonathan Wilkes's avatar
Jonathan Wilkes committed
957 958
    }
    else
959 960 961 962
    {
        sys_vgui(",");
        escape_double_quotes(s);
    }
963
    gui_array_head = 0;
964
    gui_array_tail = 0;
Jonathan Wilkes's avatar
Jonathan Wilkes committed
965 966
}

967 968 969 970 971 972 973 974 975 976
void gui_x(long unsigned int i)
{
    if (gui_array_head && !gui_array_tail)
        sys_vgui("\"x%.6lx\"", i);
    else
        sys_vgui(",\"x%.6lx\"", i);
    gui_array_head = 0;
    gui_array_tail = 0;
}

Jonathan Wilkes's avatar
Jonathan Wilkes committed
977 978 979
void gui_end_array(void)
{
    sys_gui("]");
980
    gui_array_tail = 1;
Jonathan Wilkes's avatar
Jonathan Wilkes committed
981 982
}

983
/* Old GUI command interface... */
984 985
void sys_vguid(const char *file, int line, const char *fmt, ...)
{
986
    va_list ap;
987
    char buf[MAXPDSTRING], *bufp, *endp;
988 989 990
    va_start(ap, fmt);
    vsnprintf(buf, MAXPDSTRING-1, fmt, ap);
    va_end(ap);
991 992 993 994 995 996 997 998 999 1000 1001
    /* Just display the first non-empty line, to remove console clutter. -ag */
    for (bufp = buf; *bufp && isspace(*bufp); bufp++) ;
    if ((endp = strchr(bufp, '\n')))
    {
        *endp = 0;
        if (endp[1])
        {
            /* Indicate that more stuff follows with an ellipsis. */
            strncat(bufp, "...", MAXPDSTRING);
        }
    }
1002
    gui_vmess("gui_legacy_tcl_command", "sis",
Albert Gräf's avatar
Albert Gräf committed
1003
        file, line, bufp);
1004 1005 1006
    //sys_vvguid(file,line,fmt,ap);
}

1007
int sys_flushtogui( void)
Miller Puckette's avatar
Miller Puckette committed
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
{
    int writesize = sys_guibufhead - sys_guibuftail, nwrote = 0;
    if (writesize > 0)
        nwrote = send(sys_guisock, sys_guibuf + sys_guibuftail, writesize, 0);

#if 0   
    if (writesize)
        fprintf(stderr, "wrote %d of %d\n", nwrote, writesize);
#endif

    if (nwrote < 0)
    {
        perror("pd-to-gui socket");
        sys_bail(1);
    }
    else if (!nwrote)
        return (0);
    else if (nwrote >= sys_guibufhead - sys_guibuftail)
         sys_guibufhead = sys_guibuftail = 0;
    else if (nwrote)
    {
        sys_guibuftail += nwrote;
        if (sys_guibuftail > (sys_guibufsize >> 2))
        {
            memmove(sys_guibuf, sys_guibuf + sys_guibuftail,
                sys_guibufhead - sys_guibuftail);
            sys_guibufhead = sys_guibufhead - sys_guibuftail;
            sys_guibuftail = 0;
        }
    }
    return (1);
}

void glob_ping(t_pd *dummy)
{
    sys_waitingforping = 0;
}

static int sys_flushqueue(void )
{
    int wherestop = sys_bytessincelastping + GUI_UPDATESLICE;
    if (wherestop + (GUI_UPDATESLICE >> 1) > GUI_BYTESPERPING)
        wherestop = 0x7fffffff;
    if (sys_waitingforping)
        return (0);
    if (!sys_guiqueuehead)
        return (0);
    while (1)
    {
        if (sys_bytessincelastping >= GUI_BYTESPERPING)
        {
1059
            //sys_gui("pdtk_ping\n");
Jonathan Wilkes's avatar
Jonathan Wilkes committed
1060
            gui_vmess("gui_ping", "");
Miller Puckette's avatar
Miller Puckette committed
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
            sys_bytessincelastping = 0;
            sys_waitingforping = 1;
            return (1);
        }
        if (sys_guiqueuehead)
        {
            t_guiqueue *headwas = sys_guiqueuehead;
            sys_guiqueuehead = headwas->gq_next;
            (*headwas->gq_fn)(headwas->gq_client, headwas->gq_glist);
            t_freebytes(headwas, sizeof(*headwas));
            if (sys_bytessincelastping >= wherestop)
                break;
        }
        else break;
    }
    sys_flushtogui();
    return (1);
}

    /* flush output buffer and update queue to gui in small time slices */
static int sys_poll_togui(void) /* returns 1 if did anything */
{
    if (sys_nogui)
        return (0);
        /* see if there is stuff still in the buffer, if so we
            must have fallen behind, so just try to clear that. */
    if (sys_flushtogui())
        return (1);
        /* if the flush wasn't complete, wait. */
    if (sys_guibufhead > sys_guibuftail)
        return (0);
    
        /* check for queued updates */
    if (sys_flushqueue())
        return (1);
    
    return (0);
}

    /* if some GUI object is having to do heavy computations, it can tell
    us to back off from doing more updates by faking a big one itself. */
void sys_pretendguibytes(int n)
{
    sys_bytessincelastping += n;
}

void sys_queuegui(void *client, t_glist *glist, t_guicallbackfn f)
{
    t_guiqueue **gqnextptr, *gq;
    if (!sys_guiqueuehead)
        gqnextptr = &sys_guiqueuehead;
    else
    {
        for (gq = sys_guiqueuehead; gq->gq_next; gq = gq->gq_next)
            if (gq->gq_client == client)
                return;
        if (gq->gq_client == client)
            return;
        gqnextptr = &gq->gq_next;
    }
    gq = t_getbytes(sizeof(*gq));
    gq->gq_next = 0;
    gq->gq_client = client;
    gq->gq_glist = glist;
    gq->gq_fn = f;
    gq->gq_next = 0;
    *gqnextptr = gq;
}

void sys_unqueuegui(void *client)
{
    t_guiqueue *gq, *gq2;
1133
    while (sys_guiqueuehead && sys_guiqueuehead->gq_client == client)
Miller Puckette's avatar
Miller Puckette committed
1134
    {
1135 1136 1137
        gq = sys_guiqueuehead;
        sys_guiqueuehead = sys_guiqueuehead->gq_next;
        t_freebytes(gq, sizeof(*gq));
Miller Puckette's avatar
Miller Puckette committed
1138
    }
1139 1140
    if (!sys_guiqueuehead)
        return;
1141
    for (gq = sys_guiqueuehead; gq2 = gq->gq_next; gq = gq2)
Miller Puckette's avatar
Miller Puckette committed
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
        if (gq2->gq_client == client)
    {
        gq->gq_next = gq2->gq_next;
        t_freebytes(gq2, sizeof(*gq2));
        break;
    }
}

int sys_pollgui(void)
{
1152
    // return (sys_domicrosleep(0, 1) || sys_poll_togui());
1153 1154
    // "fix" for sluggish gui proposed by Miller on 12/16/2012
    return (sys_domicrosleep(0, 1) + sys_poll_togui());
Miller Puckette's avatar
Miller Puckette committed
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
}



/* --------------------- starting up the GUI connection ------------- */

static int sys_watchfd;

#ifdef __linux__
void glob_watchdog(t_pd *dummy)
{
    if (write(sys_watchfd, "\n", 1) < 1)
    {
        fprintf(stderr, "pd: watchdog process died\n");
        sys_bail(1);
    }
}
#endif

#define FIRSTPORTNUM 5400

Miller Puckette's avatar
Miller Puckette committed
1176 1177
#define MAXFONTS 21
static int defaultfontshit[MAXFONTS] = {
Miller Puckette's avatar
Miller Puckette committed
1178 1179 1180 1181
    8, 5, 9, 10, 6, 10, 12, 7, 13, 14, 9, 17, 16, 10, 19, 24, 15, 28,
        24, 15, 28};
#define NDEFAULTFONT (sizeof(defaultfontshit)/sizeof(*defaultfontshit))

1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
extern t_symbol *pd_getplatform(void);
extern void sys_expandpath(const char *from, char *to);

/* set the datadir for nwjs. We use the published nw.js
   defaults if there's only one instance of the GUI set to
   run. Otherwise, we append the port number so that
   nw.js will spawn a new instance for us.

   Currently, users can give a command line arg to force Pd
   to start with a new GUI instance. A new GUI must also get
   created when a user turns on audio and there is a [pd~] object
   on the canvas. The latter would actually be more usable within
   a single GUI instance, but that would require some way to
   visually distinguish patches that are associated with different Pd
   engine processes.
*/ 

static void set_datadir(char *buf, int new_gui_instance, int portno)
{
    char dir[FILENAME_MAX];
    t_symbol *platform = pd_getplatform(); 
    strcpy(buf, "--user-data-dir=");
    /* Let's go ahead and quote the string to handle spaces in
       paths, etc. */
    strcat(buf, "\"");
    if (platform == gensym("darwin"))
        sys_expandpath("~/Library/Application Support/", dir);
    else if (platform != gensym("win32"))/* bsd and linux */
        sys_expandpath("~/.config/", dir);
#ifdef _WIN32
        /* win32 has a more robust API for getting the
           value of %LOCALAPPDATA%, but this works on
           Windows 7 and is straightforward... */
        char *env = getenv("LOCALAPPDATA");
        strcpy(dir, env);
        strcat(dir, "\\");
#endif
    strcat(dir, "purr-data");
    if (new_gui_instance)
    {
        char portbuf[10];
        sprintf(portbuf, "-%d", portno);
        strcat(dir, portbuf);
    }
    strcat(buf, dir);
    /* Finally, close quote... */
    strcat(buf, "\"");
}

extern int sys_unique;

Miller Puckette's avatar
Miller Puckette committed
1233 1234 1235
int sys_startgui(const char *guidir)
{
    pid_t childpid;
1236
    char cwd[FILENAME_MAX];
Miller Puckette's avatar
Miller Puckette committed
1237
    char cmdbuf[4*MAXPDSTRING];
1238
    struct sockaddr_in server = {0};
Miller Puckette's avatar
Miller Puckette committed
1239 1240 1241
    int len = sizeof(server);
    int ntry = 0, portno = FIRSTPORTNUM;
    int xsock = -1;
1242
    stderr_isatty = isatty(2);
1243
#ifdef MSW
1244 1245
    if (GetCurrentDirectory(FILENAME_MAX, cwd) == 0)
        strcpy(cwd, ".");
1246 1247
#endif
#ifdef HAVE_UNISTD_H
1248 1249
    if (!getcwd(cwd, FILENAME_MAX))
        strcpy(cwd, ".");
1250
#endif
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1251
#ifdef HAVE_UNISTD_H
Miller Puckette's avatar
Miller Puckette committed
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
    int stdinpipe[2];
#endif
    /* create an empty FD poll list */
    sys_fdpoll = (t_fdpoll *)t_getbytes(0);
    sys_nfdpoll = 0;
    inbinbuf = binbuf_new();
    if (sys_nogui)
    {
            /* fake the GUI's message giving cwd and font sizes; then
            skip starting the GUI up. */
        t_atom zz[NDEFAULTFONT+2];
        int i;
1264
        strcpy(cmdbuf, cwd);
Miller Puckette's avatar
Miller Puckette committed
1265 1266 1267 1268 1269 1270 1271 1272
        SETSYMBOL(zz, gensym(cmdbuf));
        for (i = 0; i < (int)NDEFAULTFONT; i++)
            SETFLOAT(zz+i+1, defaultfontshit[i]);
        SETFLOAT(zz+NDEFAULTFONT+1,0);
        glob_initfromgui(0, 0, 23, zz);
    }
    else if (sys_guisetportnumber)  /* GUI exists and sent us a port number */
    {
1273
        struct sockaddr_in server = {0};
Miller Puckette's avatar
Miller Puckette committed
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
        struct hostent *hp;
        /* create a socket */
        sys_guisock = socket(AF_INET, SOCK_STREAM, 0);
        if (sys_guisock < 0)
            sys_sockerror("socket");

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

        hp = gethostbyname(LOCALHOST);

        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)sys_guisetportnumber);

            /* try to connect */
        if (connect(sys_guisock, (struct sockaddr *) &server, sizeof (server))
            < 0)
        {
            sys_sockerror("connecting stream socket");
            exit(1);
        }
    }
    else    /* default behavior: start up the GUI ourselves. */
    {
#ifdef MSW
        char scriptbuf[MAXPDSTRING+30], wishbuf[MAXPDSTRING+30], portbuf[80];
        int spawnret;

#endif
#ifdef MSW
        char intarg;
#else
        int intarg;
#endif

        /* create a socket */
        xsock = socket(AF_INET, SOCK_STREAM, 0);
        if (xsock < 0) sys_sockerror("socket");
#if 0
        intarg = 0;
        if (setsockopt(xsock, SOL_SOCKET, SO_SNDBUF,
            &intarg, sizeof(intarg)) < 0)
                post("setsockopt (SO_RCVBUF) failed\n");
        intarg = 0;
        if (setsockopt(xsock, SOL_SOCKET, SO_RCVBUF,
            &intarg, sizeof(intarg)) < 0)
                post("setsockopt (SO_RCVBUF) failed\n");
#endif
        intarg = 1;
        if (setsockopt(xsock, IPPROTO_TCP, TCP_NODELAY,
            &intarg, sizeof(intarg)) < 0)
#ifndef MSW
                post("setsockopt (TCP_NODELAY) failed\n")
#endif
                    ;
        
        
        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,
                    "Pd needs your machine to be configured with\n");
                fprintf(stderr,
                  "'networking' turned on (see Pd's html doc for details.)\n");
                exit(1);
            }
            portno++;
            server.sin_port = htons((unsigned short)(portno));
        }

        if (sys_verbose) fprintf(stderr, "port %d\n", portno);


Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1368
#ifdef HAVE_UNISTD_H
1369 1370 1371
        if (!sys_guicmd)
        {
#ifdef __APPLE__
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1372
            int i;
1373
            struct stat statbuf;
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
            glob_t glob_buffer;
            char *homedir = getenv("HOME");
            char embed_glob[FILENAME_MAX];
            char embed_filename[FILENAME_MAX], home_filename[FILENAME_MAX];
            char *wish_paths[10] = {
                "(did not find an embedded wish)",
                "(did not find a home directory)",
                "/Applications/Utilities/Wish.app/Contents/MacOS/Wish",
                "/Applications/Utilities/Wish Shell.app/Contents/MacOS/Wish Shell",
                "/Applications/Wish.app/Contents/MacOS/Wish",
                "/Applications/Wish Shell.app/Contents/MacOS/Wish Shell",
                "/usr/local/bin/wish8.4",
                "/sw/bin/wish8.4"
                "/opt/bin/wish8.4"
                "/usr/bin/wish8.4"
                "/usr/local/bin/wish8.4",
                "/usr/local/bin/wish",
                "/usr/bin/wish"
            };
            /* this glob is needed so the Wish executable can have the same
             * filename as the Pd.app, i.e. 'Pd-0.42-3.app' should have a Wish
             * executable called 'Pd-0.42-3.app/Contents/MacOS/Pd-0.42-3' */
1396
            sprintf(embed_glob, "%s/../../MacOS/nwjs", guidir);
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412
            glob_buffer.gl_matchc = 1; /* we only need one match */
            glob(embed_glob, GLOB_LIMIT, NULL, &glob_buffer);
            if (glob_buffer.gl_pathc > 0) {
                strcpy(embed_filename, glob_buffer.gl_pathv[0]);
                wish_paths[0] = embed_filename;
            }
            sprintf(home_filename,
                    "%s/Applications/Wish.app/Contents/MacOS/Wish",homedir);
            wish_paths[1] = home_filename;
            for(i=0;i<10;i++) {
                if (sys_verbose)
                    fprintf(stderr, "Trying Wish at \"%s\"\n", wish_paths[i]);
                if (stat(wish_paths[i], &statbuf) >= 0)
                    break;
            }
            sprintf(cmdbuf,"\"%s\" %s/pd.tk %d\n",wish_paths[i],guidir,portno);
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
            char data_dir_flag[MAXPDSTRING];
            set_datadir(data_dir_flag, sys_unique, portno);
            /* Make a copy in case the user wants to change to the repo
               dir while developing... */
            char guidir2[MAXPDSTRING];
            /* Let's go ahead and quote the path in case there are spaces
               in it. This won't happen on a sane Linux/BSD setup. But it
               will happen under Windows, so we quote here, too, for
               the sake of consistency. */
            strcpy(guidir2, "\"");
            strcat(guidir2, guidir);
            strcat(guidir2, "\"");
Jonathan Wilkes's avatar
Jonathan Wilkes committed
1425 1426 1427 1428 1429
            /* The following line checks if our GUIDIR was defined
               to something other than empty string. If so it will
               use that dir to find the nw binary. */
            if (strcmp(GUIDIR, ""))
                strcpy(guidir2, "\"" GUIDIR "\"");
1430
            //strcpy(guidir2, "\"/home/user/purr-data/pd/nw\"");
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
            sprintf(cmdbuf,
                "\"%s\" %s %s "
                "%d localhost %s %s " X_SPECIFIER,
                wish_paths[i],
                data_dir_flag,
                guidir2,
                portno,
                (sys_k12_mode ? "pd-l2ork-k12" : "pd-l2ork"),
                guidir2,
                (long unsigned int)pd_this);
1441 1442 1443
#else
            sprintf(cmdbuf,
                "TCL_LIBRARY=\"%s/tcl/library\" TK_LIBRARY=\"%s/tk/library\" \
1444 1445
                 \"%s/pd-gui\" %d localhost %s\n",
                 sys_libdir->s_name, sys_libdir->s_name, guidir, portno, (sys_k12_mode ? "pd-l2ork-k12" : "pd-l2ork"));
Jonathan Wilkes's avatar
Jonathan Wilkes committed
1446

1447
            fprintf(stderr, "guidir is %s\n", guidir);
1448

1449 1450 1451 1452 1453
            /* For some reason, the nw binary doesn't give you access to
               the first argument-- this is the path to the directory where
               package.json lives (or the zip file if it's compressed). So
               we add it again as the last argument to make sure we can fetch
               it on the GUI side. */
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
            char data_dir_flag[MAXPDSTRING];
            set_datadir(data_dir_flag, sys_unique, portno);

            /* Make a copy in case the user wants to change to the repo
               dir while developing... */
            char guidir2[MAXPDSTRING];
            /* Let's go ahead and quote the path in case there are spaces
               in it. This won't happen on a sane Linux/BSD setup. But it
               will happen under Windows, so we quote here, too, for
               the sake of consistency. */
            strcpy(guidir2, "\"");
            strcat(guidir2, guidir);
            strcat(guidir2, "\"");
Jonathan Wilkes's avatar
Jonathan Wilkes committed
1467 1468 1469 1470 1471
            /* The following line checks if our GUIDIR was defined
               to something other than empty string. If so it will
               use that dir to find the nw binary. */
            if (strcmp(GUIDIR, ""))
                strcpy(guidir2, "\"" GUIDIR "\"");
1472
            //strcpy(guidir2, "\"/home/user/purr-data/pd/nw\"");
1473
            sprintf(cmdbuf,
1474 1475 1476 1477 1478
                "%s/nw/nw %s %s "
                "%d localhost %s %s " X_SPECIFIER,
                guidir2,
                data_dir_flag,
                guidir2,
1479
                portno,
1480
                (sys_k12_mode ? "pd-l2ork-k12" : "pd-l2ork"),
1481
                guidir2,
1482
                (long unsigned int)pd_this);
1483 1484 1485 1486 1487 1488 1489
#endif
            sys_guicmd = cmdbuf;
        }

        if (sys_verbose) 
            fprintf(stderr, "%s", sys_guicmd);

Miller Puckette's avatar
Miller Puckette committed
1490 1491 1492 1493 1494
        childpid = fork();
        if (childpid < 0)
        {
            if (errno) perror("sys_startgui");
            else fprintf(stderr, "sys_startgui failed\n");
1495
            sys_closesocket(xsock);
Miller Puckette's avatar
Miller Puckette committed
1496 1497 1498 1499
            return (1);
        }
        else if (!childpid)                     /* we're the child */
        {
1500 1501 1502 1503
            sys_closesocket(xsock); /* we're the child */
#if defined(__linux__) || defined(__FreeBSD_kernel__) || defined(__GNU__)
            sys_set_priority(MODE_NRT);
#endif
Miller Puckette's avatar
Miller Puckette committed
1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
#ifndef __APPLE__
                /* the wish process in Unix will make a wish shell and
                    read/write standard in and out unless we close the
                    file descriptors.  Somehow this doesn't make the MAC OSX
                        version of Wish happy...*/
            if (pipe(stdinpipe) < 0)
                sys_sockerror("pipe");
            else
            {
                if (stdinpipe[0] != 0)
                {
                    close (0);
                    dup2(stdinpipe[0], 0);
                    close(stdinpipe[0]);
                }
            }
1520

Miller Puckette's avatar
Miller Puckette committed
1521 1522 1523 1524
#endif
            execl("/bin/sh", "sh", "-c", sys_guicmd, (char*)0);
            perror("pd: exec");
            _exit(1);
1525
       }
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1526
#endif /* HAVE_UNISTD_H */
Miller Puckette's avatar
Miller Puckette committed
1527 1528 1529 1530 1531 1532

#ifdef MSW
            /* in MSW land "guipath" is unused; we just do everything from
            the libdir. */
        /* fprintf(stderr, "%s\n", sys_libdir->s_name); */
        
1533 1534 1535 1536 1537
        //strcpy(scriptbuf, "\"");
        //strcat(scriptbuf, sys_libdir->s_name);
        //strcat(scriptbuf, "/" PDBINDIR "pd.tk\"");
        //sys_bashfilename(scriptbuf, scriptbuf);

1538
        char pd_this_string[80];