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

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

Unified error messages and error handling for loadSingleLine and loadMultiLine

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