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

Last change on this file since 822 was 822, checked in by Maciej Komosinski, 5 years ago

Avoid false positives for script-driven mutable param sanity check ("Invalid ParamEntry? for ExpProperties?.cleardata (no procedure defined)")

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