flsupport.h 48.1 KB
Newer Older
Thomas Grill's avatar
Thomas Grill committed
1 2
/*
flext - C++ layer for Max and Pure Data externals
thomas's avatar
thomas committed
3

4
Copyright (c) 2001-2017 Thomas Grill (gr@grrrr.org)
thomas's avatar
thomas committed
5
For information on usage and redistribution, and for a DISCLAIMER OF ALL
Thomas Grill's avatar
Thomas Grill committed
6
WARRANTIES, see the file, "license.txt," in this distribution.
thomas's avatar
thomas committed
7 8 9
*/

/*! \file flsupport.h
10
    \brief flext support functions and classes   
thomas's avatar
thomas committed
11 12 13 14 15 16
*/

#ifndef __FLSUPPORT_H
#define __FLSUPPORT_H

#include "flstdc.h"
thomas's avatar
thomas committed
17
#include <new>
thomas's avatar
thomas committed
18
#include <cstring>
thomas's avatar
thomas committed
19

20 21 22

#include "flpushns.h"

thomas's avatar
thomas committed
23 24 25 26 27 28
#if C74_MAX_SDK_VERSION >= 0x0610
// really bad: post and error are #defines in Max SDK >= 610
#undef post
#undef error
#endif

29 30
/*! \defgroup FLEXT_SUPPORT Flext support classes
    @{
thomas's avatar
thomas committed
31 32
*/

33 34
FLEXT_TEMPLATE class FLEXT_SHARE FLEXT_CLASSDEF(flext_root);

Thomas Grill's avatar
Thomas Grill committed
35
typedef FLEXT_TEMPINST(FLEXT_SHARE FLEXT_CLASSDEF(flext_root)) flext_root;
thomas's avatar
thomas committed
36

thomas's avatar
thomas committed
37
/*! \brief Flext root support class
thomas's avatar
thomas committed
38

thomas's avatar
thomas committed
39 40
    Moved memory functions and console output here so that all the classes
    contained in flext can use them
thomas's avatar
thomas committed
41
*/
42
FLEXT_TEMPLATE
thomas's avatar
thomas committed
43
class FLEXT_SHARE FLEXT_CLASSDEF(flext_root) {
thomas's avatar
thomas committed
44
public:
45
// --- console output -----------------------------------------------   
thomas's avatar
thomas committed
46

47 48 49 50
    //! post message to console, with line feed (limited to 1k chars!)
    static void post(const char *fmt,...);
    //! post error message to console (limited to 1k chars!)
    static void error(const char *fmt,...);
thomas's avatar
thomas committed
51

52
// --- memory -------------------------------------------------------   
thomas's avatar
thomas committed
53

54 55 56
    /*! \defgroup FLEXT_S_MEMORY Memory allocation functions
        @{ 
    */
thomas's avatar
thomas committed
57

58
#ifdef FLEXT_NOGLOBALNEW
59 60
#error FLEXT_NOGLOBALNEW is deprecated, define FLEXT_USE_CMEM instead
#define FLEXT_USE_CMEM
61 62
#endif

63
#ifdef FLEXT_USE_CMEM
64 65 66
    inline void *operator new(size_t bytes) { return ::operator new(bytes); }
    inline void operator delete(void *blk) { ::operator delete(blk); }

67 68 69
    inline void *operator new[](size_t bytes) { return ::operator new[](bytes); }
    inline void operator delete[](void *blk) { ::operator delete[](blk); }

70 71
    static bool MemCheck(void *) { return true; }
#else
72 73 74 75 76 77 78
    /*! Overloaded new memory allocation method
        \note this uses a fast allocation method of the real-time system
        \warning Max/MSP (or MacOS) allows only 32K in overdrive mode!
    */
    void *operator new(size_t bytes);
    //! Overloaded delete method
    void operator delete(void *blk);
thomas's avatar
thomas committed
79

80
#ifndef __MRC__ // doesn't allow new[] overloading?!
81 82
    inline void *operator new[](size_t bytes) { return operator new(bytes); }
    inline void operator delete[](void *blk) { operator delete(blk); }
thomas's avatar
thomas committed
83
#endif
thomas's avatar
thomas committed
84

thomas's avatar
thomas committed
85 86 87 88 89 90
#ifdef FLEXT_DEBUGMEM
    static bool MemCheck(void *blk);
#else
    static bool MemCheck(void *) { return true; }
#endif

91
#endif // USECMEM
thomas's avatar
thomas committed
92

thomas's avatar
thomas committed
93
#ifndef __BORLANDC__
94 95
    inline void *operator new(size_t,void *p) { return p; }
    inline void operator delete(void *,void *) {}
96
#ifndef __MRC__
97 98
    inline void *operator new[](size_t,void *p) { return p; }
    inline void operator delete[](void *,void *) {}
thomas's avatar
thomas committed
99 100
#endif
#endif
thomas's avatar
thomas committed
101

102 103
    //! Get an aligned memory block
    static void *NewAligned(size_t bytes,int bitalign = 128);
thomas's avatar
thomas committed
104 105 106
    // same with templated type
    template<typename T>
    static T *NewAligned(size_t times,int bitalign = 128) { return static_cast<T *>(NewAligned(times*sizeof(T),bitalign)); }
107 108 109 110
    //! Free an aligned memory block
    static void FreeAligned(void *blk);
    //! Test for alignment
    static bool IsAligned(void *ptr,int bitalign = 128) { 
thomas's avatar
thomas committed
111 112
        return (reinterpret_cast<size_t>(ptr)&(bitalign-1)) == 0; 
    }
113
    //! @}  FLEXT_S_MEMORY      
thomas's avatar
thomas committed
114 115
};

116
#ifndef FLEXT_USE_CMEM
thomas's avatar
thomas committed
117 118 119
/************************************************************************/
// MFC doesn't like global overloading of allocators
// anyway, who likes MFC
thomas's avatar
thomas committed
120

thomas's avatar
thomas committed
121
#if !defined(_MSC_VER) && !defined(__BORLANDC__)
thomas's avatar
thomas committed
122 123 124 125 126 127 128
#define NEWTHROW throw(std::bad_alloc)
#define DELTHROW throw()
#else
#define NEWTHROW
#define DELTHROW
#endif

thomas's avatar
thomas committed
129
// define global new/delete operators
130 131
inline void *operator new(size_t bytes) NEWTHROW { return flext_root::operator new(bytes); }
inline void operator delete(void *blk) DELTHROW { flext_root::operator delete(blk); }
thomas's avatar
thomas committed
132
#ifndef __MRC__ // doesn't allow new[] overloading?!
133 134
inline void *operator new[](size_t bytes) NEWTHROW { return flext_root::operator new[](bytes); }
inline void operator delete[](void *blk) DELTHROW { flext_root::operator delete[](blk); }
thomas's avatar
thomas committed
135 136
#endif

137
#endif // FLEXT_USE_CMEM
thomas's avatar
thomas committed
138

thomas's avatar
thomas committed
139
/************************************************************************/
thomas's avatar
thomas committed
140

141 142 143
FLEXT_TEMPLATE class FLEXT_SHARE FLEXT_CLASSDEF(flext);

typedef FLEXT_TEMPINST(FLEXT_CLASSDEF(flext)) flext;
thomas's avatar
thomas committed
144

145
FLEXT_TEMPLATE class FLEXT_SHARE FLEXT_CLASSDEF(flext_base);
thomas's avatar
thomas committed
146 147 148

/*! \brief Flext support class

149 150 151 152 153
    A number of methods (most are static functions) are defined here for convenience.
    This class doesn't define any data members, hence it can be inherited to all
    classes (not only PD objects) to profit from the cross-platform functionality.
    Examples are the overloaded memory allocation, atom and atom list functions,
    thread functions and classes, the sample buffer class and others.
thomas's avatar
thomas committed
154 155 156 157 158

    This class can also be used for a non-object class (not representing an external object)
    and won't give any extra burden to it.
*/

159
FLEXT_TEMPLATE
thomas's avatar
thomas committed
160
class FLEXT_SHARE FLEXT_CLASSDEF(flext):
161
    public flext_root
thomas's avatar
thomas committed
162
{
163 164 165
    /*! \defgroup FLEXT_SUPPORT Flext support class
        @{ 
    */
thomas's avatar
thomas committed
166 167
public:

168
// --- version -----------------------------------------------  
thomas's avatar
thomas committed
169 170 171 172 173 174 175

    /*! \brief Flext version number 

        Return the version number of the flext library.
        For statically linked flext this is identical to the header definition FLEXT_VERSION,
        otherwise it reflects the version number of the shared flext library.
    */
Thomas Grill's avatar
Thomas Grill committed
176
    static int Version();
thomas's avatar
thomas committed
177 178

    //! Flext version string
thomas's avatar
thomas committed
179
    static const char *VersionStr();
thomas's avatar
thomas committed
180

181
// --- special typedefs ---------------------------------------------   
thomas's avatar
thomas committed
182

thomas's avatar
thomas committed
183 184
// later!
#if 0
thomas's avatar
thomas committed
185 186 187 188 189
    typedef t_float Float;
    typedef t_int Int;
    typedef t_sample Sample;
    typedef const t_symbol *Symbol;
    typedef t_atom Atom;
thomas's avatar
thomas committed
190
#endif
thomas's avatar
thomas committed
191

192
// --- buffer/array stuff ----------------------------------------- 
thomas's avatar
thomas committed
193

194 195 196
    /*! \defgroup FLEXT_S_BUFFER Buffer handling
        @{ 
    */
thomas's avatar
thomas committed
197

198
    //! Class for platform independent buffer handling
thomas's avatar
thomas committed
199 200
    class FLEXT_SHARE buffer:
        public flext_root
201 202
    {
    public:
thomas's avatar
thomas committed
203 204 205 206 207 208 209 210
    
#if FLEXT_SYS == FLEXT_SYS_PD
        typedef bool lock_t;
#elif FLEXT_SYS == FLEXT_SYS_MAX
        typedef long lock_t;
#else
#error Not implemented
#endif
thomas's avatar
thomas committed
211 212 213 214 215 216 217 218


// PD 64-bit buffer handling macros
#if FLEXT_SYS == FLEXT_SYS_PD
#       if PD_MINOR_VERSION >= 41
                /* use new garray support that is 64-bit safe */
#               define FLEXT_PD_ARRAYGRAB garray_getfloatwords
#               define FLEXT_ARRAYTYPE t_word
thomas's avatar
thomas committed
219
#               define FLEXT_GETSAMPLE(x) ((x).w_float)
thomas's avatar
thomas committed
220 221 222 223 224

#       else
                /* use old garray support, not 64-bit safe */
#               define FLEXT_PD_ARRAYGRAB garray_getfloatarray
#               define FLEXT_ARRAYTYPE t_sample
thomas's avatar
thomas committed
225
#               define FLEXT_GETSAMPLE(x) (x)
thomas's avatar
thomas committed
226 227
#       endif

thomas's avatar
thomas committed
228
#elif FLEXT_SYS == FLEXT_SYS_MAX
229
#       define FLEXT_ARRAYTYPE float
thomas's avatar
thomas committed
230 231 232
#       define FLEXT_GETSAMPLE(x) (x)
#endif

thomas's avatar
thomas committed
233 234 235
		class Element {
		public:
			Element() {}
236 237 238
			Element(FLEXT_ARRAYTYPE s) { FLEXT_GETSAMPLE(el) = s; }
			operator FLEXT_ARRAYTYPE &() { return FLEXT_GETSAMPLE(el); }
			operator FLEXT_ARRAYTYPE () const { return FLEXT_GETSAMPLE(el); }
thomas's avatar
thomas committed
239 240 241 242
		protected:
			FLEXT_ARRAYTYPE el;
		};

243 244 245 246 247 248 249 250 251 252 253
        /*! \brief Construct buffer.
            \param s: symbol name, can be NULL
            \param delayed = true: only sets name, needs another Set(NULL) to really initialize the buffer 
            \remark As externals can be created prior to the buffer objects they are pointing to, initialization should be done at loadbang!
        */
        buffer(const t_symbol *s = NULL,bool delayed = false);
        
        //! Destroy buffer
        ~buffer();

        /*! \brief Check if the buffer is valid for use
thomas's avatar
thomas committed
254
            \note This must be true to use any of the other functions except set
255 256 257 258
        */
        bool Ok() const 
        { 
            return sym  
thomas's avatar
thomas committed
259
#if FLEXT_SYS == FLEXT_SYS_PD
260
                && arr
thomas's avatar
thomas committed
261
#endif
262 263 264 265
                && data; 
        }
        
        /*! \brief Check if buffer content is valid (not in state of content change)
thomas's avatar
thomas committed
266
            \note buffer must be Ok()
267 268
        */
        bool Valid() const
thomas's avatar
thomas committed
269 270 271 272 273 274 275 276 277 278 279
        {
            FLEXT_ASSERT(sym);
#if FLEXT_SYS == FLEXT_SYS_PD
            return true;
#elif FLEXT_SYS == FLEXT_SYS_MAX
            const t_buffer *p = (const t_buffer *)sym->s_thing;
            return p && p->b_valid;
#else
#error not implemented
#endif
        }
280 281
        
        /*! \brief Check and update if the buffer has been changed (e.g. resized)
thomas's avatar
thomas committed
282
            \note buffer must be Ok()
283 284
        */
        bool Update();
thomas's avatar
thomas committed
285
        
286
        /*! \brief Lock buffer
thomas's avatar
thomas committed
287 288
            \return previous state (needed for Unlock)
            \note buffer must be Ok()
289
        */
thomas's avatar
thomas committed
290 291
        lock_t Lock();
        
292
        /*! \brief Unlock buffer
thomas's avatar
thomas committed
293 294
            \param prv: Previous state is returned by Lock()
            \note buffer must be Ok()
295
        */
thomas's avatar
thomas committed
296
        void Unlock(lock_t prv);
297 298 299
        
        /*! \brief Set to specified buffer.
            \param nameonly: if true sets name only, but doesn't look at buffer actually
thomas's avatar
thomas committed
300
            \return -1 on failure, 0 on success, 1 if parameters (length, data ptr, channels) have changed
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
        */
        int Set(const t_symbol *s = NULL,bool nameonly = false);
        
        /*! \brief Declare buffer content as dirty.
            \param refr: if true forces immediate graphics refresh
        */
        void Dirty(bool refr = false);

        //! Clear the dirty flag.
        void ClearDirty();

        /*! Query whether the buffer content has been changed since the last ClearDirty()
            \note With mainstream versions of PD this will always return true, since the dirtiness can't be judged
        */
        bool IsDirty() const;

        //! Get symbol of buffer 
        const t_symbol *Symbol() const { return sym; }

        //! Get literal name of buffer 
        const char *Name() const { return sym?GetString(sym):""; }
        
        /*! \brief Get pointer to buffer, channel and frame count.
            \remark Channels are interleaved
        */
thomas's avatar
thomas committed
326 327 328
        Element *Data() { return data; }

    	const Element *Data() const { return data; }
329 330 331 332 333 334 335

        //! Get channel count
        int Channels() const { return chns; }
        //! Get frame count
        int Frames() const { return frames; }
        //! Set frame count
        void Frames(int fr,bool keep = false,bool zero = true);
thomas's avatar
thomas committed
336 337

        //! Get data value in a platform-independent way
338
        inline FLEXT_ARRAYTYPE operator [](int index) const { return data[index]; }
thomas's avatar
thomas committed
339 340

        //! Reference data value in a platform-independent way
341
        inline FLEXT_ARRAYTYPE &operator [](int index) { return data[index]; }
342 343 344 345
        
        //! Graphic auto refresh interval
        void SetRefrIntv(float intv);

thomas's avatar
thomas committed
346 347 348 349 350 351 352 353 354 355 356
        //! Buffer locking class
        class Locker
        {
        public:
            Locker(buffer &b): buf(b),lock(b.Lock()) {}
            ~Locker() { buf.Unlock(lock); }
        private:
            buffer &buf;
            lock_t lock;
        };

357
    protected:
thomas's avatar
thomas committed
358
        //! buffer name
359
        const t_symbol *sym;
thomas's avatar
thomas committed
360
        //! array holding audio data
thomas's avatar
thomas committed
361
        Element *data;
thomas's avatar
thomas committed
362
        //! number of audio channels
363
        int chns;
thomas's avatar
thomas committed
364 365
        //! number of frames (multiplied by chns for the number of samples)
        int frames;
thomas's avatar
thomas committed
366
#if FLEXT_SYS == FLEXT_SYS_PD
thomas's avatar
thomas committed
367
        //! pointer to the PD array structure
368
        t_garray *arr;
thomas's avatar
thomas committed
369
        //! update interval
370
        float interval;
thomas's avatar
thomas committed
371
        //! flag signaling that the data has been changed
372
        bool isdirty;
thomas's avatar
thomas committed
373 374 375
        //! flag showing that the update clock is active
        bool ticking;
        //! update clock
376 377 378
        t_clock *tick;
        //! last time the dirty flag was cleared (using the clock_getlogicaltime function)
        double cleantime;
thomas's avatar
thomas committed
379

380
    private:
thomas's avatar
thomas committed
381
        //! update clock callback
382
        static void cb_tick(buffer *b);
thomas's avatar
thomas committed
383
#elif FLEXT_SYS == FLEXT_SYS_MAX
384 385
        //! last time the dirty flag was cleared (using the gettime function)
        long cleantime;
thomas's avatar
thomas committed
386
#endif
387
    };
thomas's avatar
thomas committed
388 389


390
//!     @} FLEXT_S_BUFFER
thomas's avatar
thomas committed
391 392 393

// --- utilities --------------------------------------------------

394 395 396
    /*! \defgroup FLEXT_S_UTIL Utility functions
        @{ 
    */
thomas's avatar
thomas committed
397

398 399
    //! Copy an atom
    static void CopyAtom(t_atom *dst,const t_atom *src) { *dst = *src; }
thomas's avatar
thomas committed
400

401 402
    //! Copy atoms
    static void CopyAtoms(int cnt,t_atom *dst,const t_atom *src);
403

404 405
    //! Print an atom
    static bool PrintAtom(const t_atom &a,char *buf,size_t bufsz);
thomas's avatar
thomas committed
406

407
    /*! Scan an atom until whitespace
thomas's avatar
thomas committed
408 409
        \return next token position, or NULL on failure
    */
410
    static const char *ScanAtom(t_atom &a,const char *buf);
thomas's avatar
thomas committed
411

412 413
    //! Copy a list of atoms
    static t_atom *CopyList(int argc,const t_atom *argv);
thomas's avatar
thomas committed
414
    
415 416
    //! Print an atom list
    static bool PrintList(int argc,const t_atom *argv,char *buf,size_t bufsz);
thomas's avatar
thomas committed
417 418 419 420 421 422 423
    
    /*! Scan an atom list
        \param argc ... maximum amount of atoms scanned
        \param argv ... array of atoms
        \param buf ... char buffer
    */
    static int ScanList(int argc,t_atom *argv,const char *buf);
thomas's avatar
thomas committed
424

425 426 427 428
    //! Copy a memory region
    static void CopyMem(void *dst,const void *src,int bytes);
    //! Copy a sample array
    static void CopySamples(t_sample *dst,const t_sample *src,int cnt);
429
    template<typename T> static void CopySamples(T *dst,const T *src,int cnt) { CopyMem(dst,src,sizeof(*src)*cnt); }
430 431 432 433
    //! Set a memory region
    static void ZeroMem(void *dst,int bytes);
    //! Set a sample array to a fixed value
    static void SetSamples(t_sample *dst,int cnt,t_sample s);
434
    template<typename T> static void SetSamples(T *dst,int cnt,t_sample s) { for(int i = 0; i < cnt; ++i) dst[i] = s; }
435 436
    //! Set a sample array to 0
    static void ZeroSamples(t_sample *dst,int cnt) { SetSamples(dst,cnt,0); }   
437
    template<typename T> static void ZeroSamples(T *dst,int cnt) { ZeroMem(dst,sizeof(*dst)*cnt); }
thomas's avatar
thomas committed
438 439


440 441
    //! Get a 32 bit hash value from an atom
    static unsigned long AtomHash(const t_atom &a);
thomas's avatar
thomas committed
442

443
//!     @} FLEXT_S_UTIL
thomas's avatar
thomas committed
444 445 446

// --- various symbols --------------------------------------------

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
    /*! \defgroup FLEXT_S_ATOM Atom/list handling
        @{ 
    */

    //! Symbol constant for ""
    static const t_symbol *sym__;
    //! Symbol constant for "float"
    static const t_symbol *sym_float;
    //! Symbol constant for "symbol"
    static const t_symbol *sym_symbol;
    //! Symbol constant for "bang"
    static const t_symbol *sym_bang;
    //! Symbol constant for "list"
    static const t_symbol *sym_list;
    //! Symbol constant for "anything"
    static const t_symbol *sym_anything;

    /*! \brief Symbol constant for "int"
        \note Only the Max/MSP system has this defined as an internal type
    */
    static const t_symbol *sym_int;

    /*! Symbol constant for "pointer" 
        \note Only PD has this defined as an internal type
    */
    static const t_symbol *sym_pointer;

    //! Symbol constant for "signal"
    static const t_symbol *sym_signal;
thomas's avatar
thomas committed
476

thomas's avatar
thomas committed
477
    //! \note This is used in macros where the type of the arg is not clear
478
    static const t_symbol *MakeSymbol(const t_symbol *s) { return s; }
thomas's avatar
thomas committed
479

480 481 482 483 484 485
    //! Make a symbol from a string
    static const t_symbol *MakeSymbol(const char *s) { return ::gensym(const_cast<char *>(s)); }
    //! Get symbol string
    static const char *GetString(const t_symbol *s) { return s->s_name; }  
    //! Check for symbol and get string
    static const char *GetAString(const t_symbol *s,const char *def = NULL) { return s?GetString(s):def; }
thomas's avatar
thomas committed
486 487

// --- atom stuff ----------------------------------------
488 489 490 491 492
        
    //! Set atom from another atom
    static void SetAtom(t_atom &a,const t_atom &b) { CopyAtom(&a,&b); }
    //! Compare two atoms
    static int CmpAtom(const t_atom &a,const t_atom &b);
thomas's avatar
thomas committed
493

494
    // there are some more comparison functions for t_atom types outside the class
thomas's avatar
thomas committed
495

496 497
    //! Set atom from another atom
    static int GetType(const t_atom &a) { return a.a_type; }
thomas's avatar
thomas committed
498

499 500 501 502
    //! Check whether the atom is nothing
    static bool IsNothing(const t_atom &a) { return a.a_type == A_NULL; }
    //! Set the atom to represent nothing
    static void SetNothing(t_atom &a) { a.a_type = A_NULL; }
thomas's avatar
thomas committed
503

504 505
    //! Check whether the atom is a float
    static bool IsFloat(const t_atom &a) { return a.a_type == A_FLOAT; }
thomas's avatar
thomas committed
506

507 508
    //! Check whether the atom can be represented as a float
    static bool CanbeFloat(const t_atom &a) { return IsFloat(a) || IsInt(a); }
thomas's avatar
thomas committed
509

510 511 512 513
    //! Access the float value (without type check)
    static float GetFloat(const t_atom &a) { return a.a_w.w_float; }
    //! Set the atom to represent a float 
    static void SetFloat(t_atom &a,float v) { a.a_type = A_FLOAT; a.a_w.w_float = v; }
thomas's avatar
thomas committed
514

515 516
    //! Check whether the atom is a symbol
    static bool IsSymbol(const t_atom &a) { return a.a_type == A_SYMBOL; }
thomas's avatar
thomas committed
517 518

#if FLEXT_SYS == FLEXT_SYS_PD
519 520 521 522
    //! Access the symbol value (without type check)
    static const t_symbol *GetSymbol(const t_atom &a) { return const_cast<const t_symbol *>(a.a_w.w_symbol); }
    //! Set the atom to represent a symbol
    static void SetSymbol(t_atom &a,const t_symbol *s) { a.a_type = A_SYMBOL; a.a_w.w_symbol = const_cast<t_symbol *>(s); }
thomas's avatar
thomas committed
523
#elif FLEXT_SYS == FLEXT_SYS_MAX
524 525 526 527
    //! Access the symbol value (without type check)
    static const t_symbol *GetSymbol(const t_atom &a) { return const_cast<const t_symbol *>(a.a_w.w_sym); }
    //! Set the atom to represent a symbol
    static void SetSymbol(t_atom &a,const t_symbol *s) { a.a_type = A_SYMBOL; a.a_w.w_sym = const_cast<t_symbol *>(s); }
thomas's avatar
thomas committed
528 529 530
#else
#error
#endif
531 532 533 534 535 536 537 538
    //! Check for a symbol and get its value 
    static const t_symbol *GetASymbol(const t_atom &a,const t_symbol *def = NULL) { return IsSymbol(a)?GetSymbol(a):def; }  // NULL or empty symbol?

    //! Check whether the atom is a string
    static bool IsString(const t_atom &a) { return IsSymbol(a); }
    //! Access the string value (without type check)
    static const char *GetString(const t_atom &a) { const t_symbol *s = GetSymbol(a); return s?GetString(s):NULL; }  
    //! Check for a string and get its value 
539
    static const char *GetAString(const t_atom &a,const char *def = NULL) { return IsSymbol(a)?GetAString(GetSymbol(a),def):def; }
540 541 542 543
    //! Check for a string and get its value 
    static void GetAString(const t_atom &a,char *buf,size_t szbuf);
    //! Set the atom to represent a string
    static void SetString(t_atom &a,const char *c) { SetSymbol(a,MakeSymbol(c)); }
thomas's avatar
thomas committed
544

545 546
    //! Check whether the atom can be represented as an integer
    static bool CanbeInt(const t_atom &a) { return IsFloat(a) || IsInt(a); }
thomas's avatar
thomas committed
547 548

#if FLEXT_SYS == FLEXT_SYS_PD
549 550 551 552 553 554 555 556 557 558 559
    //! Check for a float and get its value 
    static float GetAFloat(const t_atom &a,float def = 0) { return IsFloat(a)?GetFloat(a):def; }

    //! Check whether the atom is an integer
    static bool IsInt(const t_atom &) { return false; }
    //! Access the integer value (without type check)
    static int GetInt(const t_atom &a) { return (int)GetFloat(a); }
    //! Check for an integer and get its value 
    static int GetAInt(const t_atom &a,int def = 0) { return (int)GetAFloat(a,(float)def); }
    //! Set the atom to represent a integer (depending on the system)
    static void SetInt(t_atom &a,int v) { a.a_type = A_FLOAT; a.a_w.w_float = (float)v; }
thomas's avatar
thomas committed
560

561
#ifndef FLEXT_COMPATIBLE
562 563 564 565 566 567 568 569 570 571
    //! Check whether the atom strictly is a pointer
    static bool IsPointer(const t_atom &a) { return a.a_type == A_POINTER; }
    //! Check whether the atom can be a pointer
    static bool CanbePointer(const t_atom &a) { return IsPointer(a); }
    //! Access the pointer value (without type check)
    static t_gpointer *GetPointer(const t_atom &a) { return a.a_w.w_gpointer; }
    //! Check for a pointer and get its value 
    static t_gpointer *GetAPointer(const t_atom &a,t_gpointer *def = NULL) { return IsPointer(a)?GetPointer(a):def; }
    //! Set the atom to represent a pointer
    static void SetPointer(t_atom &a,t_gpointer *p) { a.a_type = A_POINTER; a.a_w.w_gpointer = (t_gpointer *)p; }
572
#endif
thomas's avatar
thomas committed
573 574

#elif FLEXT_SYS == FLEXT_SYS_MAX
575 576 577 578 579 580 581 582 583 584 585
    //! Check for a float and get its value 
    static float GetAFloat(const t_atom &a,float def = 0) { return IsFloat(a)?GetFloat(a):(IsInt(a)?GetInt(a):def); }

    //! Check whether the atom is an int
    static bool IsInt(const t_atom &a) { return a.a_type == A_INT; }
    //! Access the integer value (without type check)
    static int GetInt(const t_atom &a) { return a.a_w.w_long; }
    //! Check for an integer and get its value 
    static int GetAInt(const t_atom &a,int def = 0) { return IsInt(a)?GetInt(a):(IsFloat(a)?(int)GetFloat(a):def); }
    //! Set the atom to represent an integer
    static void SetInt(t_atom &a,int v) { a.a_type = A_INT; a.a_w.w_long = v; }
thomas's avatar
thomas committed
586 587 588 589
#else
#error "Platform not supported"
#endif

590 591 592 593 594 595 596 597 598 599
    // bool type - based on int

    //! Set the atom to represent a boolean
    static void SetBool(t_atom &a,bool v) { SetInt(a,v?1:0); }
    //! Check whether the atom can be represented as a boolean
    static bool CanbeBool(const t_atom &a) { return CanbeInt(a); }
    //! Check for an boolean and get its value 
    static bool GetABool(const t_atom &a) { return GetAInt(a) != 0; }
    //! Check for an boolean and get its value 
    static bool GetBool(const t_atom &a) { return GetInt(a) != 0; }
600

thomas's avatar
thomas committed
601 602
// --- atom list stuff -------------------------------------------

603
    //! Class representing a list of atoms
604 605
    class FLEXT_SHARE AtomList
        : public flext_root
606 607 608
    {
    public:
        //! Construct list
609
        AtomList(): cnt(0),lst(NULL) {}
610
        //! Construct list
611
        explicit AtomList(int argc,const t_atom *argv = NULL): cnt(0),lst(NULL) { operator()(argc,argv); }
612
        //! Construct list
613
        AtomList(const AtomList &a): cnt(0),lst(NULL) { operator =(a); }
614
        //! Destroy list
615
        virtual ~AtomList();
thomas's avatar
thomas committed
616

617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
        //! Clear list
        AtomList &Clear() { return operator()(); }

        //! Set list
        AtomList &Set(int argc,const t_atom *argv,int offs = 0,bool resize = false);
        //! Get list
        int Get(t_atom *argv,int mxsz = -1) const;

        //! Set list
        AtomList &operator()(int argc = 0,const t_atom *argv = NULL) { return Set(argc,argv,0,true); }
        //! Set list by another AtomList
        AtomList &operator =(const AtomList &a) { return operator()(a.Count(),a.Atoms()); }

        //! Compare list to another AtomList ( -1..< , 0..==, 1...> )
        int Compare(const AtomList &a) const;

        bool operator <(const AtomList &a) const { return Compare(a) < 0; }
        bool operator <=(const AtomList &a) const { return Compare(a) <= 0; }
        bool operator >(const AtomList &a) const { return Compare(a) > 0; }
        bool operator >=(const AtomList &a) const { return Compare(a) >= 0; }
        bool operator ==(const AtomList &a) const { return Compare(a) == 0; }
        bool operator !=(const AtomList &a) const { return Compare(a) != 0; }

        //! Get number of atoms in the list
        int Count() const { return cnt; }
        //! Get a reference to an indexed atom
        t_atom &operator [](int ix) { return lst[ix]; }
        //! Get a reference to an indexed atom
        const t_atom &operator [](int ix) const { return lst[ix]; }

        //! Get a pointer to the list of atoms
        t_atom *Atoms() { return lst; }
        //! Get a pointer to the list of atoms
        const t_atom *Atoms() const { return lst; }

        //! Append an atom list to the list
        AtomList &Append(int argc,const t_atom *argv = NULL)
thomas's avatar
thomas committed
654 655 656 657 658 659 660
        {
            int c = Count();
            Alloc(c+argc,0,c);
            Set(argc,argv,c);
            return *this;
        }

661 662
        //! Prepend an atom list to the list
        AtomList &Prepend(int argc,const t_atom *argv = NULL)
thomas's avatar
thomas committed
663 664 665 666 667 668 669
        {
            int c = Count();
            Alloc(c+argc,0,c,argc);
            Set(argc,argv);
            return *this;
        }

670
        //! Append an atom to the list
thomas's avatar
thomas committed
671 672
        AtomList &Append(const t_atom &a) { return Append(1,&a); }
        //! Append an atom list to the list
673 674 675 676 677
        AtomList &Append(const AtomList &a) { return Append(a.Count(),a.Atoms()); }
        //! Prepend an atom to the list
        AtomList &Prepend(const t_atom &a) { return Prepend(1,&a); }
        //! Prepend an atom list to the list
        AtomList &Prepend(const AtomList &a) { return Prepend(a.Count(),a.Atoms()); }
thomas's avatar
thomas committed
678

679 680 681 682
        //! Get a part of the list
        void GetPart(int offs,int len,AtomList &ret) const;
        //! Set to a part of the list
        AtomList &Part(int offs,int len) { GetPart(offs,len,*this); return *this; }
thomas's avatar
thomas committed
683

684 685
        //! Represent as a string
        bool Print(char *buffer,int buflen) const { return flext::PrintList(Count(),Atoms(),buffer,buflen); }
thomas's avatar
thomas committed
686

thomas's avatar
thomas committed
687 688 689 690 691
        /*! Read from string
            \note: doesn't clear or reallocate the list
        */
        int Scan(const char *buffer) { return flext::ScanList(Count(),Atoms(),buffer); }

692
    protected:
thomas's avatar
thomas committed
693
        virtual void Alloc(int sz,int keepix = -1,int keeplen = -1,int keepto = 0);
694 695
        virtual void Free();

696 697 698
        int cnt;
        t_atom *lst;
    };
thomas's avatar
thomas committed
699

700 701 702 703
    class FLEXT_SHARE AtomListStaticBase
        : public AtomList
    {
    protected:
thomas's avatar
thomas committed
704
        explicit AtomListStaticBase(int pc,t_atom *dt): precnt(pc),predata(dt) {}
705
        virtual ~AtomListStaticBase();
thomas's avatar
thomas committed
706
        virtual void Alloc(int sz,int keepix = -1,int keeplen = -1,int keepto = 0);
707 708
        virtual void Free();

thomas's avatar
thomas committed
709
        AtomListStaticBase &operator =(const AtomList &a) { AtomList::operator =(a); return *this; }
thomas's avatar
thomas committed
710
        AtomListStaticBase &operator =(const AtomListStaticBase &a) { AtomList::operator =(a); return *this; }
thomas's avatar
thomas committed
711

712 713 714 715 716
        const int precnt;
        t_atom *const predata;
    };

    template<int PRE>
thomas's avatar
thomas committed
717
    class AtomListStatic
718 719 720
        : public AtomListStaticBase
    {
    public:
721
        //! Construct list
thomas's avatar
thomas committed
722
        explicit AtomListStatic(): AtomListStaticBase(PRE,pre) {}
723
        //! Construct list
724
        explicit AtomListStatic(int argc,const t_atom *argv = NULL): AtomListStaticBase(PRE,pre) { AtomList::operator()(argc,argv); }
725
        //! Construct list
thomas's avatar
thomas committed
726
        explicit AtomListStatic(const AtomList &a): AtomListStaticBase(PRE,pre) { operator =(a); }
thomas's avatar
thomas committed
727

728
        //! Set list by another AtomList
thomas's avatar
thomas committed
729
        AtomListStatic &operator =(const AtomList &a) { AtomListStaticBase::operator =(a); return *this; }
thomas's avatar
thomas committed
730
        AtomListStatic &operator =(const AtomListStatic &a) { AtomListStaticBase::operator =(a); return *this; }
731 732 733
    protected:
        t_atom pre[PRE];
    };
thomas's avatar
thomas committed
734

735 736 737 738 739
    //! Class representing an "anything"
    class FLEXT_SHARE AtomAnything: 
        public AtomList
    {
    public:
thomas's avatar
thomas committed
740
        explicit AtomAnything(): hdr(NULL) {}
thomas's avatar
thomas committed
741 742

        //! Construct anything
743
        explicit AtomAnything(const t_symbol *h,int argc = 0,const t_atom *argv = NULL)
744 745
            : AtomList(argc,argv),hdr(h?h:sym__) 
        {}
thomas's avatar
thomas committed
746 747

        //! Construct anything
748
        explicit AtomAnything(const char *h,int argc = 0,const t_atom *argv = NULL)
749 750 751
            : AtomList(argc,argv),hdr(MakeSymbol(h)) 
        {}

752 753
        //! Construct anything
        AtomAnything(const AtomAnything &a)
754 755
            : AtomList(a),hdr(a.hdr) 
        {}
thomas's avatar
thomas committed
756

757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
        //! Clear anything
        AtomAnything &Clear() { return operator()(); }

        //! Get header symbol of anything
        const t_symbol *Header() const { return hdr; }

        //! Set header symbol of anything
        void Header(const t_symbol *h) { hdr = h; }
        
        //! Set anything
        AtomAnything &operator()(const t_symbol *h = NULL,int argc = 0,const t_atom *argv = NULL)
        { 
            hdr = h; AtomList::operator()(argc,argv);   
            return *this; 
        }

        //! Set list by another AtomAnything
        AtomAnything &operator =(const AtomAnything &a) { return operator()(a.Header(),a.Count(),a.Atoms()); }

    protected:
        const t_symbol *hdr;
    };

thomas's avatar
thomas committed
780

781
    // double type - based on two floats
thomas's avatar
thomas committed
782

783 784 785 786 787 788 789 790 791 792 793 794 795 796
#ifdef _MSC_VER
#pragma optimize("p",off)  // improve floating point precision consistency
#endif
    static t_atom *SetDouble(t_atom *dbl,double d)
    {
        float f = static_cast<float>(d);
        float r = static_cast<float>(d-f);
        SetFloat(dbl[0],f);
        SetFloat(dbl[1],r);
        return dbl;
    }
#ifdef _MSC_VER
#pragma optimize("p",on)
#endif
thomas's avatar
thomas committed
797

798 799 800 801 802
    static double GetDouble(int argc,const t_atom *argv)
    {
        double d = argc >= 1?GetAFloat(argv[0]):0;
        return argc >= 2?d+GetAFloat(argv[1]):d;
    }
thomas's avatar
thomas committed
803

804
    static AtomList &SetDouble(AtomList &l,double d) { SetDouble(l(2).Atoms(),d); return l; }
thomas's avatar
thomas committed
805

806
    static double GetDouble(const AtomList &l) { return GetDouble(l.Count(),l.Atoms()); }
thomas's avatar
thomas committed
807

808
    //! @} FLEXT_S_ATOM
thomas's avatar
thomas committed
809 810


811
// --- messages ------------------------------------------------------- 
thomas's avatar
thomas committed
812

813 814 815
    /*! \defgroup FLEXT_S_MSGBUNDLE Flext message handling 
        @{ 
    */
thomas's avatar
thomas committed
816

817 818 819 820 821 822 823 824 825 826 827 828 829
    class MsgBundle;

    //! Make new message bundle
    static MsgBundle *MsgNew();

    //! Destroy message bundle
    static void MsgFree(MsgBundle *mb);

    //! Send (and destroy) message bundle
    static void ToSysMsg(MsgBundle *mb);

    //! Send (and destroy) message bundle
    static void ToOutMsg(MsgBundle *mb);
830

831 832
    //! Send low priority (and destroy) message bundle
    static void ToQueueMsg(MsgBundle *mb);
thomas's avatar
thomas committed
833

834
    //! @} FLEXT_S_MSGBUNDLE
thomas's avatar
thomas committed
835 836


837 838 839
    /*! \defgroup FLEXT_S_MSG Flext message handling 
        @{ 
    */
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

    static bool Forward(const t_symbol *sym,const t_symbol *s,int argc,const t_atom *argv);
    static bool Forward(const t_symbol *sym,const AtomAnything &args) { return Forward(sym,args.Header(),args.Count(),args.Atoms()); }
    static bool Forward(const char *sym,const AtomAnything &args) { return Forward(MakeSymbol(sym),args.Header(),args.Count(),args.Atoms()); }
    static bool Forward(const t_symbol *sym,int argc,const t_atom *argv) { return Forward(sym,sym_list,argc,argv); }
    static bool Forward(const t_symbol *sym,const AtomList &args) { return Forward(sym,args.Count(),args.Atoms()); }
    static bool Forward(const char *sym,const AtomList &args) { return Forward(MakeSymbol(sym),args.Count(),args.Atoms()); }

    static bool SysForward(const t_symbol *sym,const t_symbol *s,int argc,const t_atom *argv);
    static bool SysForward(const t_symbol *sym,const AtomAnything &args) { return SysForward(sym,args.Header(),args.Count(),args.Atoms()); }
    static bool SysForward(const char *sym,const AtomAnything &args) { return SysForward(MakeSymbol(sym),args.Header(),args.Count(),args.Atoms()); }
    static bool SysForward(const t_symbol *sym,int argc,const t_atom *argv) { return SysForward(sym,sym_list,argc,argv); }
    static bool SysForward(const t_symbol *sym,const AtomList &args) { return SysForward(sym,args.Count(),args.Atoms()); }
    static bool SysForward(const char *sym,const AtomList &args) { return SysForward(MakeSymbol(sym),args.Count(),args.Atoms()); }

    static bool QueueForward(const t_symbol *sym,const t_symbol *s,int argc,const t_atom *argv);
    static bool QueueForward(const t_symbol *sym,const AtomAnything &args) { return QueueForward(sym,args.Header(),args.Count(),args.Atoms()); }
    static bool QueueForward(const char *sym,const AtomAnything &args) { return QueueForward(MakeSymbol(sym),args.Header(),args.Count(),args.Atoms()); }
    static bool QueueForward(const t_symbol *sym,int argc,const t_atom *argv) { return QueueForward(sym,sym_list,argc,argv); }
    static bool QueueForward(const t_symbol *sym,const AtomList &args) { return QueueForward(sym,args.Count(),args.Atoms()); }
    static bool QueueForward(const char *sym,const AtomList &args) { return QueueForward(MakeSymbol(sym),args.Count(),args.Atoms()); }

    static bool MsgForward(MsgBundle *mb,const t_symbol *sym,const t_symbol *s,int argc,const t_atom *argv);
    static bool MsgForward(MsgBundle *mb,const t_symbol *sym,const AtomAnything &args) { return MsgForward(mb,sym,args.Header(),args.Count(),args.Atoms()); }
    static bool MsgForward(MsgBundle *mb,const char *sym,const AtomAnything &args) { return MsgForward(mb,MakeSymbol(sym),args.Header(),args.Count(),args.Atoms()); }
    static bool MsgForward(MsgBundle *mb,const t_symbol *sym,int argc,const t_atom *argv) { return MsgForward(mb,sym,sym_list,argc,argv); }
    static bool MsgForward(MsgBundle *mb,const t_symbol *sym,const AtomList &args) { return MsgForward(mb,sym,args.Count(),args.Atoms()); }
    static bool MsgForward(MsgBundle *mb,const char *sym,const AtomList &args) { return MsgForward(mb,MakeSymbol(sym),args.Count(),args.Atoms()); }

    //! @} FLEXT_S_MSG
thomas's avatar
thomas committed
870 871

    
thomas's avatar
thomas committed
872 873 874

// --- thread stuff -----------------------------------------------

875 876 877
    /*! \defgroup FLEXT_S_LOCK Global system locking
        @{ 
    */
thomas's avatar
thomas committed
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895

#if FLEXT_SYS == FLEXT_SYS_PD
    #if PD_MINOR_VERSION >= 38 || (PD_MINOR_VERSION >= 37 && defined(PD_DEVEL_VERSION))
        static void Lock() { sys_lock(); }
        static void Unlock() { sys_unlock(); }
    #else
        // no system locking for old PD versions
        static void Lock() {}
        static void Unlock() {}
    #endif
#elif FLEXT_SYS == FLEXT_SYS_MAX
    // Max 4.2 upwards!
    static void Lock() { critical_enter(0); }
    static void Unlock() { critical_exit(0); }
#else
#error
#endif

896
//!     @} FLEXT_S_LOCK
thomas's avatar
thomas committed
897

898 899 900
    /*! \defgroup FLEXT_S_THREAD Flext thread handling 
        @{ 
    */
thomas's avatar
thomas committed
901

thomas's avatar
thomas committed
902
    //! Check if current thread is registered to be a secondary thread
thomas's avatar
thomas committed
903
#ifdef FLEXT_THREADS
904
    static bool IsThreadRegistered();
thomas's avatar
thomas committed
905
#else
906
    static bool IsThreadRegistered() { return false; }
thomas's avatar
thomas committed
907 908 909 910
#endif

#ifdef FLEXT_THREADS

911 912 913 914 915 916
    //! thread type
#   if FLEXT_THREADS == FLEXT_THR_MP
    typedef MPTaskID thrid_t;
#   elif FLEXT_THREADS == FLEXT_THR_POSIX
    typedef pthread_t thrid_t;
#   elif FLEXT_THREADS == FLEXT_THR_WIN32
thomas's avatar
thomas committed
917
    typedef DWORD thrid_t;