s_path.c 21.5 KB
Newer Older
Miller Puckette's avatar
Miller Puckette committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/* Copyright (c) 1999 Guenter Geiger and others.
* For information on usage and redistribution, and for a DISCLAIMER OF ALL
* WARRANTIES, see the file, "LICENSE.txt," in this distribution.  */

/*
 * This file implements the loader for linux, which includes
 * a little bit of path handling.
 *
 * Generalized by MSP to provide an open_via_path function
 * and lists of files for all purposes.
 */ 

/* #define DEBUG(x) x */
#define DEBUG(x)

#include <stdlib.h>
#ifdef UNISTD
#include <unistd.h>
#include <sys/stat.h>
#endif
#ifdef MSW
#include <io.h>
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
23
#include <windows.h>
Miller Puckette's avatar
Miller Puckette committed
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#endif

#include <string.h>
#include "m_pd.h"
#include "m_imp.h"
#include "s_stuff.h"
#include <stdio.h>
#include <fcntl.h>
#include <ctype.h>

#ifdef _LARGEFILE64_SOURCE
# define open  open64
# define lseek lseek64
# define fstat fstat64
# define stat  stat64
#endif

t_namelist *sys_externlist;
t_namelist *sys_searchpath;
t_namelist *sys_helppath;

    /* change '/' characters to the system's native file separator */
void sys_bashfilename(const char *from, char *to)
{
    char c;
    while (c = *from++)
    {
#ifdef MSW
        if (c == '/') c = '\\';
#endif
        *to++ = c;
    }
    *to = 0;
}

    /* change the system's native file separator to '/' characters  */
void sys_unbashfilename(const char *from, char *to)
{
    char c;
    while (c = *from++)
    {
#ifdef MSW
        if (c == '\\') c = '/';
#endif
        *to++ = c;
    }
    *to = 0;
}

73
74
75
76
77
78
79
80
81
82
/* expand special tags inside path that start with @ */

// utility function to expand paths (see sys_expandpathelems call below for more info)

static void sys_path_replace(
    char const * const original,
    char * returned, 
    char const * const pattern, 
    char const * const replacement
) {
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
    size_t const replen = strlen(replacement);
    size_t const patlen = strlen(pattern);
    size_t const orilen = strlen(original);

    size_t patcnt = 0;
    const char * oriptr;
    const char * patloc;

    // find how many times the pattern occurs in the original string
    for (oriptr = original; patloc = strstr(oriptr, pattern); oriptr = patloc + patlen)
    {
        patcnt++;
    }

    {
        // allocate memory for the new string
        size_t const retlen = orilen + patcnt * (replen - patlen);

        if (returned != NULL)
        {
            // copy the original string, 
            // replacing all the instances of the pattern
            char *retptr = returned;
            for (oriptr = original; patloc = strstr(oriptr, pattern); oriptr = patloc + patlen)
            {
                size_t const skplen = patloc - oriptr;
                // copy the section until the occurence of the pattern
                strncpy(retptr, oriptr, skplen);
                retptr += skplen;
                // copy the replacement 
                strncpy(retptr, replacement, replen);
                retptr += replen;
            }
            // copy the rest of the string.
            strcpy(retptr, oriptr);
        }
    }
120
121
}

Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
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
/* expand env vars and ~ at the beginning of a path and make a copy to return */
static void sys_expandpath(const char *from, char *to)
{
    if ((strlen(from) == 1 && from[0] == '~') || (strncmp(from,"~/", 2) == 0))
    {
#ifdef MSW
        const char *home = getenv("USERPROFILE");
#else
        const char *home = getenv("HOME");
#endif
        if(home) 
        {
            strncpy(to, home, FILENAME_MAX - 1);
            strncat(to, from + 1, FILENAME_MAX - strlen(from) - 2);
        }
    }
    else
        strncpy(to, from, FILENAME_MAX - 1);
#ifdef MSW
    char buf[FILENAME_MAX];
    ExpandEnvironmentStrings(to, buf, FILENAME_MAX - 2);
    strncpy(to, buf, FILENAME_MAX - 1);
#endif    
}

147
148
149
150

/* used for expanding paths for various objects */
void sys_expandpathelems(const char *name, char *result)
{
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
    //check for expandable elements in path (e.g. @pd_extra, ~/) and replace
    //fprintf(stderr,"sys_expandpathelems name=<%s>\n", name);
    char interim[FILENAME_MAX];
    if (strstr(name, "@pd_extra") != NULL)
    {
        t_namelist *path = pd_extrapath;
        while (path->nl_next)
            path = path->nl_next;
        sys_path_replace(name, interim, "@pd_extra", path->nl_string);
        //fprintf(stderr,"path->nl_string=<%s>\n", path->nl_string);
    }
    else
    {
        strcpy(interim, name);
    }
    //fprintf(stderr,"sys_expandpathelems interim=<%s>\n", interim);
    sys_expandpath(interim, result);
    //fprintf(stderr,"sys_expandpathelems result=<%s>\n", result);
169
170
}

171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
/* test if path is absolute or relative, based on leading /, env vars, ~, etc */
int sys_isabsolutepath(const char *dir)
{
    if (dir[0] == '/' || dir[0] == '~'
#ifdef MSW
        || dir[0] == '%' || (dir[1] == ':' && dir[2] == '/')
#endif
        )
    {
        return 1;
    }
    else
    {
        return 0;            
    }
}


Miller Puckette's avatar
Miller Puckette committed
189
190
/*******************  Utility functions used below ******************/

Miller Puckette's avatar
Miller Puckette committed
191
192
193
194
195
196
197
198
199
200
201
202
/*!
 * \brief copy until delimiter
 * 
 * \arg to destination buffer
 * \arg to_len destination buffer length
 * \arg from source buffer
 * \arg delim string delimiter to stop copying on
 *
 * \return position after delimiter in string.  If it was the last
 *         substring, return NULL.
 */
static const char *strtokcpy(char *to, size_t to_len, const char *from, char delim)
Miller Puckette's avatar
Miller Puckette committed
203
{
Miller Puckette's avatar
Miller Puckette committed
204
205
    unsigned int i = 0;

Miller Puckette's avatar
detab    
Miller Puckette committed
206
207
208
        for (; i < (to_len - 1) && from[i] && from[i] != delim; i++)
                to[i] = from[i];
        to[i] = '\0';
Miller Puckette's avatar
Miller Puckette committed
209

Miller Puckette's avatar
detab    
Miller Puckette committed
210
211
        if (i && from[i] != '\0')
                return from + i + 1;
Miller Puckette's avatar
Miller Puckette committed
212

Miller Puckette's avatar
detab    
Miller Puckette committed
213
        return NULL;
Miller Puckette's avatar
Miller Puckette committed
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
}

/* add a single item to a namelist.  If "allowdup" is true, duplicates
may be added; othewise they're dropped.  */

t_namelist *namelist_append(t_namelist *listwas, const char *s, int allowdup)
{
    t_namelist *nl, *nl2;
    nl2 = (t_namelist *)(getbytes(sizeof(*nl)));
    nl2->nl_next = 0;
    nl2->nl_string = (char *)getbytes(strlen(s) + 1);
    strcpy(nl2->nl_string, s);
    sys_unbashfilename(nl2->nl_string, nl2->nl_string);
    if (!listwas)
        return (nl2);
    else
    {
        for (nl = listwas; ;)
        {
            if (!allowdup && !strcmp(nl->nl_string, s))
                return (listwas);
            if (!nl->nl_next)
                break;
            nl = nl->nl_next;
        }
        nl->nl_next = nl2;
    }
    return (listwas);
}

/* add a colon-separated list of names to a namelist */

#ifdef MSW
#define SEPARATOR ';'   /* in MSW the natural separator is semicolon instead */
#else
#define SEPARATOR ':'
#endif

t_namelist *namelist_append_files(t_namelist *listwas, const char *s)
{
    const char *npos;
    char temp[MAXPDSTRING];
    t_namelist *nl = listwas, *rtn = listwas;
    
    npos = s;
    do
    {
Miller Puckette's avatar
Miller Puckette committed
261
        npos = strtokcpy(temp, sizeof(temp), npos, SEPARATOR);
Miller Puckette's avatar
Miller Puckette committed
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
        if (! *temp) continue;
        nl = namelist_append(nl, temp, 0);
    }
        while (npos);
    return (nl);
}

void namelist_free(t_namelist *listwas)
{
    t_namelist *nl, *nl2;
    for (nl = listwas; nl; nl = nl2)
    {
        nl2 = nl->nl_next;
        t_freebytes(nl->nl_string, strlen(nl->nl_string) + 1);
        t_freebytes(nl, sizeof(*nl));
    }
}

char *namelist_get(t_namelist *namelist, int n)
{
    int i;
    t_namelist *nl;
    for (i = 0, nl = namelist; i < n && nl; i++, nl = nl->nl_next)
        ;
    return (nl ? nl->nl_string : 0);
}

int sys_usestdpath = 1;

void sys_setextrapath(const char *p)
{
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
293
    char pathbuf[FILENAME_MAX];
Miller Puckette's avatar
Miller Puckette committed
294
    namelist_free(pd_extrapath);
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
295
296
    /* add standard place for users to install stuff first */
#ifdef __gnu_linux__
297
    sys_expandpath("~/pd-l2ork-externals", pathbuf);
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
298
    pd_extrapath = namelist_append(0, pathbuf, 0);
299
    pd_extrapath = namelist_append(pd_extrapath, "/usr/local/lib/pd-l2ork-externals", 0);
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
#endif

#ifdef __APPLE__
    sys_expandpath("~/Library/Pd", pathbuf);
    pd_extrapath = namelist_append(0, pathbuf, 0);
    pd_extrapath = namelist_append(pd_extrapath, "/Library/Pd", 0);
#endif

#ifdef _WIN32
    sys_expandpath("%ProgramFiles%/Common Files/Pd", pathbuf);
    pd_extrapath = namelist_append(0, pathbuf, 0);
    sys_expandpath("%UserProfile%/Application Data/Pd", pathbuf);
    pd_extrapath = namelist_append(pd_extrapath, pathbuf, 0);
#endif
    /* add built-in "extra" path last so its checked last */
    pd_extrapath = namelist_append(pd_extrapath, p, 0);
Miller Puckette's avatar
Miller Puckette committed
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
}

#ifdef MSW
#define MSWOPENFLAG(bin) (bin ? _O_BINARY : _O_TEXT)
#else
#define MSWOPENFLAG(bin) 0
#endif

    /* try to open a file in the directory "dir", named "name""ext",
    for reading.  "Name" may have slashes.  The directory is copied to
    "dirresult" which must be at least "size" bytes.  "nameresult" is set
    to point to the filename (copied elsewhere into the same buffer). 
    The "bin" flag requests opening for binary (which only makes a difference
    on Windows). */

int sys_trytoopenone(const char *dir, const char *name, const char* ext,
    char *dirresult, char **nameresult, unsigned int size, int bin)
{
    int fd;
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
335
    char buf[FILENAME_MAX];
Miller Puckette's avatar
Miller Puckette committed
336
337
    if (strlen(dir) + strlen(name) + strlen(ext) + 4 > size)
        return (-1);
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
338
339
    sys_expandpath(dir, buf);
    strcpy(dirresult, buf);
Miller Puckette's avatar
Miller Puckette committed
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
    if (*dirresult && dirresult[strlen(dirresult)-1] != '/')
        strcat(dirresult, "/");
    strcat(dirresult, name);
    strcat(dirresult, ext);
    sys_bashfilename(dirresult, dirresult);

    DEBUG(post("looking for %s",dirresult));
        /* see if we can open the file for reading */
    if ((fd=open(dirresult,O_RDONLY | MSWOPENFLAG(bin))) >= 0)
    {
            /* in unix, further check that it's not a directory */
#ifdef UNISTD
        struct stat statbuf;
        int ok =  ((fstat(fd, &statbuf) >= 0) &&
            !S_ISDIR(statbuf.st_mode));
        if (!ok)
        {
            if (sys_verbose) post("tried %s; stat failed or directory",
                dirresult);
            close (fd);
            fd = -1;
        }
        else
#endif
        {
            char *slash;
            if (sys_verbose) post("tried %s and succeeded", dirresult);
            sys_unbashfilename(dirresult, dirresult);
            slash = strrchr(dirresult, '/');
            if (slash)
            {
                *slash = 0;
                *nameresult = slash + 1;
            }
            else *nameresult = dirresult;

            return (fd);  
        }
    }
    else
    {
        if (sys_verbose) post("tried %s and failed", dirresult);
    }
    return (-1);
}

    /* check if we were given an absolute pathname, if so try to open it
    and return 1 to signal the caller to cancel any path searches */
int sys_open_absolute(const char *name, const char* ext,
    char *dirresult, char **nameresult, unsigned int size, int bin, int *fdp)
{
391
    if (sys_isabsolutepath(name))
Miller Puckette's avatar
Miller Puckette committed
392
    {
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
393
        char dirbuf[FILENAME_MAX], *z = strrchr(name, '/');
394
395
396
397
        int dirlen;
        if (!z)
            return (0);
        dirlen = z - name;
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
398
399
        if (dirlen > FILENAME_MAX-1) 
            dirlen = FILENAME_MAX-1;
Miller Puckette's avatar
Miller Puckette committed
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
        strncpy(dirbuf, name, dirlen);
        dirbuf[dirlen] = 0;
        *fdp = sys_trytoopenone(dirbuf, name+(dirlen+1), ext,
            dirresult, nameresult, size, bin);
        return (1);
    }
    else return (0);
}

/* search for a file in a specified directory, then along the globally
defined search path, using ext as filename extension.  The
fd is returned, the directory ends up in the "dirresult" which must be at
least "size" bytes.  "nameresult" is set to point to the filename, which
ends up in the same buffer as dirresult.  Exception:
if the 'name' starts with a slash or a letter, colon, and slash in MSW,
there is no search and instead we just try to open the file literally.  */

/* see also canvas_open() which, in addition, searches down the
canvas-specific path. */

static int do_open_via_path(const char *dir, const char *name,
    const char *ext, char *dirresult, char **nameresult, unsigned int size,
    int bin, t_namelist *searchpath)
{
    t_namelist *nl;
    int fd = -1;
426
    char final_name[FILENAME_MAX];
Miller Puckette's avatar
Miller Puckette committed
427

428
429
        /* first check for @ and ~ (and later others) and replace */
    sys_expandpathelems(name, final_name);    
430

Miller Puckette's avatar
Miller Puckette committed
431
        /* first check if "name" is absolute (and if so, try to open) */
432
433
    if (sys_open_absolute(final_name, ext, dirresult, nameresult, size, bin, &fd))
        goto do_open_via_path_end;
Miller Puckette's avatar
Miller Puckette committed
434
435
    
        /* otherwise "name" is relative; try the directory "dir" first. */
436
    if ((fd = sys_trytoopenone(dir, final_name, ext,
Miller Puckette's avatar
Miller Puckette committed
437
        dirresult, nameresult, size, bin)) >= 0)
438
            goto do_open_via_path_end;
Miller Puckette's avatar
Miller Puckette committed
439
440
441

        /* next go through the search path */
    for (nl = searchpath; nl; nl = nl->nl_next)
442
        if ((fd = sys_trytoopenone(nl->nl_string, final_name, ext,
Miller Puckette's avatar
Miller Puckette committed
443
            dirresult, nameresult, size, bin)) >= 0)
444
                goto do_open_via_path_end;
Miller Puckette's avatar
Miller Puckette committed
445

Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
446
447
448
        /* next look in built-in paths like "extra" */
    if (sys_usestdpath)
        for (nl = pd_extrapath; nl; nl = nl->nl_next)
449
            if ((fd = sys_trytoopenone(nl->nl_string, final_name, ext,
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
450
                dirresult, nameresult, size, bin)) >= 0)
451
                    goto do_open_via_path_end;
Miller Puckette's avatar
Miller Puckette committed
452
453
454
455

    *dirresult = 0;
    *nameresult = dirresult;
    return (-1);
456
do_open_via_path_end:
457
    return (fd);
Miller Puckette's avatar
Miller Puckette committed
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
}

    /* open via path, using the global search path. */
int open_via_path(const char *dir, const char *name, const char *ext,
    char *dirresult, char **nameresult, unsigned int size, int bin)
{
    return (do_open_via_path(dir, name, ext, dirresult, nameresult,
        size, bin, sys_searchpath));
}

    /* Open a help file using the help search path.  We expect the ".pd"
    suffix here, even though we have to tear it back off for one of the
    search attempts. */
void open_via_helppath(const char *name, const char *dir)
{
473
    char realname[MAXPDSTRING], dirbuf[MAXPDSTRING], *basename;
Miller Puckette's avatar
Miller Puckette committed
474
475
476
477
478
        /* make up a silly "dir" if none is supplied */
    const char *usedir = (*dir ? dir : "./");
    int fd;

        /* 1. "objectname-help.pd" */
479
480
    strncpy(realname, name, MAXPDSTRING-10);
    realname[MAXPDSTRING-10] = 0;
Miller Puckette's avatar
Miller Puckette committed
481
482
483
    if (strlen(realname) > 3 && !strcmp(realname+strlen(realname)-3, ".pd"))
        realname[strlen(realname)-3] = 0;
    strcat(realname, "-help.pd");
484
485
    if ((fd = do_open_via_path(usedir, realname, "", dirbuf, &basename, 
        MAXPDSTRING, 0, sys_helppath)) >= 0)
Miller Puckette's avatar
Miller Puckette committed
486
487
488
489
            goto gotone;

        /* 2. "help-objectname.pd" */
    strcpy(realname, "help-");
490
491
492
493
494
    strncat(realname, name, MAXPDSTRING-10);
    realname[MAXPDSTRING-1] = 0;
    if ((fd = do_open_via_path(usedir, realname, "", dirbuf, &basename, 
        MAXPDSTRING, 0, sys_helppath)) >= 0)
            goto gotone;
Miller Puckette's avatar
Miller Puckette committed
495
496

        /* 3. "objectname.pd" */
497
498
499
    if ((fd = do_open_via_path(usedir, name, "", dirbuf, &basename, 
        MAXPDSTRING, 0, sys_helppath)) >= 0)
            goto gotone;
Miller Puckette's avatar
Miller Puckette committed
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
    post("sorry, couldn't find help patch for \"%s\"", name);
    return;
gotone:
    close (fd);
    glob_evalfile(0, gensym((char*)basename), gensym(dirbuf));
}


/* Startup file reading for linux and __APPLE__.  As of 0.38 this will be
deprecated in favor of the "settings" mechanism */

int sys_argparse(int argc, char **argv);

#ifndef MSW

#define STARTUPNAME ".pdrc"
#define NUMARGS 1000

int sys_rcfile(void)
{
    FILE* file;
    int i;
    int k;
    int rcargc;
    char* rcargv[NUMARGS];
    char* buffer;
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
526
    char  fname[FILENAME_MAX], buf[1000], *home = getenv("HOME");
Miller Puckette's avatar
Miller Puckette committed
527
528
529
530
531
532
533
534
535
536
537
    int retval = 1; /* that's what we will return at the end; for now, let's think it'll be an error */
 
    /* initialize rc-arg-array so we can safely clean up at the end */
    for (i = 1; i < NUMARGS-1; i++)
      rcargv[i]=0;


    /* parse a startup file */
    
    *fname = '\0'; 

Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
538
    strncat(fname, home? home : ".", FILENAME_MAX-10);
Miller Puckette's avatar
Miller Puckette committed
539
540
541
542
543
544
545
546
547
548
549
550
551
    strcat(fname, "/");

    strcat(fname, STARTUPNAME);

    if (!(file = fopen(fname, "r")))
        return 1;

    post("reading startup file: %s", fname);

    rcargv[0] = ".";    /* this no longer matters to sys_argparse() */

    for (i = 1; i < NUMARGS-1; i++)
    {
552
        if (fscanf(file, "%998s", buf) < 0)
Miller Puckette's avatar
Miller Puckette committed
553
            break;
554
        buf[999] = 0;
Miller Puckette's avatar
Miller Puckette committed
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
        if (!(rcargv[i] = malloc(strlen(buf) + 1)))
            goto cleanup;
        strcpy(rcargv[i], buf);
    }
    if (i >= NUMARGS-1)
        fprintf(stderr, "startup file too long; extra args dropped\n");
    rcargv[i] = 0;

    rcargc = i;

    /* parse the options */

    fclose(file);
    if (sys_verbose)
    {
570
        if (rcargc)
Miller Puckette's avatar
Miller Puckette committed
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
        {
            post("startup args from RC file:");
            for (i = 1; i < rcargc; i++)
                post("%s", rcargv[i]);
        }
        else post("no RC file arguments found");
    }
    if (sys_argparse(rcargc-1, rcargv+1))
    {
        post("error parsing RC arguments");
        goto cleanup;
    }

    retval=0; /* we made it without an error */


 cleanup: /* prevent memleak */
    for (i = 1; i < NUMARGS-1; i++)
      if(rcargv[i])free(rcargv[i]);
    
    return(retval);
}
#endif /* MSW */

void sys_doflags( void)
{
    int i, beginstring = 0, state = 0, len = strlen(sys_flags->s_name);
    int rcargc = 0;
    char *rcargv[MAXPDSTRING];
    if (len > MAXPDSTRING)
    {
        post("flags: %s: too long", sys_flags->s_name);
        return;
    }
    for (i = 0; i < len+1; i++)
    {
        int c = sys_flags->s_name[i];
        if (state == 0)
        {
            if (c && !isspace(c))
            {
                beginstring = i;
                state = 1;
            }
        }
        else
        {
            if (!c || isspace(c))
            {
                char *foo = malloc(i - beginstring + 1);
                if (!foo)
                    return;
                strncpy(foo, sys_flags->s_name + beginstring, i - beginstring);
                foo[i - beginstring] = 0;
                rcargv[rcargc] = foo;
                rcargc++;
                if (rcargc >= MAXPDSTRING)
                    break;
                state = 0;
            }
        }
    }
    if (sys_argparse(rcargc, rcargv))
        post("error parsing startup arguments");
}

/* undo pdtl_encodedialog.  This allows dialogs to send spaces, commas,
    dollars, and semis down here. */
t_symbol *sys_decodedialog(t_symbol *s)
{
    char buf[MAXPDSTRING], *sp = s->s_name;
    int i;
    if (*sp != '+')
        bug("sys_decodedialog: %s", sp);
    else sp++;
    for (i = 0; i < MAXPDSTRING-1; i++, sp++)
    {
        if (!sp[0])
            break;
        if (sp[0] == '+')
        {
            if (sp[1] == '_')
                buf[i] = ' ', sp++;
            else if (sp[1] == '+')
                buf[i] = '+', sp++;
            else if (sp[1] == 'c')
                buf[i] = ',', sp++;
            else if (sp[1] == 's')
                buf[i] = ';', sp++;
            else if (sp[1] == 'd')
                buf[i] = '$', sp++;
            else buf[i] = sp[0];
        }
        else buf[i] = sp[0];
    }
    buf[i] = 0;
    return (gensym(buf));
}


    /* start a search path dialog window */
void glob_start_path_dialog(t_pd *dummy)
{
    char buf[MAXPDSTRING];
    int i;
    t_namelist *nl;
677

678
    sys_gui("global pd_path; set pd_path {}\n");
Miller Puckette's avatar
Miller Puckette committed
679
    for (nl = sys_searchpath, i = 0; nl; nl = nl->nl_next, i++)
Miller Puckette's avatar
Miller Puckette committed
680
        sys_vgui("lappend pd_path {%s}\n", nl->nl_string);
Miller Puckette's avatar
Miller Puckette committed
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
    sprintf(buf, "pdtk_path_dialog %%s %d %d\n", sys_usestdpath, sys_verbose);
    gfxstub_new(&glob_pdobject, (void *)glob_start_path_dialog, buf);
}

    /* new values from dialog window */
void glob_path_dialog(t_pd *dummy, t_symbol *s, int argc, t_atom *argv)
{
    int i;
    namelist_free(sys_searchpath);
    sys_searchpath = 0;
    sys_usestdpath = atom_getintarg(0, argc, argv);
    sys_verbose = atom_getintarg(1, argc, argv);
    for (i = 0; i < argc-2; i++)
    {
        t_symbol *s = sys_decodedialog(atom_getsymbolarg(i+2, argc, argv));
        if (*s->s_name)
            sys_searchpath = namelist_append_files(sys_searchpath, s->s_name);
    }
}

    /* start a startup dialog window */
void glob_start_startup_dialog(t_pd *dummy)
{
    char buf[MAXPDSTRING];
    int i;
    t_namelist *nl;
707

708
    sys_gui("global pd_startup; set pd_startup {}\n");
Miller Puckette's avatar
Miller Puckette committed
709
    for (nl = sys_externlist, i = 0; nl; nl = nl->nl_next, i++)
Miller Puckette's avatar
Miller Puckette committed
710
        sys_vgui("lappend pd_startup {%s}\n", nl->nl_string);
Miller Puckette's avatar
Miller Puckette committed
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
    sprintf(buf, "pdtk_startup_dialog %%s %d \"%s\"\n", sys_defeatrt,
        sys_flags->s_name);
    gfxstub_new(&glob_pdobject, (void *)glob_start_startup_dialog, buf);
}

    /* new values from dialog window */
void glob_startup_dialog(t_pd *dummy, t_symbol *s, int argc, t_atom *argv)
{
    int i;
    namelist_free(sys_externlist);
    sys_externlist = 0;
    sys_defeatrt = atom_getintarg(0, argc, argv);
    sys_flags = sys_decodedialog(atom_getsymbolarg(1, argc, argv));
    for (i = 0; i < argc-2; i++)
    {
        t_symbol *s = sys_decodedialog(atom_getsymbolarg(i+2, argc, argv));
        if (*s->s_name)
            sys_externlist = namelist_append_files(sys_externlist, s->s_name);
    }
}

732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
t_symbol *pd_getdirname(void)
{
    char buf[MAXPDSTRING], buf2[MAXPDSTRING];
    int len;
#ifdef _WIN32
    if ((len = GetModuleFileName(NULL, buf, sizeof(buf))) == 0)
        strcpy(buf, ".");
    else
        buf[len] = '\0';
    sys_unbashfilename(buf, buf);
#elif defined(__APPLE__)
    len = sizeof(buf);
    _NSGetExecutablePath(buf, &len);
    if (len != -1) buf[len] = '\0';
#elif defined(__FreeBSD__)
    len = (ssize_t)(readlink("/proc/curproc/file", buf, sizeof(buf)-1));
    if (len != -1) buf[len] = '\0';
#else
    len = (ssize_t)(readlink("/proc/self/exe", buf, sizeof(buf)-1));
    if (len != -1) buf[len] = '\0';
#endif
    if (len != -1)
    {
        char *lastslash;
        lastslash = strrchr(buf, '/');
        if (lastslash)
        {
            lastslash++;
            *lastslash= '\0';
            strncpy(buf2, buf, lastslash-buf);
            buf2[lastslash-buf] = '\0';
        }
        else strcpy(buf2, ".");
    }
    else
    {
        return 0;
    }
    t_symbol *foo = gensym(buf2);
   return foo;
}