[PD-cvs] externals/tclpd COPYING, NONE, 1.1 Makefile, NONE, 1.1 README, NONE, 1.1 config.h, NONE, 1.1 list_change.tcl, NONE, 1.1 pdlib.tcl, NONE, 1.1 tcl.i, NONE, 1.1 tcl_extras.cxx, NONE, 1.1 tcl_extras.h, NONE, 1.1 tcl_loader.cxx, NONE, 1.1

Federico Ferri federico__ at users.sourceforge.net
Tue Sep 18 19:19:05 CEST 2007


Update of /cvsroot/pure-data/externals/tclpd
In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv4266/tclpd

Added Files:
	COPYING Makefile README config.h list_change.tcl pdlib.tcl 
	tcl.i tcl_extras.cxx tcl_extras.h tcl_loader.cxx 
Log Message:
first commit for tclpd external


--- NEW FILE: config.h ---
#ifndef __CONFIG_H
#define __CONFIG_H
#include <tcl.h>
#endif /* __CONFIG_H */

--- NEW FILE: pdlib.tcl ---
# TCL objectized library for PD api
# by Federico Ferri <mescalinum at gmail.com> - 2007

package provide pdlib 0.1

package require Tcl 8.5

set verbose 0

namespace eval ::pd {

    proc add_inlet {self sel} {
        if $::verbose {post [info level 0]}
        variable _
        switch -- $sel {
            float {
                set ptr [new_t_float]
                lappend _($self:p_inlet) $ptr
                lappend _($self:x_inlet) [floatinlet_new [tclpd_get_object $self] $ptr]
            }
            symbol {
                set ptr [new_t_symbol]
                lappend _($self:p_inlet) $ptr
                lappend _($self:x_inlet) [symbolinlet_new [tclpd_get_object $self] $ptr]
            }
            default {
                post "inlet creation error: unsupported selector: $sel"
                return {}
            }
        }
        return [lindex $_($self:x_inlet) end]
    }

    proc inlet {self n} {
        if {$::verbose} {post [info level 0]}
        if {$n <= 0} {return {}}
        if {![info exists _($self:p_inlet)] ||
            $n >= [llength $_($self:p_inlet)]} {
            return -code error "pdlib: error: no such inlet: $n"
        }
        variable _
        return [[lindex $_($self:p_inlet) [expr $n-1]] value]
    }

    proc add_outlet {self sel} {
        if $::verbose {post [info level 0]}
        variable _
        switch -- $sel {
            float {
                lappend _($self:x_outlet) \
                    [outlet_new [tclpd_get_object $self] [gensym "float"]]
            }
            symbol {
                lappend _($self:x_outlet) \
                    [outlet_new [tclpd_get_object $self] [gensym "symbol"]]
            }
            list {
                lappend _($self:x_outlet) \
                    [outlet_new [tclpd_get_object $self] [gensym "list"]]
            }
            default {
                return -code error \
                "pdlib: outlet creation error: unsupported selector: $sel"
            }
        }
        return [lindex $_($self:x_outlet) end]
    }

    proc outlet {self n sel args} {
        if $::verbose {post [info level 0]}
        variable _
        set outlet [lindex $_($self:x_outlet) $n]
        switch -- $sel {
            float {
                set v [lindex $args 0]
                outlet_float $outlet $v
            }
            symbol {
                set v [lindex $args 0]
                outlet_symbol $outlet $v
            }
            list {
                set v [lindex $args 0]
                set sz [llength $v]
                set aa [new_atom_array $sz]
                for {set i 0} {$i < $sz} {incr i} {
                    set_atom_array $aa $i [lindex $v $i]
                }
                outlet_list $outlet [gensym "list"] $sz $aa
                delete_atom_array $aa $sz
            }
            bang {
                outlet_bang $outlet
            }
            default {
                return -code error "pdlib: outlet: unknown selector: $sel"
            }
        }
    }

    proc create_iolets {cn self} {
        if $::verbose {post [info level 0]}
        variable class_db
        variable _
        set _($self:p_inlet) {}
        set _($self:x_inlet) {}
        set _($self:x_outlet) {}
        for {set i 0} {$i < [llength $class_db($cn:d_inlet)]} {incr i} {
            add_inlet $self [lindex $class_db($cn:d_inlet) $i]
        }
        for {set i 0} {$i < [llength $class_db($cn:d_outlet)]} {incr i} {
            add_outlet $self [lindex $class_db($cn:d_outlet) $i]
        }
    }

    proc call_classmethod {classname self sel args} {
        if $::verbose {post [info level 0]}
        set m "${classname}_${sel}"
        if {[llength [info commands "::$m"]] > 0} {
            return [$m $self {*}$args]
        }
    }

    proc class {classname def} {
        variable class_db
        array set class_db {}
        set class_db($classname:d_inlet) {}
        set class_db($classname:d_outlet) {}
        set def2 [regsub -all -line {#.*$} $def {}]
        foreach {id arg} $def2 {
            switch -- $id {
                inlet {
                    lappend class_db($classname:d_inlet) $arg
                }
                outlet {
                    lappend class_db($classname:d_outlet) $arg
                }
                default {
                    proc ::${classname}_${id} {self args} \
                        "global _; [expand_macros $arg]"
                }
            }
        }

        proc ::$classname {self args} "
            ::pd::create_iolets $classname \$self
            ::pd::call_classmethod $classname \$self constructor {*}\$args
            proc ::\$self {selector args} \"
             ::pd::call_classmethod $classname \$self \\\$selector {*}\\\$args
            \"
            return \$self
        "

        tclpd_class_new $classname 3
    }

    proc expand_macros {body} {
        # from poe.tcl by Mathieu Bouchard
        return [regsub -all @(\\\$?\[\\w\\?\]+) $body _(\$self:\\1)]
    }

    proc post {args} {
        poststring2 [concat {*}$args]
    }

    proc assert= {a b} {
        if {$a != $b} {
            post "ASSERTION FAILED: \"$a\" == \"$b\""
            return 0
        }
        return 1
    }

    proc args {} {
        return [uplevel 1 "llength \$args"]
    }

    proc arg_float {n} {
        set v [uplevel 1 "lindex \$args $n"]
        foreach {selector value} $v {break}
        assert= $selector "float"
        return $value
    }

    proc arg_int {n} {
        set v [uplevel 1 "lindex \$args $n"]
        foreach {selector value} $v {break}
        assert= $selector "float"
        return [expr {int($value)}]
    }

    proc arg_symbol {n} {
        set v [uplevel 1 "lindex \$args $n"]
        foreach {selector value} $v {break}
        assert= $selector "symbol"
        return $value
    }

}


--- NEW FILE: Makefile ---
#!/usr/bin/make

CPU=athlon-xp
CFLAGS += -I/usr/include -I. -xc++ -funroll-loops -fno-operator-names -fno-omit-frame-pointer -falign-functions=16 -mtune=$(CPU) -march=$(CPU) -Wall -Wno-unused -Wunused-variable -Wno-strict-aliasing -g -fPIC -I.
LDSOFLAGS += -lm -L/usr/lib -ltcl8.5 -L/usr/X11R6/lib
CXX = g++
OS = linux
LDSHARED = $(CXX) $(PDBUNDLEFLAGS)

all:: tcl

clean::
	rm -f tcl.pd_linux tcl_wrap.cxx *.o *~

.SUFFIXES:

ifeq ($(OS),darwin)
  PDSUF = .pd_darwin
  PDBUNDLEFLAGS = -bundle -flat_namespace -undefined suppress
else
  ifeq ($(OS),nt)
    PDSUF = .dll
    PDBUNDLEFLAGS = -shared
  else
    PDSUF = .pd_linux
    PDBUNDLEFLAGS = -shared -rdynamic
  endif
endif

tcl:: tcl.pd_linux

tcl.pd_linux: tcl_wrap.cxx tcl_extras.cxx tcl_loader.cxx tcl_extras.h Makefile
	$(LDSHARED) $(CFLAGS) -DPDSUF=\"$(PDSUF)\" -o tcl$(PDSUF) \
		tcl_wrap.cxx tcl_extras.cxx tcl_loader.cxx $(LDSOFLAGS)

tcl_wrap.cxx: tcl.i tcl_extras.h
	swig -v -c++ -tcl -o tcl_wrap.cxx -I/usr/include -I/usr/local/include tcl.i


--- NEW FILE: list_change.tcl ---
source pdlib.tcl

pd::class list_change {
#    inlet float
    outlet list
#    outlet float

    constructor {
        if [pd::args] {
            set n [pd::arg_int 0]
            for {set i 0} {$i < $n} {incr i} {
                pd::add_inlet $self float
            }
        }
        set @curlist {}
    }

    0_list {
        set newlist $args
        if {$newlist != $@curlist} {
            pd::outlet $self 0 list $newlist
        }
        set @curlist $newlist

        pd::outlet $self 1 float [pd::inlet $self 1]
    }

    0_bang {
        pd::post "right value is: [pd::inlet $self 1]"
    }
}


--- NEW FILE: tcl_extras.h ---
#include "m_pd.h"
#include <tcl.h>

typedef struct t_tcl {
  t_object o;
  Tcl_Obj *self;
} t_tcl;

void         poststring2          (const char* s);

t_class*     tclpd_class_new      (char* name, int flags);
t_pd*        tclpd_get_instance   (const char* cereal);
t_object*    tclpd_get_object     (const char* cereal);
t_pd*        tclpd_get_object_pd  (const char* cereal);

int          pd_to_tcl            (t_atom* input, Tcl_Obj** output);
int          tcl_to_pd            (Tcl_Obj* input, t_atom* output);

extern Tcl_Interp *tcl_for_pd;

/* tcl loader */
typedef int (*loader_t)(t_canvas *canvas, char *classname);
extern "C" void sys_register_loader(loader_t loader);
extern "C" int sys_onloadlist(char *classname);
extern "C" void sys_putonloadlist(char *classname);
extern "C" void class_set_extern_dir(t_symbol *s);
extern "C" int tclpd_do_load_lib    (t_canvas *canvas, char *objectname);


--- NEW FILE: COPYING ---
		    GNU GENERAL PUBLIC LICENSE
		       Version 2, June 1991

 Copyright (C) 1989, 1991 Free Software Foundation, Inc.
                       59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

			    Preamble

  The licenses for most software are designed to take away your
freedom to share and change it.  By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users.  This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it.  (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.)  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.

  To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have.  You must make sure that they, too, receive or can get the
source code.  And you must show them these terms so they know their
rights.

  We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.

  Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software.  If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.

  Finally, any free program is threatened constantly by software
patents.  We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary.  To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.

  The precise terms and conditions for copying, distribution and
modification follow.

		    GNU GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License.  The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language.  (Hereinafter, translation is included without limitation in
the term "modification".)  Each licensee is addressed as "you".

Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.

  1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.

You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.

  2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

    a) You must cause the modified files to carry prominent notices
    stating that you changed the files and the date of any change.

    b) You must cause any work that you distribute or publish, that in
    whole or in part contains or is derived from the Program or any
    part thereof, to be licensed as a whole at no charge to all third
    parties under the terms of this License.

    c) If the modified program normally reads commands interactively
    when run, you must cause it, when started running for such
    interactive use in the most ordinary way, to print or display an
    announcement including an appropriate copyright notice and a
    notice that there is no warranty (or else, saying that you provide
    a warranty) and that users may redistribute the program under
    these conditions, and telling the user how to view a copy of this
    License.  (Exception: if the Program itself is interactive but
    does not normally print such an announcement, your work based on
    the Program is not required to print an announcement.)

These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.

In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

  3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:

    a) Accompany it with the complete corresponding machine-readable
    source code, which must be distributed under the terms of Sections
    1 and 2 above on a medium customarily used for software interchange; or,

    b) Accompany it with a written offer, valid for at least three
    years, to give any third party, for a charge no more than your
    cost of physically performing source distribution, a complete
    machine-readable copy of the corresponding source code, to be
    distributed under the terms of Sections 1 and 2 above on a medium
    customarily used for software interchange; or,

    c) Accompany it with the information you received as to the offer
    to distribute corresponding source code.  (This alternative is
    allowed only for noncommercial distribution and only if you
    received the program in object code or executable form with such
    an offer, in accord with Subsection b above.)

The source code for a work means the preferred form of the work for
making modifications to it.  For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable.  However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.

If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.

  4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License.  Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.

  5. You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Program or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.

  6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.

  7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all.  For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.

If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

  8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded.  In such case, this License incorporates
the limitation as if written in the body of this License.

  9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

Each version is given a distinguishing version number.  If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation.  If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.

  10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission.  For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this.  Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.

			    NO WARRANTY

  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.

  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.

		     END OF TERMS AND CONDITIONS

--- NEW FILE: README ---

 Tcl for Pd
 ==========

this library allows you to to write externals for Pd using the
Tcl language. despite tot/toxy/widget externals, Tcl code ran
with tclpd actually runs in server (rather than gui process).

this is a PRE-ALPHA release: it means something work, but don't
expect to do serious things right now. also expect changes to
the Tcl API and around.


 Data conversion between Tcl <=> Pd
 ==================================

In pd exists 'atoms'. An atom is a float, a symbol, a list item,
and such.
Tcl does not have data types. In Tcl everything is a string,
also numbers and lists. Just when something needs to be read as
number, then evaluation comes in.
This leads to loss of information about atom types. Imagine a
symbol '456' comes into tclpd, you won't know anymore if "456"
is a symbol or a float.

Here a little convention comes in action: in tclpd an atom gets
converted to a two-item list, where first item is atom type,
and second item is its value.

Some examples of conversion:

 Pd:  456
 Tcl: {float 456}

 Pd:  symbol foo
 Tcl: {symbol foo}

 Pd:  list cat dog 123 456 weee
 Tcl: {{symbol cat} {symbol dog} {float 123} {float 456} {symbol wee}}


 Examples
 ========

I provided small examples.
after loading pd with option '-lib tcl', just type the filename
(minus the .tcl extension) to load the Tcl externals examples.

actually there is one simple example: list_change (behaves like
[change] object, but work with lists only)

examples make use of pdlib.tcl, a little API I wrote to make
things more cute.
you are free to not use it (just look in pdlib.tcl to know what
happens for real) or better: YOU ARE ENCOURAGED to write an OOP
system for writing externals with tclpd.


 Authors
 =======

 * Federico Ferri <mescalinum at gmail.com>
 * Mathieu Bouchard <matju at artengine.ca>


 License
 =======

See COPYING file provided with the package.



--- NEW FILE: tcl_extras.cxx ---
#include "tcl_extras.h"
#include <map>
#include <string>

using namespace std;

static long cereal=0;
map<string,t_class*> class_table;
map<string,t_pd*> object_table;

void poststring2 (const char *s) {post("%s",s);}

static void *tclpd_init (t_symbol *classsym, int ac, t_atom *at) {
  const char *name = classsym->s_name;
  t_class *qlass = class_table[string(name)];
  t_tcl *self = (t_tcl *)pd_new(qlass);
  char s[32];
  sprintf(s,"pd%06lx",cereal++);
  self->self = Tcl_NewStringObj(s,strlen(s));
  object_table[string(s)] = (t_pd*)self;
  Tcl_IncrRefCount(self->self);
  Tcl_Obj *av[ac+2];
  av[0] = Tcl_NewStringObj(name,strlen(name));
  av[1] = self->self;
  for(int i=0; i<ac; i++) {
    if(pd_to_tcl(&at[i], &av[2+i]) == TCL_ERROR) {
      post("tcl error: %s\n", Tcl_GetString(Tcl_GetObjResult(tcl_for_pd)));
      pd_free((t_pd *)self);
      return 0;
    }
  }
  if (Tcl_EvalObjv(tcl_for_pd,ac+2,av,0) != TCL_OK) {
    post("tcl error: %s\n", Tcl_GetString(Tcl_GetObjResult(tcl_for_pd)));
    pd_free((t_pd *)self);
    return 0;
  }
  return self;
}

t_pd* tclpd_get_instance(const char* cereal) {
  return object_table[cereal];
}

t_object* tclpd_get_object(const char* cereal) {
  t_tcl* x = (t_tcl*)tclpd_get_instance(cereal);
  return &x->o;
}

t_pd* tclpd_get_object_pd(const char* cereal) {
  t_object* o = tclpd_get_object(cereal);
  return &o->ob_pd;
}

static void tclpd_anything (t_tcl *self, t_symbol *s, int ac, t_atom *at) {
  /* proxy method */
  Tcl_Obj *av[ac+2];
  av[0] = self->self;
  av[1] = Tcl_NewIntObj(0); // TODO: 0 -> outlet_number
  Tcl_AppendToObj(av[1],"_",1);
  Tcl_AppendToObj(av[1],s->s_name,strlen(s->s_name)); // selector
  for(int i=0; i<ac; i++) {
    if(pd_to_tcl(&at[i], &av[2+i]) == TCL_ERROR) {
      post("tcl error: %s\n", Tcl_GetString(Tcl_GetObjResult(tcl_for_pd)));
      return;
    }
  }
  if (Tcl_EvalObjv(tcl_for_pd,ac+2,av,0) != TCL_OK)
    post("tcl error: %s\n", Tcl_GetString(Tcl_GetObjResult(tcl_for_pd)));
}

static void tclpd_free (t_tcl *self) {
  post("tclpd_free called");
}

t_class *tclpd_class_new (char *name, int flags) {
  t_class *qlass = class_new(gensym(name), (t_newmethod) tclpd_init,
    (t_method) tclpd_free, sizeof(t_tcl), flags, A_GIMME, A_NULL);
  class_table[string(name)] = qlass;
  class_addanything(qlass,tclpd_anything);
  return qlass;
}

--- NEW FILE: tcl.i ---
%module tclpd
%include exception.i
%include cpointer.i

/* functions that are in m_pd.h but don't exist in modern versions of pd */
%ignore pd_getfilename;
%ignore pd_getdirname;
%ignore pd_anything;
%ignore class_parentwidget;
%ignore sys_isreadablefile;
%ignore garray_get;
%ignore c_extern;
%ignore c_addmess;

/* functions that are only in Miller's pd, not in devel_0_39/DesireData */
%ignore sys_idlehook;

/* functions that are not supported by DesireData */
%ignore class_getpropertiesfn;
%ignore class_setpropertiesfn;
%ignore class_getwidget;
%ignore class_setwidget;
%ignore sys_fontwidth;
%ignore sys_fontheight;
%ignore sys_queuegui;
%ignore sys_unqueuegui;
%ignore sys_pretendguibytes;
%ignore class_setparentwidget;
%ignore pd_getparentwidget;
%ignore getzbytes;
%ignore gfxstub_new;
%ignore gfxstub_deleteforkey;
%ignore glist_grab;

/* functions that we can't auto-wrap, because they have varargs */
%ignore post;
%ignore class_new;

/* end of ignore-list */

%include "m_pd.h"
%include "tcl_extras.h"

%{
#include "m_pd.h"

typedef t_atom t_atom_array;
%}

%name(outlet_list) EXTERN void outlet_list(t_outlet *x, t_symbol *s, int argc, t_atom_array *argv);

%pointer_class(t_float, t_float)
%pointer_class(t_symbol, t_symbol)

%{
#include "tcl_extras.h"

#include <unistd.h>
#include "config.h"

Tcl_Interp *tcl_for_pd = 0;

extern "C" SWIGEXPORT int Tclpd_SafeInit(Tcl_Interp *interp);

extern "C" void tcl_setup (void) {
  /* Pd initialization */

  if (tcl_for_pd) {
    post("Tcl: already loaded");
    return;
  }
  post("Tcl external v0.1-alpha - 09.2007");
  post("by Federico Ferri <mescalinum at gmail.com>, Mathieu Bouchard <matju at artengine.ca>");
  tcl_for_pd = Tcl_CreateInterp();
  Tcl_Init(tcl_for_pd);
  Tclpd_SafeInit(tcl_for_pd);

  char *dirname   = new char[242];
  char *dirresult = new char[242];
  /* nameresult is only a pointer in dirresult space so don't delete[] it. */
  char *nameresult;
  if (getcwd(dirname,242)<0) {post("AAAARRRRGGGGHHHH!"); exit(69);}
  int       fd=open_via_path(dirname,"gridflow/tcl",PDSUF,dirresult,&nameresult,242,1);
  if (fd<0) fd=open_via_path(dirname,         "tcl",PDSUF,dirresult,&nameresult,242,1);
  if (fd>=0) {
    close(fd);
  } else {
    post("%s was not found via the -path!","tcl"PDSUF);
  }
  Tcl_SetVar(tcl_for_pd,"DIR",dirresult,0);
  Tcl_Eval(tcl_for_pd,"set auto_path [concat [list $DIR/.. $DIR $DIR/optional/rblti] $auto_path]");

  if (Tcl_Eval(tcl_for_pd,"source $DIR/tcl.tcl") == TCL_OK)
    post("Tcl: loaded %s/tcl.tcl", dirresult);

  if (Tcl_Eval(tcl_for_pd,"source $env(HOME)/.pd.tcl") == TCL_OK)
    post("Tcl: loaded ~/.pd.tcl");

  delete[] dirresult;
  delete[] dirname;

  post("Tcl: registering tcl loader");
  sys_register_loader(tclpd_do_load_lib);
}

int tcl_to_pd(Tcl_Obj *input, t_atom *output) {
  int llength;
  if(Tcl_ListObjLength(tcl_for_pd, input, &llength) == TCL_ERROR)
    return TCL_ERROR;
  if(llength != 2)
    /*SWIG_exception(SWIG_ValueError, "Bad t_atom: expeting a 2-elements list.");*/
    return TCL_ERROR;

  int i;
  Tcl_Obj* obj[2];
  for(i = 0; i < 2; i++) Tcl_ListObjIndex(tcl_for_pd, input, i, &obj[i]);
  char* argv0 = Tcl_GetStringFromObj(obj[0], 0);

  if(strcmp(argv0, "float") == 0) {
    double dbl;
    if(Tcl_GetDoubleFromObj(tcl_for_pd, obj[1], &dbl) == TCL_ERROR)
      return TCL_ERROR;
    SETFLOAT(output, dbl);
  } else if(strcmp(argv0, "symbol") == 0) {
    SETSYMBOL(output, gensym(Tcl_GetStringFromObj(obj[1], 0)));
  } else if(strcmp(argv0, "pointer") == 0) {
    // TODO:
  }
  return TCL_OK;
}

int pd_to_tcl(t_atom *input, Tcl_Obj **output) {
  Tcl_Obj* tcl_t_atom[2];
  /*post("pd_to_tcl got an atom of type %d (%s)",
    input->a_type, input->a_type == A_FLOAT ? "A_FLOAT" :
    input->a_type == A_SYMBOL ? "A_SYMBOL" :
    input->a_type == A_POINTER ? "A_POINTER" : "?");*/
  switch (input->a_type) {
    case A_FLOAT: {
      tcl_t_atom[0] = Tcl_NewStringObj("float", -1);
      tcl_t_atom[1] = Tcl_NewDoubleObj(input->a_w.w_float);
      break;
    }
    case A_SYMBOL: {
      tcl_t_atom[0] = Tcl_NewStringObj("symbol", -1);
      tcl_t_atom[1] = Tcl_NewStringObj(input->a_w.w_symbol->s_name, strlen(input->a_w.w_symbol->s_name));
      break;
    }
    case A_POINTER: {
      tcl_t_atom[0] = Tcl_NewStringObj("pointer", -1);
      tcl_t_atom[1] = Tcl_NewDoubleObj((long)input->a_w.w_gpointer);
      break;
    }
    default: {
      tcl_t_atom[0] = Tcl_NewStringObj("?", -1);
      tcl_t_atom[1] = Tcl_NewStringObj("", 0);
      break;
    }
  }
  *output = Tcl_NewListObj(2, &tcl_t_atom[0]);
  return TCL_OK;
}

%}

%typemap(in) t_atom * {
  t_atom *a = (t_atom*)getbytes(sizeof(t_atom));
  if(tcl_to_pd($input, a) == TCL_ERROR)
    return TCL_ERROR;
  $1 = a;
}

%typemap(freearg) t_atom * {
  freebytes($1, sizeof(t_atom));
}

%typemap(out) t_atom* {
  Tcl_Obj* res_obj;
  if(pd_to_tcl($1, &res_obj) == TCL_ERROR)
    return TCL_ERROR;
  Tcl_SetObjResult(tcl_for_pd, res_obj);
}

/* helper functions for t_atom arrays */
%inline %{
t_atom_array *new_atom_array(int size) {
  return (t_atom_array*)getbytes(size*sizeof(t_atom));
}
void delete_atom_array(t_atom_array *a, int size) {
  freebytes(a, size*sizeof(t_atom));
}
t_atom* get_atom_array(t_atom_array *a, int index) {
  return &a[index];
}
void set_atom_array(t_atom_array *a, int index, t_atom *n) {
  memcpy(&a[index], n, sizeof(t_atom));
}
%}



--- NEW FILE: tcl_loader.cxx ---
#include "tcl_extras.h"
#include <string.h>
#include <unistd.h>

extern "C" int tclpd_do_load_lib(t_canvas *canvas, char *objectname)
{
    char filename[MAXPDSTRING], dirbuf[MAXPDSTRING],
        *classname, *nameptr;
    int fd;
    if (classname = strrchr(objectname, '/'))
        classname++;
    else classname = objectname;
    if (sys_onloadlist(objectname))
    {
        post("%s: already loaded", objectname);
        return (1);
    }
        /* try looking in the path for (objectname).(tcl) ... */
    if ((fd = canvas_open(canvas, objectname, ".tcl",
        dirbuf, &nameptr, MAXPDSTRING, 1)) >= 0)
            goto gotone;
        /* next try (objectname)/(classname).(sys_dllextent) ... */
    strncpy(filename, objectname, MAXPDSTRING);
    filename[MAXPDSTRING-2] = 0;
    strcat(filename, "/");
    strncat(filename, classname, MAXPDSTRING-strlen(filename));
    filename[MAXPDSTRING-1] = 0;
    if ((fd = canvas_open(canvas, filename, ".tcl",
        dirbuf, &nameptr, MAXPDSTRING, 1)) >= 0)
            goto gotone;
    //post("Tcl_loader: tried and failed");
    return (0);
gotone:
    close(fd);
    class_set_extern_dir(gensym(dirbuf));
        /* rebuild the absolute pathname */
    strncpy(filename, dirbuf, MAXPDSTRING);
    filename[MAXPDSTRING-2] = 0;
    strcat(filename, "/");
    strncat(filename, nameptr, MAXPDSTRING-strlen(filename));
    filename[MAXPDSTRING-1] = 0;

    // load tcl:
    char b[MAXPDSTRING+10];
    snprintf(&b[0], MAXPDSTRING+10, "source %s", filename);
    if (Tcl_Eval(tcl_for_pd,b) == TCL_OK)
        post("Tcl_loader: loaded %s", b);
    else
        post("Tcl_loader: error trying to load %s", b);

    class_set_extern_dir(&s_);
    sys_putonloadlist(objectname);
    return (1);
}






More information about the Pd-cvs mailing list