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

Last change on this file since 754 was 754, checked in by Maciej Komosinski, 6 years ago

More strict rules for Param type descriptions and "unlimited range value" and "unlimited string length": "d 0 -1", "f 0 -1", "s 0 0", "s 1 0" (see formatspec.html)

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