source: cpp/frams/param/param.cpp @ 704

Last change on this file since 704 was 704, checked in by Maciej Komosinski, 7 years ago

ParamInterface::getText() improved: removed pointless iteration when no ~enum is present (caused major performance hit for big integer values)

  • Property svn:eol-style set to native
File size: 30.0 KB
Line 
1// This file is a part of Framsticks SDK.  http://www.framsticks.com/
2// Copyright (C) 1999-2017  Maciej Komosinski and Szymon Ulatowski.
3// See LICENSE.txt for details.
4
5#include <stdio.h>
6#include <ctype.h>
7
8#include "param.h"
9#include <frams/util/extvalue.h>
10#include "common/log.h"
11#include <frams/util/sstringutils.h>
12
13//#define SAVE_ALL_NAMES
14#define SAVE_SELECTED_NAMES
15#define WARN_MISSING_NAME
16
17char MakeCodeGuardHappy;
18
19ParamEntry empty_paramtab[] =
20{ { "Empty", 1, 0, "Empty", }, { 0, 0, 0, }, };
21
22/** return: true if tilde was found, false if finished at EOF */
23static bool readUntilTilde(VirtFILE *f, SString &s)
24{
25        SString temp;
26        int z;
27        char last_char = 0;
28        bool tilde_found = false;
29        while ((z = f->Vgetc()) != EOF)
30        {
31                if (z == '~')
32                        if (last_char != '\\') { tilde_found = true; break; }
33                last_char = (char)z;
34                temp += last_char;
35        }
36        s = temp;
37        return tilde_found;
38}
39
40static const char *strchrlimit(const char *t, int ch, const char *limit)
41{
42        if (limit < t) return NULL;
43        return (const char*)memchr((const void*)t, ch, limit - t);
44}
45
46void ParamInterface::copyFrom(ParamInterface *src)
47{
48        int n = getPropCount();
49        ExtValue v;
50        int j;
51        for (int i = 0; i < n; i++)
52                if ((!(flags(i)&PARAM_READONLY))
53                        && (*type(i) != 'p'))
54                {
55                j = src->findId(id(i));
56                if (j < 0) continue;
57                src->get(j, v);
58                set(i, v);
59                }
60}
61
62void ParamInterface::quickCopyFrom(ParamInterface *src)
63{
64        int n = getPropCount();
65        ExtValue v;
66        for (int i = 0; i < n; i++)
67                if ((!(flags(i)&PARAM_READONLY))
68                        && (*type(i) != 'p'))
69                {
70                src->get(i, v);
71                set(i, v);
72                }
73}
74
75int ParamInterface::getMinMax(int prop, paInt& minumum, paInt& maximum, paInt &def)
76{
77        return getMinMax(type(prop), minumum, maximum, def);
78}
79
80int ParamInterface::getMinMax(int prop, double& minumum, double& maximum, double& def)
81{
82        return getMinMax(type(prop), minumum, maximum, def);
83}
84
85int ParamInterface::getMinMax(int prop, int& minumum, int& maximum, SString& def)
86{
87        return getMinMax(type(prop), minumum, maximum, def);
88}
89
90int ParamInterface::getMinMax(const char* t, paInt& minumum, paInt& maximum, paInt &def)
91{
92        while (*t) if (*t == ' ') break; else t++;
93        return sscanf(t, PA_INT_SCANF " " PA_INT_SCANF " " PA_INT_SCANF, &minumum, &maximum, &def);
94}
95
96int ParamInterface::getMinMax(const char* t, double& minumum, double& maximum, double& def)
97{
98        while (*t) if (*t == ' ') break; else t++;
99        return sscanf(t, "%lg %lg %lg", &minumum, &maximum, &def);
100}
101
102int ParamInterface::getMinMax(const char* t, int& minumum, int& maximum, SString& def)
103{
104        while (*t) if (*t == ' ') break; else t++;
105        int ret = sscanf(t, "%d %d", &minumum, &maximum);
106        def = SString::empty();
107        if (ret == 2)
108        {
109                while (*t == ' ') t++;
110                for (int skip_fields = 2; skip_fields > 0; skip_fields--)
111                {
112                        while (*t) if (*t == ' ') break; else t++;
113                        while (*t == ' ') t++;
114                }
115                if (*t)
116                {
117                        const char* end = strchr(t, '~');
118                        if (!end)
119                                end = t + strlen(t);
120                        while ((end > t) && (end[-1] == ' ')) end--;
121                        def = SString(t, end - t);
122                }
123                return 3;
124        }
125        else
126                return ret;
127}
128
129void ParamInterface::setDefault()
130{
131        for (int i = 0; i < getPropCount(); i++)
132                setDefault(i);
133}
134
135void ParamInterface::setMin()
136{
137        for (int i = 0; i < getPropCount(); i++)
138                setMin(i);
139}
140
141void ParamInterface::setMax()
142{
143        for (int i = 0; i < getPropCount(); i++)
144                setMax(i);
145}
146
147void ParamInterface::setDefault(int i)
148{
149        const char *t = type(i);
150        switch (*t)
151        {
152        case 'f':
153        {
154                double mn = 0, mx = 0, def = 0;
155                if (getMinMax(t, mn, mx, def) < 3) def = mn;
156                setDouble(i, def);
157        }
158                break;
159        case 'd':
160        {
161                paInt mn = 0, mx = 0, def = 0;
162                if (getMinMax(t, mn, mx, def) < 3) def = mn;
163                setInt(i, def);
164        }
165                break;
166        case 's': case 'x':
167        {
168                int mn, mx; SString def;
169                getMinMax(t, mn, mx, def);
170                if (*t == 's')
171                        setString(i, def);
172                else
173                {
174                        if (def.len() > 0) setExtValue(i, ExtValue(def)); else setExtValue(i, ExtValue::empty());
175                }
176        }
177                break;
178        case 'o':
179                setObject(i, ExtObject::empty());
180                break;
181        }
182}
183
184void ParamInterface::setMin(int i)
185{
186        const char *t = type(i);
187        switch (*t)
188        {
189        case 'f':
190        {
191                double mn = 0, mx = 0, def = 0;
192                getMinMax(t, mn, mx, def);
193                setDouble(i, mn);
194        }
195                break;
196        case 'd':
197        {
198                paInt mn = 0, mx = 0, def = 0;
199                getMinMax(t, mn, mx, def);
200                setInt(i, mn);
201        }
202                break;
203        default: set(i, "");
204        }
205}
206
207void ParamInterface::setMax(int i)
208{
209        const char *t = type(i);
210        switch (*t)
211        {
212        case 'f':
213        {
214                double mn = 0, mx = 0, def = 0;
215                getMinMax(t, mn, mx, def);
216                setDouble(i, mx);
217        }
218                break;
219        case 'd':
220        {
221                paInt mn = 0, mx = 0, def = 0;
222                getMinMax(t, mn, mx, def);
223                setInt(i, mx);
224        }
225                break;
226        default: set(i, "");
227        }
228}
229
230SString ParamInterface::getStringById(const char*prop)
231{
232        int i = findId(prop); if (i >= 0) return getString(i); else return SString();
233}
234paInt ParamInterface::getIntById(const char*prop)
235{
236        int i = findId(prop); if (i >= 0) return getInt(i); else return 0;
237}
238double ParamInterface::getDoubleById(const char*prop)
239{
240        int i = findId(prop); if (i >= 0) return getDouble(i); else return 0;
241}
242ExtObject ParamInterface::getObjectById(const char*prop)
243{
244        int i = findId(prop); if (i >= 0) return getObject(i); else return ExtObject();
245}
246ExtValue ParamInterface::getExtValueById(const char*prop)
247{
248        int i = findId(prop); if (i >= 0) return getExtValue(i); else return ExtValue();
249}
250
251int ParamInterface::setIntById(const char* prop, paInt v)
252{
253        int i = findId(prop); if (i >= 0) return setInt(i, v); else return PSET_NOPROPERTY;
254}
255int ParamInterface::setDoubleById(const char* prop, double v)
256{
257        int i = findId(prop); if (i >= 0) return setDouble(i, v); else return PSET_NOPROPERTY;
258}
259int ParamInterface::setStringById(const char* prop, const SString &v)
260{
261        int i = findId(prop); if (i >= 0) return setString(i, v); else return PSET_NOPROPERTY;
262}
263int ParamInterface::setObjectById(const char* prop, const ExtObject &v)
264{
265        int i = findId(prop); if (i >= 0) return setObject(i, v); else return PSET_NOPROPERTY;
266}
267int ParamInterface::setExtValueById(const char* prop, const ExtValue &v)
268{
269        int i = findId(prop); if (i >= 0) return setExtValue(i, v); else return PSET_NOPROPERTY;
270}
271int ParamInterface::setById(const char* prop, const ExtValue &v)
272{
273        int i = findId(prop); if (i >= 0) return set(i, v); else return PSET_NOPROPERTY;
274}
275
276int ParamInterface::save(VirtFILE* f, const char* altname, bool force)
277{
278        const char *p;
279        SString ws;
280        int err = 0, i;
281        bool withname = false;
282        if ((altname == NULL) || (altname[0] != 0))
283        {
284                err |= (f->Vputs(altname ? altname : getName()) == EOF);
285                err |= (f->Vputs(":\n") == EOF);
286                withname = true;
287        }
288        for (i = 0; p = id(i); i++)
289                err |= saveprop(f, i, p, force);
290        if (withname)
291                err |= (f->Vputs("\n") == EOF);
292        return err;
293}
294
295const char* ParamInterface::SERIALIZATION_PREFIX = "@Serialized:";
296
297int ParamInterface::saveprop(VirtFILE* f, int i, const char* p, bool force)
298{
299        if ((flags(i)&PARAM_DONTSAVE) && (!force)) return 0;
300        const char *typ = type(i);
301        if (*typ == 'p') return 0;
302
303        const char *t, *w;
304        SString ws;
305        int err = 0, cr;
306
307        err |= (f->Vputs(p) == EOF); f->Vputc(':');
308        cr = 0;
309        if ((*typ == 'x') || (*typ == 'o'))
310        {
311                ExtValue ex;
312                get(i, ex);
313                ws = SString(SERIALIZATION_PREFIX) + ex.serialize(NativeSerialization);
314        }
315        else
316                ws = get(i);
317        quoteTilde(ws);
318        w = ws.c_str();
319        if (ws.len() > 50) cr = 1;
320        else for (t = w; *t; t++) if ((*t == 10) || (*t == 13)) { cr = 1; break; }
321        if (cr) f->Vputs("~\n");
322        err |= (f->Vputs(w) == EOF);
323        err |= (f->Vputs(cr ? "~\n" : "\n") == EOF);
324        return err;
325}
326
327
328int SimpleAbstractParam::isequal(int i, void* defdata)
329{ // defdata->member == object->member ?
330        void *backup = object;
331        switch (type(i)[0])
332        {
333        case 'd':
334        {
335                select(defdata);
336                paInt x = getInt(i);
337                select(backup);
338                return x == getInt(i);
339        }
340        case 'f':
341        {
342                select(defdata);
343                double x = getDouble(i);
344                select(backup);
345                return x == getDouble(i);
346        }
347        case 's':
348        {
349                select(defdata);
350                SString x = getString(i);
351                select(backup);
352                return x == getString(i);
353        }
354        }
355        return 1;
356}
357
358void SimpleAbstractParam::save2(SString& f, void *defdata, bool addcr, bool all_names)
359{ // defdata!=NULL -> does not save default values
360        const char *p;
361        int i;
362        int needlabel = 0;
363        int first = 1;
364        SString val;
365        SString t;
366        int fl;
367        // t+=SString(getName()); t+=':';
368        for (i = 0; p = id(i); i++)
369                if (!((fl = flags(i))&PARAM_DONTSAVE))
370                {
371                if (defdata && isequal(i, defdata))
372                        needlabel = 1;
373                else
374                {
375                        if (!first) t += ", ";
376#ifndef SAVE_ALL_NAMES
377#ifdef SAVE_SELECTED_NAMES
378                        if (needlabel || all_names || !(fl & PARAM_CANOMITNAME))
379#else
380                        if (needlabel)
381#endif
382#endif
383                        {
384                                t += p; t += "="; needlabel = 0;
385                        }
386                        if (type(i)[0] == 's')
387                        { // string - special case
388                                SString str = getString(i);
389                                if (strContainsOneOf(str.c_str(), ", \\\n\r\t\""))
390                                {
391                                        t += "\"";
392                                        sstringQuote(str);
393                                        t += str;
394                                        t += "\"";
395                                }
396                                else
397                                        t += str;
398                        }
399                        else
400                                t += get(i);
401                        first = 0;
402                }
403                }
404        if (addcr)
405                t += "\n";
406        f += t;
407}
408
409static void closingTildeError(ParamInterface *pi, VirtFILE *file, int field_index)
410{
411        SString fileinfo;
412        const char* fname = file->VgetPath();
413        if (fname != NULL)
414                fileinfo = SString::sprintf(" while reading from '%s'", fname);
415        SString field;
416        if (field_index >= 0)
417                field = SString::sprintf("'%s.%s'", pi->getName(), pi->id(field_index));
418        else
419                field = SString::sprintf("unknown property of '%s'", pi->getName());
420        logPrintf("ParamInterface", "load", LOG_WARN, "Closing '~' (tilde) not found in %s%s", field.c_str(), fileinfo.c_str());
421}
422
423int ParamInterface::load(VirtFILE* f, bool warn_unknown_fields, bool *abortable, int *linenum)
424{
425        SString buf;
426        int i;
427        const char *p, *p0;
428        int p_len;
429        bool loaded;
430        int fields_loaded = 0;
431        int unexpected_line = 0;
432        vector<bool> seen;
433        seen.resize(getPropCount());
434        if ((i = findId("beforeLoad")) >= 0)
435                call(i, NULL, NULL);
436        while (((!abortable) || (!*abortable)) && loadSStringLine(f, buf))
437        {
438                if (linenum) (*linenum)++;
439                const char* t = buf.c_str();
440                p0 = t; while (isblank(*p0)) p0++;
441                if (!*p0) break;
442                if (p0[0] == '#') { unexpected_line = 0; continue; }
443                p = strchr(p0, ':');
444                if (!p)
445                {
446                        switch (unexpected_line)
447                        {
448                        case 0:
449                                logPrintf("ParamInterface", "load", LOG_WARN, "Ignored unexpected line %s while reading object '%s'",
450                                        linenum ?
451                                        SString::sprintf("%d", *linenum).c_str()
452                                        : SString::sprintf("'%s'", p0).c_str(),
453                                        getName());
454                                break;
455                        case 1:
456                                logPrintf("ParamInterface", "load", LOG_WARN, "The following line(s) were also unexpected and were ignored");
457                                break;
458                        }
459                        unexpected_line++;
460                        continue;
461                }
462                unexpected_line = 0;
463                p_len = (int)(p - p0);
464                loaded = false;
465                if (p_len && ((i = findIdn(p0, p_len)) >= 0))
466                {
467                        if (seen[i])
468                        {
469                                SString fileinfo;
470                                const char* fname = f->VgetPath();
471                                if (fname != NULL)
472                                {
473                                        fileinfo = SString::sprintf(" while reading from '%s'", fname);
474                                        if (linenum)
475                                                fileinfo += SString::sprintf(" (line %d)", *linenum);
476                                }
477                                logPrintf("ParamInterface", "load", LOG_WARN, "Multiple '%s.%s' fields found%s", getName(), id(i), fileinfo.c_str());
478                        }
479                        else
480                                seen[i] = true;
481                        if (!(flags(i)&PARAM_DONTLOAD))
482                        {
483                                if (p0[p_len + 1] == '~')
484                                {
485                                        SString s;
486                                        if (!readUntilTilde(f, s))
487                                                closingTildeError(this, f, i);
488                                        int lfcount = 1;
489                                        const char* tmp = s.c_str();
490                                        while (tmp)
491                                                if ((tmp = strchr(tmp, '\n')))
492                                                {
493                                                lfcount++; tmp++;
494                                                }
495                                        removeCR(s);
496                                        int ch; while ((ch = f->Vgetc()) != EOF) if (ch == '\n') break;
497                                        unquoteTilde(s);
498                                        if (linenum && (flags(i)&PARAM_LINECOMMENT))
499                                                s = SString::sprintf("@file %s\n@line %d\n", f->VgetPath(), *linenum + 1) + s;
500                                        set(i, s.c_str());
501                                        if (linenum)
502                                                (*linenum) += lfcount;
503                                }
504                                else
505                                {
506                                        set(i, p0 + p_len + 1);
507                                }
508                                fields_loaded++;
509                                loaded = true;
510                        }
511                }
512                else if (warn_unknown_fields)
513                {
514                        SString name(p0, p_len);
515                        logPrintf("ParamInterface", "load", LOG_WARN, "Ignored unknown property '%s' while reading object '%s'", name.c_str(), getName());
516                }
517
518                if ((!loaded) && (p0[p_len + 1] == '~'))
519                { // eat unrecognized multiline field
520                        SString s;
521                        if (!readUntilTilde(f, s))
522                                closingTildeError(this, f, -1);
523                        if (linenum)
524                        {
525                                const char* tmp = s.c_str();
526                                int lfcount = 1;
527                                while (tmp)
528                                        if ((tmp = strchr(tmp, '\n')))
529                                        {
530                                        lfcount++; tmp++;
531                                        }
532                                (*linenum) += lfcount;
533                        }
534                        int ch; while ((ch = f->Vgetc()) != EOF) if (ch == '\n') break;
535                }
536        }
537        if ((i = findId("afterLoad")) >= 0)
538                call(i, NULL, NULL);
539        return fields_loaded;
540}
541
542
543/*
544SString SimpleAbstractParam::getString(int i)
545{
546char *t;
547switch (*(t=type(i)))
548{
549case 'd':
550{
551for (i=atol(get(i));i>=0;i--) if (t) t=strchr(t+1,'~');
552if (t)
553{
554t++;
555char *t2=strchr(t,'~');
556if (!t2) t2=t+strlen(t);
557SString str;
558strncpy(str.directWrite(t2-t),t,t2-t);
559str.endWrite(t2-t);
560return str;
561}
562}
563}
564return get(i);
565}
566*/
567
568int ParamInterface::findId(const char* n)
569{
570        int i; const char *p;
571        for (i = 0; p = id(i); i++) if (!strcmp(n, p)) return i;
572        return -1;
573}
574
575int ParamInterface::findIdn(const char* naz, int n)
576{
577        int i; const char *p;
578        for (i = 0; p = id(i); i++) if ((!strncmp(naz, p, n)) && (!p[n])) return i;
579        return -1;
580}
581
582void ParamInterface::get(int i, ExtValue &ret)
583{
584        switch (type(i)[0])
585        {
586        case 'd':       ret.setInt(getInt(i)); break;
587        case 'f':       ret.setDouble(getDouble(i)); break;
588        case 's':       ret.setString(getString(i)); break;
589        case 'o':       ret.setObject(getObject(i)); break;
590        case 'x':       ret = getExtValue(i); break;
591        default: logPrintf("ParamInterface", "get", LOG_ERROR, "'%s.%s' is not a field", getName(), id(i));
592        }
593}
594
595int ParamInterface::setInt(int i, const char* str, bool strict)
596{
597        paInt value;
598        if (!ExtValue::parseInt(str, value, strict, true))
599        {
600                paInt mn, mx, def;
601                if (getMinMax(i, mn, mx, def) >= 3)
602                        return setInt(i, def) | PSET_PARSEFAILED;
603                else
604                        return setInt(i, (paInt)0) | PSET_PARSEFAILED;
605        }
606        else
607                return setInt(i, value);
608}
609
610int ParamInterface::setDouble(int i, const char* str)
611{
612        double value;
613        if (!ExtValue::parseDouble(str, value, true))
614        {
615                double mn, mx, def;
616                if (getMinMax(i, mn, mx, def) >= 3)
617                        return setDouble(i, def) | PSET_PARSEFAILED;
618                else
619                        return setDouble(i, (double)0) | PSET_PARSEFAILED;
620        }
621        else
622                return setDouble(i, value);
623}
624
625int ParamInterface::set(int i, const ExtValue &v)
626{
627        switch (type(i)[0])
628        {
629        case 'd':
630                if ((v.type == TInt) || (v.type == TDouble)) return setInt(i, v.getInt());
631                else
632                {
633                        if (v.type == TObj)
634                        {
635                                logPrintf("ParamInterface", "set", LOG_ERROR, "Setting int '%s.%s' from object reference (%s)", getName(), id(i), v.getString().c_str());
636                                return 0;
637                        }
638                        else
639                                return setInt(i, v.getString().c_str());
640                }
641        case 'f':
642                if ((v.type == TInt) || (v.type == TDouble)) return setDouble(i, v.getDouble());
643                else
644                {
645                        if (v.type == TObj)
646                        {
647                                logPrintf("ParamInterface", "set", LOG_ERROR, "Setting float '%s.%s' from object reference (%s)", getName(), id(i), v.getString().c_str());
648                                return 0;
649                        }
650                        else
651                                return setDouble(i, v.getString().c_str());
652                }
653        case 's': { SString t = v.getString(); return setString(i, t); }
654        case 'o':
655                if ((v.type != TUnknown) && (v.type != TObj))
656                        logPrintf("ParamInterface", "set", LOG_ERROR, "Setting object '%s.%s' from %s", getName(), id(i), v.typeAndValue().c_str());
657                else
658                        return setObject(i, v.getObject());
659                break;
660        case 'x': return setExtValue(i, v);
661        default: logPrintf("ParamInterface", "set", LOG_ERROR, "'%s.%s' is not a field", getName(), id(i));
662        }
663        return 0;
664}
665
666int ParamInterface::set(int i, const char *v, bool strict)
667{
668        char typ = type(i)[0];
669        switch (typ)
670        {
671        case 'd': return setInt(i, v, strict);
672        case 'f': return setDouble(i, v);
673        case 's': { SString t(v); return setString(i, t); }
674        case 'x': case 'o':
675        {
676                ExtValue e;
677                const char* after;
678                if (!strncmp(v, SERIALIZATION_PREFIX, strlen(SERIALIZATION_PREFIX)))
679                {
680                        after = e.deserialize(v + strlen(SERIALIZATION_PREFIX));
681                        if ((after == NULL) || (*after))
682                        {
683                                logPrintf("ParamInterface", "set", LOG_ERROR, "serialization format mismatch in %s.%s", (getName() ? getName() : "<Unknown>"), id(i));
684                                e.setEmpty();
685                        }
686                }
687                else if ((after = e.parseNumber(v)) && (*after == 0)) //consumed the whole string
688                {
689                        //OK!
690                }
691                else
692                {
693                        e.setString(SString(v));
694                }
695                if (typ == 'x')
696                        return setExtValue(i, e);
697                else
698                        return setObject(i, e.getObject());
699        }
700        }
701        return 0;
702}
703
704SString ParamInterface::getText(int i) //find the current enum text or call get(i) if not enum
705{
706        const char *t;
707        if (((*(t = type(i))) == 'd') && (strchr(t, '~')!=NULL)) //type is int and contains enum labels
708        {
709                paInt mn, mx, def;
710                int value = getInt(i);
711                if (getMinMax(t, mn, mx, def) >= 2)
712                {
713                        if (value > mx)
714                                return get(i);//unexpected value of out bounds (should never happen) -> fallback
715                        value -= mn;
716                }
717                if (value < 0) return get(i); //unexpected value of out bounds (should never happen) -> fallback
718                // now value is 0-based index of ~text
719                for (; value >= 0; value--) if (t) t = strchr(t + 1, '~'); else break;
720                if (t) // found n-th ~text in type description (else: not enough ~texts in type description)
721                {
722                        t++;
723                        const char *t2 = strchr(t, '~');
724                        if (!t2) t2 = t + strlen(t);
725                        return SString(t, (int)(t2 - t));
726                }
727        }
728        return get(i); //fallback - return int value as string
729}
730
731SString ParamInterface::get(int i)
732{
733        switch (type(i)[0])
734        {
735        case 'd': return SString::valueOf(getInt(i));
736        case 'f': return SString::valueOf(getDouble(i));
737        case 's': return getString(i);
738        }
739        ExtValue v;
740        get(i, v);
741        return v.getString();
742}
743
744bool ParamInterface::isValidTypeDescription(const char* t)
745{
746        if (t == NULL) return false;
747        if (*t == 0) return false;
748        if (strchr("dfsoxp", *t) == NULL) return false;
749        switch (*t)
750        {
751        case 'd':
752        {paInt a, b, c; if (getMinMax(t, a, b, c) == 1) return false; }
753                break;
754        case 'f':
755        {double a, b, c; if (getMinMax(t, a, b, c) == 1) return false; }
756                break;
757        }
758        return true;
759}
760
761SString ParamInterface::describeType(const char* type)
762{
763        SString t;
764        switch (type[0])
765        {
766        case 'd': t += "integer";
767        {paInt a, b, c; int n = getMinMax(type, a, b, c); if ((n >= 2) && (b >= a)) t += SString::sprintf(" %d..%d", a, b); if (n >= 3) t += SString::sprintf(" (default %d)", c); }
768                break;
769        case 'f': t += "float";
770        {double a, b, c; int n = getMinMax(type, a, b, c); if ((n >= 2) && (b >= a)) t += SString::sprintf(" %g..%g", a, b); if (n >= 3) t += SString::sprintf(" (default %g)", c); }
771                break;
772        case 's': t += "string";
773        {int a, b; SString c; int n = getMinMax(type, a, b, c); if ((n >= 2) && (b > 0)) t += SString::sprintf(", max %d chars", b); if (n >= 3) t += SString::sprintf(" (default \"%s\")", c.c_str()); }
774                break;
775        case 'x': t += "untyped value"; break;
776        case 'p': t += "function"; break;
777        case 'o': t += "object"; if (type[1]) { t += " of class "; t += type + 1; } break;
778        default: return "unknown type";
779        }
780        return t;
781}
782
783//////////////////////////////// PARAM ////////////////////////////////////
784
785#ifdef _DEBUG
786void SimpleAbstractParam::sanityCheck(int i)
787{
788        ParamEntry *pe = entry(i);
789
790        const char* t = pe->type;
791        const char* err = NULL;
792
793        if (!isValidTypeDescription(t))
794                err = "invalid type description";
795        if (*t == 'p')
796        {
797                if (pe->fun1 == NULL)
798                        err = "no procedure defined";
799                if (pe->flags & PARAM_READONLY)
800                        err = "function can't be PARAM_READONLY";
801        }
802        else
803        {
804                if (!(pe->flags & (PARAM_READONLY | PARAM_DONTSAVE | PARAM_USERREADONLY | PARAM_CONST | PARAM_DONTLOAD | PARAM_LINECOMMENT | PARAM_OBJECTSET)))
805                { //write access
806                        if ((pe->fun2 == NULL) && (pe->offset == PARAM_ILLEGAL_OFFSET))
807                                err = "no field defined (GETONLY without PARAM_READONLY?)";
808                }
809        }
810        if (err != NULL)
811                logPrintf("SimpleAbstractParam", "sanityCheck", LOG_ERROR,
812                "Invalid ParamEntry for %s.%s (%s)", getName(), pe->id, err);
813}
814#endif
815
816void *SimpleAbstractParam::getTarget(int i)
817{
818        return (void*)(((char*)object) + entry(i)->offset);
819        //return &(object->*(entry(i)->fldptr));
820}
821
822///////// get
823
824#ifdef _DEBUG
825#define SANITY_CHECK(i) sanityCheck(i)
826#else
827#define SANITY_CHECK(i)
828#endif
829
830paInt SimpleAbstractParam::getInt(int i)
831{
832        SANITY_CHECK(i);
833        ExtValue v;
834        ParamEntry *pe = entry(i);
835        if (pe->fun1)
836        {
837                (*(void(*)(void*, ExtValue*))pe->fun1)(object, &v);
838                return v.getInt();
839        }
840        else
841        {
842                void *target = getTarget(i);
843                return *((paInt*)target);
844        }
845}
846
847double SimpleAbstractParam::getDouble(int i)
848{
849        SANITY_CHECK(i);
850        ExtValue v;
851        ParamEntry *pe = entry(i);
852        if (pe->fun1)
853        {
854                (*(void(*)(void*, ExtValue*))pe->fun1)(object, &v);
855                return v.getDouble();
856        }
857        else
858        {
859                void *target = getTarget(i);
860                return *((double*)target);
861        }
862}
863
864SString SimpleAbstractParam::getString(int i)
865{
866        SANITY_CHECK(i);
867        ExtValue v;
868        ParamEntry *pe = entry(i);
869        if (pe->fun1)
870        {
871                (*(void(*)(void*, ExtValue*))pe->fun1)(object, &v);
872                return v.getString();
873        }
874        else
875        {
876                void *target = getTarget(i);
877                return *((SString*)target);
878        }
879}
880
881ExtObject SimpleAbstractParam::getObject(int i)
882{
883        SANITY_CHECK(i);
884        ExtValue v;
885        ParamEntry *pe = entry(i);
886        if (pe->fun1)
887        {
888                (*(void(*)(void*, ExtValue*))pe->fun1)(object, &v);
889                return v.getObject();
890        }
891        else
892        {
893                void *target = getTarget(i);
894                return *((ExtObject*)target);
895        }
896}
897
898ExtValue SimpleAbstractParam::getExtValue(int i)
899{
900        SANITY_CHECK(i);
901        ExtValue v;
902        ParamEntry *pe = entry(i);
903        if (pe->fun1)
904        {
905                (*(void(*)(void*, ExtValue*))pe->fun1)(object, &v);
906                return v;
907        }
908        else
909        {
910                void *target = getTarget(i);
911                return *((ExtValue*)target);
912        }
913}
914
915
916//////// set
917
918int SimpleAbstractParam::setInt(int i, paInt x)
919{
920        SANITY_CHECK(i);
921        ExtValue v;
922        ParamEntry *pe = entry(i);
923        if (pe->flags&PARAM_READONLY) return PSET_RONLY;
924        paInt xcopy = x; //only needed for messageOnExceedRange(): retain original, requested value of x because it may be changed below
925        paInt mn = 0, mx = 0, de = 0;
926        int result = 0;
927        if (getMinMax(pe->type, mn, mx, de) >= 2)
928                if (mn <= mx) // else if mn>mx then the min/max constraint makes no sense and there is no checking
929                {
930                if (x < mn) { x = mn; result = PSET_HITMIN; }
931                else if (x > mx) { x = mx; result = PSET_HITMAX; }
932                }
933
934        if (pe->fun2)
935        {
936                v.setInt(x);
937                result |= (*(int(*)(void*, const ExtValue*))pe->fun2)(object, &v);
938        }
939        else
940        {
941                void *target = getTarget(i);
942                if (dontcheckchanges || (*((paInt*)target) != x))
943                {
944                        result |= PSET_CHANGED;
945                        *((paInt*)target) = x;
946                }
947        }
948        messageOnExceedRange(i, result, xcopy);
949        return result;
950}
951
952int SimpleAbstractParam::setDouble(int i, double x)
953{
954        SANITY_CHECK(i);
955        ExtValue v;
956        ParamEntry *pe = entry(i);
957        if (pe->flags&PARAM_READONLY) return PSET_RONLY;
958        double xcopy = x; //only needed for messageOnExceedRange(): retain original, requested value of x because it may be changed below
959        double mn = 0, mx = 0, de = 0;
960        int result = 0;
961        if (getMinMax(pe->type, mn, mx, de) >= 2)
962                if (mn <= mx) // else if mn>mx then the min/max constraint makes no sense and there is no checking
963                {
964                if (x < mn) { x = mn; result = PSET_HITMIN; }
965                else if (x > mx) { x = mx; result = PSET_HITMAX; }
966                }
967
968        if (pe->fun2)
969        {
970                v.setDouble(x);
971                result |= (*(int(*)(void*, const ExtValue*))pe->fun2)(object, &v);
972        }
973        else
974        {
975                void *target = getTarget(i);
976                if (dontcheckchanges || (*((double*)target) != x))
977                {
978                        result |= PSET_CHANGED;
979                        *((double*)target) = x;
980                }
981        }
982        messageOnExceedRange(i, result, xcopy);
983        return result;
984}
985
986int SimpleAbstractParam::setString(int i, const SString& x)
987{
988        SANITY_CHECK(i);
989        ExtValue v;
990        SString vs;
991        const SString *xx = &x;
992        ParamEntry *pe = entry(i);
993        if (pe->flags&PARAM_READONLY) return PSET_RONLY;
994        SString xcopy = x; //only needed for messageOnExceedRange(): retain original, requested value of x because it may be changed below
995        const char* t = pe->type + 1;
996        while (*t) if (*t == ' ') break; else t++;
997        int mn = 0, mx = 0;
998        int result = 0;
999        if (sscanf(t, "%d %d", &mn, &mx) == 2) //using getMinMax would also get default value, which is not needed here
1000        {
1001                if ((x.len() > mx) && (mx > 0))
1002                {
1003                        vs = x.substr(0, mx);
1004                        xx = &vs;
1005                        result |= PSET_HITMAX;
1006                }
1007        }
1008
1009        if (pe->fun2)
1010        {
1011                v.setString(*xx);
1012                result |= (*(int(*)(void*, const ExtValue*))pe->fun2)(object, &v);
1013        }
1014        else
1015        {
1016                void *target = getTarget(i);
1017                if (dontcheckchanges || (!(*((SString*)target) == *xx)))
1018                {
1019                        result |= PSET_CHANGED;
1020                        *((SString*)target) = *xx;
1021                }
1022        }
1023        messageOnExceedRange(i, result, xcopy);
1024        return result;
1025}
1026
1027int SimpleAbstractParam::setObject(int i, const ExtObject& x)
1028{
1029        SANITY_CHECK(i);
1030        ExtValue v;
1031        ParamEntry *pe = entry(i);
1032        if (pe->flags&PARAM_READONLY) return PSET_RONLY;
1033        if (pe->flags&PARAM_OBJECTSET)
1034        {
1035                ExtObject o = getObject(i);
1036                Param tmp;
1037                ParamInterface* oif = o.getParamInterface(tmp);
1038                int ass;
1039                if (oif && ((ass = oif->findId("assign")) >= 0))
1040                {
1041                        ExtValue arg = x;
1042                        oif->call(ass, &arg, &v);
1043                }
1044                else
1045                        logPrintf("SimpleAbstractParam", "setObject", LOG_ERROR,
1046                        "'%s.%s' is PARAM_OBJECTSET but no 'assign()' in %s", getName(), pe->id, o.interfaceName());
1047                return PSET_CHANGED;
1048        }
1049        ExtObject xcopy = x; //only needed for messageOnExceedRange(): retain original, requested value of x because it may be changed below
1050        if (pe->fun2)
1051        {
1052                v.setObject(x);
1053                int result = (*(int(*)(void*, const ExtValue*))pe->fun2)(object, &v);
1054                messageOnExceedRange(i, result, xcopy);
1055                return result;
1056        }
1057        else
1058        {
1059                void *target = getTarget(i);
1060                *((ExtObject*)target) = x;
1061                return PSET_CHANGED;
1062        }
1063}
1064
1065int SimpleAbstractParam::setExtValue(int i, const ExtValue& x)
1066{
1067        SANITY_CHECK(i);
1068        ParamEntry *pe = entry(i);
1069        if (pe->flags&PARAM_READONLY) return PSET_RONLY;
1070        ExtValue xcopy = x; //only needed for messageOnExceedRange(): retain original, requested value of x because it may be changed below
1071        if (pe->fun2)
1072        {
1073                int result = (*(int(*)(void*, const ExtValue*))pe->fun2)(object, &x);
1074                messageOnExceedRange(i, result, xcopy);
1075                return result;
1076        }
1077        else
1078        {
1079                void *target = getTarget(i);
1080                *((ExtValue*)target) = x;
1081                return PSET_CHANGED;
1082        }
1083}
1084
1085void SimpleAbstractParam::call(int i, ExtValue *args, ExtValue *ret)
1086{
1087        SANITY_CHECK(i);
1088        ParamEntry *pe = entry(i);
1089        if (!pe) return;
1090        if (pe->fun1 && (pe->type[0] == 'p'))
1091                (*(void(*)(void*, ExtValue*, ExtValue*))pe->fun1)(object, args, ret);
1092        else
1093        {
1094                logPrintf("SimpleAbstractParam", "call", LOG_ERROR,
1095                        (*pe->type != 'p') ? "'%s.%s' is not a function" : "Internal error - undefined function pointer for '%s.%s'", getName(), pe->id);
1096                ret->setInvalid();
1097        }
1098}
1099
1100void SimpleAbstractParam::setDefault()
1101{
1102        bool save = dontcheckchanges;
1103        dontcheckchanges = 1;
1104        ParamInterface::setDefault();
1105        dontcheckchanges = save;
1106}
1107
1108void SimpleAbstractParam::setDefault(int i)
1109{
1110        bool save = dontcheckchanges;
1111        dontcheckchanges = 1;
1112        ParamInterface::setDefault(i);
1113        dontcheckchanges = save;
1114}
1115
1116// Returns the address of the beginning of the line.
1117// len = line length (without \n).
1118// 0 may mean the line with length=0 or the end of the SString.
1119// poz is advanced to the beginning of the next line.
1120// A typical loop: for(poz=0;poz<s.d;) {line=getline(s,poz,len);...
1121static const char *getline(const SString &s, int &poz, int &len)
1122{
1123        const char *beg = s.c_str() + poz;
1124        if (poz >= s.len()) { poz = s.len(); len = 0; return s.c_str() + s.len(); }
1125        const char *lf = strchr(beg, '\n');
1126        if (!lf) { lf = s.c_str() + s.len() - 1; poz = s.len(); }
1127        else { poz = (int)(lf - s.c_str()) + 1; if (poz > s.len()) poz = s.len(); }
1128        while (lf >= beg) if ((*lf == '\n') || (*lf == '\r')) lf--; else break;
1129        len = (int)(lf - beg) + 1;
1130        return beg;
1131}
1132
1133int ParamInterface::load2(const SString &s, int &poz)
1134{
1135        int i; // the index number of the parameter
1136        int tmpi;
1137        int len;
1138        int ret;
1139        int fields_loaded = 0;
1140        const char *t, *lin, *end;
1141        const char *equals_sign, *field_end, *next_field;
1142        char remember;
1143        const char *quote, *quote2;
1144        const char *value, *valstop;
1145        SString tmpvalue;
1146        bool parse_failed = false;
1147        if (poz >= s.len()) return fields_loaded;
1148        t = s.c_str() + poz;
1149
1150        lin = getline(s, poz, len); // all fields must be encoded in a single line
1151        if (!len) return fields_loaded; // empty line = end
1152        i = 0;
1153        end = lin + len;
1154        while (t < end)
1155        {
1156                // processing a single field
1157                // "p:name=field_value,  field_name=field_value  , name=value..."
1158                //                     ^ ^-t (after)           ^ ^_next_field
1159                //                     \_t (before)            \_field_end
1160                while (isspace(*t)) if (t < end) t++; else return fields_loaded;
1161
1162                field_end = strchrlimit(t, ',', end); if (!field_end) field_end = end;
1163                next_field = field_end;
1164                while ((field_end>t) && isblank(field_end[-1])) field_end--;
1165                quote = strchrlimit(t, '\"', field_end);
1166                if (quote)
1167                {
1168                        quote2 = skipQuoteString(quote + 1, end);
1169                        if (quote2 > field_end)
1170                        {
1171                                field_end = strchrlimit(quote2 + 1, ',', end);
1172                                if (!field_end) field_end = end;
1173                                next_field = field_end;
1174                        }
1175                        equals_sign = strchrlimit(t, '=', quote);
1176                }
1177                else
1178                {
1179                        equals_sign = strchrlimit(t, '=', field_end);
1180                        quote2 = 0;
1181                }
1182                if (equals_sign == t) { t++; equals_sign = 0; }
1183                if (field_end == t)     // skip empty value
1184                {
1185                        t++; i++;
1186                        continue;
1187                }
1188                if (equals_sign) // have parameter name
1189                {
1190                        tmpi = findIdn(t, (int)(equals_sign - t));
1191                        i = tmpi;
1192                        if (tmpi < 0)
1193                        {
1194                                SString name(t, (int)(equals_sign - t));
1195                                logPrintf("Param", "load2", LOG_WARN, "Unknown property '%s' while reading object '%s' (ignored)", name.c_str(), getName());
1196                        }
1197                        t = equals_sign + 1; // t=value
1198                }
1199#ifdef WARN_MISSING_NAME
1200                else
1201#ifdef SAVE_SELECTED_NAMES
1202                        if ((i >= getPropCount()) || !(flags(i)&PARAM_CANOMITNAME))
1203#endif
1204                        {
1205                        if (id(i))
1206                                logPrintf("Param", "load2", LOG_WARN, "Missing property name in '%s' (assuming '%s')", getName(), id(i));
1207                        else
1208                                logPrintf("Param", "load2", LOG_WARN, "Value after the last property of '%s'", getName());
1209                        }
1210#endif
1211                if ((i >= 0) && id(i))
1212                {
1213                        value = t;
1214                        if (quote)
1215                        {
1216                                tmpvalue.copyFrom(quote + 1, (int)(quote2 - quote) - 1);
1217                                sstringUnquote(tmpvalue);
1218                                value = tmpvalue.c_str();
1219                                valstop = quote2;
1220                        }
1221                        else
1222                                if (field_end < end) valstop = field_end; else valstop = end;
1223
1224                        remember = *valstop;
1225                        *(char*)valstop = 0;
1226                        ret = set(i, value, true);
1227                        fields_loaded++;
1228                        if (ret&(PSET_HITMAX | PSET_HITMIN))
1229                                logPrintf("Param", "load2", LOG_WARN, "Adjusted '%s' in '%s' (was too %s)",
1230                                id(i), getName(), (ret&PSET_HITMAX) ? "big" : "small");
1231                        if (ret&PSET_PARSEFAILED)
1232                                parse_failed = true;
1233                        *(char*)valstop = remember;
1234                }
1235
1236                if (i >= 0) i++;
1237#ifdef __CODEGUARD__
1238                if (next_field<end-1) t=next_field+1; else return fields_loaded;
1239#else
1240                t = next_field + 1;
1241#endif
1242        }
1243        return fields_loaded | (parse_failed ? LOAD2_PARSE_FAILED : 0);
1244}
1245
1246int Param::grmember(int g, int a)
1247{
1248        if ((getGroupCount() < 2) && (!g))
1249                return (a < getPropCount()) ? a : -9999;
1250
1251        ParamEntry *e = entry(0);
1252        int x = 0, i = 0;
1253        for (; e->id; i++, e++)
1254        {
1255                if (e->group == g)
1256                        if (a == x) return i; else x++;
1257        }
1258        return -9999;
1259}
Note: See TracBrowser for help on using the repository browser.