x_text.c 74.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
/* Copyright (c) 1997-1999 Miller Puckette and others.
* For information on usage and redistribution, and for a DISCLAIMER OF ALL
* WARRANTIES, see the file, "LICENSE.txt," in this distribution.  */

/* historically this file defined the qlist and textfile objects - at the
moment it also defines "text" but it may later be better to split this off. */

#include "m_pd.h"
#include "g_canvas.h"    /* just for glist_getfont, bother */
#include "s_stuff.h"    /* just for sys_hostfontsize, phooey */
#include <string.h>
#include <stdio.h>
13 14
#define __USE_GNU
#include <stdlib.h>
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef _WIN32
#include <io.h>
#endif
extern t_pd *newest;    /* OK - this should go into a .h file now :) */
static t_class *text_define_class;

#ifdef _WIN32
# include <malloc.h> /* MSVC or mingw on windows */
#elif defined(__linux__) || defined(__APPLE__)
# include <alloca.h> /* linux, mac, mingw, cygwin */
#else
# include <stdlib.h> /* BSDs for example */
#endif

32 33 34 35
#ifdef _WIN32
#define qsort_r qsort_s   /* of course Microsoft decides to be different */
#endif

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
#ifndef HAVE_ALLOCA     /* can work without alloca() but we never need it */
#define HAVE_ALLOCA 1
#endif
#define TEXT_NGETBYTE 100 /* bigger that this we use alloc, not alloca */
#if HAVE_ALLOCA
#define ATOMS_ALLOCA(x, n) ((x) = (t_atom *)((n) < TEXT_NGETBYTE ?  \
        alloca((n) * sizeof(t_atom)) : getbytes((n) * sizeof(t_atom))))
#define ATOMS_FREEA(x, n) ( \
    ((n) < TEXT_NGETBYTE || (freebytes((x), (n) * sizeof(t_atom)), 0)))
#else
#define ATOMS_ALLOCA(x, n) ((x) = (t_atom *)getbytes((n) * sizeof(t_atom)))
#define ATOMS_FREEA(x, n) (freebytes((x), (n) * sizeof(t_atom)))
#endif

/* --- common code for text define, textfile, and qlist for storing text -- */

typedef struct _textbuf
{
    t_object b_ob;
    t_binbuf *b_binbuf;
    t_canvas *b_canvas;
    t_guiconnect *b_guiconnect;
Jonathan Wilkes's avatar
Jonathan Wilkes committed
58
    t_symbol *b_sym;
59 60
} t_textbuf;

Jonathan Wilkes's avatar
Jonathan Wilkes committed
61
static void textbuf_init(t_textbuf *x, t_symbol *sym)
62 63 64
{
    x->b_binbuf = binbuf_new();
    x->b_canvas = canvas_getcurrent();
Jonathan Wilkes's avatar
Jonathan Wilkes committed
65
    x->b_sym = sym;
66 67 68 69 70 71
}

static void textbuf_senditup(t_textbuf *x)
{
    int i, ntxt;
    char *txt;
72 73 74 75 76 77 78 79
    /* I don't think the Pd Vanilla interface can handle cases
       where a single line is greater than MAXPDSTRING, at least
       coming from the GUI to Pd. So instead of the %.*s specifier
       we just use a character array of MAXPDSTRING size. I suppose
       that means we'll fail on the Pd side, while Pd Vanilla would
       fail when the GUI tries to forward that line back to Pd.
    */
    char buf[MAXPDSTRING];
80 81 82
    if (!x->b_guiconnect)
        return;
    binbuf_gettext(x->b_binbuf, &txt, &ntxt);
83
    //sys_vgui("pdtk_textwindow_clear .x%zx\n", x);
84
    gui_vmess("gui_text_dialog_clear", "x", x);
85 86 87 88
    for (i = 0; i < ntxt; )
    {
        char *j = strchr(txt+i, '\n');
        if (!j) j = txt + ntxt;
89
        //sys_vgui("pdtk_textwindow_append .x%zx {%.*s\n}\n",
90 91 92 93 94 95 96
        //    x, j-txt-i, txt+i);
        if (j - txt - i >= MAXPDSTRING)
        {
            pd_error(x, "text: can't display lines greater than %d characters",
                MAXPDSTRING);
            break;
        }
97
        sprintf(buf, "%.*s\n", (int)(j-txt-i), txt+i);
98 99
        gui_vmess("gui_text_dialog_append", "xs",
            x, buf);
100 101
        i = (j-txt)+1;
    }
102
    //sys_vgui("pdtk_textwindow_setdirty .x%zx 0\n", x);
103
    gui_vmess("gui_text_dialog_set_dirty", "xi", x, 0);
104 105 106
    t_freebytes(txt, ntxt);
}

107 108 109 110 111 112
static void textbuf_map(t_textbuf *x)
{
    if (x->b_guiconnect)
        textbuf_senditup(x);
}

113 114 115 116
static void textbuf_open(t_textbuf *x)
{
    if (x->b_guiconnect)
    {
117 118 119
        //sys_vgui("wm deiconify .x%zx\n", x);
        //sys_vgui("raise .x%zx\n", x);
        //sys_vgui("focus .x%zx.text\n", x);
120
        gui_vmess("gui_text_dialog_raise", "x", x);
121 122 123 124
    }
    else
    {
        char buf[40];
125
        //sys_vgui("pdtk_textwindow_open .x%zx %dx%d {%s: %s} %d\n",
126 127
        //    x, 600, 340, "myname", "text",
        //         sys_hostfontsize(glist_getfont(x->b_canvas)));//,
128
                    //glist_getzoom(x->b_canvas)));
129
        sprintf(buf, "x%zx", (t_uint)x);
130
        x->b_guiconnect = guiconnect_new(&x->b_ob.ob_pd, gensym(buf));
Jonathan Wilkes's avatar
Jonathan Wilkes committed
131
        gui_vmess("gui_text_dialog", "xsiii",
132
            x,
Jonathan Wilkes's avatar
Jonathan Wilkes committed
133
            x->b_sym->s_name,
134 135
            480,
            550,
Jonathan Wilkes's avatar
Jonathan Wilkes committed
136
            sys_hostfontsize(glist_getfont(x->b_canvas)));
137
        //textbuf_senditup(x);
138 139 140 141 142
    }
}

static void textbuf_close(t_textbuf *x)
{
143
    //sys_vgui("pdtk_textwindow_doclose .x%zx\n", x);
144
    gui_vmess("gui_text_dialog_close_from_pd", "x", x, 1);
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
    if (x->b_guiconnect)
    {
        guiconnect_notarget(x->b_guiconnect, 1000);
        x->b_guiconnect = 0;
    }
}

static void textbuf_addline(t_textbuf *b, t_symbol *s, int argc, t_atom *argv)
{
    t_binbuf *z = binbuf_new();
    binbuf_restore(z, argc, argv);
    binbuf_add(b->b_binbuf, binbuf_getnatom(z), binbuf_getvec(z));
    binbuf_free(z);
    textbuf_senditup(b);
}

static void textbuf_read(t_textbuf *x, t_symbol *s, int argc, t_atom *argv)
{
    int cr = 0;
    t_symbol *filename;
    while (argc && argv->a_type == A_SYMBOL &&
        *argv->a_w.w_symbol->s_name == '-')
    {
        if (!strcmp(argv->a_w.w_symbol->s_name, "-c"))
            cr = 1;
        else
        {
            pd_error(x, "text read: unknown flag ...");
            postatom(argc, argv); endpost();
        }
        argc--; argv++;
    }
    if (argc && argv->a_type == A_SYMBOL)
    {
        filename = argv->a_w.w_symbol;
        argc--; argv++;
    }
    else
    {
        pd_error(x, "text read: no file name given");
        return;
    }
    if (argc)
    {
        post("warning: text define ignoring extra argument: ");
        postatom(argc, argv); endpost();
    }
    if (binbuf_read_via_canvas(x->b_binbuf, filename->s_name, x->b_canvas, cr))
            pd_error(x, "%s: read failed", filename->s_name);
    textbuf_senditup(x);
}

static void textbuf_write(t_textbuf *x, t_symbol *s, int argc, t_atom *argv)
{
    int cr = 0;
    t_symbol *filename;
    char buf[MAXPDSTRING];
    while (argc && argv->a_type == A_SYMBOL &&
        *argv->a_w.w_symbol->s_name == '-')
    {
        if (!strcmp(argv->a_w.w_symbol->s_name, "-c"))
            cr = 1;
        else
        {
            pd_error(x, "text write: unknown flag ...");
            postatom(argc, argv); endpost();
        }
        argc--; argv++;
    }
    if (argc && argv->a_type == A_SYMBOL)
    {
        filename = argv->a_w.w_symbol;
        argc--; argv++;
    }
    else
    {
        pd_error(x, "text write: no file name given");
        return;
    }
    if (argc)
    {
        post("warning: text define ignoring extra argument: ");
        postatom(argc, argv); endpost();
    }
    canvas_makefilename(x->b_canvas, filename->s_name,
        buf, MAXPDSTRING);
    if (binbuf_write(x->b_binbuf, buf, "", cr))
            pd_error(x, "%s: write failed", filename->s_name);
}

static void textbuf_free(t_textbuf *x)
{
    t_pd *x2;
    binbuf_free(x->b_binbuf);
    if (x->b_guiconnect)
    {
241
        //sys_vgui("destroy .x%zx\n", x);
242
        gui_vmess("gui_text_dialog_close_from_pd", "xi", x, 0);
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
        guiconnect_notarget(x->b_guiconnect, 1000);
    }
        /* just in case we're still bound to #A from loading... */
    while ((x2 = pd_findbyclass(gensym("#A"), text_define_class)))
        pd_unbind(x2, gensym("#A"));
}

    /* random helper function */
static int text_nthline(int n, t_atom *vec, int line, int *startp, int *endp)
{
    int i, cnt = 0;
    for (i = 0; i < n; i++)
    {
        if (cnt == line)
        {
258
            int j = i;
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
            while (j < n && vec[j].a_type != A_SEMI &&
                vec[j].a_type != A_COMMA)
                    j++;
            *startp = i;
            *endp = j;
            return (1);
        }
        else if (vec[i].a_type == A_SEMI || vec[i].a_type == A_COMMA)
            cnt++;
    }
    return (0);
}

/* text_define object - text buffer, accessible by other accessor objects */

typedef struct _text_define
{
    t_textbuf x_textbuf;
    t_outlet *x_out;
Jonathan Wilkes's avatar
Jonathan Wilkes committed
278
    t_outlet *x_notifyout;
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
    t_symbol *x_bindsym;
    t_scalar *x_scalar;     /* faux scalar (struct text-scalar) to point to */
    t_gpointer x_gp;        /* pointer to it */
    t_canvas *x_canvas;     /* owning canvas whose stub we use for x_gp */
    unsigned char x_keep;   /* whether to embed contents in patch on save */
} t_text_define;

#define x_ob x_textbuf.b_ob
#define x_binbuf x_textbuf.b_binbuf
#define x_canvas x_textbuf.b_canvas

static void *text_define_new(t_symbol *s, int argc, t_atom *argv)
{
    t_text_define *x = (t_text_define *)pd_new(text_define_class);
    t_symbol *asym = gensym("#A");
    x->x_keep = 0;
    x->x_bindsym = &s_;
    while (argc && argv->a_type == A_SYMBOL &&
        *argv->a_w.w_symbol->s_name == '-')
    {
        if (!strcmp(argv->a_w.w_symbol->s_name, "-k"))
            x->x_keep = 1;
        else
        {
            pd_error(x, "text define: unknown flag ...");
            postatom(argc, argv); endpost();
        }
        argc--; argv++;
    }
    if (argc && argv->a_type == A_SYMBOL)
    {
        pd_bind(&x->x_ob.ob_pd, argv->a_w.w_symbol);
        x->x_bindsym = argv->a_w.w_symbol;
        argc--; argv++;
    }
    if (argc)
    {
        post("warning: text define ignoring extra argument: ");
        postatom(argc, argv); endpost();
    }
Jonathan Wilkes's avatar
Jonathan Wilkes committed
319 320
    textbuf_init(&x->x_textbuf, *x->x_bindsym->s_name ? x->x_bindsym :
        gensym("text"));
321 322 323 324 325
        /* set up a scalar and a pointer to it that we can output */
    x->x_scalar = scalar_new(canvas_getcurrent(), gensym("pd-text"));
    binbuf_free(x->x_scalar->sc_vec[2].w_binbuf);
    x->x_scalar->sc_vec[2].w_binbuf = x->x_binbuf;
    x->x_out = outlet_new(&x->x_ob, &s_pointer);
Jonathan Wilkes's avatar
Jonathan Wilkes committed
326
    x->x_notifyout = outlet_new(&x->x_ob, 0);
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
    gpointer_init(&x->x_gp);
    x->x_canvas = canvas_getcurrent();
           /* bashily unbind #A -- this would create garbage if #A were
           multiply bound but we believe in this context it's at most
           bound to whichever text_define or array was created most recently */
    asym->s_thing = 0;
        /* and now bind #A to us to receive following messages in the
        saved file or copy buffer */
    pd_bind(&x->x_ob.ob_pd, asym);
    return (x);
}

static void text_define_clear(t_text_define *x)
{
    binbuf_clear(x->x_binbuf);
    textbuf_senditup(&x->x_textbuf);
}

    /* from g_traversal.c - maybe put in a header? */
t_binbuf *pointertobinbuf(t_pd *x, t_gpointer *gp, t_symbol *s,
    const char *fname);

    /* these are unused; they copy text from this object to and from a text
        field in a scalar. */
351
/*
352 353 354 355 356 357 358 359 360 361 362
static void text_define_frompointer(t_text_define *x, t_gpointer *gp,
    t_symbol *s)
{
    t_binbuf *b = pointertobinbuf(&x->x_textbuf.b_ob.ob_pd,
        gp, s, "text_frompointer");
    if (b)
    {
        binbuf_clear(x->x_textbuf.b_binbuf);
        binbuf_add(x->x_textbuf.b_binbuf, binbuf_getnatom(b), binbuf_getvec(b));
    }
}
363
*/
364

365 366
/* This doesn't seem to be used, either... */
/*
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
static void text_define_topointer(t_text_define *x, t_gpointer *gp, t_symbol *s)
{
    t_binbuf *b = pointertobinbuf(&x->x_textbuf.b_ob.ob_pd,
        gp, s, "text_topointer");
    if (b)
    {
        t_gstub *gs = gp->gp_stub;
        binbuf_clear(b);
        binbuf_add(b, binbuf_getnatom(x->x_textbuf.b_binbuf),
            binbuf_getvec(x->x_textbuf.b_binbuf));
        if (gs->gs_which == GP_GLIST)
            scalar_redraw((t_scalar *)(gp->gp_un.gp_gobj), gs->gs_un.gs_glist);
        else
        {
            t_array *owner_array = gs->gs_un.gs_array;
            while (owner_array->a_gp.gp_stub->gs_which == GP_ARRAY)
                owner_array = owner_array->a_gp.gp_stub->gs_un.gs_array;
            scalar_redraw((t_scalar *)(owner_array->a_gp.gp_un.gp_gobj),
                owner_array->a_gp.gp_stub->gs_un.gs_glist);
        }
    }
}
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

    /* bang: output a pointer to a struct containing this text */
void text_define_bang(t_text_define *x)
{
    gpointer_setglist(&x->x_gp, x->x_canvas, (t_gobj *)x->x_scalar);
    outlet_pointer(x->x_out, &x->x_gp);
}

    /* set from a list */
void text_define_set(t_text_define *x, t_symbol *s, int argc, t_atom *argv)
{
    binbuf_restore(x->x_binbuf, argc, argv);
    textbuf_senditup(&x->x_textbuf);
}


static void text_define_save(t_gobj *z, t_binbuf *bb)
{
    t_text_define *x = (t_text_define *)z;
    binbuf_addv(bb, "ssff", &s__X, gensym("obj"),
        (float)x->x_ob.te_xpix, (float)x->x_ob.te_ypix);
    binbuf_addbinbuf(bb, x->x_ob.ob_binbuf);
    binbuf_addsemi(bb);
    if (x->x_keep)
    {
        binbuf_addv(bb, "ss", gensym("#A"), gensym("set"));
        binbuf_addbinbuf(bb, x->x_binbuf);
        binbuf_addsemi(bb);
    }
    obj_saveformat(&x->x_ob, bb);
}

Jonathan Wilkes's avatar
Jonathan Wilkes committed
422 423 424 425 426 427 428 429 430 431 432 433 434
    /* send a pointer to the scalar that owns this text to
       whomever is bound to the given symbol */
static void text_define_send(t_text_define *x, t_symbol *s)
{
    if (!s->s_thing)
        pd_error(x, "text_define_send: %s: no such object", s->s_name);
    else
    {
        gpointer_setglist(&x->x_gp, x->x_canvas, (t_gobj *)x->x_scalar);
        pd_pointer(s->s_thing, &x->x_gp);
    }
}

435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
typedef struct _keyinfo
{
    int ki_forward; /* one if forward, -1 if reversed */
    int ki_onset;   /* number of fields to skip over */
} t_keyinfo;

    /* apple products seem to have their own prototypes for qsort_r (?) */
#ifdef __APPLE__
static int text_sortcompare(void *zkeyinfo, const void *z1, const void *z2)
#else
static int text_sortcompare(const void *z1, const void *z2, void *zkeyinfo)
#endif
{
    const t_atom *a1 = *(t_atom **)z1, *a2 = *(t_atom **)z2;
    t_keyinfo *k = (t_keyinfo *)zkeyinfo;
    int count;
        /* advance first line by key onset and react if we run out early */
    for (count = k->ki_onset; count--; a1++)
    {
        if (a1->a_type == A_SEMI || a1->a_type == A_COMMA)
        {
                /* if second line runs out early too consider them equal */
            for (count = k->ki_onset; count--; a2++)
                if (a2->a_type == A_SEMI || a2->a_type == A_COMMA)
                    goto equal;
            return (-k->ki_forward);
        }
    }
    for (count = k->ki_onset; count--; a2++)
        if (a2->a_type == A_SEMI || a2->a_type == A_COMMA)
            return (-k->ki_forward);
        /* compare remaining fields */
    for (; ; a1++, a2++)
    {
        if (a1->a_type == A_SEMI || a1->a_type == A_COMMA)
        {
                /* hit end of first line */
            if (a2->a_type == A_SEMI || a2->a_type == A_COMMA)
                 goto equal;
            else return (-k->ki_forward);
        }
        else if (a2->a_type == A_SEMI || a2->a_type == A_COMMA)
            return (k->ki_forward); /* hit end of second line */

            /* otherwise if they're different return something, and
            if not proceed to next field */
        else if (a1->a_type == A_FLOAT)
        {
            if (a2->a_type == A_FLOAT)
            {
                if (a1->a_w.w_float < a2->a_w.w_float)
                    return (-k->ki_forward);
                else if (a1->a_w.w_float > a2->a_w.w_float)
                    return (k->ki_forward);
            }
            else return (-k->ki_forward);
        }
        else if (a1->a_type == A_SYMBOL)
        {
            if (a2->a_type == A_SYMBOL)
            {
                int z = strcmp(a1->a_w.w_symbol->s_name,
                    a2->a_w.w_symbol->s_name);
                if (z)
                    return (z * k->ki_forward);
            }
            else return (k->ki_forward);
        }
    }
equal:
    /* ran out of both lines at same time, so we're "equal".
    in this case compare pointers so that "equal" lines (which
    might not be identical because of a nonzero onset) stay in the
    same order as before. */
    if (a1 < a2)
        return (-1);
    else return (1);
}

/* I can't seem to get to qsort_s on W2K - clicking on Pd complains it isn't
found in msvcrt (which indeed it isn't in).  Rather than waste more time
on this, just call qsort if we're Microsoft and single-instance.  I hope nobody
will try to compile multi-instance Pd for 32-bit windows, but if they
do, they might run into my qsort_s problem again. */
#if defined(_WIN32) && !defined(PDINSTANCE)
#define MICROSOFT_STUPID_SORT
static void *stupid_zkeyinfo;
static int stupid_sortcompare(const void *z1, const void *z2) {
    return (text_sortcompare(z1, z2, stupid_zkeyinfo)); }
#endif

    /* sort the contents */
static void text_define_sort(t_text_define *x, t_symbol *s,
    int argc, t_atom *argv)
{
    int nlines, unique = 0,  natom = binbuf_getnatom(x->x_binbuf), i,
        thisline, startline;
    t_atom *vec = binbuf_getvec(x->x_binbuf), **sortbuf, *a1, *a2;
    t_binbuf *newb;
    t_keyinfo k;
    k.ki_forward = 1;
    k.ki_onset = 0;
    while (argc && argv->a_type == A_SYMBOL &&
        *argv->a_w.w_symbol->s_name == '-')
    {
        if (!strcmp(argv->a_w.w_symbol->s_name, "-u"))
            unique = 1;
        else if (!strcmp(argv->a_w.w_symbol->s_name, "-r"))
            k.ki_forward = -1;
        else if (!strcmp(argv->a_w.w_symbol->s_name, "-k")  && argc > 1
            && argv[1].a_type == A_FLOAT)
        {
            if ((k.ki_onset = argv[1].a_w.w_float) < 0)
                k.ki_onset = 0;
            argc--; argv++;
        }
        else
        {
            pd_error(x, "text define sort: unknown flag ...");
            postatom(argc, argv); endpost();
        }
        argc--; argv++;
    }
    if (argc)
    {
        post("warning: text define sort ignoring extra argument: ");
        postatom(argc, argv); endpost();
    }
    if (!natom)
        return;
            /* last thing in buffer should be a terminator */
    if (vec[natom-1].a_type != A_SEMI &&
        vec[natom-1].a_type != A_COMMA)
            binbuf_addsemi(x->x_binbuf),
                vec = binbuf_getvec(x->x_binbuf),
                    natom = binbuf_getnatom(x->x_binbuf),
                        nlines++;
    for (i = nlines = 0; i < natom; i++)
        if (vec[i].a_type == A_SEMI || vec[i].a_type == A_COMMA)
            nlines++;
    sortbuf = (t_atom **)getbytes(nlines * sizeof(*sortbuf));
    for (i = thisline = 0, startline = 1; i < natom; i++)
    {
        if (startline)
        {
            if (thisline >= nlines)
                bug("text_define_sort");
            sortbuf[thisline++] = vec+i;
        }
        startline =  (vec[i].a_type == A_SEMI || vec[i].a_type == A_COMMA);
    }
#ifdef MICROSOFT_STUPID_SORT
    stupid_zkeyinfo = &k;
    qsort(sortbuf, nlines, sizeof(*sortbuf), stupid_sortcompare);
#else
#ifdef __APPLE__
    qsort_r(sortbuf, nlines, sizeof(*sortbuf), &k, text_sortcompare);
#else /* __APPLE__ */
    qsort_r(sortbuf, nlines, sizeof(*sortbuf), text_sortcompare, &k);
#endif /* __APPLE__ */
#endif /* MICROSOFT_STUPID_SORT */
    newb = binbuf_new();
    for (thisline = 0; thisline < nlines; thisline++)
    {
        if (unique && thisline > 0)   /* check for duplicates */
        {
            for (a1 = sortbuf[thisline-1], a2 = sortbuf[thisline]; ; a1++, a2++)
            {
                if (a1->a_type == A_SEMI || a1->a_type == A_COMMA)
                {
                    if (a1->a_type == a2->a_type)
                        goto skipit; /* duplicate line, don't copy */
                    else goto doit;
                }
                else if (a1->a_type != a2->a_type ||
                    (a1->a_type == A_FLOAT &&
                        a1->a_w.w_float != a2->a_w.w_float) ||
                    (a1->a_type == A_SYMBOL &&
                        a1->a_w.w_symbol != a2->a_w.w_symbol))
                            goto doit;
            }
        }
    doit:
        for (i = 0, a1 = sortbuf[thisline];
            a1->a_type != A_SEMI && a1->a_type != A_COMMA; i++, a1++)
                ;
        binbuf_add(newb, i+1, sortbuf[thisline]);
    skipit: ;
    }
    binbuf_free(x->x_binbuf);
    x->x_scalar->sc_vec[2].w_binbuf = x->x_binbuf = newb;
    freebytes(sortbuf, nlines * sizeof(*sortbuf));
    textbuf_senditup(&x->x_textbuf);
}

Jonathan Wilkes's avatar
Jonathan Wilkes committed
630 631 632 633 634 635 636 637
    /* notification from GUI that we've been updated */
static void text_define_notify(t_text_define *x)
{
    outlet_anything(x->x_notifyout, gensym("updated"), 0, 0);
    textbuf_senditup(&x->x_textbuf);
}


638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 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 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
static void text_define_free(t_text_define *x)
{
    textbuf_free(&x->x_textbuf);
    if (x->x_bindsym != &s_)
        pd_unbind(&x->x_ob.ob_pd, x->x_bindsym);
    gpointer_unset(&x->x_gp);
}

/* ---  text_client - common code for objects that refer to text buffers -- */

typedef struct _text_client
{
    t_object tc_obj;
    t_symbol *tc_sym;
    t_gpointer tc_gp;
    t_symbol *tc_struct;
    t_symbol *tc_field;
} t_text_client;

    /* parse buffer-finding arguments */
static void text_client_argparse(t_text_client *x, int *argcp, t_atom **argvp,
    char *name)
{
    int argc = *argcp;
    t_atom *argv = *argvp;
    x->tc_sym = x->tc_struct = x->tc_field = 0;
    gpointer_init(&x->tc_gp);
    while (argc && argv->a_type == A_SYMBOL &&
        *argv->a_w.w_symbol->s_name == '-')
    {
        if (!strcmp(argv->a_w.w_symbol->s_name, "-s") &&
            argc >= 3 && argv[1].a_type == A_SYMBOL && argv[2].a_type == A_SYMBOL)
        {
            x->tc_struct = canvas_makebindsym(argv[1].a_w.w_symbol);
            x->tc_field = argv[2].a_w.w_symbol;
            argc -= 2; argv += 2;
        }
        else
        {
            pd_error(x, "%s: unknown flag '%s'...", name,
                argv->a_w.w_symbol->s_name);
        }
        argc--; argv++;
    }
    if (argc && argv->a_type == A_SYMBOL)
    {
        if (x->tc_struct)
            pd_error(x, "%s: extra names after -s..", name);
        else x->tc_sym = argv->a_w.w_symbol;
        argc--; argv++;
    }
    *argcp = argc;
    *argvp = argv;
}

    /* find the binbuf for this object.  This should be reusable for other
    objects.  Prints an error  message and returns 0 on failure. */
static t_binbuf *text_client_getbuf(t_text_client *x)
{
    if (x->tc_sym)       /* named text object */
    {
        t_textbuf *y = (t_textbuf *)pd_findbyclass(x->tc_sym,
            text_define_class);
        if (y)
            return (y->b_binbuf);
        else
        {
            pd_error(x, "text: couldn't find text buffer '%s'",
                x->tc_sym->s_name);
            return (0);
        }
    }
    else if (x->tc_struct)   /* by pointer */
    {
        t_template *template = template_findbyname(x->tc_struct);
        t_gstub *gs = x->tc_gp.gp_stub;
        t_word *vec;
        int onset, type;
        t_symbol *arraytype;
        if (!template)
        {
            pd_error(x, "text: couldn't find struct %s", x->tc_struct->s_name);
            return (0);
        }
        if (!gpointer_check(&x->tc_gp, 0))
        {
            pd_error(x, "text: stale or empty pointer");
            return (0);
        }
        if (gs->gs_which == GP_ARRAY)
            vec = x->tc_gp.gp_un.gp_w;
        else vec = ((t_scalar *)(x->tc_gp.gp_un.gp_gobj))->sc_vec;

        if (!template_find_field(template,
            x->tc_field, &onset, &type, &arraytype))
        {
            pd_error(x, "text: no field named %s", x->tc_field->s_name);
            return (0);
        }
        if (type != DT_TEXT)
        {
            pd_error(x, "text: field %s not of type text", x->tc_field->s_name);
            return (0);
        }
        return (*(t_binbuf **)(((char *)vec) + onset));
    }
    else return (0);    /* shouldn't happen */
}

static  void text_client_senditup(t_text_client *x)
{
    if (x->tc_sym)       /* named text object */
    {
        t_textbuf *y = (t_textbuf *)pd_findbyclass(x->tc_sym,
            text_define_class);
        if (y)
            textbuf_senditup(y);
        else bug("text_client_senditup");
    }
    else if (x->tc_struct)   /* by pointer */
    {
        t_template *template = template_findbyname(x->tc_struct);
        t_gstub *gs = x->tc_gp.gp_stub;
        if (!template)
        {
            pd_error(x, "text: couldn't find struct %s", x->tc_struct->s_name);
            return;
        }
        if (!gpointer_check(&x->tc_gp, 0))
        {
            pd_error(x, "text: stale or empty pointer");
            return;
        }
        if (gs->gs_which == GP_GLIST)
            scalar_redraw((t_scalar *)(x->tc_gp.gp_un.gp_gobj), gs->gs_un.gs_glist);
        else
        {
            t_array *owner_array = gs->gs_un.gs_array;
            while (owner_array->a_gp.gp_stub->gs_which == GP_ARRAY)
                owner_array = owner_array->a_gp.gp_stub->gs_un.gs_array;
            scalar_redraw((t_scalar *)(owner_array->a_gp.gp_un.gp_gobj),
                owner_array->a_gp.gp_stub->gs_un.gs_glist);
        }
    }
}

static void text_client_free(t_text_client *x)
{
    gpointer_unset(&x->tc_gp);
}

/* ------- text_get object - output all or part of nth lines ----------- */
t_class *text_get_class;

typedef struct _text_get
{
    t_text_client x_tc;
    t_outlet *x_out1;       /* list */
    t_outlet *x_out2;       /* 1 if comma terminated, 0 if semi, 2 if none */
    t_float x_f1;           /* field number, -1 for whole line */
    t_float x_f2;           /* number of fields */
} t_text_get;

#define x_obj x_tc.tc_obj
#define x_sym x_tc.tc_sym
#define x_gp x_tc.tc_gp
#define x_struct x_tc.tc_struct
#define x_field x_tc.tc_field

static void *text_get_new(t_symbol *s, int argc, t_atom *argv)
{
    t_text_get *x = (t_text_get *)pd_new(text_get_class);
    x->x_out1 = outlet_new(&x->x_obj, &s_list);
    x->x_out2 = outlet_new(&x->x_obj, &s_float);
    floatinlet_new(&x->x_obj, &x->x_f1);
    floatinlet_new(&x->x_obj, &x->x_f2);
    x->x_f1 = -1;
    x->x_f2 = 1;
    text_client_argparse(&x->x_tc, &argc, &argv, "text get");
    if (argc)
    {
        if (argv->a_type == A_FLOAT)
            x->x_f1 = argv->a_w.w_float;
        else
        {
            post("text get: can't understand field number");
            postatom(argc, argv); endpost();
        }
        argc--; argv++;
    }
    if (argc)
    {
        if (argv->a_type == A_FLOAT)
            x->x_f2 = argv->a_w.w_float;
        else
        {
            post("text get: can't understand field count");
            postatom(argc, argv); endpost();
        }
        argc--; argv++;
    }
    if (argc)
    {
        post("warning: text get ignoring extra argument: ");
        postatom(argc, argv); endpost();
    }
    if (x->x_struct)
        pointerinlet_new(&x->x_obj, &x->x_gp);
    else symbolinlet_new(&x->x_obj, &x->x_tc.tc_sym);
    return (x);
}

static void text_get_float(t_text_get *x, t_floatarg f)
{
    t_binbuf *b = text_client_getbuf(&x->x_tc);
    int start, end, n, startfield, nfield;
    t_atom *vec;
    if (!b)
       return;
    vec = binbuf_getvec(b);
    n = binbuf_getnatom(b);
    startfield = x->x_f1;
    nfield = x->x_f2;
    if (text_nthline(n, vec, f, &start, &end))
    {
        int outc = end - start, k;
        t_atom *outv;
        if (x->x_f1 < 0)    /* negative start field for whole line */
        {
                /* tell us what terminated the line (semi or comma) */
            outlet_float(x->x_out2, (end < n && vec[end].a_type == A_COMMA));
            ATOMS_ALLOCA(outv, outc);
            for (k = 0; k < outc; k++)
                outv[k] = vec[start+k];
            outlet_list(x->x_out1, 0, outc, outv);
            ATOMS_FREEA(outv, outc);
        }
        else if (startfield + nfield > outc)
            pd_error(x, "text get: field request (%d %d) out of range",
                startfield, nfield);
        else
        {
            ATOMS_ALLOCA(outv, nfield);
            for (k = 0; k < nfield; k++)
                outv[k] = vec[(start+startfield)+k];
            outlet_list(x->x_out1, 0, nfield, outv);
            ATOMS_FREEA(outv, nfield);
        }
    }
    else if (x->x_f1 < 0)   /* whole line but out of range: empty list and 2 */
    {
        outlet_float(x->x_out2, 2);         /* 2 for out of range */
        outlet_list(x->x_out1, 0, 0, 0);    /* ... and empty list */
    }
}

/* --------- text_set object - replace all or part of nth line ----------- */
typedef struct _text_set
{
    t_text_client x_tc;
    t_float x_f1;           /* line number */
    t_float x_f2;           /* field number, -1 for whole line */
} t_text_set;

t_class *text_set_class;

static void *text_set_new(t_symbol *s, int argc, t_atom *argv)
{
    t_text_set *x = (t_text_set *)pd_new(text_set_class);
    floatinlet_new(&x->x_obj, &x->x_f1);
    floatinlet_new(&x->x_obj, &x->x_f2);
    x->x_f1 = 0;
    x->x_f2 = -1;
    text_client_argparse(&x->x_tc, &argc, &argv, "text set");
    if (argc)
    {
        if (argv->a_type == A_FLOAT)
            x->x_f1 = argv->a_w.w_float;
        else
        {
            post("text set: can't understand field number");
            postatom(argc, argv); endpost();
        }
        argc--; argv++;
    }
    if (argc)
    {
        if (argv->a_type == A_FLOAT)
            x->x_f2 = argv->a_w.w_float;
        else
        {
            post("text set: can't understand field count");
            postatom(argc, argv); endpost();
        }
        argc--; argv++;
    }
    if (argc)
    {
        post("warning: text set ignoring extra argument: ");
        postatom(argc, argv); endpost();
    }
    if (x->x_struct)
        pointerinlet_new(&x->x_obj, &x->x_gp);
    else symbolinlet_new(&x->x_obj, &x->x_tc.tc_sym);
    return (x);
}

static void text_set_list(t_text_set *x,
    t_symbol *s, int argc, t_atom *argv)
{
    t_binbuf *b = text_client_getbuf(&x->x_tc);
    int start, end, n, lineno = x->x_f1, fieldno = x->x_f2, i;
    t_atom *vec;
    if (!b)
       return;
    vec = binbuf_getvec(b);
    n = binbuf_getnatom(b);
    if (lineno < 0)
    {
        pd_error(x, "text set: line number (%d) < 0", lineno);
        return;
    }
    if (text_nthline(n, vec, lineno, &start, &end))
    {
        if (fieldno < 0)
        {
            if (end - start != argc)  /* grow or shrink */
            {
                int oldn = n;
                n = n + (argc - (end-start));
                if (n > oldn)
                    (void)binbuf_resize(b, n);
                vec = binbuf_getvec(b);
                memmove(&vec[start + argc], &vec[end],
                    sizeof(*vec) * (oldn - end));
                if (n < oldn)
                {
                    (void)binbuf_resize(b, n);
                    vec = binbuf_getvec(b);
                }
            }
        }
        else
        {
            if (fieldno >= end - start)
            {
                pd_error(x, "text set: field number (%d) past end of line",
                    fieldno);
                return;
            }
            if (fieldno + argc > end - start)
                argc = (end - start) - fieldno;
            start += fieldno;
        }
    }
    else if (fieldno < 0)  /* if line number too high just append to end */
    {
        int addsemi = (n && vec[n-1].a_type != A_SEMI &&
            vec[n-1].a_type != A_COMMA), newsize = n + addsemi + argc + 1;
        (void)binbuf_resize(b, newsize);
        vec = binbuf_getvec(b);
        if (addsemi)
            SETSEMI(&vec[n]);
        SETSEMI(&vec[newsize-1]);
        start = n+addsemi;
    }
    else
    {
        post("text set: %d: line number out of range", lineno);
        return;
    }
    for (i = 0; i < argc; i++)
    {
        if (argv[i].a_type == A_POINTER)
            SETSYMBOL(&vec[start+i], gensym("(pointer)"));
        else vec[start+i] = argv[i];
    }
    text_client_senditup(&x->x_tc);
}

Jonathan Wilkes's avatar
Jonathan Wilkes committed
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 1059 1060 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
/* --------- text_insert object - insert a line ----------- */
typedef struct _text_insert
{
    t_text_client x_tc;
    t_float x_f1;           /* line number */
} t_text_insert;

t_class *text_insert_class;

static void *text_insert_new(t_symbol *s, int argc, t_atom *argv)
{
    t_text_insert *x = (t_text_insert *)pd_new(text_insert_class);
    floatinlet_new(&x->x_obj, &x->x_f1);
    x->x_f1 = 0;
    text_client_argparse(&x->x_tc, &argc, &argv, "text insert");
    if (argc)
    {
        if (argv->a_type == A_FLOAT)
            x->x_f1 = argv->a_w.w_float;
        else
        {
            post("text insert: can't understand line number");
            postatom(argc, argv); endpost();
        }
        argc--; argv++;
    }
    if (argc)
    {
        post("warning: text insert ignoring extra argument: ");
        postatom(argc, argv); endpost();
    }
    if (x->x_struct)
        pointerinlet_new(&x->x_obj, &x->x_gp);
    else symbolinlet_new(&x->x_obj, &x->x_tc.tc_sym);
    return (x);
}

static void text_insert_list(t_text_insert *x,
    t_symbol *s, int argc, t_atom *argv)
{
    t_binbuf *b = text_client_getbuf(&x->x_tc);
    int start, end, n, nwas, i,
        lineno = (x->x_f1 > (double)0x7fffffff ? 0x7fffffff : x->x_f1);

    t_atom *vec;
    if (!b)
        return; 
    if (lineno < 0)
    {
        pd_error(x, "text insert: line number (%d) < 0", lineno);
        return;
    }
    nwas = binbuf_getnatom(b);
    if (!text_nthline(nwas, binbuf_getvec(b), lineno, &start, &end))
        start = nwas;
    (void)binbuf_resize(b, (n = nwas + argc + 1));
    vec = binbuf_getvec(b);
    if (start < n)
        memmove(&vec[start+(argc+1)], &vec[start], sizeof(*vec) * (nwas-start));
    for (i = 0; i < argc; i++)
    {
        if (argv[i].a_type == A_POINTER)
        SETSYMBOL(&vec[start+i], gensym("(pointer)"));
        else vec[start+i] = argv[i];
    }
    SETSEMI(&vec[start+argc]);
    text_client_senditup(&x->x_tc);
}

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 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 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 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 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
/* --------- text_delete object - delete nth line ----------- */
typedef struct _text_delete
{
    t_text_client x_tc;
} t_text_delete;

t_class *text_delete_class;

static void *text_delete_new(t_symbol *s, int argc, t_atom *argv)
{
    t_text_delete *x = (t_text_delete *)pd_new(text_delete_class);
    text_client_argparse(&x->x_tc, &argc, &argv, "text delete");
    if (argc)
    {
        post("warning: text delete ignoring extra argument: ");
        postatom(argc, argv); endpost();
    }
    if (x->x_struct)
        pointerinlet_new(&x->x_obj, &x->x_gp);
    else symbolinlet_new(&x->x_obj, &x->x_tc.tc_sym);
    return (x);
}

static void text_delete_float(t_text_delete *x, t_floatarg f)
{
    t_binbuf *b = text_client_getbuf(&x->x_tc);
    int start, end, n, lineno = f;
    t_atom *vec;
    if (!b)
       return;
    vec = binbuf_getvec(b);
    n = binbuf_getnatom(b);
    if (lineno < 0)
        binbuf_clear(b);
    else if (text_nthline(n, vec, lineno, &start, &end))
    {
        if (end < n)
            end++;
        memmove(&vec[start], &vec[end], sizeof(*vec) * (n - end));
        (void)binbuf_resize(b, n - (end - start));
    }
    else
    {
        post("text delete: %d: line number out of range", lineno);
        return;
    }
    text_client_senditup(&x->x_tc);
}

/* ---------------- text_size object - output number of lines -------------- */
t_class *text_size_class;

typedef struct _text_size
{
    t_text_client x_tc;
    t_outlet *x_out1;       /* float */
} t_text_size;

static void *text_size_new(t_symbol *s, int argc, t_atom *argv)
{
    t_text_size *x = (t_text_size *)pd_new(text_size_class);
    x->x_out1 = outlet_new(&x->x_obj, &s_float);
    text_client_argparse(&x->x_tc, &argc, &argv, "text size");
    if (argc)
    {
        post("warning: text size ignoring extra argument: ");
        postatom(argc, argv); endpost();
    }
    if (x->x_struct)
        pointerinlet_new(&x->x_obj, &x->x_gp);
    else symbolinlet_new(&x->x_obj, &x->x_tc.tc_sym);
    return (x);
}

static void text_size_bang(t_text_size *x)
{
    t_binbuf *b = text_client_getbuf(&x->x_tc);
    int n, i, cnt = 0;
    t_atom *vec;
    if (!b)
       return;
    vec = binbuf_getvec(b);
    n = binbuf_getnatom(b);
    for (i = 0; i < n; i++)
    {
        if (vec[i].a_type == A_SEMI || vec[i].a_type == A_COMMA)
            cnt++;
    }
    if (n && vec[n-1].a_type != A_SEMI && vec[n-1].a_type != A_COMMA)
        cnt++;
    outlet_float(x->x_out1, cnt);
}

static void text_size_float(t_text_size *x, t_floatarg f)
{
    t_binbuf *b = text_client_getbuf(&x->x_tc);
    int start, end, n;
    t_atom *vec;
    if (!b)
       return;
    vec = binbuf_getvec(b);
    n = binbuf_getnatom(b);
    if (text_nthline(n, vec, f, &start, &end))
        outlet_float(x->x_out1, end-start);
    else outlet_float(x->x_out1, -1);
}

/* ---------------- text_tolist object - output text as a list ----------- */
t_class *text_tolist_class;

#define t_text_tolist t_text_client

static void *text_tolist_new(t_symbol *s, int argc, t_atom *argv)
{
    t_text_tolist *x = (t_text_tolist *)pd_new(text_tolist_class);
    outlet_new(&x->tc_obj, &s_list);
    text_client_argparse(x, &argc, &argv, "text tolist");
    if (argc)
    {
        post("warning: text tolist ignoring extra argument: ");
        postatom(argc, argv); endpost();
    }
    if (x->tc_struct)
        pointerinlet_new(&x->tc_obj, &x->tc_gp);
    else symbolinlet_new(&x->tc_obj, &x->tc_sym);
    return (x);
}

static void text_tolist_bang(t_text_tolist *x)
{
    t_binbuf *b = text_client_getbuf(x), *b2;
    if (!b)
       return;
    b2 = binbuf_new();
    binbuf_addbinbuf(b2, b);
    outlet_list(x->tc_obj.ob_outlet, 0, binbuf_getnatom(b2), binbuf_getvec(b2));
    binbuf_free(b2);
}

/* ------------- text_fromlist object - set text from a list -------- */
t_class *text_fromlist_class;

#define t_text_fromlist t_text_client

static void *text_fromlist_new(t_symbol *s, int argc, t_atom *argv)
{
    t_text_fromlist *x = (t_text_fromlist *)pd_new(text_fromlist_class);
    text_client_argparse(x, &argc, &argv, "text fromlist");
    if (argc)
    {
        post("warning: text fromlist ignoring extra argument: ");
        postatom(argc, argv); endpost();
    }
    if (x->tc_struct)
        pointerinlet_new(&x->tc_obj, &x->tc_gp);
    else symbolinlet_new(&x->tc_obj, &x->tc_sym);
    return (x);
}

static void text_fromlist_list(t_text_fromlist *x,
    t_symbol *s, int argc, t_atom *argv)
{
    t_binbuf *b = text_client_getbuf(x);
    if (!b)
       return;
    binbuf_clear(b);
    binbuf_restore(b, argc, argv);
    text_client_senditup(x);
}

/* ---- text_search object - output index of line(s) matching criteria ---- */

t_class *text_search_class;

    /* relations we can test when searching: */
#define KB_EQ 0     /*  equal */
#define KB_GT 1     /* > (etc..) */
#define KB_GE 2
#define KB_LT 3
#define KB_LE 4
#define KB_NEAR 5   /* anything matches but closer is better */

typedef struct _key
{
    int k_field;
    int k_binop;
} t_key;

typedef struct _text_search
{
    t_text_client x_tc;
    t_outlet *x_out1;       /* line indices */
    int x_nkeys;
    t_key *x_keyvec;
} t_text_search;

static void *text_search_new(t_symbol *s, int argc, t_atom *argv)
{
    t_text_search *x = (t_text_search *)pd_new(text_search_class);
    int i, key, nkey, nextop;
    x->x_out1 = outlet_new(&x->x_obj, &s_list);
    text_client_argparse(&x->x_tc, &argc, &argv, "text search");
    for (i = nkey = 0; i < argc; i++)
        if (argv[i].a_type == A_FLOAT)
            nkey++;
    if (nkey == 0)
        nkey = 1;
    x->x_nkeys = nkey;
    x->x_keyvec = (t_key *)getbytes(nkey * sizeof(*x->x_keyvec));
    if (!argc)
        x->x_keyvec[0].k_field = 0, x->x_keyvec[0].k_binop = KB_EQ;
    else for (i = key = 0, nextop = -1; i < argc; i++)
    {
        if (argv[i].a_type == A_FLOAT)
        {
            x->x_keyvec[key].k_field =
                (argv[i].a_w.w_float > 0 ? argv[i].a_w.w_float : 0);
            x->x_keyvec[key].k_binop = (nextop >= 0 ? nextop : KB_EQ);
            nextop = -1;
            key++;
        }
        else
        {
            char *s = argv[i].a_w.w_symbol->s_name;
            if (nextop >= 0)
                pd_error(x,
                    "text search: extra operation argument ignored: %s", s);
            else if (!strcmp(argv[i].a_w.w_symbol->s_name, ">"))
                nextop = KB_GT;
            else if (!strcmp(argv[i].a_w.w_symbol->s_name, ">="))
                nextop = KB_GE;
            else if (!strcmp(argv[i].a_w.w_symbol->s_name, "<"))
                nextop = KB_LT;
            else if (!strcmp(argv[i].a_w.w_symbol->s_name, "<="))
                nextop = KB_LE;
            else if (!strcmp(argv[i].a_w.w_symbol->s_name, "near"))
                nextop = KB_NEAR;
            else pd_error(x,
                    "text search: unknown operation argument: %s", s);
        }
    }
    if (x->x_struct)
        pointerinlet_new(&x->x_obj, &x->x_gp);
    else symbolinlet_new(&x->x_obj, &x->x_tc.tc_sym);
    return (x);
}

static void text_search_list(t_text_search *x,
    t_symbol *s, int argc, t_atom *argv)
{
    t_binbuf *b = text_client_getbuf(&x->x_tc);
1338
    int i, n, lineno, bestline = -1, beststart=-1, thisstart,
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 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
        nkeys = x->x_nkeys, failed = 0;
    t_atom *vec;
    if (!b)
       return;
    if (argc < nkeys)
    {
        pd_error(x, "need %d keys, only got %d in list",
            nkeys, argc);
    }
    vec = binbuf_getvec(b);
    n = binbuf_getnatom(b);
    if (nkeys < 1)
        bug("text_search");
    for (i = lineno = thisstart = 0; i < n; i++)
    {
        if (vec[i].a_type == A_SEMI || vec[i].a_type == A_COMMA || i == n-1)
        {
            int thisn = i - thisstart, j, field = x->x_keyvec[0].k_field,
                binop = x->x_keyvec[0].k_binop;
                /* do we match? */
            for (j = 0; j < argc; )
            {
                if (field >= thisn ||
                    vec[thisstart+field].a_type != argv[j].a_type)
                        goto nomatch;
                if (argv[j].a_type == A_FLOAT)      /* arg is a float */
                {
                    switch (binop)
                    {
                        case KB_EQ:
                            if (vec[thisstart+field].a_w.w_float !=
                                argv[j].a_w.w_float)
                                    goto nomatch;
                        break;
                        case KB_GT:
                            if (vec[thisstart+field].a_w.w_float <=
                                argv[j].a_w.w_float)
                                    goto nomatch;
                        break;
                        case KB_GE:
                            if (vec[thisstart+field].a_w.w_float <
                                argv[j].a_w.w_float)
                                    goto nomatch;
                        break;
                        case KB_LT:
                            if (vec[thisstart+field].a_w.w_float >=
                                argv[j].a_w.w_float)
                                    goto nomatch;
                        break;
                        case KB_LE:
                            if (vec[thisstart+field].a_w.w_float >
                                argv[j].a_w.w_float)
                                    goto nomatch;
                        break;
                            /* the other possibility ('near') never fails */
                    }
                }
                else                                /* arg is a symbol */
                {
                    if (binop != KB_EQ)
                    {
                        if (!failed)
                        {
                            pd_error(x,
                    "text search (%s): only exact matches allowed for symbols",
                                argv[j].a_w.w_symbol->s_name);
                            failed = 1;
                        }
                        goto nomatch;
                    }
                    if (vec[thisstart+field].a_w.w_symbol !=
                        argv[j].a_w.w_symbol)
                            goto nomatch;
                }
                if (++j >= nkeys)    /* if at last key just increment field */
                    field++;
                else field = x->x_keyvec[j].k_field,    /* else next key */
                        binop = x->x_keyvec[j].k_binop;
            }
                /* the line matches.  Now, if there is a previous match, are
                we better than it? */
            if (bestline >= 0)
            {
                field = x->x_keyvec[0].k_field;
                binop = x->x_keyvec[0].k_binop;
                for (j = 0; j < argc; )
                {
                    if (field >= thisn
                        || vec[thisstart+field].a_type != argv[j].a_type)
                            bug("text search 2");
                    if (argv[j].a_type == A_FLOAT)      /* arg is a float */
                    {
                        float thisv = vec[thisstart+field].a_w.w_float,
                            bestv = (beststart >= 0 ?
                                vec[beststart+field].a_w.w_float : -1e20);
                        switch (binop)
                        {
                            case KB_GT:
                            case KB_GE:
                                if (thisv < bestv)
                                    goto replace;
                                else if (thisv > bestv)
                                    goto nomatch;
                            break;
                            case KB_LT:
                            case KB_LE:
                                if (thisv > bestv)
                                    goto replace;
                                else if (thisv < bestv)
                                    goto nomatch;
                            break;
                            case KB_NEAR:
                                if (thisv >= argv[j].a_w.w_float &&
                                    bestv >= argv[j].a_w.w_float)
                                {
                                    if (thisv < bestv)
                                        goto replace;
                                    else if (thisv > bestv)
                                        goto nomatch;
                                }
                                else if (thisv <= argv[j].a_w.w_float &&
                                    bestv <= argv[j].a_w.w_float)
                                {
                                    if (thisv > bestv)
                                        goto replace;
                                    else if (thisv < bestv)
                                        goto nomatch;
                                }
                                else
                                {
                                    float d1 = thisv - argv[j].a_w.w_float,
                                        d2 = bestv - argv[j].a_w.w_float;
                                    if (d1 < 0)
                                        d1 = -d1;
                                    if (d2 < 0)
                                        d2 = -d2;

                                    if (d1 < d2)
                                        goto replace;
                                    else if (d1 > d2)
                                        goto nomatch;
                                }
                            break;
                                /* the other possibility ('=') never decides */
                        }
                    }
                    if (++j >= nkeys)    /* last key - increment field */
                        field++;
                    else field = x->x_keyvec[j].k_field,    /* else next key */
                            binop = x->x_keyvec[j].k_binop;
                }
                goto nomatch;   /* a tie - keep the old one */
            replace:
1492
                bestline = lineno, beststart = thisstart;
1493 1494
            }
                /* no previous match so we're best */
1495
            else bestline = lineno, beststart = thisstart;
1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
        nomatch:
            lineno++;
            thisstart = i+1;
        }
    }
    outlet_float(x->x_out1, bestline);
}

/* ---------------- text_sequence object - sequencer ----------- */
t_class *text_sequence_class;

typedef struct _text_sequence
{
    t_text_client x_tc;
    t_outlet *x_mainout;    /* outlet for lists, zero if "global" */
    t_outlet *x_waitout;    /* outlet for wait times, zero if we never wait */
    t_outlet *x_endout;    /* bang when hit end */
    int x_onset;
    int x_argc;
    t_atom *x_argv;
    t_symbol *x_waitsym;    /* symbol to initiate wait, zero if none */
    int x_waitargc;         /* how many leading numbers to use for waiting */
    t_clock *x_clock;       /* calback for auto mode */
    t_float x_nextdelay;
    t_symbol *x_lastto;     /* destination symbol if we're after a comma */
    unsigned char x_eaten;  /* true if we've eaten leading numbers already */
    unsigned char x_loop;   /* true if we can send multiple lines */
    unsigned char x_auto;   /* set timer when we hit single-number time list */
} t_text_sequence;

static void text_sequence_tick(t_text_sequence *x);
static void text_sequence_tempo(t_text_sequence *x,
    t_symbol *unitname, t_floatarg tempo);
void parsetimeunits(void *x, t_float amount, t_symbol *unitname,
    t_float *unit, int *samps); /* time unit parsing from x_time.c */

static void *text_sequence_new(t_symbol *s, int argc, t_atom *argv)
{
    t_text_sequence *x = (t_text_sequence *)pd_new(text_sequence_class);
    int global = 0;
    text_client_argparse(&x->x_tc, &argc, &argv, "text sequence");
    x->x_waitsym = 0;
    x->x_waitargc = 0;
    x->x_eaten = 0;
    x->x_loop = 0;
    x->x_lastto = 0;
1542
    x->x_clock = clock_new(x, (t_method)text_sequence_tick);
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
    while (argc && argv->a_type == A_SYMBOL &&
        *argv->a_w.w_symbol->s_name == '-')
    {
        if (!strcmp(argv->a_w.w_symbol->s_name, "-w") && argc >= 2)
        {
            if (argv[1].a_type == A_SYMBOL)
            {
                x->x_waitsym = argv[1].a_w.w_symbol;
                x->x_waitargc = 0;
            }
            else
            {
                x->x_waitsym = 0;
                if ((x->x_waitargc = argv[1].a_w.w_float) < 0)
                    x->x_waitargc = 0;
            }
            argc -= 1; argv += 1;
        }
        else if (!strcmp(argv->a_w.w_symbol->s_name, "-g"))
            global = 1;
        else if (!strcmp(argv->a_w.w_symbol->s_name, "-t") && argc >= 3)
        {
            text_sequence_tempo(x, atom_getsymbolarg(2, argc, argv),
                atom_getfloatarg(1, argc, argv));
             argc -= 2; argv += 2;
        }
        else
        {
            pd_error(x, "text sequence: unknown flag '%s'...",
                argv->a_w.w_symbol->s_name);
        }
        argc--; argv++;
    }
    if (argc)
    {
        post("warning: text sequence ignoring extra argument: ");
        postatom(argc, argv); endpost();
    }
    if (x->x_tc.tc_struct)
        pointerinlet_new(&x->x_tc.tc_obj, &x->x_tc.tc_gp);
    else symbolinlet_new(&x->x_tc.tc_obj, &x->x_tc.tc_sym);
    x->x_argc = 0;
    x->x_argv = (t_atom *)getbytes(0);
    x->x_onset = 0x7fffffff;
    x->x_mainout = (!global ? outlet_new(&x->x_obj, &s_list) : 0);
    x->x_waitout = (global || x->x_waitsym || x->x_waitargc ?
        outlet_new(&x->x_obj, &s_list) : 0);
    x->x_endout = outlet_new(&x->x_obj, &s_bang);
    if (global)
    {
        if (x->x_waitargc)
            pd_error(x,
       "warning: text sequence: numeric 'w' argument ignored if '-g' given");
        x->x_waitargc = 0x40000000;
    }
    return (x);
}

static void text_sequence_doit(t_text_sequence *x, int argc, t_atom *argv)
{
1603
    t_binbuf *b = text_client_getbuf(&x->x_tc);
1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
    int n, i, onset, nfield, wait, eatsemi = 1, gotcomma = 0;
    t_atom *vec, *outvec, *ap;
    if (!b)
        goto nosequence;
    vec = binbuf_getvec(b);
    n = binbuf_getnatom(b);
    if (x->x_onset >= n)
    {
    nosequence:
        x->x_onset = 0x7fffffff;
        x->x_loop = x->x_auto = 0;
        outlet_bang(x->x_endout);
        return;
    }
    onset = x->x_onset;

        /* test if leading numbers, or a leading symbol equal to our
        "wait symbol", are directing us to wait */
    if (!x->x_lastto && (
        (vec[onset].a_type == A_FLOAT && x->x_waitargc && !x->x_eaten) ||
            (vec[onset].a_type == A_SYMBOL &&
                vec[onset].a_w.w_symbol == x->x_waitsym)))
    {
        if (vec[onset].a_type == A_FLOAT)
        {
            for (i = onset; i < n && i < onset + x->x_waitargc &&
                vec[i].a_type == A_FLOAT; i++)
                    ;
            x->x_eaten = 1;
            eatsemi = 0;
        }
        else
        {
            for (i = onset; i < n && vec[i].a_type != A_SEMI &&
                vec[i].a_type != A_COMMA; i++)
                    ;
            x->x_eaten = 1;
            onset++;    /* symbol isn't part of wait list */
        }
        wait = 1;
    }
    else    /* message to send */
    {
        for (i = onset; i < n && vec[i].a_type != A_SEMI &&
            vec[i].a_type != A_COMMA; i++)
                ;
        wait = 0;
        x->x_eaten = 0;
        if (i < n && vec[i].a_type == A_COMMA)
            gotcomma = 1;
    }
    nfield = i - onset;
    i += eatsemi;
    if (i >= n)
        i = 0x7fffffff;
    x->x_onset = i;
1660
        /* generate output list, realizing dollar sign atoms.  Allocate one
1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778