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

Last change on this file since 993 was 993, checked in by Maciej Komosinski, 4 years ago

Skip 'p' items in saveSingleLine()

  • Property svn:eol-style set to native
File size: 34.9 KB
Line 
1// This file is a part of Framsticks SDK.  http://www.framsticks.com/
2// Copyright (C) 1999-2020  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.length() > 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.length() > 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
333SString ParamInterface::nameDotProperty(int prop)
334{
335        SString ret = getName();
336        ret += ".";
337        ret += id(prop);
338        return ret;
339}
340
341SString ParamInterface::nameDotPropertyForMessages(int prop)
342{
343        SString name_dot_prop = nameDotProperty(prop);
344        if (strcmp(getName(), getLongName()) == 0)
345        {
346                if (strcmp(id(prop), name(prop)) == 0)
347                        return name_dot_prop;
348                else
349                        return SString("'") + name(prop) + "': " + name_dot_prop;
350        }
351        else
352                return SString("'") + name(prop) + "' in '" + getLongName() + "': " + name_dot_prop;
353}
354
355int SimpleAbstractParam::isequal(int i, void* defdata)
356{ // defdata->member == object->member ?
357        void *backup = object;
358        switch (type(i)[0])
359        {
360        case 'd':
361        {
362                select(defdata);
363                paInt x = getInt(i);
364                select(backup);
365                return x == getInt(i);
366        }
367        case 'f':
368        {
369                select(defdata);
370                double x = getDouble(i);
371                select(backup);
372                return x == getDouble(i);
373        }
374        case 's':
375        {
376                select(defdata);
377                SString x = getString(i);
378                select(backup);
379                return x == getString(i);
380        }
381        }
382        return 1;
383}
384
385void SimpleAbstractParam::saveSingleLine(SString& f, void *defdata, bool addcr, bool all_names)
386{ // defdata!=NULL -> does not save default values
387        const char *p;
388        int i;
389        int needlabel = 0;
390        int first = 1;
391        SString val;
392        SString t;
393        int fl;
394        // t+=SString(getName()); t+=':';
395        for (i = 0; p = id(i); i++)
396                if ((!((fl = flags(i)) & PARAM_DONTSAVE)) && type(i)[0]!='p')
397                {
398                        if (defdata && isequal(i, defdata))
399                                needlabel = 1;
400                        else
401                        {
402                                if (!first) t += ", ";
403#ifndef SAVE_ALL_NAMES
404#ifdef SAVE_SELECTED_NAMES
405                                if (needlabel || all_names || !(fl & PARAM_CANOMITNAME))
406#else
407                                if (needlabel)
408#endif
409#endif
410                                {
411                                        t += p; t += "="; needlabel = 0;
412                                }
413                                if (type(i)[0] == 's')
414                                { // string - special case
415                                        SString str = getString(i);
416                                        if (strContainsOneOf(str.c_str(), ", \\\n\r\t\""))
417                                        {
418                                                t += "\"";
419                                                sstringQuote(str);
420                                                t += str;
421                                                t += "\"";
422                                        }
423                                        else
424                                                t += str;
425                                }
426                                else
427                                        t += get(i);
428                                first = 0;
429                        }
430                }
431        if (addcr)
432                t += "\n";
433        f += t;
434}
435
436static void closingTildeError(ParamInterface *pi, VirtFILE *file, int field_index)
437{
438        SString fileinfo;
439        const char* fname = file->VgetPath();
440        if (fname != NULL)
441                fileinfo = SString::sprintf(" while reading from '%s'", fname);
442        SString field;
443        if (field_index >= 0)
444                field = pi->nameDotPropertyForMessages(field_index);
445        else
446                field = SString::sprintf("unknown property of '%s'", pi->getName());
447        logPrintf("ParamInterface", "load", LOG_WARN, "Closing '~' (tilde) not found in %s%s", field.c_str(), fileinfo.c_str());
448}
449
450template<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
451{
452        if (setflags & (PSET_HITMIN | PSET_HITMAX))
453        {
454                ExtValue v(valuetoset);
455                pi->messageOnExceedRange(i, setflags, v);
456        }
457}
458
459void SimpleAbstractParam::messageOnExceedRange(int i, int setflags, ExtValue& valuetoset) ///< prints a warning when setflags indicates that allowed param range has been exceeded during set
460{
461        if (setflags & (PSET_HITMIN | PSET_HITMAX))
462        {
463                SString svaluetoset = valuetoset.getString(); //converts any type to SString
464                SString actual = get(i);
465                bool s_type = type(i)[0] == 's';
466                bool show_length = valuetoset.getType() == TString;
467                const char* quote = (valuetoset.getType() == TString) ? "\"" : "'";
468                logPrintf("Param", "set", LOG_WARN, "Setting %s = %s exceeded allowed range (too %s). %s to %s.",
469                        nameDotPropertyForMessages(i).c_str(),
470                        ::sstringDelimitAndShorten(svaluetoset, 30, show_length, quote, quote).c_str(),
471                        (setflags & PSET_HITMAX) ? (s_type ? "long" : "big") : "small", s_type ? "Truncated" : "Adjusted",
472                        ::sstringDelimitAndShorten(actual, 30, show_length, quote, quote).c_str()
473                );
474        }
475}
476
477int ParamInterface::load(FileFormat format, VirtFILE* f, LoadOptions *options)
478{
479        LoadOptions default_options;
480        if (options == NULL)
481                options = &default_options;
482        switch (format)
483        {
484        case FormatMultiLine:
485                return loadMultiLine(f, *options);
486
487        case FormatSingleLine:
488        {
489                StringFILE *sf = dynamic_cast<StringFILE*>(f);
490                SString s;
491                if (sf)
492                {
493                        s = sf->getString().c_str();
494                        options->offset += sf->Vtell();
495                }
496                else
497                {
498                        if (!loadSStringLine(f, s))
499                                return -1;
500                }
501                return loadSingleLine(s, *options);
502        }
503        }
504        return -1;
505}
506
507int ParamInterface::load(FileFormat format, const SString &s, LoadOptions *options)
508{
509        LoadOptions default_options;
510        if (options == NULL)
511                options = &default_options;
512        switch (format)
513        {
514        case FormatMultiLine:
515        {
516                string std_string(s.c_str());
517                StringFILE f(std_string);
518                return loadMultiLine(&f, *options);
519        }
520
521        case FormatSingleLine:
522                return loadSingleLine(s, *options);
523        }
524        return -1;
525}
526
527int ParamInterface::loadMultiLine(VirtFILE* f, LoadOptions &options)
528{
529        SString buf;
530        int i;
531        const char *p, *p0;
532        int p_len;
533        bool loaded;
534        int fields_loaded = 0;
535        int unexpected_line = 0;
536        vector<bool> seen;
537        seen.resize(getPropCount());
538        if ((i = findId("beforeLoad")) >= 0)
539                call(i, NULL, NULL);
540        while (((!options.abortable) || (!*options.abortable)) && loadSStringLine(f, buf))
541        {
542                if (options.linenum) (*options.linenum)++;
543                const char* t = buf.c_str();
544                p0 = t; while (isblank(*p0)) p0++;
545                if (!*p0) break;
546                if (p0[0] == '#') { unexpected_line = 0; continue; }
547                p = strchr(p0, ':');
548                if (!p)
549                {
550                        switch (unexpected_line)
551                        {
552                        case 0:
553                                logPrintf("ParamInterface", "load", LOG_WARN, "Ignored unexpected line %s while reading object '%s'",
554                                        options.linenum ?
555                                        SString::sprintf("%d", *options.linenum).c_str()
556                                        : SString::sprintf("'%s'", p0).c_str(),
557                                        getName());
558                                break;
559                        case 1:
560                                logPrintf("ParamInterface", "load", LOG_WARN, "The following line(s) were also unexpected and were ignored");
561                                break;
562                        }
563                        unexpected_line++;
564                        continue;
565                }
566                unexpected_line = 0;
567                p_len = (int)(p - p0);
568                loaded = false;
569                if (p_len && ((i = findIdn(p0, p_len)) >= 0))
570                {
571                        if (seen[i])
572                        {
573                                SString fileinfo;
574                                const char* fname = f->VgetPath();
575                                if (fname != NULL)
576                                {
577                                        fileinfo = SString::sprintf(" while reading from '%s'", fname);
578                                        if (options.linenum)
579                                                fileinfo += SString::sprintf(" (line %d)", *options.linenum);
580                                }
581                                logPrintf("ParamInterface", "load", LOG_WARN, "Multiple '%s.%s' properties found%s", getName(), id(i), fileinfo.c_str());
582                        }
583                        else
584                                seen[i] = true;
585                        if (!(flags(i) & PARAM_DONTLOAD))
586                        {
587                                if (p0[p_len + 1] == '~')
588                                {
589                                        SString s;
590                                        if (!readUntilTilde(f, s))
591                                                closingTildeError(this, f, i);
592                                        int lfcount = 1;
593                                        const char* tmp = s.c_str();
594                                        while (tmp)
595                                                if ((tmp = strchr(tmp, '\n')))
596                                                {
597                                                        lfcount++; tmp++;
598                                                }
599                                        removeCR(s);
600                                        int ch; while ((ch = f->Vgetc()) != EOF) if (ch == '\n') break;
601                                        unquoteTilde(s);
602                                        if (options.linenum && (flags(i) & PARAM_LINECOMMENT))
603                                                s = SString::sprintf("@file %s\n@line %d\n", f->VgetPath(), *options.linenum + 1) + s;
604                                        setFromString(i, s.c_str(), false);
605                                        if (options.linenum)
606                                                (*options.linenum) += lfcount;
607                                }
608                                else
609                                {
610                                        SString s = SString(p0 + p_len + 1);
611                                        unquoteTilde(s);
612                                        setFromString(i, s.c_str(), false);
613                                }
614                                fields_loaded++;
615                                loaded = true;
616                        }
617                }
618                else if (options.warn_unknown_fields)
619                {
620                        SString name(p0, p_len);
621                        logPrintf("ParamInterface", "load", LOG_WARN, "Ignored unknown property '%s.%s'", getName(), name.c_str());
622                }
623
624                if ((!loaded) && (p0[p_len + 1] == '~'))
625                { // eat unrecognized multiline field
626                        SString s;
627                        if (!readUntilTilde(f, s))
628                                closingTildeError(this, f, -1);
629                        if (options.linenum)
630                        {
631                                const char* tmp = s.c_str();
632                                int lfcount = 1;
633                                while (tmp)
634                                        if ((tmp = strchr(tmp, '\n')))
635                                        {
636                                                lfcount++; tmp++;
637                                        }
638                                (*options.linenum) += lfcount;
639                        }
640                        int ch; while ((ch = f->Vgetc()) != EOF) if (ch == '\n') break;
641                }
642        }
643        if ((i = findId("afterLoad")) >= 0)
644                call(i, NULL, NULL);
645        return fields_loaded;
646}
647
648
649/*
650SString SimpleAbstractParam::getString(int i)
651{
652char *t;
653switch (*(t=type(i)))
654{
655case 'd':
656{
657for (i=atol(get(i));i>=0;i--) if (t) t=strchr(t+1,'~');
658if (t)
659{
660t++;
661char *t2=strchr(t,'~');
662if (!t2) t2=t+strlen(t);
663SString str;
664strncpy(str.directWrite(t2-t),t,t2-t);
665str.endWrite(t2-t);
666return str;
667}
668}
669}
670return get(i);
671}
672*/
673
674int ParamInterface::findId(const char* n)
675{
676        int i; const char *p;
677        for (i = 0; p = id(i); i++) if (!strcmp(n, p)) return i;
678        return -1;
679}
680
681int ParamInterface::findIdn(const char* naz, int n)
682{
683        int i; const char *p;
684        for (i = 0; p = id(i); i++) if ((!strncmp(naz, p, n)) && (!p[n])) return i;
685        return -1;
686}
687
688void ParamInterface::get(int i, ExtValue &ret)
689{
690        switch (type(i)[0])
691        {
692        case 'd':       ret.setInt(getInt(i)); break;
693        case 'f':       ret.setDouble(getDouble(i)); break;
694        case 's':       ret.setString(getString(i)); break;
695        case 'o':       ret.setObject(getObject(i)); break;
696        case 'x':       ret = getExtValue(i); break;
697        default: logPrintf("ParamInterface", "get", LOG_ERROR, "%s is not a property", nameDotPropertyForMessages(i).c_str());
698        }
699}
700
701int ParamInterface::setIntFromString(int i, const char* str, bool strict)
702{
703        paInt value;
704        if (!ExtValue::parseInt(str, value, strict, true))
705        {
706                paInt mn, mx, def;
707                if (getMinMaxInt(i, mn, mx, def) >= 3)
708                        return setInt(i, def) | PSET_PARSEFAILED;
709                else
710                        return setInt(i, (paInt)0) | PSET_PARSEFAILED;
711        }
712        else
713                return setInt(i, value);
714}
715
716int ParamInterface::setDoubleFromString(int i, const char* str)
717{
718        double value;
719        if (!ExtValue::parseDouble(str, value, true))
720        {
721                double mn, mx, def;
722                if (getMinMaxDouble(i, mn, mx, def) >= 3)
723                        return setDouble(i, def) | PSET_PARSEFAILED;
724                else
725                        return setDouble(i, (double)0) | PSET_PARSEFAILED;
726        }
727        else
728                return setDouble(i, value);
729}
730
731int ParamInterface::set(int i, const ExtValue &v)
732{
733        switch (type(i)[0])
734        {
735        case 'd':
736                if ((v.type == TInt) || (v.type == TDouble)) return setInt(i, v.getInt());
737                else
738                {
739                        if (v.type == TObj)
740                        {
741                                logPrintf("ParamInterface", "set", LOG_ERROR, "Setting int %s from object reference (%s)", nameDotPropertyForMessages(i).c_str(), v.getString().c_str());
742                                return 0;
743                        }
744                        else
745                                return setIntFromString(i, v.getString().c_str(), false);
746                }
747        case 'f':
748                if ((v.type == TInt) || (v.type == TDouble)) return setDouble(i, v.getDouble());
749                else
750                {
751                        if (v.type == TObj)
752                        {
753                                logPrintf("ParamInterface", "set", LOG_ERROR, "Setting float %s from object reference (%s)", nameDotPropertyForMessages(i).c_str(), v.getString().c_str());
754                                return 0;
755                        }
756                        else
757                                return setDoubleFromString(i, v.getString().c_str());
758                }
759        case 's': { SString t = v.getString(); return setString(i, t); }
760        case 'o':
761                if ((v.type != TUnknown) && (v.type != TObj))
762                        logPrintf("ParamInterface", "set", LOG_ERROR, "Setting object %s from %s", nameDotPropertyForMessages(i).c_str(), v.typeAndValue().c_str());
763                else
764                        return setObject(i, v.getObject());
765                break;
766        case 'x': return setExtValue(i, v);
767        default: logPrintf("ParamInterface", "set", LOG_ERROR, "%s is not a property", nameDotPropertyForMessages(i).c_str());
768        }
769        return 0;
770}
771
772int ParamInterface::setFromString(int i, const char *v, bool strict)
773{
774        char typ = type(i)[0];
775        switch (typ)
776        {
777        case 'd': return setIntFromString(i, v, strict);
778        case 'f': return setDoubleFromString(i, v);
779        case 's': { SString t(v); return setString(i, t); }
780        case 'x': case 'o':
781        {
782                ExtValue e;
783                const char* after;
784                if (!strncmp(v, SERIALIZATION_PREFIX, strlen(SERIALIZATION_PREFIX)))
785                {
786                        after = e.deserialize(v + strlen(SERIALIZATION_PREFIX));
787                        if ((after == NULL) || (*after))
788                        {
789                                logPrintf("ParamInterface", "set", LOG_ERROR, "serialization format mismatch in %s.%s", (getName() ? getName() : "<Unknown>"), id(i));
790                                e.setEmpty();
791                        }
792                }
793                else if ((after = e.parseNumber(v)) && (*after == 0)) //consumed the whole string
794                {
795                        //OK!
796                }
797                else
798                {
799                        e.setString(SString(v));
800                }
801                if (typ == 'x')
802                        return setExtValue(i, e);
803                else
804                        return setObject(i, e.getObject());
805        }
806        }
807        return 0;
808}
809
810SString ParamInterface::getText(int i) //find the current enum text or call get(i) if not enum
811{
812        const char *t;
813        if (((*(t = type(i))) == 'd') && (strchr(t, '~') != NULL)) //type is int and contains enum labels
814        {
815                paInt mn, mx, def;
816                int value = getInt(i);
817                if (getMinMaxIntFromTypeDef(t, mn, mx, def) >= 2)
818                {
819                        if (value > mx)
820                                return get(i);//unexpected value of out bounds (should never happen) -> fallback
821                        value -= mn;
822                }
823                if (value < 0) return get(i); //unexpected value of out bounds (should never happen) -> fallback
824                // now value is 0-based index of ~text
825                for (; value >= 0; value--) if (t) t = strchr(t + 1, '~'); else break;
826                if (t) // found n-th ~text in type description (else: not enough ~texts in type description)
827                {
828                        t++;
829                        const char *t2 = strchr(t, '~');
830                        if (!t2) t2 = t + strlen(t);
831                        return SString(t, (int)(t2 - t));
832                }
833        }
834        return get(i); //fallback - return int value as string
835}
836
837SString ParamInterface::get(int i)
838{
839        switch (type(i)[0])
840        {
841        case 'd': return SString::valueOf(getInt(i));
842        case 'f': return SString::valueOf(getDouble(i));
843        case 's': return getString(i);
844        }
845        ExtValue v;
846        get(i, v);
847        return v.getString();
848}
849
850bool ParamInterface::isValidTypeDescription(const char* t)
851{
852        if (t == NULL) return false;
853        if (*t == 0) return false;
854        if (strchr("dfsoxp", *t) == NULL) return false;
855        switch (*t)
856        {
857        case 'd':
858        {
859                paInt a, b, c;
860                int have = getMinMaxIntFromTypeDef(t, a, b, c);
861                if (have == 1) return false;
862                if ((have >= 2) && (b < a) && (a != 0) && (b != -1)) return false; // max<min meaning 'undefined' is only allowed as "d 0 -1"
863        }
864        break;
865        case 'f':
866        {
867                double a, b, c;
868                int have = getMinMaxDoubleFromTypeDef(t, a, b, c);
869                if (have == 1) return false;
870                if ((have >= 2) && (b < a) && (a != 0) && (b != -1)) return false; // max<min meaning 'undefined' is only allowed as "f 0 -1"
871        }
872        break;
873        case 's':
874        {
875                int a, b; SString c;
876                int have = getMinMaxStringFromTypeDef(t, a, b, c);
877                //if (have == 1) return false; //not sure?
878                if ((have >= 1) && (!((a == 0) || (a == 1)))) return false; // 'min' for string (single/multi) can be only 0 or 1
879                if ((have >= 2) && (b < 0)) return false; // max=0 means unlimited, max<0 is not allowed
880        }
881        break;
882        }
883        return true;
884}
885
886SString ParamInterface::friendlyTypeDescrFromTypeDef(const char* type)
887{
888        SString t;
889        switch (type[0])
890        {
891        case 'd': t += "integer";
892        {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); }
893        break;
894        case 'f': t += "float";
895        {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); }
896        break;
897        case 's': t += "string";
898        {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()); }
899        break;
900        case 'x': t += "untyped value"; break;
901        case 'p': t += "function"; break;
902        case 'o': t += "object"; if (type[1]) { t += " of class "; t += type + 1; } break;
903        default: return "unknown type";
904        }
905        return t;
906}
907
908//////////////////////////////// PARAM ////////////////////////////////////
909
910#ifdef _DEBUG
911void SimpleAbstractParam::sanityCheck(int i)
912{
913        ParamEntry *pe = entry(i);
914
915        const char* t = pe->type;
916        const char* err = NULL;
917
918        if (!isValidTypeDescription(t))
919                err = "invalid type description";
920        if (*t == 'p')
921        {
922                if (pe->fun1 == NULL)
923                {
924                        MutableParamInterface *mpi = dynamic_cast<MutableParamInterface*>(this);
925                        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.
926                                err = "no procedure defined";
927                }
928                if (pe->flags & PARAM_READONLY)
929                        err = "function can't be PARAM_READONLY";
930        }
931        else
932        {
933                if ((t[0] == 'o') && (t[1] == ' '))
934                {
935                        err = "space after 'o'";
936                }
937                if (!(pe->flags & (PARAM_READONLY | PARAM_DONTSAVE | PARAM_USERREADONLY | PARAM_CONST | PARAM_DONTLOAD | PARAM_LINECOMMENT | PARAM_OBJECTSET)))
938                { //write access
939                        if ((pe->fun2 == NULL) && (pe->offset == PARAM_ILLEGAL_OFFSET))
940                                err = "no field defined (GETONLY without PARAM_READONLY?)";
941                }
942        }
943        if (err != NULL)
944                logPrintf("SimpleAbstractParam", "sanityCheck", LOG_ERROR,
945                        "Invalid ParamEntry for %s (%s)", nameDotPropertyForMessages(i).c_str(), err);
946}
947#endif
948
949void *SimpleAbstractParam::getTarget(int i)
950{
951        return (void*)(((char*)object) + entry(i)->offset);
952        //return &(object->*(entry(i)->fldptr));
953}
954
955///////// get
956
957#ifdef _DEBUG
958#define SANITY_CHECK(i) sanityCheck(i)
959#else
960#define SANITY_CHECK(i)
961#endif
962
963paInt SimpleAbstractParam::getInt(int i)
964{
965        SANITY_CHECK(i);
966        ExtValue v;
967        ParamEntry *pe = entry(i);
968        if (pe->fun1)
969        {
970                (*(void(*)(void*, ExtValue*))pe->fun1)(object, &v);
971                return v.getInt();
972        }
973        else
974        {
975                void *target = getTarget(i);
976                return *((paInt*)target);
977        }
978}
979
980double SimpleAbstractParam::getDouble(int i)
981{
982        SANITY_CHECK(i);
983        ExtValue v;
984        ParamEntry *pe = entry(i);
985        if (pe->fun1)
986        {
987                (*(void(*)(void*, ExtValue*))pe->fun1)(object, &v);
988                return v.getDouble();
989        }
990        else
991        {
992                void *target = getTarget(i);
993                return *((double*)target);
994        }
995}
996
997SString SimpleAbstractParam::getString(int i)
998{
999        SANITY_CHECK(i);
1000        ExtValue v;
1001        ParamEntry *pe = entry(i);
1002        if (pe->fun1)
1003        {
1004                (*(void(*)(void*, ExtValue*))pe->fun1)(object, &v);
1005                return v.getString();
1006        }
1007        else
1008        {
1009                void *target = getTarget(i);
1010                return *((SString*)target);
1011        }
1012}
1013
1014ExtObject SimpleAbstractParam::getObject(int i)
1015{
1016        SANITY_CHECK(i);
1017        ExtValue v;
1018        ParamEntry *pe = entry(i);
1019        if (pe->fun1)
1020        {
1021                (*(void(*)(void*, ExtValue*))pe->fun1)(object, &v);
1022                return v.getObject();
1023        }
1024        else
1025        {
1026                void *target = getTarget(i);
1027                return *((ExtObject*)target);
1028        }
1029}
1030
1031ExtValue SimpleAbstractParam::getExtValue(int i)
1032{
1033        SANITY_CHECK(i);
1034        ExtValue v;
1035        ParamEntry *pe = entry(i);
1036        if (pe->fun1)
1037        {
1038                (*(void(*)(void*, ExtValue*))pe->fun1)(object, &v);
1039                return v;
1040        }
1041        else
1042        {
1043                void *target = getTarget(i);
1044                return *((ExtValue*)target);
1045        }
1046}
1047
1048
1049//////// set
1050
1051int SimpleAbstractParam::setInt(int i, paInt x)
1052{
1053        SANITY_CHECK(i);
1054        ExtValue v;
1055        ParamEntry *pe = entry(i);
1056        if (pe->flags & PARAM_READONLY) return PSET_RONLY;
1057        paInt xcopy = x; //only needed for messageOnExceedRange(): retain original, requested value of x because it may be changed below
1058        paInt mn = 0, mx = 0, de = 0;
1059        int result = 0;
1060        if (getMinMaxIntFromTypeDef(pe->type, mn, mx, de) >= 2)
1061                if (mn <= mx) // else if mn>mx then the min/max constraint makes no sense and there is no checking
1062                {
1063                        if (x < mn) { x = mn; result = PSET_HITMIN; }
1064                        else if (x > mx) { x = mx; result = PSET_HITMAX; }
1065                }
1066
1067        if (pe->fun2)
1068        {
1069                v.setInt(x);
1070                result |= (*(int(*)(void*, const ExtValue*))pe->fun2)(object, &v);
1071        }
1072        else
1073        {
1074                void *target = getTarget(i);
1075                if (dontcheckchanges || (*((paInt*)target) != x))
1076                {
1077                        result |= PSET_CHANGED;
1078                        *((paInt*)target) = x;
1079                }
1080        }
1081        ::messageOnExceedRange(this, i, result, xcopy);
1082        return result;
1083}
1084
1085int SimpleAbstractParam::setDouble(int i, double x)
1086{
1087        SANITY_CHECK(i);
1088        ExtValue v;
1089        ParamEntry *pe = entry(i);
1090        if (pe->flags & PARAM_READONLY) return PSET_RONLY;
1091        double xcopy = x; //only needed for messageOnExceedRange(): retain original, requested value of x because it may be changed below
1092        double mn = 0, mx = 0, de = 0;
1093        int result = 0;
1094        if (getMinMaxDoubleFromTypeDef(pe->type, mn, mx, de) >= 2)
1095                if (mn <= mx) // else if mn>mx then the min/max constraint makes no sense and there is no checking
1096                {
1097                        if (x < mn) { x = mn; result = PSET_HITMIN; }
1098                        else if (x > mx) { x = mx; result = PSET_HITMAX; }
1099                }
1100
1101        if (pe->fun2)
1102        {
1103                v.setDouble(x);
1104                result |= (*(int(*)(void*, const ExtValue*))pe->fun2)(object, &v);
1105        }
1106        else
1107        {
1108                void *target = getTarget(i);
1109                if (dontcheckchanges || (*((double*)target) != x))
1110                {
1111                        result |= PSET_CHANGED;
1112                        *((double*)target) = x;
1113                }
1114        }
1115        ::messageOnExceedRange(this, i, result, xcopy);
1116        return result;
1117}
1118
1119int SimpleAbstractParam::setString(int i, const SString& x)
1120{
1121        SANITY_CHECK(i);
1122        ExtValue v;
1123        SString vs;
1124        const SString *xx = &x;
1125        ParamEntry *pe = entry(i);
1126        if (pe->flags & PARAM_READONLY) return PSET_RONLY;
1127        SString xcopy = x; //only needed for messageOnExceedRange(): retain original, requested value of x because it may be changed below
1128        const char* t = pe->type + 1;
1129        while (*t) if (*t == ' ') break; else t++;
1130        int mn = 0, mx = 0;
1131        int result = 0;
1132        if (sscanf(t, "%d %d", &mn, &mx) == 2) //using getMinMax would also get default value, which is not needed here
1133        {
1134                if ((x.length() > mx) && (mx > 0))
1135                {
1136                        vs = x.substr(0, mx);
1137                        xx = &vs;
1138                        result |= PSET_HITMAX;
1139                }
1140        }
1141
1142        if (pe->fun2)
1143        {
1144                v.setString(*xx);
1145                result |= (*(int(*)(void*, const ExtValue*))pe->fun2)(object, &v);
1146        }
1147        else
1148        {
1149                void *target = getTarget(i);
1150                if (dontcheckchanges || (!(*((SString*)target) == *xx)))
1151                {
1152                        result |= PSET_CHANGED;
1153                        *((SString*)target) = *xx;
1154                }
1155        }
1156        ::messageOnExceedRange(this, i, result, xcopy);
1157        return result;
1158}
1159
1160int SimpleAbstractParam::setObject(int i, const ExtObject& x)
1161{
1162        SANITY_CHECK(i);
1163        ExtValue v;
1164        ParamEntry *pe = entry(i);
1165        if (pe->flags & PARAM_READONLY) return PSET_RONLY;
1166        if (pe->flags & PARAM_OBJECTSET)
1167        {
1168                ExtObject o = getObject(i);
1169                Param tmp;
1170                ParamInterface* oif = o.getParamInterface(tmp);
1171                int ass;
1172                if (oif && ((ass = oif->findId("assign")) >= 0))
1173                {
1174                        ExtValue arg = x;
1175                        oif->call(ass, &arg, &v);
1176                }
1177                else
1178                        logPrintf("SimpleAbstractParam", "setObject", LOG_ERROR,
1179                                "%s is PARAM_OBJECTSET but no 'assign()' in %s", nameDotPropertyForMessages(i).c_str(), o.interfaceName());
1180                return PSET_CHANGED;
1181        }
1182        ExtObject xcopy = x; //only needed for messageOnExceedRange(): retain original, requested value of x because it may be changed below
1183        if (pe->fun2)
1184        {
1185                v.setObject(x);
1186                int result = (*(int(*)(void*, const ExtValue*))pe->fun2)(object, &v);
1187                ::messageOnExceedRange(this, i, result, xcopy);
1188                return result;
1189        }
1190        else
1191        {
1192                void *target = getTarget(i);
1193                *((ExtObject*)target) = x;
1194                return PSET_CHANGED;
1195        }
1196}
1197
1198int SimpleAbstractParam::setExtValue(int i, const ExtValue& x)
1199{
1200        SANITY_CHECK(i);
1201        ParamEntry *pe = entry(i);
1202        if (pe->flags & PARAM_READONLY) return PSET_RONLY;
1203        ExtValue xcopy = x; //only needed for messageOnExceedRange(): retain original, requested value of x because it may be changed below
1204        if (pe->fun2)
1205        {
1206                int result = (*(int(*)(void*, const ExtValue*))pe->fun2)(object, &x);
1207                ::messageOnExceedRange(this, i, result, xcopy);
1208                return result;
1209        }
1210        else
1211        {
1212                void *target = getTarget(i);
1213                *((ExtValue*)target) = x;
1214                return PSET_CHANGED;
1215        }
1216}
1217
1218void SimpleAbstractParam::call(int i, ExtValue *args, ExtValue *ret)
1219{
1220        SANITY_CHECK(i);
1221        ParamEntry *pe = entry(i);
1222        if (!pe) return;
1223        if (pe->fun1 && (pe->type[0] == 'p'))
1224                (*(void(*)(void*, ExtValue*, ExtValue*))pe->fun1)(object, args, ret);
1225        else
1226        {
1227                logPrintf("SimpleAbstractParam", "call", LOG_ERROR,
1228                        (*pe->type != 'p') ? "%s is not a function" : "Internal error - undefined function pointer for %s", nameDotPropertyForMessages(i).c_str());
1229                ret->setInvalid();
1230        }
1231}
1232
1233void SimpleAbstractParam::setDefault()
1234{
1235        bool save = dontcheckchanges;
1236        dontcheckchanges = 1;
1237        ParamInterface::setDefault();
1238        dontcheckchanges = save;
1239}
1240
1241void SimpleAbstractParam::setDefault(int i)
1242{
1243        bool save = dontcheckchanges;
1244        dontcheckchanges = 1;
1245        ParamInterface::setDefault(i);
1246        dontcheckchanges = save;
1247}
1248
1249// Returns the address of the beginning of the line.
1250// len = line length (without \n).
1251// 0 may mean the line with length=0 or the end of the SString.
1252// poz is advanced to the beginning of the next line.
1253// A typical loop: for(poz=0;poz<s.d;) {line=getline(s,poz,len);...
1254static const char *getline(const SString &s, int &poz, int &len)
1255{
1256        const char *beg = s.c_str() + poz;
1257        if (poz >= s.length()) { poz = s.length(); len = 0; return s.c_str() + s.length(); }
1258        const char *lf = strchr(beg, '\n');
1259        if (!lf) { lf = s.c_str() + s.length() - 1; poz = s.length(); }
1260        else { poz = (int)(lf - s.c_str()) + 1; if (poz > s.length()) poz = s.length(); }
1261        while (lf >= beg) if ((*lf == '\n') || (*lf == '\r')) lf--; else break;
1262        len = (int)(lf - beg) + 1;
1263        return beg;
1264}
1265
1266int ParamInterface::loadSingleLine(const SString &s, LoadOptions &options)
1267{
1268        int i; // the index number of the parameter
1269        int tmpi;
1270        int len;
1271        int ret;
1272        int fields_loaded = 0;
1273        const char *t, *lin, *end;
1274        const char *equals_sign, *field_end, *next_field;
1275        char remember;
1276        const char *quote, *quote2;
1277        const char *value, *valstop;
1278        SString tmpvalue;
1279        bool parse_failed = false;
1280        if (options.offset >= s.length()) return fields_loaded;
1281        t = s.c_str() + options.offset;
1282
1283        lin = getline(s, options.offset, len); // all fields must be encoded in a single line
1284        if (!len) return fields_loaded; // empty line = end
1285        i = 0;
1286        end = lin + len;
1287        while (t < end)
1288        {
1289                // processing a single field
1290                // "p:name=field_value,  field_name=field_value  , name=value..."
1291                //                     ^ ^-t (after)           ^ ^_next_field
1292                //                     \_t (before)            \_field_end
1293                while (isspace(*t)) if (t < end) t++; else return fields_loaded;
1294
1295                field_end = strchrlimit(t, ',', end); if (!field_end) field_end = end;
1296                next_field = field_end;
1297                while ((field_end > t) && isblank(field_end[-1])) field_end--;
1298                quote = strchrlimit(t, '\"', field_end);
1299                if (quote)
1300                {
1301                        quote2 = skipQuoteString(quote + 1, end);
1302                        if (quote2 > field_end)
1303                        {
1304                                field_end = strchrlimit(quote2 + 1, ',', end);
1305                                if (!field_end) field_end = end;
1306                                next_field = field_end;
1307                        }
1308                        equals_sign = strchrlimit(t, '=', quote);
1309                }
1310                else
1311                {
1312                        equals_sign = strchrlimit(t, '=', field_end);
1313                        quote2 = 0;
1314                }
1315                if (equals_sign == t) { t++; equals_sign = 0; }
1316                if (field_end == t)     // skip empty value
1317                {
1318                        t++; if (i >= 0) i++;
1319                        continue;
1320                }
1321                if (equals_sign) // have parameter name
1322                {
1323                        tmpi = findIdn(t, (int)(equals_sign - t));
1324                        i = tmpi;
1325                        if (tmpi < 0)
1326                        {
1327                                SString name(t, (int)(equals_sign - t));
1328                                logPrintf("Param", "loadSingleLine", LOG_WARN, "Unknown property '%s.%s' (ignored)", getName(), name.c_str());
1329                        }
1330                        t = equals_sign + 1; // t=value
1331                }
1332#ifdef WARN_MISSING_NAME
1333                else // no parameter name
1334                {
1335#ifdef SAVE_SELECTED_NAMES
1336                        if ((i < 0) // field after unknown field
1337                                || (i >= getPropCount()) // field after last field
1338                                || !(flags(i) & PARAM_CANOMITNAME)) // valid field but it can't be skipped
1339#endif
1340                        {
1341                                if (i < getPropCount())
1342                                        logPrintf("Param", "loadSingleLine", LOG_WARN, "Missing property name in '%s'", getName());
1343                                else // 'i' can go past PropCount because of moving to subsequent properties by i++, id(i) is then NULL
1344                                        logPrintf("Param", "loadSingleLine", LOG_WARN, "Value after the last property of '%s'", getName());
1345                        }
1346                }
1347                //else skipping a skippable field
1348#endif
1349                if ((i >= 0) && id(i)) // shared by name and skippped name cases
1350                {
1351                        value = t;
1352                        if (quote)
1353                        {
1354                                tmpvalue.copyFrom(quote + 1, (int)(quote2 - quote) - 1);
1355                                sstringUnquote(tmpvalue);
1356                                value = tmpvalue.c_str();
1357                                valstop = quote2;
1358                        }
1359                        else
1360                                if (field_end < end) valstop = field_end; else valstop = end;
1361
1362                        remember = *valstop;
1363                        *(char*)valstop = 0;
1364                        ret = setFromString(i, value, true);
1365                        fields_loaded++;
1366                        if (ret & PSET_PARSEFAILED)
1367                                parse_failed = true;
1368                        *(char*)valstop = remember;
1369                }
1370
1371                if (i >= 0) i++;
1372#ifdef __CODEGUARD__
1373                if (next_field < end - 1) t = next_field + 1; else return fields_loaded;
1374#else
1375                t = next_field + 1;
1376#endif
1377        }
1378        if (parse_failed) options.parse_failed = true;
1379        return fields_loaded;
1380}
1381
1382int Param::grmember(int g, int a)
1383{
1384        if ((getGroupCount() < 2) && (!g))
1385                return (a < getPropCount()) ? a : -9999;
1386
1387        ParamEntry *e = entry(0);
1388        int x = 0, i = 0;
1389        for (; e->id; i++, e++)
1390        {
1391                if (e->group == g)
1392                        if (a == x) return i; else x++;
1393        }
1394        return -9999;
1395}
Note: See TracBrowser for help on using the repository browser.