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

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

Unquote tilde \~ needed when loading single-line Param values

  • Property svn:eol-style set to native
File size: 33.9 KB
Line 
1// This file is a part of Framsticks SDK.  http://www.framsticks.com/
2// Copyright (C) 1999-2019  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                                        SString s = SString(p0 + p_len + 1);
590                                        unquoteTilde(s);
591                                        setFromString(i, s.c_str(), false);
592                                }
593                                fields_loaded++;
594                                loaded = true;
595                        }
596                }
597                else if (options.warn_unknown_fields)
598                {
599                        SString name(p0, p_len);
600                        logPrintf("ParamInterface", "load", LOG_WARN, "Ignored unknown property '%s.%s'", getName(), name.c_str());
601                }
602
603                if ((!loaded) && (p0[p_len + 1] == '~'))
604                { // eat unrecognized multiline field
605                        SString s;
606                        if (!readUntilTilde(f, s))
607                                closingTildeError(this, f, -1);
608                        if (options.linenum)
609                        {
610                                const char* tmp = s.c_str();
611                                int lfcount = 1;
612                                while (tmp)
613                                        if ((tmp = strchr(tmp, '\n')))
614                                        {
615                                                lfcount++; tmp++;
616                                        }
617                                (*options.linenum) += lfcount;
618                        }
619                        int ch; while ((ch = f->Vgetc()) != EOF) if (ch == '\n') break;
620                }
621        }
622        if ((i = findId("afterLoad")) >= 0)
623                call(i, NULL, NULL);
624        return fields_loaded;
625}
626
627
628/*
629SString SimpleAbstractParam::getString(int i)
630{
631char *t;
632switch (*(t=type(i)))
633{
634case 'd':
635{
636for (i=atol(get(i));i>=0;i--) if (t) t=strchr(t+1,'~');
637if (t)
638{
639t++;
640char *t2=strchr(t,'~');
641if (!t2) t2=t+strlen(t);
642SString str;
643strncpy(str.directWrite(t2-t),t,t2-t);
644str.endWrite(t2-t);
645return str;
646}
647}
648}
649return get(i);
650}
651*/
652
653int ParamInterface::findId(const char* n)
654{
655        int i; const char *p;
656        for (i = 0; p = id(i); i++) if (!strcmp(n, p)) return i;
657        return -1;
658}
659
660int ParamInterface::findIdn(const char* naz, int n)
661{
662        int i; const char *p;
663        for (i = 0; p = id(i); i++) if ((!strncmp(naz, p, n)) && (!p[n])) return i;
664        return -1;
665}
666
667void ParamInterface::get(int i, ExtValue &ret)
668{
669        switch (type(i)[0])
670        {
671        case 'd':       ret.setInt(getInt(i)); break;
672        case 'f':       ret.setDouble(getDouble(i)); break;
673        case 's':       ret.setString(getString(i)); break;
674        case 'o':       ret.setObject(getObject(i)); break;
675        case 'x':       ret = getExtValue(i); break;
676        default: logPrintf("ParamInterface", "get", LOG_ERROR, "'%s.%s' is not a property", getName(), id(i));
677        }
678}
679
680int ParamInterface::setIntFromString(int i, const char* str, bool strict)
681{
682        paInt value;
683        if (!ExtValue::parseInt(str, value, strict, true))
684        {
685                paInt mn, mx, def;
686                if (getMinMaxInt(i, mn, mx, def) >= 3)
687                        return setInt(i, def) | PSET_PARSEFAILED;
688                else
689                        return setInt(i, (paInt)0) | PSET_PARSEFAILED;
690        }
691        else
692                return setInt(i, value);
693}
694
695int ParamInterface::setDoubleFromString(int i, const char* str)
696{
697        double value;
698        if (!ExtValue::parseDouble(str, value, true))
699        {
700                double mn, mx, def;
701                if (getMinMaxDouble(i, mn, mx, def) >= 3)
702                        return setDouble(i, def) | PSET_PARSEFAILED;
703                else
704                        return setDouble(i, (double)0) | PSET_PARSEFAILED;
705        }
706        else
707                return setDouble(i, value);
708}
709
710int ParamInterface::set(int i, const ExtValue &v)
711{
712        switch (type(i)[0])
713        {
714        case 'd':
715                if ((v.type == TInt) || (v.type == TDouble)) return setInt(i, v.getInt());
716                else
717                {
718                        if (v.type == TObj)
719                        {
720                                logPrintf("ParamInterface", "set", LOG_ERROR, "Setting int '%s.%s' from object reference (%s)", getName(), id(i), v.getString().c_str());
721                                return 0;
722                        }
723                        else
724                                return setIntFromString(i, v.getString().c_str(), false);
725                }
726        case 'f':
727                if ((v.type == TInt) || (v.type == TDouble)) return setDouble(i, v.getDouble());
728                else
729                {
730                        if (v.type == TObj)
731                        {
732                                logPrintf("ParamInterface", "set", LOG_ERROR, "Setting float '%s.%s' from object reference (%s)", getName(), id(i), v.getString().c_str());
733                                return 0;
734                        }
735                        else
736                                return setDoubleFromString(i, v.getString().c_str());
737                }
738        case 's': { SString t = v.getString(); return setString(i, t); }
739        case 'o':
740                if ((v.type != TUnknown) && (v.type != TObj))
741                        logPrintf("ParamInterface", "set", LOG_ERROR, "Setting object '%s.%s' from %s", getName(), id(i), v.typeAndValue().c_str());
742                else
743                        return setObject(i, v.getObject());
744                break;
745        case 'x': return setExtValue(i, v);
746        default: logPrintf("ParamInterface", "set", LOG_ERROR, "'%s.%s' is not a property", getName(), id(i));
747        }
748        return 0;
749}
750
751int ParamInterface::setFromString(int i, const char *v, bool strict)
752{
753        char typ = type(i)[0];
754        switch (typ)
755        {
756        case 'd': return setIntFromString(i, v, strict);
757        case 'f': return setDoubleFromString(i, v);
758        case 's': { SString t(v); return setString(i, t); }
759        case 'x': case 'o':
760        {
761                ExtValue e;
762                const char* after;
763                if (!strncmp(v, SERIALIZATION_PREFIX, strlen(SERIALIZATION_PREFIX)))
764                {
765                        after = e.deserialize(v + strlen(SERIALIZATION_PREFIX));
766                        if ((after == NULL) || (*after))
767                        {
768                                logPrintf("ParamInterface", "set", LOG_ERROR, "serialization format mismatch in %s.%s", (getName() ? getName() : "<Unknown>"), id(i));
769                                e.setEmpty();
770                        }
771                }
772                else if ((after = e.parseNumber(v)) && (*after == 0)) //consumed the whole string
773                {
774                        //OK!
775                }
776                else
777                {
778                        e.setString(SString(v));
779                }
780                if (typ == 'x')
781                        return setExtValue(i, e);
782                else
783                        return setObject(i, e.getObject());
784        }
785        }
786        return 0;
787}
788
789SString ParamInterface::getText(int i) //find the current enum text or call get(i) if not enum
790{
791        const char *t;
792        if (((*(t = type(i))) == 'd') && (strchr(t, '~') != NULL)) //type is int and contains enum labels
793        {
794                paInt mn, mx, def;
795                int value = getInt(i);
796                if (getMinMaxIntFromTypeDef(t, mn, mx, def) >= 2)
797                {
798                        if (value > mx)
799                                return get(i);//unexpected value of out bounds (should never happen) -> fallback
800                        value -= mn;
801                }
802                if (value < 0) return get(i); //unexpected value of out bounds (should never happen) -> fallback
803                // now value is 0-based index of ~text
804                for (; value >= 0; value--) if (t) t = strchr(t + 1, '~'); else break;
805                if (t) // found n-th ~text in type description (else: not enough ~texts in type description)
806                {
807                        t++;
808                        const char *t2 = strchr(t, '~');
809                        if (!t2) t2 = t + strlen(t);
810                        return SString(t, (int)(t2 - t));
811                }
812        }
813        return get(i); //fallback - return int value as string
814}
815
816SString ParamInterface::get(int i)
817{
818        switch (type(i)[0])
819        {
820        case 'd': return SString::valueOf(getInt(i));
821        case 'f': return SString::valueOf(getDouble(i));
822        case 's': return getString(i);
823        }
824        ExtValue v;
825        get(i, v);
826        return v.getString();
827}
828
829bool ParamInterface::isValidTypeDescription(const char* t)
830{
831        if (t == NULL) return false;
832        if (*t == 0) return false;
833        if (strchr("dfsoxp", *t) == NULL) return false;
834        switch (*t)
835        {
836        case 'd':
837        {
838                paInt a, b, c;
839                int have = getMinMaxIntFromTypeDef(t, a, b, c);
840                if (have == 1) return false;
841                if ((have >= 2) && (b < a) && (a != 0) && (b != -1)) return false; // max<min meaning 'undefined' is only allowed as "d 0 -1"
842        }
843        break;
844        case 'f':
845        {
846                double a, b, c;
847                int have = getMinMaxDoubleFromTypeDef(t, a, b, c);
848                if (have == 1) return false;
849                if ((have >= 2) && (b < a) && (a != 0) && (b != -1)) return false; // max<min meaning 'undefined' is only allowed as "f 0 -1"
850        }
851        break;
852        case 's':
853        {
854                int a, b; SString c;
855                int have = getMinMaxStringFromTypeDef(t, a, b, c);
856                //if (have == 1) return false; //not sure?
857                if ((have >= 1) && (!((a == 0) || (a == 1)))) return false; // 'min' for string (single/multi) can be only 0 or 1
858                if ((have >= 2) && (b < 0)) return false; // max=0 means unlimited, max<0 is not allowed
859        }
860        break;
861        }
862        return true;
863}
864
865SString ParamInterface::friendlyTypeDescrFromTypeDef(const char* type)
866{
867        SString t;
868        switch (type[0])
869        {
870        case 'd': t += "integer";
871        {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); }
872        break;
873        case 'f': t += "float";
874        {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); }
875        break;
876        case 's': t += "string";
877        {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()); }
878        break;
879        case 'x': t += "untyped value"; break;
880        case 'p': t += "function"; break;
881        case 'o': t += "object"; if (type[1]) { t += " of class "; t += type + 1; } break;
882        default: return "unknown type";
883        }
884        return t;
885}
886
887//////////////////////////////// PARAM ////////////////////////////////////
888
889#ifdef _DEBUG
890void SimpleAbstractParam::sanityCheck(int i)
891{
892        ParamEntry *pe = entry(i);
893
894        const char* t = pe->type;
895        const char* err = NULL;
896
897        if (!isValidTypeDescription(t))
898                err = "invalid type description";
899        if (*t == 'p')
900        {
901                if (pe->fun1 == NULL)
902                {
903                        MutableParamInterface *mpi = dynamic_cast<MutableParamInterface*>(this);
904                        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.
905                                err = "no procedure defined";
906                }
907                if (pe->flags & PARAM_READONLY)
908                        err = "function can't be PARAM_READONLY";
909        }
910        else
911        {
912                if ((t[0] == 'o') && (t[1] == ' '))
913                {
914                        err = "space after 'o'";
915                }
916                if (!(pe->flags & (PARAM_READONLY | PARAM_DONTSAVE | PARAM_USERREADONLY | PARAM_CONST | PARAM_DONTLOAD | PARAM_LINECOMMENT | PARAM_OBJECTSET)))
917                { //write access
918                        if ((pe->fun2 == NULL) && (pe->offset == PARAM_ILLEGAL_OFFSET))
919                                err = "no field defined (GETONLY without PARAM_READONLY?)";
920                }
921        }
922        if (err != NULL)
923                logPrintf("SimpleAbstractParam", "sanityCheck", LOG_ERROR,
924                        "Invalid ParamEntry for %s.%s (%s)", getName(), pe->id, err);
925}
926#endif
927
928void *SimpleAbstractParam::getTarget(int i)
929{
930        return (void*)(((char*)object) + entry(i)->offset);
931        //return &(object->*(entry(i)->fldptr));
932}
933
934///////// get
935
936#ifdef _DEBUG
937#define SANITY_CHECK(i) sanityCheck(i)
938#else
939#define SANITY_CHECK(i)
940#endif
941
942paInt SimpleAbstractParam::getInt(int i)
943{
944        SANITY_CHECK(i);
945        ExtValue v;
946        ParamEntry *pe = entry(i);
947        if (pe->fun1)
948        {
949                (*(void(*)(void*, ExtValue*))pe->fun1)(object, &v);
950                return v.getInt();
951        }
952        else
953        {
954                void *target = getTarget(i);
955                return *((paInt*)target);
956        }
957}
958
959double SimpleAbstractParam::getDouble(int i)
960{
961        SANITY_CHECK(i);
962        ExtValue v;
963        ParamEntry *pe = entry(i);
964        if (pe->fun1)
965        {
966                (*(void(*)(void*, ExtValue*))pe->fun1)(object, &v);
967                return v.getDouble();
968        }
969        else
970        {
971                void *target = getTarget(i);
972                return *((double*)target);
973        }
974}
975
976SString SimpleAbstractParam::getString(int i)
977{
978        SANITY_CHECK(i);
979        ExtValue v;
980        ParamEntry *pe = entry(i);
981        if (pe->fun1)
982        {
983                (*(void(*)(void*, ExtValue*))pe->fun1)(object, &v);
984                return v.getString();
985        }
986        else
987        {
988                void *target = getTarget(i);
989                return *((SString*)target);
990        }
991}
992
993ExtObject SimpleAbstractParam::getObject(int i)
994{
995        SANITY_CHECK(i);
996        ExtValue v;
997        ParamEntry *pe = entry(i);
998        if (pe->fun1)
999        {
1000                (*(void(*)(void*, ExtValue*))pe->fun1)(object, &v);
1001                return v.getObject();
1002        }
1003        else
1004        {
1005                void *target = getTarget(i);
1006                return *((ExtObject*)target);
1007        }
1008}
1009
1010ExtValue SimpleAbstractParam::getExtValue(int i)
1011{
1012        SANITY_CHECK(i);
1013        ExtValue v;
1014        ParamEntry *pe = entry(i);
1015        if (pe->fun1)
1016        {
1017                (*(void(*)(void*, ExtValue*))pe->fun1)(object, &v);
1018                return v;
1019        }
1020        else
1021        {
1022                void *target = getTarget(i);
1023                return *((ExtValue*)target);
1024        }
1025}
1026
1027
1028//////// set
1029
1030int SimpleAbstractParam::setInt(int i, paInt x)
1031{
1032        SANITY_CHECK(i);
1033        ExtValue v;
1034        ParamEntry *pe = entry(i);
1035        if (pe->flags&PARAM_READONLY) return PSET_RONLY;
1036        paInt xcopy = x; //only needed for messageOnExceedRange(): retain original, requested value of x because it may be changed below
1037        paInt mn = 0, mx = 0, de = 0;
1038        int result = 0;
1039        if (getMinMaxIntFromTypeDef(pe->type, mn, mx, de) >= 2)
1040                if (mn <= mx) // else if mn>mx then the min/max constraint makes no sense and there is no checking
1041                {
1042                        if (x < mn) { x = mn; result = PSET_HITMIN; }
1043                        else if (x > mx) { x = mx; result = PSET_HITMAX; }
1044                }
1045
1046        if (pe->fun2)
1047        {
1048                v.setInt(x);
1049                result |= (*(int(*)(void*, const ExtValue*))pe->fun2)(object, &v);
1050        }
1051        else
1052        {
1053                void *target = getTarget(i);
1054                if (dontcheckchanges || (*((paInt*)target) != x))
1055                {
1056                        result |= PSET_CHANGED;
1057                        *((paInt*)target) = x;
1058                }
1059        }
1060        ::messageOnExceedRange(this, i, result, xcopy);
1061        return result;
1062}
1063
1064int SimpleAbstractParam::setDouble(int i, double x)
1065{
1066        SANITY_CHECK(i);
1067        ExtValue v;
1068        ParamEntry *pe = entry(i);
1069        if (pe->flags&PARAM_READONLY) return PSET_RONLY;
1070        double xcopy = x; //only needed for messageOnExceedRange(): retain original, requested value of x because it may be changed below
1071        double mn = 0, mx = 0, de = 0;
1072        int result = 0;
1073        if (getMinMaxDoubleFromTypeDef(pe->type, mn, mx, de) >= 2)
1074                if (mn <= mx) // else if mn>mx then the min/max constraint makes no sense and there is no checking
1075                {
1076                        if (x < mn) { x = mn; result = PSET_HITMIN; }
1077                        else if (x > mx) { x = mx; result = PSET_HITMAX; }
1078                }
1079
1080        if (pe->fun2)
1081        {
1082                v.setDouble(x);
1083                result |= (*(int(*)(void*, const ExtValue*))pe->fun2)(object, &v);
1084        }
1085        else
1086        {
1087                void *target = getTarget(i);
1088                if (dontcheckchanges || (*((double*)target) != x))
1089                {
1090                        result |= PSET_CHANGED;
1091                        *((double*)target) = x;
1092                }
1093        }
1094        ::messageOnExceedRange(this, i, result, xcopy);
1095        return result;
1096}
1097
1098int SimpleAbstractParam::setString(int i, const SString& x)
1099{
1100        SANITY_CHECK(i);
1101        ExtValue v;
1102        SString vs;
1103        const SString *xx = &x;
1104        ParamEntry *pe = entry(i);
1105        if (pe->flags&PARAM_READONLY) return PSET_RONLY;
1106        SString xcopy = x; //only needed for messageOnExceedRange(): retain original, requested value of x because it may be changed below
1107        const char* t = pe->type + 1;
1108        while (*t) if (*t == ' ') break; else t++;
1109        int mn = 0, mx = 0;
1110        int result = 0;
1111        if (sscanf(t, "%d %d", &mn, &mx) == 2) //using getMinMax would also get default value, which is not needed here
1112        {
1113                if ((x.len() > mx) && (mx > 0))
1114                {
1115                        vs = x.substr(0, mx);
1116                        xx = &vs;
1117                        result |= PSET_HITMAX;
1118                }
1119        }
1120
1121        if (pe->fun2)
1122        {
1123                v.setString(*xx);
1124                result |= (*(int(*)(void*, const ExtValue*))pe->fun2)(object, &v);
1125        }
1126        else
1127        {
1128                void *target = getTarget(i);
1129                if (dontcheckchanges || (!(*((SString*)target) == *xx)))
1130                {
1131                        result |= PSET_CHANGED;
1132                        *((SString*)target) = *xx;
1133                }
1134        }
1135        ::messageOnExceedRange(this, i, result, xcopy);
1136        return result;
1137}
1138
1139int SimpleAbstractParam::setObject(int i, const ExtObject& x)
1140{
1141        SANITY_CHECK(i);
1142        ExtValue v;
1143        ParamEntry *pe = entry(i);
1144        if (pe->flags&PARAM_READONLY) return PSET_RONLY;
1145        if (pe->flags&PARAM_OBJECTSET)
1146        {
1147                ExtObject o = getObject(i);
1148                Param tmp;
1149                ParamInterface* oif = o.getParamInterface(tmp);
1150                int ass;
1151                if (oif && ((ass = oif->findId("assign")) >= 0))
1152                {
1153                        ExtValue arg = x;
1154                        oif->call(ass, &arg, &v);
1155                }
1156                else
1157                        logPrintf("SimpleAbstractParam", "setObject", LOG_ERROR,
1158                                "'%s.%s' is PARAM_OBJECTSET but no 'assign()' in %s", getName(), pe->id, o.interfaceName());
1159                return PSET_CHANGED;
1160        }
1161        ExtObject xcopy = x; //only needed for messageOnExceedRange(): retain original, requested value of x because it may be changed below
1162        if (pe->fun2)
1163        {
1164                v.setObject(x);
1165                int result = (*(int(*)(void*, const ExtValue*))pe->fun2)(object, &v);
1166                ::messageOnExceedRange(this, i, result, xcopy);
1167                return result;
1168        }
1169        else
1170        {
1171                void *target = getTarget(i);
1172                *((ExtObject*)target) = x;
1173                return PSET_CHANGED;
1174        }
1175}
1176
1177int SimpleAbstractParam::setExtValue(int i, const ExtValue& x)
1178{
1179        SANITY_CHECK(i);
1180        ParamEntry *pe = entry(i);
1181        if (pe->flags&PARAM_READONLY) return PSET_RONLY;
1182        ExtValue xcopy = x; //only needed for messageOnExceedRange(): retain original, requested value of x because it may be changed below
1183        if (pe->fun2)
1184        {
1185                int result = (*(int(*)(void*, const ExtValue*))pe->fun2)(object, &x);
1186                ::messageOnExceedRange(this, i, result, xcopy);
1187                return result;
1188        }
1189        else
1190        {
1191                void *target = getTarget(i);
1192                *((ExtValue*)target) = x;
1193                return PSET_CHANGED;
1194        }
1195}
1196
1197void SimpleAbstractParam::call(int i, ExtValue *args, ExtValue *ret)
1198{
1199        SANITY_CHECK(i);
1200        ParamEntry *pe = entry(i);
1201        if (!pe) return;
1202        if (pe->fun1 && (pe->type[0] == 'p'))
1203                (*(void(*)(void*, ExtValue*, ExtValue*))pe->fun1)(object, args, ret);
1204        else
1205        {
1206                logPrintf("SimpleAbstractParam", "call", LOG_ERROR,
1207                        (*pe->type != 'p') ? "'%s.%s' is not a function" : "Internal error - undefined function pointer for '%s.%s'", getName(), pe->id);
1208                ret->setInvalid();
1209        }
1210}
1211
1212void SimpleAbstractParam::setDefault()
1213{
1214        bool save = dontcheckchanges;
1215        dontcheckchanges = 1;
1216        ParamInterface::setDefault();
1217        dontcheckchanges = save;
1218}
1219
1220void SimpleAbstractParam::setDefault(int i)
1221{
1222        bool save = dontcheckchanges;
1223        dontcheckchanges = 1;
1224        ParamInterface::setDefault(i);
1225        dontcheckchanges = save;
1226}
1227
1228// Returns the address of the beginning of the line.
1229// len = line length (without \n).
1230// 0 may mean the line with length=0 or the end of the SString.
1231// poz is advanced to the beginning of the next line.
1232// A typical loop: for(poz=0;poz<s.d;) {line=getline(s,poz,len);...
1233static const char *getline(const SString &s, int &poz, int &len)
1234{
1235        const char *beg = s.c_str() + poz;
1236        if (poz >= s.len()) { poz = s.len(); len = 0; return s.c_str() + s.len(); }
1237        const char *lf = strchr(beg, '\n');
1238        if (!lf) { lf = s.c_str() + s.len() - 1; poz = s.len(); }
1239        else { poz = (int)(lf - s.c_str()) + 1; if (poz > s.len()) poz = s.len(); }
1240        while (lf >= beg) if ((*lf == '\n') || (*lf == '\r')) lf--; else break;
1241        len = (int)(lf - beg) + 1;
1242        return beg;
1243}
1244
1245int ParamInterface::loadSingleLine(const SString &s, LoadOptions &options)
1246{
1247        int i; // the index number of the parameter
1248        int tmpi;
1249        int len;
1250        int ret;
1251        int fields_loaded = 0;
1252        const char *t, *lin, *end;
1253        const char *equals_sign, *field_end, *next_field;
1254        char remember;
1255        const char *quote, *quote2;
1256        const char *value, *valstop;
1257        SString tmpvalue;
1258        bool parse_failed = false;
1259        if (options.offset >= s.len()) return fields_loaded;
1260        t = s.c_str() + options.offset;
1261
1262        lin = getline(s, options.offset, len); // all fields must be encoded in a single line
1263        if (!len) return fields_loaded; // empty line = end
1264        i = 0;
1265        end = lin + len;
1266        while (t < end)
1267        {
1268                // processing a single field
1269                // "p:name=field_value,  field_name=field_value  , name=value..."
1270                //                     ^ ^-t (after)           ^ ^_next_field
1271                //                     \_t (before)            \_field_end
1272                while (isspace(*t)) if (t < end) t++; else return fields_loaded;
1273
1274                field_end = strchrlimit(t, ',', end); if (!field_end) field_end = end;
1275                next_field = field_end;
1276                while ((field_end > t) && isblank(field_end[-1])) field_end--;
1277                quote = strchrlimit(t, '\"', field_end);
1278                if (quote)
1279                {
1280                        quote2 = skipQuoteString(quote + 1, end);
1281                        if (quote2 > field_end)
1282                        {
1283                                field_end = strchrlimit(quote2 + 1, ',', end);
1284                                if (!field_end) field_end = end;
1285                                next_field = field_end;
1286                        }
1287                        equals_sign = strchrlimit(t, '=', quote);
1288                }
1289                else
1290                {
1291                        equals_sign = strchrlimit(t, '=', field_end);
1292                        quote2 = 0;
1293                }
1294                if (equals_sign == t) { t++; equals_sign = 0; }
1295                if (field_end == t)     // skip empty value
1296                {
1297                        t++; i++;
1298                        continue;
1299                }
1300                if (equals_sign) // have parameter name
1301                {
1302                        tmpi = findIdn(t, (int)(equals_sign - t));
1303                        i = tmpi;
1304                        if (tmpi < 0)
1305                        {
1306                                SString name(t, (int)(equals_sign - t));
1307                                logPrintf("Param", "loadSingleLine", LOG_WARN, "Unknown property '%s.%s' (ignored)", getName(), name.c_str());
1308                        }
1309                        t = equals_sign + 1; // t=value
1310                }
1311#ifdef WARN_MISSING_NAME
1312                else
1313#ifdef SAVE_SELECTED_NAMES
1314                        if ((i >= getPropCount()) || !(flags(i)&PARAM_CANOMITNAME))
1315#endif
1316                        {
1317                                if (id(i))
1318                                        logPrintf("Param", "loadSingleLine", LOG_WARN, "Missing property name in '%s' (assuming '%s')", getName(), id(i));
1319                                else
1320                                        logPrintf("Param", "loadSingleLine", LOG_WARN, "Value after the last property of '%s'", getName());
1321                        }
1322#endif
1323                if ((i >= 0) && id(i))
1324                {
1325                        value = t;
1326                        if (quote)
1327                        {
1328                                tmpvalue.copyFrom(quote + 1, (int)(quote2 - quote) - 1);
1329                                sstringUnquote(tmpvalue);
1330                                value = tmpvalue.c_str();
1331                                valstop = quote2;
1332                        }
1333                        else
1334                                if (field_end < end) valstop = field_end; else valstop = end;
1335
1336                        remember = *valstop;
1337                        *(char*)valstop = 0;
1338                        ret = setFromString(i, value, true);
1339                        fields_loaded++;
1340                        if (ret&PSET_PARSEFAILED)
1341                                parse_failed = true;
1342                        *(char*)valstop = remember;
1343                }
1344
1345                if (i >= 0) i++;
1346#ifdef __CODEGUARD__
1347                if (next_field < end - 1) t = next_field + 1; else return fields_loaded;
1348#else
1349                t = next_field + 1;
1350#endif
1351        }
1352        if (parse_failed) options.parse_failed = true;
1353        return fields_loaded;
1354}
1355
1356int Param::grmember(int g, int a)
1357{
1358        if ((getGroupCount() < 2) && (!g))
1359                return (a < getPropCount()) ? a : -9999;
1360
1361        ParamEntry *e = entry(0);
1362        int x = 0, i = 0;
1363        for (; e->id; i++, e++)
1364        {
1365                if (e->group == g)
1366                        if (a == x) return i; else x++;
1367        }
1368        return -9999;
1369}
Note: See TracBrowser for help on using the repository browser.