1 //---------------------------------------------------------------------------------
2 //
3 // Little Color Management System
4 // Copyright (c) 1998-2020 Marti Maria Saguer
5 //
6 // Permission is hereby granted, free of charge, to any person obtaining
7 // a copy of this software and associated documentation files (the "Software"),
8 // to deal in the Software without restriction, including without limitation
9 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 // and/or sell copies of the Software, and to permit persons to whom the Software
11 // is furnished to do so, subject to the following conditions:
12 //
13 // The above copyright notice and this permission notice shall be included in
14 // all copies or substantial portions of the Software.
15 //
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
18 // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 //
24 //---------------------------------------------------------------------------------
25 //
26
27 #include "lcms2_internal.h"
28
29
30 // IT8.7 / CGATS.17-200x handling -----------------------------------------------------------------------------
31
32
33 #define MAXID 128 // Max length of identifier
34 #define MAXSTR 1024 // Max length of string
35 #define MAXTABLES 255 // Max Number of tables in a single stream
36 #define MAXINCLUDE 20 // Max number of nested includes
37
38 #define DEFAULT_DBL_FORMAT "%.10g" // Double formatting
39
40 #ifdef CMS_IS_WINDOWS_
41 # include <io.h>
42 # define DIR_CHAR '\\'
43 #else
44 # define DIR_CHAR '/'
45 #endif
46
47
48 // Symbols
49 typedef enum {
50
51 SUNDEFINED,
52 SINUM, // Integer
53 SDNUM, // Real
54 SIDENT, // Identifier
55 SSTRING, // string
56 SCOMMENT, // comment
57 SEOLN, // End of line
58 SEOF, // End of stream
59 SSYNERROR, // Syntax error found on stream
60
61 // Keywords
62
63 SBEGIN_DATA,
64 SBEGIN_DATA_FORMAT,
65 SEND_DATA,
66 SEND_DATA_FORMAT,
67 SKEYWORD,
68 SDATA_FORMAT_ID,
69 SINCLUDE
70
71 } SYMBOL;
72
73
74 // How to write the value
75 typedef enum {
76
77 WRITE_UNCOOKED,
78 WRITE_STRINGIFY,
79 WRITE_HEXADECIMAL,
80 WRITE_BINARY,
81 WRITE_PAIR
82
83 } WRITEMODE;
84
85 // Linked list of variable names
86 typedef struct _KeyVal {
87
88 struct _KeyVal* Next;
89 char* Keyword; // Name of variable
90 struct _KeyVal* NextSubkey; // If key is a dictionary, points to the next item
91 char* Subkey; // If key is a dictionary, points to the subkey name
92 char* Value; // Points to value
93 WRITEMODE WriteAs; // How to write the value
94
95 } KEYVALUE;
96
97
98 // Linked list of memory chunks (Memory sink)
99 typedef struct _OwnedMem {
100
101 struct _OwnedMem* Next;
102 void * Ptr; // Point to value
103
104 } OWNEDMEM;
105
106 // Suballocator
107 typedef struct _SubAllocator {
108
109 cmsUInt8Number* Block;
110 cmsUInt32Number BlockSize;
111 cmsUInt32Number Used;
112
113 } SUBALLOCATOR;
114
115 // Table. Each individual table can hold properties and rows & cols
116 typedef struct _Table {
117
118 char SheetType[MAXSTR]; // The first row of the IT8 (the type)
119
120 int nSamples, nPatches; // Cols, Rows
121 int SampleID; // Pos of ID
122
123 KEYVALUE* HeaderList; // The properties
124
125 char** DataFormat; // The binary stream descriptor
126 char** Data; // The binary stream
127
128 } TABLE;
129
130 // File stream being parsed
131 typedef struct _FileContext {
132 char FileName[cmsMAX_PATH]; // File name if being read from file
133 FILE* Stream; // File stream or NULL if holded in memory
134 } FILECTX;
135
136 // This struct hold all information about an open IT8 handler.
137 typedef struct {
138
139
140 cmsUInt32Number TablesCount; // How many tables in this stream
141 cmsUInt32Number nTable; // The actual table
142
143 TABLE Tab[MAXTABLES];
144
145 // Memory management
146 OWNEDMEM* MemorySink; // The storage backend
147 SUBALLOCATOR Allocator; // String suballocator -- just to keep it fast
148
149 // Parser state machine
150 SYMBOL sy; // Current symbol
151 int ch; // Current character
152
153 cmsInt32Number inum; // integer value
154 cmsFloat64Number dnum; // real value
155
156 char id[MAXID]; // identifier
157 char str[MAXSTR]; // string
158
159 // Allowed keywords & datasets. They have visibility on whole stream
160 KEYVALUE* ValidKeywords;
161 KEYVALUE* ValidSampleID;
162
163 char* Source; // Points to loc. being parsed
164 cmsInt32Number lineno; // line counter for error reporting
165
166 FILECTX* FileStack[MAXINCLUDE]; // Stack of files being parsed
167 cmsInt32Number IncludeSP; // Include Stack Pointer
168
169 char* MemoryBlock; // The stream if holded in memory
170
171 char DoubleFormatter[MAXID];// Printf-like 'cmsFloat64Number' formatter
172
173 cmsContext ContextID; // The threading context
174
175 } cmsIT8;
176
177
178 // The stream for save operations
179 typedef struct {
180
181 FILE* stream; // For save-to-file behaviour
182
183 cmsUInt8Number* Base;
184 cmsUInt8Number* Ptr; // For save-to-mem behaviour
185 cmsUInt32Number Used;
186 cmsUInt32Number Max;
187
188 } SAVESTREAM;
189
190
191 // ------------------------------------------------------ cmsIT8 parsing routines
192
193
194 // A keyword
195 typedef struct {
196
197 const char *id;
198 SYMBOL sy;
199
200 } KEYWORD;
201
202 // The keyword->symbol translation table. Sorting is required.
203 static const KEYWORD TabKeys[] = {
204
205 {"$INCLUDE", SINCLUDE}, // This is an extension!
206 {".INCLUDE", SINCLUDE}, // This is an extension!
207
208 {"BEGIN_DATA", SBEGIN_DATA },
209 {"BEGIN_DATA_FORMAT", SBEGIN_DATA_FORMAT },
210 {"DATA_FORMAT_IDENTIFIER", SDATA_FORMAT_ID},
211 {"END_DATA", SEND_DATA},
212 {"END_DATA_FORMAT", SEND_DATA_FORMAT},
213 {"KEYWORD", SKEYWORD}
214 };
215
216 #define NUMKEYS (sizeof(TabKeys)/sizeof(KEYWORD))
217
218 // Predefined properties
219
220 // A property
221 typedef struct {
222 const char *id; // The identifier
223 WRITEMODE as; // How is supposed to be written
224 } PROPERTY;
225
226 static PROPERTY PredefinedProperties[] = {
227
228 {"NUMBER_OF_FIELDS", WRITE_UNCOOKED}, // Required - NUMBER OF FIELDS
229 {"NUMBER_OF_SETS", WRITE_UNCOOKED}, // Required - NUMBER OF SETS
230 {"ORIGINATOR", WRITE_STRINGIFY}, // Required - Identifies the specific system, organization or individual that created the data file.
231 {"FILE_DESCRIPTOR", WRITE_STRINGIFY}, // Required - Describes the purpose or contents of the data file.
232 {"CREATED", WRITE_STRINGIFY}, // Required - Indicates date of creation of the data file.
233 {"DESCRIPTOR", WRITE_STRINGIFY}, // Required - Describes the purpose or contents of the data file.
234 {"DIFFUSE_GEOMETRY", WRITE_STRINGIFY}, // The diffuse geometry used. Allowed values are "sphere" or "opal".
235 {"MANUFACTURER", WRITE_STRINGIFY},
236 {"MANUFACTURE", WRITE_STRINGIFY}, // Some broken Fuji targets does store this value
237 {"PROD_DATE", WRITE_STRINGIFY}, // Identifies year and month of production of the target in the form yyyy:mm.
238 {"SERIAL", WRITE_STRINGIFY}, // Uniquely identifies individual physical target.
239
240 {"MATERIAL", WRITE_STRINGIFY}, // Identifies the material on which the target was produced using a code
241 // uniquely identifying th e material. This is intend ed to be used for IT8.7
242 // physical targets only (i.e . IT8.7/1 a nd IT8.7/2).
243
244 {"INSTRUMENTATION", WRITE_STRINGIFY}, // Used to report the specific instrumentation used (manufacturer and
245 // model number) to generate the data reported. This data will often
246 // provide more information about the particular data collected than an
247 // extensive list of specific details. This is particularly important for
248 // spectral data or data derived from spectrophotometry.
249
250 {"MEASUREMENT_SOURCE", WRITE_STRINGIFY}, // Illumination used for spectral measurements. This data helps provide
251 // a guide to the potential for issues of paper fluorescence, etc.
252
253 {"PRINT_CONDITIONS", WRITE_STRINGIFY}, // Used to define the characteristics of the printed sheet being reported.
254 // Where standard conditions have been defined (e.g., SWOP at nominal)
255 // named conditions may suffice. Otherwise, detailed information is
256 // needed.
257
258 {"SAMPLE_BACKING", WRITE_STRINGIFY}, // Identifies the backing material used behind the sample during
259 // measurement. Allowed values are "black", "white", or {"na".
260
261 {"CHISQ_DOF", WRITE_STRINGIFY}, // Degrees of freedom associated with the Chi squared statistic
262 // below properties are new in recent specs:
263
264 {"MEASUREMENT_GEOMETRY", WRITE_STRINGIFY}, // The type of measurement, either reflection or transmission, should be indicated
265 // along with details of the geometry and the aperture size and shape. For example,
266 // for transmission measurements it is important to identify 0/diffuse, diffuse/0,
267 // opal or integrating sphere, etc. For reflection it is important to identify 0/45,
268 // 45/0, sphere (specular included or excluded), etc.
269
270 {"FILTER", WRITE_STRINGIFY}, // Identifies the use of physical filter(s) during measurement. Typically used to
271 // denote the use of filters such as none, D65, Red, Green or Blue.
272
273 {"POLARIZATION", WRITE_STRINGIFY}, // Identifies the use of a physical polarization filter during measurement. Allowed
274 // values are {"yes", "white", "none" or "na".
275
276 {"WEIGHTING_FUNCTION", WRITE_PAIR}, // Indicates such functions as: the CIE standard observer functions used in the
277 // calculation of various data parameters (2 degree and 10 degree), CIE standard
278 // illuminant functions used in the calculation of various data parameters (e.g., D50,
279 // D65, etc.), density status response, etc. If used there shall be at least one
280 // name-value pair following the WEIGHTING_FUNCTION tag/keyword. The first attribute
281 // in the set shall be {"name" and shall identify the particular parameter used.
282 // The second shall be {"value" and shall provide the value associated with that name.
283 // For ASCII data, a string containing the Name and Value attribute pairs shall follow
284 // the weighting function keyword. A semi-colon separates attribute pairs from each
285 // other and within the attribute the name and value are separated by a comma.
286
287 {"COMPUTATIONAL_PARAMETER", WRITE_PAIR}, // Parameter that is used in computing a value from measured data. Name is the name
288 // of the calculation, parameter is the name of the parameter used in the calculation
289 // and value is the value of the parameter.
290
291 {"TARGET_TYPE", WRITE_STRINGIFY}, // The type of target being measured, e.g. IT8.7/1, IT8.7/3, user defined, etc.
292
293 {"COLORANT", WRITE_STRINGIFY}, // Identifies the colorant(s) used in creating the target.
294
295 {"TABLE_DESCRIPTOR", WRITE_STRINGIFY}, // Describes the purpose or contents of a data table.
296
297 {"TABLE_NAME", WRITE_STRINGIFY} // Provides a short name for a data table.
298 };
299
300 #define NUMPREDEFINEDPROPS (sizeof(PredefinedProperties)/sizeof(PROPERTY))
301
302
303 // Predefined sample types on dataset
304 static const char* PredefinedSampleID[] = {
305 "SAMPLE_ID", // Identifies sample that data represents
306 "STRING", // Identifies label, or other non-machine readable value.
307 // Value must begin and end with a " symbol
308
309 "CMYK_C", // Cyan component of CMYK data expressed as a percentage
310 "CMYK_M", // Magenta component of CMYK data expressed as a percentage
311 "CMYK_Y", // Yellow component of CMYK data expressed as a percentage
312 "CMYK_K", // Black component of CMYK data expressed as a percentage
313 "D_RED", // Red filter density
314 "D_GREEN", // Green filter density
315 "D_BLUE", // Blue filter density
316 "D_VIS", // Visual filter density
317 "D_MAJOR_FILTER", // Major filter d ensity
318 "RGB_R", // Red component of RGB data
319 "RGB_G", // Green component of RGB data
320 "RGB_B", // Blue com ponent of RGB data
321 "SPECTRAL_NM", // Wavelength of measurement expressed in nanometers
322 "SPECTRAL_PCT", // Percentage reflectance/transmittance
323 "SPECTRAL_DEC", // Reflectance/transmittance
324 "XYZ_X", // X component of tristimulus data
325 "XYZ_Y", // Y component of tristimulus data
326 "XYZ_Z", // Z component of tristimulus data
327 "XYY_X", // x component of chromaticity data
328 "XYY_Y", // y component of chromaticity data
329 "XYY_CAPY", // Y component of tristimulus data
330 "LAB_L", // L* component of Lab data
331 "LAB_A", // a* component of Lab data
332 "LAB_B", // b* component of Lab data
333 "LAB_C", // C*ab component of Lab data
334 "LAB_H", // hab component of Lab data
335 "LAB_DE", // CIE dE
336 "LAB_DE_94", // CIE dE using CIE 94
337 "LAB_DE_CMC", // dE using CMC
338 "LAB_DE_2000", // CIE dE using CIE DE 2000
339 "MEAN_DE", // Mean Delta E (LAB_DE) of samples compared to batch average
340 // (Used for data files for ANSI IT8.7/1 and IT8.7/2 targets)
341 "STDEV_X", // Standard deviation of X (tristimulus data)
342 "STDEV_Y", // Standard deviation of Y (tristimulus data)
343 "STDEV_Z", // Standard deviation of Z (tristimulus data)
344 "STDEV_L", // Standard deviation of L*
345 "STDEV_A", // Standard deviation of a*
346 "STDEV_B", // Standard deviation of b*
347 "STDEV_DE", // Standard deviation of CIE dE
348 "CHI_SQD_PAR"}; // The average of the standard deviations of L*, a* and b*. It is
349 // used to derive an estimate of the chi-squared parameter which is
350 // recommended as the predictor of the variability of dE
351
352 #define NUMPREDEFINEDSAMPLEID (sizeof(PredefinedSampleID)/sizeof(char *))
353
354 //Forward declaration of some internal functions
355 static void* AllocChunk(cmsIT8* it8, cmsUInt32Number size);
356
357 // Checks whatever c is a separator
358 static
isseparator(int c)359 cmsBool isseparator(int c)
360 {
361 return (c == ' ') || (c == '\t') ;
362 }
363
364 // Checks whatever c is a valid identifier char
365 static
ismiddle(int c)366 cmsBool ismiddle(int c)
367 {
368 return (!isseparator(c) && (c != '#') && (c !='\"') && (c != '\'') && (c > 32) && (c < 127));
369 }
370
371 // Checks whatsever c is a valid identifier middle char.
372 static
isidchar(int c)373 cmsBool isidchar(int c)
374 {
375 return isalnum(c) || ismiddle(c);
376 }
377
378 // Checks whatsever c is a valid identifier first char.
379 static
isfirstidchar(int c)380 cmsBool isfirstidchar(int c)
381 {
382 return !isdigit(c) && ismiddle(c);
383 }
384
385 // Guess whether the supplied path looks like an absolute path
386 static
isabsolutepath(const char * path)387 cmsBool isabsolutepath(const char *path)
388 {
389 char ThreeChars[4];
390
391 if(path == NULL)
392 return FALSE;
393 if (path[0] == 0)
394 return FALSE;
395
396 strncpy(ThreeChars, path, 3);
397 ThreeChars[3] = 0;
398
399 if(ThreeChars[0] == DIR_CHAR)
400 return TRUE;
401
402 #ifdef CMS_IS_WINDOWS_
403 if (isalpha((int) ThreeChars[0]) && ThreeChars[1] == ':')
404 return TRUE;
405 #endif
406 return FALSE;
407 }
408
409
410 // Makes a file path based on a given reference path
411 // NOTE: this function doesn't check if the path exists or even if it's legal
412 static
BuildAbsolutePath(const char * relPath,const char * basePath,char * buffer,cmsUInt32Number MaxLen)413 cmsBool BuildAbsolutePath(const char *relPath, const char *basePath, char *buffer, cmsUInt32Number MaxLen)
414 {
415 char *tail;
416 cmsUInt32Number len;
417
418 // Already absolute?
419 if (isabsolutepath(relPath)) {
420
421 strncpy(buffer, relPath, MaxLen);
422 buffer[MaxLen-1] = 0;
423 return TRUE;
424 }
425
426 // No, search for last
427 strncpy(buffer, basePath, MaxLen);
428 buffer[MaxLen-1] = 0;
429
430 tail = strrchr(buffer, DIR_CHAR);
431 if (tail == NULL) return FALSE; // Is not absolute and has no separators??
432
433 len = (cmsUInt32Number) (tail - buffer);
434 if (len >= MaxLen) return FALSE;
435
436 // No need to assure zero terminator over here
437 strncpy(tail + 1, relPath, MaxLen - len);
438
439 return TRUE;
440 }
441
442
443 // Make sure no exploit is being even tried
444 static
NoMeta(const char * str)445 const char* NoMeta(const char* str)
446 {
447 if (strchr(str, '%') != NULL)
448 return "**** CORRUPTED FORMAT STRING ***";
449
450 return str;
451 }
452
453 // Syntax error
454 static
SynError(cmsIT8 * it8,const char * Txt,...)455 cmsBool SynError(cmsIT8* it8, const char *Txt, ...)
456 {
457 char Buffer[256], ErrMsg[1024];
458 va_list args;
459
460 va_start(args, Txt);
461 vsnprintf(Buffer, 255, Txt, args);
462 Buffer[255] = 0;
463 va_end(args);
464
465 snprintf(ErrMsg, 1023, "%s: Line %d, %s", it8->FileStack[it8 ->IncludeSP]->FileName, it8->lineno, Buffer);
466 ErrMsg[1023] = 0;
467 it8->sy = SSYNERROR;
468 cmsSignalError(it8 ->ContextID, cmsERROR_CORRUPTION_DETECTED, "%s", ErrMsg);
469 return FALSE;
470 }
471
472 // Check if current symbol is same as specified. issue an error else.
473 static
Check(cmsIT8 * it8,SYMBOL sy,const char * Err)474 cmsBool Check(cmsIT8* it8, SYMBOL sy, const char* Err)
475 {
476 if (it8 -> sy != sy)
477 return SynError(it8, NoMeta(Err));
478 return TRUE;
479 }
480
481 // Read Next character from stream
482 static
NextCh(cmsIT8 * it8)483 void NextCh(cmsIT8* it8)
484 {
485 if (it8 -> FileStack[it8 ->IncludeSP]->Stream) {
486
487 it8 ->ch = fgetc(it8 ->FileStack[it8 ->IncludeSP]->Stream);
488
489 if (feof(it8 -> FileStack[it8 ->IncludeSP]->Stream)) {
490
491 if (it8 ->IncludeSP > 0) {
492
493 fclose(it8 ->FileStack[it8->IncludeSP--]->Stream);
494 it8 -> ch = ' '; // Whitespace to be ignored
495
496 } else
497 it8 ->ch = 0; // EOF
498 }
499 }
500 else {
501 it8->ch = *it8->Source;
502 if (it8->ch) it8->Source++;
503 }
504 }
505
506
507 // Try to see if current identifier is a keyword, if so return the referred symbol
508 static
BinSrchKey(const char * id)509 SYMBOL BinSrchKey(const char *id)
510 {
511 int l = 1;
512 int r = NUMKEYS;
513 int x, res;
514
515 while (r >= l)
516 {
517 x = (l+r)/2;
518 res = cmsstrcasecmp(id, TabKeys[x-1].id);
519 if (res == 0) return TabKeys[x-1].sy;
520 if (res < 0) r = x - 1;
521 else l = x + 1;
522 }
523
524 return SUNDEFINED;
525 }
526
527
528 // 10 ^n
529 static
xpow10(int n)530 cmsFloat64Number xpow10(int n)
531 {
532 return pow(10, (cmsFloat64Number) n);
533 }
534
535
536 // Reads a Real number, tries to follow from integer number
537 static
ReadReal(cmsIT8 * it8,cmsInt32Number inum)538 void ReadReal(cmsIT8* it8, cmsInt32Number inum)
539 {
540 it8->dnum = (cmsFloat64Number)inum;
541
542 while (isdigit(it8->ch)) {
543
544 it8->dnum = (cmsFloat64Number)it8->dnum * 10.0 + (cmsFloat64Number)(it8->ch - '0');
545 NextCh(it8);
546 }
547
548 if (it8->ch == '.') { // Decimal point
549
550 cmsFloat64Number frac = 0.0; // fraction
551 int prec = 0; // precision
552
553 NextCh(it8); // Eats dec. point
554
555 while (isdigit(it8->ch)) {
556
557 frac = frac * 10.0 + (cmsFloat64Number)(it8->ch - '0');
558 prec++;
559 NextCh(it8);
560 }
561
562 it8->dnum = it8->dnum + (frac / xpow10(prec));
563 }
564
565 // Exponent, example 34.00E+20
566 if (toupper(it8->ch) == 'E') {
567
568 cmsInt32Number e;
569 cmsInt32Number sgn;
570
571 NextCh(it8); sgn = 1;
572
573 if (it8->ch == '-') {
574
575 sgn = -1; NextCh(it8);
576 }
577 else
578 if (it8->ch == '+') {
579
580 sgn = +1;
581 NextCh(it8);
582 }
583
584 e = 0;
585 while (isdigit(it8->ch)) {
586
587 cmsInt32Number digit = (it8->ch - '0');
588
589 if ((cmsFloat64Number)e * 10.0 + (cmsFloat64Number)digit < (cmsFloat64Number)+2147483647.0)
590 e = e * 10 + digit;
591
592 NextCh(it8);
593 }
594
595 e = sgn*e;
596 it8->dnum = it8->dnum * xpow10(e);
597 }
598 }
599
600 // Parses a float number
601 // This can not call directly atof because it uses locale dependent
602 // parsing, while CCMX files always use . as decimal separator
603 static
ParseFloatNumber(const char * Buffer)604 cmsFloat64Number ParseFloatNumber(const char *Buffer)
605 {
606 cmsFloat64Number dnum = 0.0;
607 int sign = 1;
608
609 // keep safe
610 if (Buffer == NULL) return 0.0;
611
612 if (*Buffer == '-' || *Buffer == '+') {
613
614 sign = (*Buffer == '-') ? -1 : 1;
615 Buffer++;
616 }
617
618
619 while (*Buffer && isdigit((int)*Buffer)) {
620
621 dnum = dnum * 10.0 + (*Buffer - '0');
622 if (*Buffer) Buffer++;
623 }
624
625 if (*Buffer == '.') {
626
627 cmsFloat64Number frac = 0.0; // fraction
628 int prec = 0; // precision
629
630 if (*Buffer) Buffer++;
631
632 while (*Buffer && isdigit((int)*Buffer)) {
633
634 frac = frac * 10.0 + (*Buffer - '0');
635 prec++;
636 if (*Buffer) Buffer++;
637 }
638
639 dnum = dnum + (frac / xpow10(prec));
640 }
641
642 // Exponent, example 34.00E+20
643 if (*Buffer && toupper(*Buffer) == 'E') {
644
645 int e;
646 int sgn;
647
648 if (*Buffer) Buffer++;
649 sgn = 1;
650
651 if (*Buffer == '-') {
652
653 sgn = -1;
654 if (*Buffer) Buffer++;
655 }
656 else
657 if (*Buffer == '+') {
658
659 sgn = +1;
660 if (*Buffer) Buffer++;
661 }
662
663 e = 0;
664 while (*Buffer && isdigit((int)*Buffer)) {
665
666 cmsInt32Number digit = (*Buffer - '0');
667
668 if ((cmsFloat64Number)e * 10.0 + digit < (cmsFloat64Number)+2147483647.0)
669 e = e * 10 + digit;
670
671 if (*Buffer) Buffer++;
672 }
673
674 e = sgn*e;
675 dnum = dnum * xpow10(e);
676 }
677
678 return sign * dnum;
679 }
680
681
682 // Reads next symbol
683 static
InSymbol(cmsIT8 * it8)684 void InSymbol(cmsIT8* it8)
685 {
686 CMSREGISTER char *idptr;
687 CMSREGISTER int k;
688 SYMBOL key;
689 int sng;
690
691 do {
692
693 while (isseparator(it8->ch))
694 NextCh(it8);
695
696 if (isfirstidchar(it8->ch)) { // Identifier
697
698 k = 0;
699 idptr = it8->id;
700
701 do {
702
703 if (++k < MAXID) *idptr++ = (char) it8->ch;
704
705 NextCh(it8);
706
707 } while (isidchar(it8->ch));
708
709 *idptr = '\0';
710
711
712 key = BinSrchKey(it8->id);
713 if (key == SUNDEFINED) it8->sy = SIDENT;
714 else it8->sy = key;
715
716 }
717 else // Is a number?
718 if (isdigit(it8->ch) || it8->ch == '.' || it8->ch == '-' || it8->ch == '+')
719 {
720 int sign = 1;
721
722 if (it8->ch == '-') {
723 sign = -1;
724 NextCh(it8);
725 }
726
727 it8->inum = 0;
728 it8->sy = SINUM;
729
730 if (it8->ch == '0') { // 0xnnnn (Hexa) or 0bnnnn (Binary)
731
732 NextCh(it8);
733 if (toupper(it8->ch) == 'X') {
734
735 int j;
736
737 NextCh(it8);
738 while (isxdigit(it8->ch))
739 {
740 it8->ch = toupper(it8->ch);
741 if (it8->ch >= 'A' && it8->ch <= 'F') j = it8->ch -'A'+10;
742 else j = it8->ch - '0';
743
744 if ((cmsFloat64Number) it8->inum * 16.0 + (cmsFloat64Number) j > (cmsFloat64Number)+2147483647.0)
745 {
746 SynError(it8, "Invalid hexadecimal number");
747 return;
748 }
749
750 it8->inum = it8->inum * 16 + j;
751 NextCh(it8);
752 }
753 return;
754 }
755
756 if (toupper(it8->ch) == 'B') { // Binary
757
758 int j;
759
760 NextCh(it8);
761 while (it8->ch == '0' || it8->ch == '1')
762 {
763 j = it8->ch - '0';
764
765 if ((cmsFloat64Number) it8->inum * 2.0 + j > (cmsFloat64Number)+2147483647.0)
766 {
767 SynError(it8, "Invalid binary number");
768 return;
769 }
770
771 it8->inum = it8->inum * 2 + j;
772 NextCh(it8);
773 }
774 return;
775 }
776 }
777
778
779 while (isdigit(it8->ch)) {
780
781 cmsInt32Number digit = (it8->ch - '0');
782
783 if ((cmsFloat64Number) it8->inum * 10.0 + (cmsFloat64Number) digit > (cmsFloat64Number) +2147483647.0) {
784 ReadReal(it8, it8->inum);
785 it8->sy = SDNUM;
786 it8->dnum *= sign;
787 return;
788 }
789
790 it8->inum = it8->inum * 10 + digit;
791 NextCh(it8);
792 }
793
794 if (it8->ch == '.') {
795
796 ReadReal(it8, it8->inum);
797 it8->sy = SDNUM;
798 it8->dnum *= sign;
799 return;
800 }
801
802 it8 -> inum *= sign;
803
804 // Special case. Numbers followed by letters are taken as identifiers
805
806 if (isidchar(it8 ->ch)) {
807
808 if (it8 ->sy == SINUM) {
809
810 snprintf(it8->id, 127, "%d", it8->inum);
811 }
812 else {
813
814 snprintf(it8->id, 127, it8 ->DoubleFormatter, it8->dnum);
815 }
816
817 k = (int) strlen(it8 ->id);
818 idptr = it8 ->id + k;
819 do {
820
821 if (++k < MAXID) *idptr++ = (char) it8->ch;
822
823 NextCh(it8);
824
825 } while (isidchar(it8->ch));
826
827 *idptr = '\0';
828 it8->sy = SIDENT;
829 }
830 return;
831
832 }
833 else
834 switch ((int) it8->ch) {
835
836 // EOF marker -- ignore it
837 case '\x1a':
838 NextCh(it8);
839 break;
840
841 // Eof stream markers
842 case 0:
843 case -1:
844 it8->sy = SEOF;
845 break;
846
847
848 // Next line
849 case '\r':
850 NextCh(it8);
851 if (it8 ->ch == '\n')
852 NextCh(it8);
853 it8->sy = SEOLN;
854 it8->lineno++;
855 break;
856
857 case '\n':
858 NextCh(it8);
859 it8->sy = SEOLN;
860 it8->lineno++;
861 break;
862
863 // Comment
864 case '#':
865 NextCh(it8);
866 while (it8->ch && it8->ch != '\n' && it8->ch != '\r')
867 NextCh(it8);
868
869 it8->sy = SCOMMENT;
870 break;
871
872 // String.
873 case '\'':
874 case '\"':
875 idptr = it8->str;
876 sng = it8->ch;
877 k = 0;
878 NextCh(it8);
879
880 while (k < (MAXSTR-1) && it8->ch != sng) {
881
882 if (it8->ch == '\n'|| it8->ch == '\r') k = MAXSTR+1;
883 else {
884 *idptr++ = (char) it8->ch;
885 NextCh(it8);
886 k++;
887 }
888 }
889
890 it8->sy = SSTRING;
891 *idptr = '\0';
892 NextCh(it8);
893 break;
894
895
896 default:
897 SynError(it8, "Unrecognized character: 0x%x", it8 ->ch);
898 return;
899 }
900
901 } while (it8->sy == SCOMMENT);
902
903 // Handle the include special token
904
905 if (it8 -> sy == SINCLUDE) {
906
907 FILECTX* FileNest;
908
909 if(it8 -> IncludeSP >= (MAXINCLUDE-1)) {
910
911 SynError(it8, "Too many recursion levels");
912 return;
913 }
914
915 InSymbol(it8);
916 if (!Check(it8, SSTRING, "Filename expected")) return;
917
918 FileNest = it8 -> FileStack[it8 -> IncludeSP + 1];
919 if(FileNest == NULL) {
920
921 FileNest = it8 ->FileStack[it8 -> IncludeSP + 1] = (FILECTX*)AllocChunk(it8, sizeof(FILECTX));
922 //if(FileNest == NULL)
923 // TODO: how to manage out-of-memory conditions?
924 }
925
926 if (BuildAbsolutePath(it8->str,
927 it8->FileStack[it8->IncludeSP]->FileName,
928 FileNest->FileName, cmsMAX_PATH-1) == FALSE) {
929 SynError(it8, "File path too long");
930 return;
931 }
932
933 FileNest->Stream = fopen(FileNest->FileName, "rt");
934 if (FileNest->Stream == NULL) {
935
936 SynError(it8, "File %s not found", FileNest->FileName);
937 return;
938 }
939 it8->IncludeSP++;
940
941 it8 ->ch = ' ';
942 InSymbol(it8);
943 }
944
945 }
946
947 // Checks end of line separator
948 static
CheckEOLN(cmsIT8 * it8)949 cmsBool CheckEOLN(cmsIT8* it8)
950 {
951 if (!Check(it8, SEOLN, "Expected separator")) return FALSE;
952 while (it8 -> sy == SEOLN)
953 InSymbol(it8);
954 return TRUE;
955
956 }
957
958 // Skip a symbol
959
960 static
Skip(cmsIT8 * it8,SYMBOL sy)961 void Skip(cmsIT8* it8, SYMBOL sy)
962 {
963 if (it8->sy == sy && it8->sy != SEOF)
964 InSymbol(it8);
965 }
966
967
968 // Skip multiple EOLN
969 static
SkipEOLN(cmsIT8 * it8)970 void SkipEOLN(cmsIT8* it8)
971 {
972 while (it8->sy == SEOLN) {
973 InSymbol(it8);
974 }
975 }
976
977
978 // Returns a string holding current value
979 static
GetVal(cmsIT8 * it8,char * Buffer,cmsUInt32Number max,const char * ErrorTitle)980 cmsBool GetVal(cmsIT8* it8, char* Buffer, cmsUInt32Number max, const char* ErrorTitle)
981 {
982 switch (it8->sy) {
983
984 case SEOLN: // Empty value
985 Buffer[0]=0;
986 break;
987 case SIDENT: strncpy(Buffer, it8->id, max);
988 Buffer[max-1]=0;
989 break;
990 case SINUM: snprintf(Buffer, max, "%d", it8 -> inum); break;
991 case SDNUM: snprintf(Buffer, max, it8->DoubleFormatter, it8 -> dnum); break;
992 case SSTRING: strncpy(Buffer, it8->str, max);
993 Buffer[max-1] = 0;
994 break;
995
996
997 default:
998 return SynError(it8, "%s", ErrorTitle);
999 }
1000
1001 Buffer[max] = 0;
1002 return TRUE;
1003 }
1004
1005 // ---------------------------------------------------------- Table
1006
1007 static
GetTable(cmsIT8 * it8)1008 TABLE* GetTable(cmsIT8* it8)
1009 {
1010 if ((it8 -> nTable >= it8 ->TablesCount)) {
1011
1012 SynError(it8, "Table %d out of sequence", it8 -> nTable);
1013 return it8 -> Tab;
1014 }
1015
1016 return it8 ->Tab + it8 ->nTable;
1017 }
1018
1019 // ---------------------------------------------------------- Memory management
1020
1021
1022 // Frees an allocator and owned memory
cmsIT8Free(cmsHANDLE hIT8)1023 void CMSEXPORT cmsIT8Free(cmsHANDLE hIT8)
1024 {
1025 cmsIT8* it8 = (cmsIT8*) hIT8;
1026
1027 if (it8 == NULL)
1028 return;
1029
1030 if (it8->MemorySink) {
1031
1032 OWNEDMEM* p;
1033 OWNEDMEM* n;
1034
1035 for (p = it8->MemorySink; p != NULL; p = n) {
1036
1037 n = p->Next;
1038 if (p->Ptr) _cmsFree(it8 ->ContextID, p->Ptr);
1039 _cmsFree(it8 ->ContextID, p);
1040 }
1041 }
1042
1043 if (it8->MemoryBlock)
1044 _cmsFree(it8 ->ContextID, it8->MemoryBlock);
1045
1046 _cmsFree(it8 ->ContextID, it8);
1047 }
1048
1049
1050 // Allocates a chunk of data, keep linked list
1051 static
AllocBigBlock(cmsIT8 * it8,cmsUInt32Number size)1052 void* AllocBigBlock(cmsIT8* it8, cmsUInt32Number size)
1053 {
1054 OWNEDMEM* ptr1;
1055 void* ptr = _cmsMallocZero(it8->ContextID, size);
1056
1057 if (ptr != NULL) {
1058
1059 ptr1 = (OWNEDMEM*) _cmsMallocZero(it8 ->ContextID, sizeof(OWNEDMEM));
1060
1061 if (ptr1 == NULL) {
1062
1063 _cmsFree(it8 ->ContextID, ptr);
1064 return NULL;
1065 }
1066
1067 ptr1-> Ptr = ptr;
1068 ptr1-> Next = it8 -> MemorySink;
1069 it8 -> MemorySink = ptr1;
1070 }
1071
1072 return ptr;
1073 }
1074
1075
1076 // Suballocator.
1077 static
AllocChunk(cmsIT8 * it8,cmsUInt32Number size)1078 void* AllocChunk(cmsIT8* it8, cmsUInt32Number size)
1079 {
1080 cmsUInt32Number Free = it8 ->Allocator.BlockSize - it8 ->Allocator.Used;
1081 cmsUInt8Number* ptr;
1082
1083 size = _cmsALIGNMEM(size);
1084
1085 if (size > Free) {
1086
1087 if (it8 -> Allocator.BlockSize == 0)
1088
1089 it8 -> Allocator.BlockSize = 20*1024;
1090 else
1091 it8 ->Allocator.BlockSize *= 2;
1092
1093 if (it8 ->Allocator.BlockSize < size)
1094 it8 ->Allocator.BlockSize = size;
1095
1096 it8 ->Allocator.Used = 0;
1097 it8 ->Allocator.Block = (cmsUInt8Number*) AllocBigBlock(it8, it8 ->Allocator.BlockSize);
1098 }
1099
1100 ptr = it8 ->Allocator.Block + it8 ->Allocator.Used;
1101 it8 ->Allocator.Used += size;
1102
1103 return (void*) ptr;
1104
1105 }
1106
1107
1108 // Allocates a string
1109 static
AllocString(cmsIT8 * it8,const char * str)1110 char *AllocString(cmsIT8* it8, const char* str)
1111 {
1112 cmsUInt32Number Size = (cmsUInt32Number) strlen(str)+1;
1113 char *ptr;
1114
1115
1116 ptr = (char *) AllocChunk(it8, Size);
1117 if (ptr) strncpy (ptr, str, Size-1);
1118
1119 return ptr;
1120 }
1121
1122 // Searches through linked list
1123
1124 static
IsAvailableOnList(KEYVALUE * p,const char * Key,const char * Subkey,KEYVALUE ** LastPtr)1125 cmsBool IsAvailableOnList(KEYVALUE* p, const char* Key, const char* Subkey, KEYVALUE** LastPtr)
1126 {
1127 if (LastPtr) *LastPtr = p;
1128
1129 for (; p != NULL; p = p->Next) {
1130
1131 if (LastPtr) *LastPtr = p;
1132
1133 if (*Key != '#') { // Comments are ignored
1134
1135 if (cmsstrcasecmp(Key, p->Keyword) == 0)
1136 break;
1137 }
1138 }
1139
1140 if (p == NULL)
1141 return FALSE;
1142
1143 if (Subkey == 0)
1144 return TRUE;
1145
1146 for (; p != NULL; p = p->NextSubkey) {
1147
1148 if (p ->Subkey == NULL) continue;
1149
1150 if (LastPtr) *LastPtr = p;
1151
1152 if (cmsstrcasecmp(Subkey, p->Subkey) == 0)
1153 return TRUE;
1154 }
1155
1156 return FALSE;
1157 }
1158
1159
1160
1161 // Add a property into a linked list
1162 static
AddToList(cmsIT8 * it8,KEYVALUE ** Head,const char * Key,const char * Subkey,const char * xValue,WRITEMODE WriteAs)1163 KEYVALUE* AddToList(cmsIT8* it8, KEYVALUE** Head, const char *Key, const char *Subkey, const char* xValue, WRITEMODE WriteAs)
1164 {
1165 KEYVALUE* p;
1166 KEYVALUE* last;
1167
1168
1169 // Check if property is already in list
1170
1171 if (IsAvailableOnList(*Head, Key, Subkey, &p)) {
1172
1173 // This may work for editing properties
1174
1175 // return SynError(it8, "duplicate key <%s>", Key);
1176 }
1177 else {
1178
1179 last = p;
1180
1181 // Allocate the container
1182 p = (KEYVALUE*) AllocChunk(it8, sizeof(KEYVALUE));
1183 if (p == NULL)
1184 {
1185 SynError(it8, "AddToList: out of memory");
1186 return NULL;
1187 }
1188
1189 // Store name and value
1190 p->Keyword = AllocString(it8, Key);
1191 p->Subkey = (Subkey == NULL) ? NULL : AllocString(it8, Subkey);
1192
1193 // Keep the container in our list
1194 if (*Head == NULL) {
1195 *Head = p;
1196 }
1197 else
1198 {
1199 if (Subkey != NULL && last != NULL) {
1200
1201 last->NextSubkey = p;
1202
1203 // If Subkey is not null, then last is the last property with the same key,
1204 // but not necessarily is the last property in the list, so we need to move
1205 // to the actual list end
1206 while (last->Next != NULL)
1207 last = last->Next;
1208 }
1209
1210 if (last != NULL) last->Next = p;
1211 }
1212
1213 p->Next = NULL;
1214 p->NextSubkey = NULL;
1215 }
1216
1217 p->WriteAs = WriteAs;
1218
1219 if (xValue != NULL) {
1220
1221 p->Value = AllocString(it8, xValue);
1222 }
1223 else {
1224 p->Value = NULL;
1225 }
1226
1227 return p;
1228 }
1229
1230 static
AddAvailableProperty(cmsIT8 * it8,const char * Key,WRITEMODE as)1231 KEYVALUE* AddAvailableProperty(cmsIT8* it8, const char* Key, WRITEMODE as)
1232 {
1233 return AddToList(it8, &it8->ValidKeywords, Key, NULL, NULL, as);
1234 }
1235
1236
1237 static
AddAvailableSampleID(cmsIT8 * it8,const char * Key)1238 KEYVALUE* AddAvailableSampleID(cmsIT8* it8, const char* Key)
1239 {
1240 return AddToList(it8, &it8->ValidSampleID, Key, NULL, NULL, WRITE_UNCOOKED);
1241 }
1242
1243
1244 static
AllocTable(cmsIT8 * it8)1245 void AllocTable(cmsIT8* it8)
1246 {
1247 TABLE* t;
1248
1249 t = it8 ->Tab + it8 ->TablesCount;
1250
1251 t->HeaderList = NULL;
1252 t->DataFormat = NULL;
1253 t->Data = NULL;
1254
1255 it8 ->TablesCount++;
1256 }
1257
1258
cmsIT8SetTable(cmsHANDLE IT8,cmsUInt32Number nTable)1259 cmsInt32Number CMSEXPORT cmsIT8SetTable(cmsHANDLE IT8, cmsUInt32Number nTable)
1260 {
1261 cmsIT8* it8 = (cmsIT8*) IT8;
1262
1263 if (nTable >= it8 ->TablesCount) {
1264
1265 if (nTable == it8 ->TablesCount) {
1266
1267 AllocTable(it8);
1268 }
1269 else {
1270 SynError(it8, "Table %d is out of sequence", nTable);
1271 return -1;
1272 }
1273 }
1274
1275 it8 ->nTable = nTable;
1276
1277 return (cmsInt32Number) nTable;
1278 }
1279
1280
1281
1282 // Init an empty container
cmsIT8Alloc(cmsContext ContextID)1283 cmsHANDLE CMSEXPORT cmsIT8Alloc(cmsContext ContextID)
1284 {
1285 cmsIT8* it8;
1286 cmsUInt32Number i;
1287
1288 it8 = (cmsIT8*) _cmsMallocZero(ContextID, sizeof(cmsIT8));
1289 if (it8 == NULL) return NULL;
1290
1291 AllocTable(it8);
1292
1293 it8->MemoryBlock = NULL;
1294 it8->MemorySink = NULL;
1295
1296 it8 ->nTable = 0;
1297
1298 it8->ContextID = ContextID;
1299 it8->Allocator.Used = 0;
1300 it8->Allocator.Block = NULL;
1301 it8->Allocator.BlockSize = 0;
1302
1303 it8->ValidKeywords = NULL;
1304 it8->ValidSampleID = NULL;
1305
1306 it8 -> sy = SUNDEFINED;
1307 it8 -> ch = ' ';
1308 it8 -> Source = NULL;
1309 it8 -> inum = 0;
1310 it8 -> dnum = 0.0;
1311
1312 it8->FileStack[0] = (FILECTX*)AllocChunk(it8, sizeof(FILECTX));
1313 it8->IncludeSP = 0;
1314 it8 -> lineno = 1;
1315
1316 strcpy(it8->DoubleFormatter, DEFAULT_DBL_FORMAT);
1317 cmsIT8SetSheetType((cmsHANDLE) it8, "CGATS.17");
1318
1319 // Initialize predefined properties & data
1320
1321 for (i=0; i < NUMPREDEFINEDPROPS; i++)
1322 AddAvailableProperty(it8, PredefinedProperties[i].id, PredefinedProperties[i].as);
1323
1324 for (i=0; i < NUMPREDEFINEDSAMPLEID; i++)
1325 AddAvailableSampleID(it8, PredefinedSampleID[i]);
1326
1327
1328 return (cmsHANDLE) it8;
1329 }
1330
1331
cmsIT8GetSheetType(cmsHANDLE hIT8)1332 const char* CMSEXPORT cmsIT8GetSheetType(cmsHANDLE hIT8)
1333 {
1334 return GetTable((cmsIT8*) hIT8)->SheetType;
1335 }
1336
cmsIT8SetSheetType(cmsHANDLE hIT8,const char * Type)1337 cmsBool CMSEXPORT cmsIT8SetSheetType(cmsHANDLE hIT8, const char* Type)
1338 {
1339 TABLE* t = GetTable((cmsIT8*) hIT8);
1340
1341 strncpy(t ->SheetType, Type, MAXSTR-1);
1342 t ->SheetType[MAXSTR-1] = 0;
1343 return TRUE;
1344 }
1345
cmsIT8SetComment(cmsHANDLE hIT8,const char * Val)1346 cmsBool CMSEXPORT cmsIT8SetComment(cmsHANDLE hIT8, const char* Val)
1347 {
1348 cmsIT8* it8 = (cmsIT8*) hIT8;
1349
1350 if (!Val) return FALSE;
1351 if (!*Val) return FALSE;
1352
1353 return AddToList(it8, &GetTable(it8)->HeaderList, "# ", NULL, Val, WRITE_UNCOOKED) != NULL;
1354 }
1355
1356 // Sets a property
cmsIT8SetPropertyStr(cmsHANDLE hIT8,const char * Key,const char * Val)1357 cmsBool CMSEXPORT cmsIT8SetPropertyStr(cmsHANDLE hIT8, const char* Key, const char *Val)
1358 {
1359 cmsIT8* it8 = (cmsIT8*) hIT8;
1360
1361 if (!Val) return FALSE;
1362 if (!*Val) return FALSE;
1363
1364 return AddToList(it8, &GetTable(it8)->HeaderList, Key, NULL, Val, WRITE_STRINGIFY) != NULL;
1365 }
1366
cmsIT8SetPropertyDbl(cmsHANDLE hIT8,const char * cProp,cmsFloat64Number Val)1367 cmsBool CMSEXPORT cmsIT8SetPropertyDbl(cmsHANDLE hIT8, const char* cProp, cmsFloat64Number Val)
1368 {
1369 cmsIT8* it8 = (cmsIT8*) hIT8;
1370 char Buffer[1024];
1371
1372 snprintf(Buffer, 1023, it8->DoubleFormatter, Val);
1373
1374 return AddToList(it8, &GetTable(it8)->HeaderList, cProp, NULL, Buffer, WRITE_UNCOOKED) != NULL;
1375 }
1376
cmsIT8SetPropertyHex(cmsHANDLE hIT8,const char * cProp,cmsUInt32Number Val)1377 cmsBool CMSEXPORT cmsIT8SetPropertyHex(cmsHANDLE hIT8, const char* cProp, cmsUInt32Number Val)
1378 {
1379 cmsIT8* it8 = (cmsIT8*) hIT8;
1380 char Buffer[1024];
1381
1382 snprintf(Buffer, 1023, "%u", Val);
1383
1384 return AddToList(it8, &GetTable(it8)->HeaderList, cProp, NULL, Buffer, WRITE_HEXADECIMAL) != NULL;
1385 }
1386
cmsIT8SetPropertyUncooked(cmsHANDLE hIT8,const char * Key,const char * Buffer)1387 cmsBool CMSEXPORT cmsIT8SetPropertyUncooked(cmsHANDLE hIT8, const char* Key, const char* Buffer)
1388 {
1389 cmsIT8* it8 = (cmsIT8*) hIT8;
1390
1391 return AddToList(it8, &GetTable(it8)->HeaderList, Key, NULL, Buffer, WRITE_UNCOOKED) != NULL;
1392 }
1393
cmsIT8SetPropertyMulti(cmsHANDLE hIT8,const char * Key,const char * SubKey,const char * Buffer)1394 cmsBool CMSEXPORT cmsIT8SetPropertyMulti(cmsHANDLE hIT8, const char* Key, const char* SubKey, const char *Buffer)
1395 {
1396 cmsIT8* it8 = (cmsIT8*) hIT8;
1397
1398 return AddToList(it8, &GetTable(it8)->HeaderList, Key, SubKey, Buffer, WRITE_PAIR) != NULL;
1399 }
1400
1401 // Gets a property
cmsIT8GetProperty(cmsHANDLE hIT8,const char * Key)1402 const char* CMSEXPORT cmsIT8GetProperty(cmsHANDLE hIT8, const char* Key)
1403 {
1404 cmsIT8* it8 = (cmsIT8*) hIT8;
1405 KEYVALUE* p;
1406
1407 if (IsAvailableOnList(GetTable(it8) -> HeaderList, Key, NULL, &p))
1408 {
1409 return p -> Value;
1410 }
1411 return NULL;
1412 }
1413
1414
cmsIT8GetPropertyDbl(cmsHANDLE hIT8,const char * cProp)1415 cmsFloat64Number CMSEXPORT cmsIT8GetPropertyDbl(cmsHANDLE hIT8, const char* cProp)
1416 {
1417 const char *v = cmsIT8GetProperty(hIT8, cProp);
1418
1419 if (v == NULL) return 0.0;
1420
1421 return ParseFloatNumber(v);
1422 }
1423
cmsIT8GetPropertyMulti(cmsHANDLE hIT8,const char * Key,const char * SubKey)1424 const char* CMSEXPORT cmsIT8GetPropertyMulti(cmsHANDLE hIT8, const char* Key, const char *SubKey)
1425 {
1426 cmsIT8* it8 = (cmsIT8*) hIT8;
1427 KEYVALUE* p;
1428
1429 if (IsAvailableOnList(GetTable(it8) -> HeaderList, Key, SubKey, &p)) {
1430 return p -> Value;
1431 }
1432 return NULL;
1433 }
1434
1435 // ----------------------------------------------------------------- Datasets
1436
1437
1438 static
AllocateDataFormat(cmsIT8 * it8)1439 void AllocateDataFormat(cmsIT8* it8)
1440 {
1441 TABLE* t = GetTable(it8);
1442
1443 if (t -> DataFormat) return; // Already allocated
1444
1445 t -> nSamples = (int) cmsIT8GetPropertyDbl(it8, "NUMBER_OF_FIELDS");
1446
1447 if (t -> nSamples <= 0) {
1448
1449 SynError(it8, "AllocateDataFormat: Unknown NUMBER_OF_FIELDS");
1450 t -> nSamples = 10;
1451 }
1452
1453 t -> DataFormat = (char**) AllocChunk (it8, ((cmsUInt32Number) t->nSamples + 1) * sizeof(char *));
1454 if (t->DataFormat == NULL) {
1455
1456 SynError(it8, "AllocateDataFormat: Unable to allocate dataFormat array");
1457 }
1458
1459 }
1460
1461 static
GetDataFormat(cmsIT8 * it8,int n)1462 const char *GetDataFormat(cmsIT8* it8, int n)
1463 {
1464 TABLE* t = GetTable(it8);
1465
1466 if (t->DataFormat)
1467 return t->DataFormat[n];
1468
1469 return NULL;
1470 }
1471
1472 static
SetDataFormat(cmsIT8 * it8,int n,const char * label)1473 cmsBool SetDataFormat(cmsIT8* it8, int n, const char *label)
1474 {
1475 TABLE* t = GetTable(it8);
1476
1477 if (!t->DataFormat)
1478 AllocateDataFormat(it8);
1479
1480 if (n > t -> nSamples) {
1481 SynError(it8, "More than NUMBER_OF_FIELDS fields.");
1482 return FALSE;
1483 }
1484
1485 if (t->DataFormat) {
1486 t->DataFormat[n] = AllocString(it8, label);
1487 }
1488
1489 return TRUE;
1490 }
1491
1492
cmsIT8SetDataFormat(cmsHANDLE h,int n,const char * Sample)1493 cmsBool CMSEXPORT cmsIT8SetDataFormat(cmsHANDLE h, int n, const char *Sample)
1494 {
1495 cmsIT8* it8 = (cmsIT8*)h;
1496 return SetDataFormat(it8, n, Sample);
1497 }
1498
1499 // A safe atoi that returns 0 when NULL input is given
1500 static
satoi(const char * b)1501 cmsInt32Number satoi(const char* b)
1502 {
1503 if (b == NULL) return 0;
1504 return atoi(b);
1505 }
1506
1507 static
AllocateDataSet(cmsIT8 * it8)1508 void AllocateDataSet(cmsIT8* it8)
1509 {
1510 TABLE* t = GetTable(it8);
1511
1512 if (t -> Data) return; // Already allocated
1513
1514 t-> nSamples = satoi(cmsIT8GetProperty(it8, "NUMBER_OF_FIELDS"));
1515 t-> nPatches = satoi(cmsIT8GetProperty(it8, "NUMBER_OF_SETS"));
1516
1517 if (t -> nSamples < 0 || t->nSamples > 0x7ffe || t->nPatches < 0 || t->nPatches > 0x7ffe)
1518 {
1519 SynError(it8, "AllocateDataSet: too much data");
1520 }
1521 else {
1522 // Some dumb analizers warns of possible overflow here, just take a look couple of lines above.
1523 t->Data = (char**)AllocChunk(it8, ((cmsUInt32Number)t->nSamples + 1) * ((cmsUInt32Number)t->nPatches + 1) * sizeof(char*));
1524 if (t->Data == NULL) {
1525
1526 SynError(it8, "AllocateDataSet: Unable to allocate data array");
1527 }
1528 }
1529
1530 }
1531
1532 static
GetData(cmsIT8 * it8,int nSet,int nField)1533 char* GetData(cmsIT8* it8, int nSet, int nField)
1534 {
1535 TABLE* t = GetTable(it8);
1536 int nSamples = t -> nSamples;
1537 int nPatches = t -> nPatches;
1538
1539 if (nSet >= nPatches || nField >= nSamples)
1540 return NULL;
1541
1542 if (!t->Data) return NULL;
1543 return t->Data [nSet * nSamples + nField];
1544 }
1545
1546 static
SetData(cmsIT8 * it8,int nSet,int nField,const char * Val)1547 cmsBool SetData(cmsIT8* it8, int nSet, int nField, const char *Val)
1548 {
1549 TABLE* t = GetTable(it8);
1550
1551 if (!t->Data)
1552 AllocateDataSet(it8);
1553
1554 if (!t->Data) return FALSE;
1555
1556 if (nSet > t -> nPatches || nSet < 0) {
1557
1558 return SynError(it8, "Patch %d out of range, there are %d patches", nSet, t -> nPatches);
1559 }
1560
1561 if (nField > t ->nSamples || nField < 0) {
1562 return SynError(it8, "Sample %d out of range, there are %d samples", nField, t ->nSamples);
1563
1564 }
1565
1566 t->Data [nSet * t -> nSamples + nField] = AllocString(it8, Val);
1567 return TRUE;
1568 }
1569
1570
1571 // --------------------------------------------------------------- File I/O
1572
1573
1574 // Writes a string to file
1575 static
WriteStr(SAVESTREAM * f,const char * str)1576 void WriteStr(SAVESTREAM* f, const char *str)
1577 {
1578 cmsUInt32Number len;
1579
1580 if (str == NULL)
1581 str = " ";
1582
1583 // Length to write
1584 len = (cmsUInt32Number) strlen(str);
1585 f ->Used += len;
1586
1587
1588 if (f ->stream) { // Should I write it to a file?
1589
1590 if (fwrite(str, 1, len, f->stream) != len) {
1591 cmsSignalError(0, cmsERROR_WRITE, "Write to file error in CGATS parser");
1592 return;
1593 }
1594
1595 }
1596 else { // Or to a memory block?
1597
1598 if (f ->Base) { // Am I just counting the bytes?
1599
1600 if (f ->Used > f ->Max) {
1601
1602 cmsSignalError(0, cmsERROR_WRITE, "Write to memory overflows in CGATS parser");
1603 return;
1604 }
1605
1606 memmove(f ->Ptr, str, len);
1607 f->Ptr += len;
1608 }
1609
1610 }
1611 }
1612
1613
1614 // Write formatted
1615
1616 static
Writef(SAVESTREAM * f,const char * frm,...)1617 void Writef(SAVESTREAM* f, const char* frm, ...)
1618 {
1619 char Buffer[4096];
1620 va_list args;
1621
1622 va_start(args, frm);
1623 vsnprintf(Buffer, 4095, frm, args);
1624 Buffer[4095] = 0;
1625 WriteStr(f, Buffer);
1626 va_end(args);
1627
1628 }
1629
1630 // Writes full header
1631 static
WriteHeader(cmsIT8 * it8,SAVESTREAM * fp)1632 void WriteHeader(cmsIT8* it8, SAVESTREAM* fp)
1633 {
1634 KEYVALUE* p;
1635 TABLE* t = GetTable(it8);
1636
1637 // Writes the type
1638 WriteStr(fp, t->SheetType);
1639 WriteStr(fp, "\n");
1640
1641 for (p = t->HeaderList; (p != NULL); p = p->Next)
1642 {
1643 if (*p ->Keyword == '#') {
1644
1645 char* Pt;
1646
1647 WriteStr(fp, "#\n# ");
1648 for (Pt = p ->Value; *Pt; Pt++) {
1649
1650
1651 Writef(fp, "%c", *Pt);
1652
1653 if (*Pt == '\n') {
1654 WriteStr(fp, "# ");
1655 }
1656 }
1657
1658 WriteStr(fp, "\n#\n");
1659 continue;
1660 }
1661
1662
1663 if (!IsAvailableOnList(it8-> ValidKeywords, p->Keyword, NULL, NULL)) {
1664
1665 #ifdef CMS_STRICT_CGATS
1666 WriteStr(fp, "KEYWORD\t\"");
1667 WriteStr(fp, p->Keyword);
1668 WriteStr(fp, "\"\n");
1669 #endif
1670
1671 AddAvailableProperty(it8, p->Keyword, WRITE_UNCOOKED);
1672 }
1673
1674 WriteStr(fp, p->Keyword);
1675 if (p->Value) {
1676
1677 switch (p ->WriteAs) {
1678
1679 case WRITE_UNCOOKED:
1680 Writef(fp, "\t%s", p ->Value);
1681 break;
1682
1683 case WRITE_STRINGIFY:
1684 Writef(fp, "\t\"%s\"", p->Value );
1685 break;
1686
1687 case WRITE_HEXADECIMAL:
1688 Writef(fp, "\t0x%X", satoi(p ->Value));
1689 break;
1690
1691 case WRITE_BINARY:
1692 Writef(fp, "\t0x%B", satoi(p ->Value));
1693 break;
1694
1695 case WRITE_PAIR:
1696 Writef(fp, "\t\"%s,%s\"", p->Subkey, p->Value);
1697 break;
1698
1699 default: SynError(it8, "Unknown write mode %d", p ->WriteAs);
1700 return;
1701 }
1702 }
1703
1704 WriteStr (fp, "\n");
1705 }
1706
1707 }
1708
1709
1710 // Writes the data format
1711 static
WriteDataFormat(SAVESTREAM * fp,cmsIT8 * it8)1712 void WriteDataFormat(SAVESTREAM* fp, cmsIT8* it8)
1713 {
1714 int i, nSamples;
1715 TABLE* t = GetTable(it8);
1716
1717 if (!t -> DataFormat) return;
1718
1719 WriteStr(fp, "BEGIN_DATA_FORMAT\n");
1720 WriteStr(fp, " ");
1721 nSamples = satoi(cmsIT8GetProperty(it8, "NUMBER_OF_FIELDS"));
1722
1723 for (i = 0; i < nSamples; i++) {
1724
1725 WriteStr(fp, t->DataFormat[i]);
1726 WriteStr(fp, ((i == (nSamples-1)) ? "\n" : "\t"));
1727 }
1728
1729 WriteStr (fp, "END_DATA_FORMAT\n");
1730 }
1731
1732
1733 // Writes data array
1734 static
WriteData(SAVESTREAM * fp,cmsIT8 * it8)1735 void WriteData(SAVESTREAM* fp, cmsIT8* it8)
1736 {
1737 int i, j;
1738 TABLE* t = GetTable(it8);
1739
1740 if (!t->Data) return;
1741
1742 WriteStr (fp, "BEGIN_DATA\n");
1743
1744 t->nPatches = satoi(cmsIT8GetProperty(it8, "NUMBER_OF_SETS"));
1745
1746 for (i = 0; i < t-> nPatches; i++) {
1747
1748 WriteStr(fp, " ");
1749
1750 for (j = 0; j < t->nSamples; j++) {
1751
1752 char *ptr = t->Data[i*t->nSamples+j];
1753
1754 if (ptr == NULL) WriteStr(fp, "\"\"");
1755 else {
1756 // If value contains whitespace, enclose within quote
1757
1758 if (strchr(ptr, ' ') != NULL) {
1759
1760 WriteStr(fp, "\"");
1761 WriteStr(fp, ptr);
1762 WriteStr(fp, "\"");
1763 }
1764 else
1765 WriteStr(fp, ptr);
1766 }
1767
1768 WriteStr(fp, ((j == (t->nSamples-1)) ? "\n" : "\t"));
1769 }
1770 }
1771 WriteStr (fp, "END_DATA\n");
1772 }
1773
1774
1775
1776 // Saves whole file
cmsIT8SaveToFile(cmsHANDLE hIT8,const char * cFileName)1777 cmsBool CMSEXPORT cmsIT8SaveToFile(cmsHANDLE hIT8, const char* cFileName)
1778 {
1779 SAVESTREAM sd;
1780 cmsUInt32Number i;
1781 cmsIT8* it8 = (cmsIT8*) hIT8;
1782
1783 memset(&sd, 0, sizeof(sd));
1784
1785 sd.stream = fopen(cFileName, "wt");
1786 if (!sd.stream) return FALSE;
1787
1788 for (i=0; i < it8 ->TablesCount; i++) {
1789
1790 cmsIT8SetTable(hIT8, i);
1791 WriteHeader(it8, &sd);
1792 WriteDataFormat(&sd, it8);
1793 WriteData(&sd, it8);
1794 }
1795
1796 if (fclose(sd.stream) != 0) return FALSE;
1797
1798 return TRUE;
1799 }
1800
1801
1802 // Saves to memory
cmsIT8SaveToMem(cmsHANDLE hIT8,void * MemPtr,cmsUInt32Number * BytesNeeded)1803 cmsBool CMSEXPORT cmsIT8SaveToMem(cmsHANDLE hIT8, void *MemPtr, cmsUInt32Number* BytesNeeded)
1804 {
1805 SAVESTREAM sd;
1806 cmsUInt32Number i;
1807 cmsIT8* it8 = (cmsIT8*) hIT8;
1808
1809 memset(&sd, 0, sizeof(sd));
1810
1811 sd.stream = NULL;
1812 sd.Base = (cmsUInt8Number*) MemPtr;
1813 sd.Ptr = sd.Base;
1814
1815 sd.Used = 0;
1816
1817 if (sd.Base)
1818 sd.Max = *BytesNeeded; // Write to memory?
1819 else
1820 sd.Max = 0; // Just counting the needed bytes
1821
1822 for (i=0; i < it8 ->TablesCount; i++) {
1823
1824 cmsIT8SetTable(hIT8, i);
1825 WriteHeader(it8, &sd);
1826 WriteDataFormat(&sd, it8);
1827 WriteData(&sd, it8);
1828 }
1829
1830 sd.Used++; // The \0 at the very end
1831
1832 if (sd.Base)
1833 *sd.Ptr = 0;
1834
1835 *BytesNeeded = sd.Used;
1836
1837 return TRUE;
1838 }
1839
1840
1841 // -------------------------------------------------------------- Higher level parsing
1842
1843 static
DataFormatSection(cmsIT8 * it8)1844 cmsBool DataFormatSection(cmsIT8* it8)
1845 {
1846 int iField = 0;
1847 TABLE* t = GetTable(it8);
1848
1849 InSymbol(it8); // Eats "BEGIN_DATA_FORMAT"
1850 CheckEOLN(it8);
1851
1852 while (it8->sy != SEND_DATA_FORMAT &&
1853 it8->sy != SEOLN &&
1854 it8->sy != SEOF &&
1855 it8->sy != SSYNERROR) {
1856
1857 if (it8->sy != SIDENT) {
1858
1859 return SynError(it8, "Sample type expected");
1860 }
1861
1862 if (!SetDataFormat(it8, iField, it8->id)) return FALSE;
1863 iField++;
1864
1865 InSymbol(it8);
1866 SkipEOLN(it8);
1867 }
1868
1869 SkipEOLN(it8);
1870 Skip(it8, SEND_DATA_FORMAT);
1871 SkipEOLN(it8);
1872
1873 if (iField != t ->nSamples) {
1874 SynError(it8, "Count mismatch. NUMBER_OF_FIELDS was %d, found %d\n", t ->nSamples, iField);
1875
1876
1877 }
1878
1879 return TRUE;
1880 }
1881
1882
1883
1884 static
DataSection(cmsIT8 * it8)1885 cmsBool DataSection (cmsIT8* it8)
1886 {
1887 int iField = 0;
1888 int iSet = 0;
1889 char Buffer[256];
1890 TABLE* t = GetTable(it8);
1891
1892 InSymbol(it8); // Eats "BEGIN_DATA"
1893 CheckEOLN(it8);
1894
1895 if (!t->Data)
1896 AllocateDataSet(it8);
1897
1898 while (it8->sy != SEND_DATA && it8->sy != SEOF)
1899 {
1900 if (iField >= t -> nSamples) {
1901 iField = 0;
1902 iSet++;
1903
1904 }
1905
1906 if (it8->sy != SEND_DATA && it8->sy != SEOF) {
1907
1908 if (!GetVal(it8, Buffer, 255, "Sample data expected"))
1909 return FALSE;
1910
1911 if (!SetData(it8, iSet, iField, Buffer))
1912 return FALSE;
1913
1914 iField++;
1915
1916 InSymbol(it8);
1917 SkipEOLN(it8);
1918 }
1919 }
1920
1921 SkipEOLN(it8);
1922 Skip(it8, SEND_DATA);
1923 SkipEOLN(it8);
1924
1925 // Check for data completion.
1926
1927 if ((iSet+1) != t -> nPatches)
1928 return SynError(it8, "Count mismatch. NUMBER_OF_SETS was %d, found %d\n", t ->nPatches, iSet+1);
1929
1930 return TRUE;
1931 }
1932
1933
1934
1935
1936 static
HeaderSection(cmsIT8 * it8)1937 cmsBool HeaderSection(cmsIT8* it8)
1938 {
1939 char VarName[MAXID];
1940 char Buffer[MAXSTR];
1941 KEYVALUE* Key;
1942
1943 while (it8->sy != SEOF &&
1944 it8->sy != SSYNERROR &&
1945 it8->sy != SBEGIN_DATA_FORMAT &&
1946 it8->sy != SBEGIN_DATA) {
1947
1948
1949 switch (it8 -> sy) {
1950
1951 case SKEYWORD:
1952 InSymbol(it8);
1953 if (!GetVal(it8, Buffer, MAXSTR-1, "Keyword expected")) return FALSE;
1954 if (!AddAvailableProperty(it8, Buffer, WRITE_UNCOOKED)) return FALSE;
1955 InSymbol(it8);
1956 break;
1957
1958
1959 case SDATA_FORMAT_ID:
1960 InSymbol(it8);
1961 if (!GetVal(it8, Buffer, MAXSTR-1, "Keyword expected")) return FALSE;
1962 if (!AddAvailableSampleID(it8, Buffer)) return FALSE;
1963 InSymbol(it8);
1964 break;
1965
1966
1967 case SIDENT:
1968 strncpy(VarName, it8->id, MAXID - 1);
1969 VarName[MAXID - 1] = 0;
1970
1971 if (!IsAvailableOnList(it8->ValidKeywords, VarName, NULL, &Key)) {
1972
1973 #ifdef CMS_STRICT_CGATS
1974 return SynError(it8, "Undefined keyword '%s'", VarName);
1975 #else
1976 Key = AddAvailableProperty(it8, VarName, WRITE_UNCOOKED);
1977 if (Key == NULL) return FALSE;
1978 #endif
1979 }
1980
1981 InSymbol(it8);
1982 if (!GetVal(it8, Buffer, MAXSTR - 1, "Property data expected")) return FALSE;
1983
1984 if (Key->WriteAs != WRITE_PAIR) {
1985 AddToList(it8, &GetTable(it8)->HeaderList, VarName, NULL, Buffer,
1986 (it8->sy == SSTRING) ? WRITE_STRINGIFY : WRITE_UNCOOKED);
1987 }
1988 else {
1989 const char *Subkey;
1990 char *Nextkey;
1991 if (it8->sy != SSTRING)
1992 return SynError(it8, "Invalid value '%s' for property '%s'.", Buffer, VarName);
1993
1994 // chop the string as a list of "subkey, value" pairs, using ';' as a separator
1995 for (Subkey = Buffer; Subkey != NULL; Subkey = Nextkey)
1996 {
1997 char *Value, *temp;
1998
1999 // identify token pair boundary
2000 Nextkey = (char*)strchr(Subkey, ';');
2001 if (Nextkey)
2002 *Nextkey++ = '\0';
2003
2004 // for each pair, split the subkey and the value
2005 Value = (char*)strrchr(Subkey, ',');
2006 if (Value == NULL)
2007 return SynError(it8, "Invalid value for property '%s'.", VarName);
2008
2009 // gobble the spaces before the coma, and the coma itself
2010 temp = Value++;
2011 do *temp-- = '\0'; while (temp >= Subkey && *temp == ' ');
2012
2013 // gobble any space at the right
2014 temp = Value + strlen(Value) - 1;
2015 while (*temp == ' ') *temp-- = '\0';
2016
2017 // trim the strings from the left
2018 Subkey += strspn(Subkey, " ");
2019 Value += strspn(Value, " ");
2020
2021 if (Subkey[0] == 0 || Value[0] == 0)
2022 return SynError(it8, "Invalid value for property '%s'.", VarName);
2023 AddToList(it8, &GetTable(it8)->HeaderList, VarName, Subkey, Value, WRITE_PAIR);
2024 }
2025 }
2026
2027 InSymbol(it8);
2028 break;
2029
2030
2031 case SEOLN: break;
2032
2033 default:
2034 return SynError(it8, "expected keyword or identifier");
2035 }
2036
2037 SkipEOLN(it8);
2038 }
2039
2040 return TRUE;
2041
2042 }
2043
2044
2045 static
ReadType(cmsIT8 * it8,char * SheetTypePtr)2046 void ReadType(cmsIT8* it8, char* SheetTypePtr)
2047 {
2048 cmsInt32Number cnt = 0;
2049
2050 // First line is a very special case.
2051
2052 while (isseparator(it8->ch))
2053 NextCh(it8);
2054
2055 while (it8->ch != '\r' && it8 ->ch != '\n' && it8->ch != '\t' && it8 -> ch != 0) {
2056
2057 if (cnt++ < MAXSTR)
2058 *SheetTypePtr++= (char) it8 ->ch;
2059 NextCh(it8);
2060 }
2061
2062 *SheetTypePtr = 0;
2063 }
2064
2065
2066 static
ParseIT8(cmsIT8 * it8,cmsBool nosheet)2067 cmsBool ParseIT8(cmsIT8* it8, cmsBool nosheet)
2068 {
2069 char* SheetTypePtr = it8 ->Tab[0].SheetType;
2070
2071 if (nosheet == 0) {
2072 ReadType(it8, SheetTypePtr);
2073 }
2074
2075 InSymbol(it8);
2076
2077 SkipEOLN(it8);
2078
2079 while (it8-> sy != SEOF &&
2080 it8-> sy != SSYNERROR) {
2081
2082 switch (it8 -> sy) {
2083
2084 case SBEGIN_DATA_FORMAT:
2085 if (!DataFormatSection(it8)) return FALSE;
2086 break;
2087
2088 case SBEGIN_DATA:
2089
2090 if (!DataSection(it8)) return FALSE;
2091
2092 if (it8 -> sy != SEOF) {
2093
2094 AllocTable(it8);
2095 it8 ->nTable = it8 ->TablesCount - 1;
2096
2097 // Read sheet type if present. We only support identifier and string.
2098 // <ident> <eoln> is a type string
2099 // anything else, is not a type string
2100 if (nosheet == 0) {
2101
2102 if (it8 ->sy == SIDENT) {
2103
2104 // May be a type sheet or may be a prop value statement. We cannot use insymbol in
2105 // this special case...
2106 while (isseparator(it8->ch))
2107 NextCh(it8);
2108
2109 // If a newline is found, then this is a type string
2110 if (it8 ->ch == '\n' || it8->ch == '\r') {
2111
2112 cmsIT8SetSheetType(it8, it8 ->id);
2113 InSymbol(it8);
2114 }
2115 else
2116 {
2117 // It is not. Just continue
2118 cmsIT8SetSheetType(it8, "");
2119 }
2120 }
2121 else
2122 // Validate quoted strings
2123 if (it8 ->sy == SSTRING) {
2124 cmsIT8SetSheetType(it8, it8 ->str);
2125 InSymbol(it8);
2126 }
2127 }
2128
2129 }
2130 break;
2131
2132 case SEOLN:
2133 SkipEOLN(it8);
2134 break;
2135
2136 default:
2137 if (!HeaderSection(it8)) return FALSE;
2138 }
2139
2140 }
2141
2142 return (it8 -> sy != SSYNERROR);
2143 }
2144
2145
2146
2147 // Init useful pointers
2148
2149 static
CookPointers(cmsIT8 * it8)2150 void CookPointers(cmsIT8* it8)
2151 {
2152 int idField, i;
2153 char* Fld;
2154 cmsUInt32Number j;
2155 cmsUInt32Number nOldTable = it8 ->nTable;
2156
2157 for (j=0; j < it8 ->TablesCount; j++) {
2158
2159 TABLE* t = it8 ->Tab + j;
2160
2161 t -> SampleID = 0;
2162 it8 ->nTable = j;
2163
2164 for (idField = 0; idField < t -> nSamples; idField++)
2165 {
2166 if (t ->DataFormat == NULL){
2167 SynError(it8, "Undefined DATA_FORMAT");
2168 return;
2169 }
2170
2171 Fld = t->DataFormat[idField];
2172 if (!Fld) continue;
2173
2174
2175 if (cmsstrcasecmp(Fld, "SAMPLE_ID") == 0) {
2176
2177 t -> SampleID = idField;
2178 }
2179
2180 // "LABEL" is an extension. It keeps references to forward tables
2181
2182 if ((cmsstrcasecmp(Fld, "LABEL") == 0) || Fld[0] == '$') {
2183
2184 // Search for table references...
2185 for (i = 0; i < t->nPatches; i++) {
2186
2187 char* Label = GetData(it8, i, idField);
2188
2189 if (Label) {
2190
2191 cmsUInt32Number k;
2192
2193 // This is the label, search for a table containing
2194 // this property
2195
2196 for (k = 0; k < it8->TablesCount; k++) {
2197
2198 TABLE* Table = it8->Tab + k;
2199 KEYVALUE* p;
2200
2201 if (IsAvailableOnList(Table->HeaderList, Label, NULL, &p)) {
2202
2203 // Available, keep type and table
2204 char Buffer[256];
2205
2206 char* Type = p->Value;
2207 int nTable = (int)k;
2208
2209 snprintf(Buffer, 255, "%s %d %s", Label, nTable, Type);
2210
2211 SetData(it8, i, idField, Buffer);
2212 }
2213 }
2214
2215
2216 }
2217
2218 }
2219
2220
2221 }
2222
2223 }
2224 }
2225
2226 it8 ->nTable = nOldTable;
2227 }
2228
2229 // Try to infere if the file is a CGATS/IT8 file at all. Read first line
2230 // that should be something like some printable characters plus a \n
2231 // returns 0 if this is not like a CGATS, or an integer otherwise. This integer is the number of words in first line?
2232 static
IsMyBlock(const cmsUInt8Number * Buffer,cmsUInt32Number n)2233 int IsMyBlock(const cmsUInt8Number* Buffer, cmsUInt32Number n)
2234 {
2235 int words = 1, space = 0, quot = 0;
2236 cmsUInt32Number i;
2237
2238 if (n < 10) return 0; // Too small
2239
2240 if (n > 132)
2241 n = 132;
2242
2243 for (i = 1; i < n; i++) {
2244
2245 switch(Buffer[i])
2246 {
2247 case '\n':
2248 case '\r':
2249 return ((quot == 1) || (words > 2)) ? 0 : words;
2250 case '\t':
2251 case ' ':
2252 if(!quot && !space)
2253 space = 1;
2254 break;
2255 case '\"':
2256 quot = !quot;
2257 break;
2258 default:
2259 if (Buffer[i] < 32) return 0;
2260 if (Buffer[i] > 127) return 0;
2261 words += space;
2262 space = 0;
2263 break;
2264 }
2265 }
2266
2267 return 0;
2268 }
2269
2270
2271 static
IsMyFile(const char * FileName)2272 cmsBool IsMyFile(const char* FileName)
2273 {
2274 FILE *fp;
2275 cmsUInt32Number Size;
2276 cmsUInt8Number Ptr[133];
2277
2278 fp = fopen(FileName, "rt");
2279 if (!fp) {
2280 cmsSignalError(0, cmsERROR_FILE, "File '%s' not found", FileName);
2281 return FALSE;
2282 }
2283
2284 Size = (cmsUInt32Number) fread(Ptr, 1, 132, fp);
2285
2286 if (fclose(fp) != 0)
2287 return FALSE;
2288
2289 Ptr[Size] = '\0';
2290
2291 return IsMyBlock(Ptr, Size);
2292 }
2293
2294 // ---------------------------------------------------------- Exported routines
2295
2296
cmsIT8LoadFromMem(cmsContext ContextID,const void * Ptr,cmsUInt32Number len)2297 cmsHANDLE CMSEXPORT cmsIT8LoadFromMem(cmsContext ContextID, const void *Ptr, cmsUInt32Number len)
2298 {
2299 cmsHANDLE hIT8;
2300 cmsIT8* it8;
2301 int type;
2302
2303 _cmsAssert(Ptr != NULL);
2304 _cmsAssert(len != 0);
2305
2306 type = IsMyBlock((const cmsUInt8Number*)Ptr, len);
2307 if (type == 0) return NULL;
2308
2309 hIT8 = cmsIT8Alloc(ContextID);
2310 if (!hIT8) return NULL;
2311
2312 it8 = (cmsIT8*) hIT8;
2313 it8 ->MemoryBlock = (char*) _cmsMalloc(ContextID, len + 1);
2314 if (it8->MemoryBlock == NULL)
2315 {
2316 cmsIT8Free(hIT8);
2317 return FALSE;
2318 }
2319
2320 strncpy(it8 ->MemoryBlock, (const char*) Ptr, len);
2321 it8 ->MemoryBlock[len] = 0;
2322
2323 strncpy(it8->FileStack[0]->FileName, "", cmsMAX_PATH-1);
2324 it8-> Source = it8 -> MemoryBlock;
2325
2326 if (!ParseIT8(it8, type-1)) {
2327
2328 cmsIT8Free(hIT8);
2329 return FALSE;
2330 }
2331
2332 CookPointers(it8);
2333 it8 ->nTable = 0;
2334
2335 _cmsFree(ContextID, it8->MemoryBlock);
2336 it8 -> MemoryBlock = NULL;
2337
2338 return hIT8;
2339
2340
2341 }
2342
2343
cmsIT8LoadFromFile(cmsContext ContextID,const char * cFileName)2344 cmsHANDLE CMSEXPORT cmsIT8LoadFromFile(cmsContext ContextID, const char* cFileName)
2345 {
2346
2347 cmsHANDLE hIT8;
2348 cmsIT8* it8;
2349 int type;
2350
2351 _cmsAssert(cFileName != NULL);
2352
2353 type = IsMyFile(cFileName);
2354 if (type == 0) return NULL;
2355
2356 hIT8 = cmsIT8Alloc(ContextID);
2357 it8 = (cmsIT8*) hIT8;
2358 if (!hIT8) return NULL;
2359
2360
2361 it8 ->FileStack[0]->Stream = fopen(cFileName, "rt");
2362
2363 if (!it8 ->FileStack[0]->Stream) {
2364 cmsIT8Free(hIT8);
2365 return NULL;
2366 }
2367
2368
2369 strncpy(it8->FileStack[0]->FileName, cFileName, cmsMAX_PATH-1);
2370 it8->FileStack[0]->FileName[cmsMAX_PATH-1] = 0;
2371
2372 if (!ParseIT8(it8, type-1)) {
2373
2374 fclose(it8 ->FileStack[0]->Stream);
2375 cmsIT8Free(hIT8);
2376 return NULL;
2377 }
2378
2379 CookPointers(it8);
2380 it8 ->nTable = 0;
2381
2382 if (fclose(it8 ->FileStack[0]->Stream)!= 0) {
2383 cmsIT8Free(hIT8);
2384 return NULL;
2385 }
2386
2387 return hIT8;
2388
2389 }
2390
cmsIT8EnumDataFormat(cmsHANDLE hIT8,char *** SampleNames)2391 int CMSEXPORT cmsIT8EnumDataFormat(cmsHANDLE hIT8, char ***SampleNames)
2392 {
2393 cmsIT8* it8 = (cmsIT8*) hIT8;
2394 TABLE* t;
2395
2396 _cmsAssert(hIT8 != NULL);
2397
2398 t = GetTable(it8);
2399
2400 if (SampleNames)
2401 *SampleNames = t -> DataFormat;
2402 return t -> nSamples;
2403 }
2404
2405
cmsIT8EnumProperties(cmsHANDLE hIT8,char *** PropertyNames)2406 cmsUInt32Number CMSEXPORT cmsIT8EnumProperties(cmsHANDLE hIT8, char ***PropertyNames)
2407 {
2408 cmsIT8* it8 = (cmsIT8*) hIT8;
2409 KEYVALUE* p;
2410 cmsUInt32Number n;
2411 char **Props;
2412 TABLE* t;
2413
2414 _cmsAssert(hIT8 != NULL);
2415
2416 t = GetTable(it8);
2417
2418 // Pass#1 - count properties
2419
2420 n = 0;
2421 for (p = t -> HeaderList; p != NULL; p = p->Next) {
2422 n++;
2423 }
2424
2425
2426 Props = (char **) AllocChunk(it8, sizeof(char *) * n);
2427
2428 // Pass#2 - Fill pointers
2429 n = 0;
2430 for (p = t -> HeaderList; p != NULL; p = p->Next) {
2431 Props[n++] = p -> Keyword;
2432 }
2433
2434 *PropertyNames = Props;
2435 return n;
2436 }
2437
cmsIT8EnumPropertyMulti(cmsHANDLE hIT8,const char * cProp,const char *** SubpropertyNames)2438 cmsUInt32Number CMSEXPORT cmsIT8EnumPropertyMulti(cmsHANDLE hIT8, const char* cProp, const char ***SubpropertyNames)
2439 {
2440 cmsIT8* it8 = (cmsIT8*) hIT8;
2441 KEYVALUE *p, *tmp;
2442 cmsUInt32Number n;
2443 const char **Props;
2444 TABLE* t;
2445
2446 _cmsAssert(hIT8 != NULL);
2447
2448
2449 t = GetTable(it8);
2450
2451 if(!IsAvailableOnList(t->HeaderList, cProp, NULL, &p)) {
2452 *SubpropertyNames = 0;
2453 return 0;
2454 }
2455
2456 // Pass#1 - count properties
2457
2458 n = 0;
2459 for (tmp = p; tmp != NULL; tmp = tmp->NextSubkey) {
2460 if(tmp->Subkey != NULL)
2461 n++;
2462 }
2463
2464
2465 Props = (const char **) AllocChunk(it8, sizeof(char *) * n);
2466
2467 // Pass#2 - Fill pointers
2468 n = 0;
2469 for (tmp = p; tmp != NULL; tmp = tmp->NextSubkey) {
2470 if(tmp->Subkey != NULL)
2471 Props[n++] = p ->Subkey;
2472 }
2473
2474 *SubpropertyNames = Props;
2475 return n;
2476 }
2477
2478 static
LocatePatch(cmsIT8 * it8,const char * cPatch)2479 int LocatePatch(cmsIT8* it8, const char* cPatch)
2480 {
2481 int i;
2482 const char *data;
2483 TABLE* t = GetTable(it8);
2484
2485 for (i=0; i < t-> nPatches; i++) {
2486
2487 data = GetData(it8, i, t->SampleID);
2488
2489 if (data != NULL) {
2490
2491 if (cmsstrcasecmp(data, cPatch) == 0)
2492 return i;
2493 }
2494 }
2495
2496 // SynError(it8, "Couldn't find patch '%s'\n", cPatch);
2497 return -1;
2498 }
2499
2500
2501 static
LocateEmptyPatch(cmsIT8 * it8)2502 int LocateEmptyPatch(cmsIT8* it8)
2503 {
2504 int i;
2505 const char *data;
2506 TABLE* t = GetTable(it8);
2507
2508 for (i=0; i < t-> nPatches; i++) {
2509
2510 data = GetData(it8, i, t->SampleID);
2511
2512 if (data == NULL)
2513 return i;
2514
2515 }
2516
2517 return -1;
2518 }
2519
2520 static
LocateSample(cmsIT8 * it8,const char * cSample)2521 int LocateSample(cmsIT8* it8, const char* cSample)
2522 {
2523 int i;
2524 const char *fld;
2525 TABLE* t = GetTable(it8);
2526
2527 for (i=0; i < t->nSamples; i++) {
2528
2529 fld = GetDataFormat(it8, i);
2530 if (fld != NULL) {
2531 if (cmsstrcasecmp(fld, cSample) == 0)
2532 return i;
2533 }
2534 }
2535
2536 return -1;
2537
2538 }
2539
2540
cmsIT8FindDataFormat(cmsHANDLE hIT8,const char * cSample)2541 int CMSEXPORT cmsIT8FindDataFormat(cmsHANDLE hIT8, const char* cSample)
2542 {
2543 cmsIT8* it8 = (cmsIT8*) hIT8;
2544
2545 _cmsAssert(hIT8 != NULL);
2546
2547 return LocateSample(it8, cSample);
2548 }
2549
2550
2551
cmsIT8GetDataRowCol(cmsHANDLE hIT8,int row,int col)2552 const char* CMSEXPORT cmsIT8GetDataRowCol(cmsHANDLE hIT8, int row, int col)
2553 {
2554 cmsIT8* it8 = (cmsIT8*) hIT8;
2555
2556 _cmsAssert(hIT8 != NULL);
2557
2558 return GetData(it8, row, col);
2559 }
2560
2561
cmsIT8GetDataRowColDbl(cmsHANDLE hIT8,int row,int col)2562 cmsFloat64Number CMSEXPORT cmsIT8GetDataRowColDbl(cmsHANDLE hIT8, int row, int col)
2563 {
2564 const char* Buffer;
2565
2566 Buffer = cmsIT8GetDataRowCol(hIT8, row, col);
2567
2568 if (Buffer == NULL) return 0.0;
2569
2570 return ParseFloatNumber(Buffer);
2571 }
2572
2573
cmsIT8SetDataRowCol(cmsHANDLE hIT8,int row,int col,const char * Val)2574 cmsBool CMSEXPORT cmsIT8SetDataRowCol(cmsHANDLE hIT8, int row, int col, const char* Val)
2575 {
2576 cmsIT8* it8 = (cmsIT8*) hIT8;
2577
2578 _cmsAssert(hIT8 != NULL);
2579
2580 return SetData(it8, row, col, Val);
2581 }
2582
2583
cmsIT8SetDataRowColDbl(cmsHANDLE hIT8,int row,int col,cmsFloat64Number Val)2584 cmsBool CMSEXPORT cmsIT8SetDataRowColDbl(cmsHANDLE hIT8, int row, int col, cmsFloat64Number Val)
2585 {
2586 cmsIT8* it8 = (cmsIT8*) hIT8;
2587 char Buff[256];
2588
2589 _cmsAssert(hIT8 != NULL);
2590
2591 snprintf(Buff, 255, it8->DoubleFormatter, Val);
2592
2593 return SetData(it8, row, col, Buff);
2594 }
2595
2596
2597
cmsIT8GetData(cmsHANDLE hIT8,const char * cPatch,const char * cSample)2598 const char* CMSEXPORT cmsIT8GetData(cmsHANDLE hIT8, const char* cPatch, const char* cSample)
2599 {
2600 cmsIT8* it8 = (cmsIT8*) hIT8;
2601 int iField, iSet;
2602
2603 _cmsAssert(hIT8 != NULL);
2604
2605 iField = LocateSample(it8, cSample);
2606 if (iField < 0) {
2607 return NULL;
2608 }
2609
2610 iSet = LocatePatch(it8, cPatch);
2611 if (iSet < 0) {
2612 return NULL;
2613 }
2614
2615 return GetData(it8, iSet, iField);
2616 }
2617
2618
cmsIT8GetDataDbl(cmsHANDLE it8,const char * cPatch,const char * cSample)2619 cmsFloat64Number CMSEXPORT cmsIT8GetDataDbl(cmsHANDLE it8, const char* cPatch, const char* cSample)
2620 {
2621 const char* Buffer;
2622
2623 Buffer = cmsIT8GetData(it8, cPatch, cSample);
2624
2625 return ParseFloatNumber(Buffer);
2626 }
2627
2628
2629
cmsIT8SetData(cmsHANDLE hIT8,const char * cPatch,const char * cSample,const char * Val)2630 cmsBool CMSEXPORT cmsIT8SetData(cmsHANDLE hIT8, const char* cPatch, const char* cSample, const char *Val)
2631 {
2632 cmsIT8* it8 = (cmsIT8*) hIT8;
2633 int iField, iSet;
2634 TABLE* t;
2635
2636 _cmsAssert(hIT8 != NULL);
2637
2638 t = GetTable(it8);
2639
2640 iField = LocateSample(it8, cSample);
2641
2642 if (iField < 0)
2643 return FALSE;
2644
2645 if (t-> nPatches == 0) {
2646
2647 AllocateDataFormat(it8);
2648 AllocateDataSet(it8);
2649 CookPointers(it8);
2650 }
2651
2652 if (cmsstrcasecmp(cSample, "SAMPLE_ID") == 0) {
2653
2654 iSet = LocateEmptyPatch(it8);
2655 if (iSet < 0) {
2656 return SynError(it8, "Couldn't add more patches '%s'\n", cPatch);
2657 }
2658
2659 iField = t -> SampleID;
2660 }
2661 else {
2662 iSet = LocatePatch(it8, cPatch);
2663 if (iSet < 0) {
2664 return FALSE;
2665 }
2666 }
2667
2668 return SetData(it8, iSet, iField, Val);
2669 }
2670
2671
cmsIT8SetDataDbl(cmsHANDLE hIT8,const char * cPatch,const char * cSample,cmsFloat64Number Val)2672 cmsBool CMSEXPORT cmsIT8SetDataDbl(cmsHANDLE hIT8, const char* cPatch,
2673 const char* cSample,
2674 cmsFloat64Number Val)
2675 {
2676 cmsIT8* it8 = (cmsIT8*) hIT8;
2677 char Buff[256];
2678
2679 _cmsAssert(hIT8 != NULL);
2680
2681 snprintf(Buff, 255, it8->DoubleFormatter, Val);
2682 return cmsIT8SetData(hIT8, cPatch, cSample, Buff);
2683 }
2684
2685 // Buffer should get MAXSTR at least
2686
cmsIT8GetPatchName(cmsHANDLE hIT8,int nPatch,char * buffer)2687 const char* CMSEXPORT cmsIT8GetPatchName(cmsHANDLE hIT8, int nPatch, char* buffer)
2688 {
2689 cmsIT8* it8 = (cmsIT8*) hIT8;
2690 TABLE* t;
2691 char* Data;
2692
2693 _cmsAssert(hIT8 != NULL);
2694
2695 t = GetTable(it8);
2696 Data = GetData(it8, nPatch, t->SampleID);
2697
2698 if (!Data) return NULL;
2699 if (!buffer) return Data;
2700
2701 strncpy(buffer, Data, MAXSTR-1);
2702 buffer[MAXSTR-1] = 0;
2703 return buffer;
2704 }
2705
cmsIT8GetPatchByName(cmsHANDLE hIT8,const char * cPatch)2706 int CMSEXPORT cmsIT8GetPatchByName(cmsHANDLE hIT8, const char *cPatch)
2707 {
2708 _cmsAssert(hIT8 != NULL);
2709
2710 return LocatePatch((cmsIT8*)hIT8, cPatch);
2711 }
2712
cmsIT8TableCount(cmsHANDLE hIT8)2713 cmsUInt32Number CMSEXPORT cmsIT8TableCount(cmsHANDLE hIT8)
2714 {
2715 cmsIT8* it8 = (cmsIT8*) hIT8;
2716
2717 _cmsAssert(hIT8 != NULL);
2718
2719 return it8 ->TablesCount;
2720 }
2721
2722 // This handles the "LABEL" extension.
2723 // Label, nTable, Type
2724
cmsIT8SetTableByLabel(cmsHANDLE hIT8,const char * cSet,const char * cField,const char * ExpectedType)2725 int CMSEXPORT cmsIT8SetTableByLabel(cmsHANDLE hIT8, const char* cSet, const char* cField, const char* ExpectedType)
2726 {
2727 const char* cLabelFld;
2728 char Type[256], Label[256];
2729 cmsUInt32Number nTable;
2730
2731 _cmsAssert(hIT8 != NULL);
2732
2733 if (cField != NULL && *cField == 0)
2734 cField = "LABEL";
2735
2736 if (cField == NULL)
2737 cField = "LABEL";
2738
2739 cLabelFld = cmsIT8GetData(hIT8, cSet, cField);
2740 if (!cLabelFld) return -1;
2741
2742 if (sscanf(cLabelFld, "%255s %u %255s", Label, &nTable, Type) != 3)
2743 return -1;
2744
2745 if (ExpectedType != NULL && *ExpectedType == 0)
2746 ExpectedType = NULL;
2747
2748 if (ExpectedType) {
2749
2750 if (cmsstrcasecmp(Type, ExpectedType) != 0) return -1;
2751 }
2752
2753 return cmsIT8SetTable(hIT8, nTable);
2754 }
2755
2756
cmsIT8SetIndexColumn(cmsHANDLE hIT8,const char * cSample)2757 cmsBool CMSEXPORT cmsIT8SetIndexColumn(cmsHANDLE hIT8, const char* cSample)
2758 {
2759 cmsIT8* it8 = (cmsIT8*) hIT8;
2760 int pos;
2761
2762 _cmsAssert(hIT8 != NULL);
2763
2764 pos = LocateSample(it8, cSample);
2765 if(pos == -1)
2766 return FALSE;
2767
2768 it8->Tab[it8->nTable].SampleID = pos;
2769 return TRUE;
2770 }
2771
2772
cmsIT8DefineDblFormat(cmsHANDLE hIT8,const char * Formatter)2773 void CMSEXPORT cmsIT8DefineDblFormat(cmsHANDLE hIT8, const char* Formatter)
2774 {
2775 cmsIT8* it8 = (cmsIT8*) hIT8;
2776
2777 _cmsAssert(hIT8 != NULL);
2778
2779 if (Formatter == NULL)
2780 strcpy(it8->DoubleFormatter, DEFAULT_DBL_FORMAT);
2781 else
2782 strncpy(it8->DoubleFormatter, Formatter, sizeof(it8->DoubleFormatter));
2783
2784 it8 ->DoubleFormatter[sizeof(it8 ->DoubleFormatter)-1] = 0;
2785 }
2786
2787