Tizen 2.0 Release
[external/lcms.git] / src / cmsio0.c
1 //---------------------------------------------------------------------------------
2 //
3 //  Little Color Management System
4 //  Copyright (c) 1998-2011 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 // Generic I/O, tag dictionary management, profile struct
30
31 // IOhandlers are abstractions used by littleCMS to read from whatever file, stream,
32 // memory block or any storage. Each IOhandler provides implementations for read,
33 // write, seek and tell functions. LittleCMS code deals with IO across those objects.
34 // In this way, is easier to add support for new storage media.
35
36 // NULL stream, for taking care of used space -------------------------------------
37
38 // NULL IOhandler basically does nothing but keep track on how many bytes have been
39 // written. This is handy when creating profiles, where the file size is needed in the
40 // header. Then, whole profile is serialized across NULL IOhandler and a second pass 
41 // writes the bytes to the pertinent IOhandler.
42
43 typedef struct {        
44     cmsUInt32Number Pointer;         // Points to current location
45 } FILENULL;
46
47 static
48 cmsUInt32Number NULLRead(cmsIOHANDLER* iohandler, void *Buffer, cmsUInt32Number size, cmsUInt32Number count)
49 {   
50     FILENULL* ResData = (FILENULL*) iohandler ->stream;
51     
52     cmsUInt32Number len = size * count;
53     ResData -> Pointer += len;
54     return count;
55
56     cmsUNUSED_PARAMETER(Buffer);
57 }
58
59 static
60 cmsBool  NULLSeek(cmsIOHANDLER* iohandler, cmsUInt32Number offset)
61 {
62     FILENULL* ResData = (FILENULL*) iohandler ->stream;
63
64     ResData ->Pointer = offset; 
65     return TRUE; 
66 }
67
68 static
69 cmsUInt32Number NULLTell(cmsIOHANDLER* iohandler)
70 {
71     FILENULL* ResData = (FILENULL*) iohandler ->stream;
72     return ResData -> Pointer;     
73 }
74
75 static
76 cmsBool  NULLWrite(cmsIOHANDLER* iohandler, cmsUInt32Number size, const void *Ptr)
77 {
78     FILENULL* ResData = (FILENULL*) iohandler ->stream;
79
80     ResData ->Pointer += size;
81     if (ResData ->Pointer > iohandler->UsedSpace)
82         iohandler->UsedSpace = ResData ->Pointer;
83
84     return TRUE;
85
86     cmsUNUSED_PARAMETER(Ptr);
87 }
88
89 static
90 cmsBool  NULLClose(cmsIOHANDLER* iohandler)
91 {   
92     FILENULL* ResData = (FILENULL*) iohandler ->stream;
93     
94     _cmsFree(iohandler ->ContextID, ResData);
95     _cmsFree(iohandler ->ContextID, iohandler);
96     return TRUE;
97 }
98
99 // The NULL IOhandler creator
100 cmsIOHANDLER*  CMSEXPORT cmsOpenIOhandlerFromNULL(cmsContext ContextID)
101 {
102     struct _cms_io_handler* iohandler = NULL;
103     FILENULL* fm = NULL;
104         
105     iohandler = (struct _cms_io_handler*) _cmsMallocZero(ContextID, sizeof(struct _cms_io_handler));
106     if (iohandler == NULL) return NULL;
107
108     fm = (FILENULL*) _cmsMallocZero(ContextID, sizeof(FILENULL));
109     if (fm == NULL) goto Error;
110     
111     fm ->Pointer = 0;
112
113     iohandler ->ContextID = ContextID;
114     iohandler ->stream  = (void*) fm;   
115     iohandler ->UsedSpace = 0;
116     iohandler ->ReportedSize = 0;
117     iohandler ->PhysicalFile[0] = 0;
118
119     iohandler ->Read    = NULLRead;
120     iohandler ->Seek    = NULLSeek;
121     iohandler ->Close   = NULLClose;
122     iohandler ->Tell    = NULLTell;
123     iohandler ->Write   = NULLWrite;
124
125     return iohandler;
126
127 Error:
128     if (fm) _cmsFree(ContextID, fm);
129     if (iohandler) _cmsFree(ContextID, iohandler);
130     return NULL;
131
132 }
133
134
135 // Memory-based stream --------------------------------------------------------------
136
137 // Those functions implements an iohandler which takes a block of memory as storage medium.
138
139 typedef struct {
140     cmsUInt8Number* Block;    // Points to allocated memory
141     cmsUInt32Number Size;     // Size of allocated memory
142     cmsUInt32Number Pointer;  // Points to current location
143     int FreeBlockOnClose;     // As title
144
145 } FILEMEM;
146
147 static
148 cmsUInt32Number MemoryRead(struct _cms_io_handler* iohandler, void *Buffer, cmsUInt32Number size, cmsUInt32Number count)
149 {   
150     FILEMEM* ResData = (FILEMEM*) iohandler ->stream;
151     cmsUInt8Number* Ptr;
152     cmsUInt32Number len = size * count;
153
154     if (ResData -> Pointer + len > ResData -> Size){
155
156         len = (ResData -> Size - ResData -> Pointer);
157         cmsSignalError(iohandler ->ContextID, cmsERROR_READ, "Read from memory error. Got %d bytes, block should be of %d bytes", len, count * size);
158         return 0;
159     }
160
161     Ptr  = ResData -> Block;
162     Ptr += ResData -> Pointer;
163     memmove(Buffer, Ptr, len);        
164     ResData -> Pointer += len;
165
166     return count;
167 }
168
169 // SEEK_CUR is assumed
170 static
171 cmsBool  MemorySeek(struct _cms_io_handler* iohandler, cmsUInt32Number offset)
172 {
173     FILEMEM* ResData = (FILEMEM*) iohandler ->stream;
174
175     if (offset > ResData ->Size) {
176         cmsSignalError(iohandler ->ContextID, cmsERROR_SEEK,  "Too few data; probably corrupted profile");        
177         return FALSE;
178     }
179
180     ResData ->Pointer = offset; 
181     return TRUE; 
182 }
183
184 // Tell for memory
185 static
186 cmsUInt32Number MemoryTell(struct _cms_io_handler* iohandler)
187 {
188     FILEMEM* ResData = (FILEMEM*) iohandler ->stream;
189
190         if (ResData == NULL) return 0;
191     return ResData -> Pointer;     
192 }
193
194
195 // Writes data to memory, also keeps used space for further reference. 
196 static
197 cmsBool  MemoryWrite(struct _cms_io_handler* iohandler, cmsUInt32Number size, const void *Ptr)
198 {
199     FILEMEM* ResData = (FILEMEM*) iohandler ->stream;
200
201         if (ResData == NULL) return FALSE; // Housekeeping
202
203     if (size == 0) return TRUE;     // Write zero bytes is ok, but does nothing
204
205     memmove(ResData ->Block + ResData ->Pointer, Ptr, size);
206     ResData ->Pointer += size;
207
208     if (ResData ->Pointer > iohandler->UsedSpace)
209         iohandler->UsedSpace = ResData ->Pointer;
210
211     
212     iohandler->UsedSpace += size;    
213
214     return TRUE;
215 }
216
217
218 static
219 cmsBool  MemoryClose(struct _cms_io_handler* iohandler)
220 {   
221     FILEMEM* ResData = (FILEMEM*) iohandler ->stream;
222
223     if (ResData ->FreeBlockOnClose) {
224
225         if (ResData ->Block) _cmsFree(iohandler ->ContextID, ResData ->Block);
226     }
227     
228     _cmsFree(iohandler ->ContextID, ResData);
229     _cmsFree(iohandler ->ContextID, iohandler);
230
231     return TRUE;
232 }
233
234 // Create a iohandler for memory block. AccessMode=='r' assumes the iohandler is going to read, and makes
235 // a copy of the memory block for letting user to free the memory after invoking open profile. In write 
236 // mode ("w"), Buffere points to the begin of memory block to be written.
237 cmsIOHANDLER* CMSEXPORT cmsOpenIOhandlerFromMem(cmsContext ContextID, void *Buffer, cmsUInt32Number size, const char* AccessMode)
238 {
239     cmsIOHANDLER* iohandler = NULL;
240     FILEMEM* fm = NULL;
241
242         _cmsAssert(AccessMode != NULL);
243
244     iohandler = (cmsIOHANDLER*) _cmsMallocZero(ContextID, sizeof(cmsIOHANDLER));
245     if (iohandler == NULL) return NULL;
246
247     switch (*AccessMode) {
248
249     case 'r':
250         fm = (FILEMEM*) _cmsMallocZero(ContextID, sizeof(FILEMEM));
251         if (fm == NULL) goto Error;
252
253         if (Buffer == NULL) {
254             cmsSignalError(ContextID, cmsERROR_READ, "Couldn't read profile from NULL pointer");
255             goto Error;
256         }
257
258         fm ->Block = (cmsUInt8Number*) _cmsMalloc(ContextID, size);
259         if (fm ->Block == NULL) {
260
261             _cmsFree(ContextID, fm);
262             _cmsFree(ContextID, iohandler);
263             cmsSignalError(ContextID, cmsERROR_READ, "Couldn't allocate %ld bytes for profile", size);
264             return NULL;
265         }
266
267
268         memmove(fm->Block, Buffer, size);
269         fm ->FreeBlockOnClose = TRUE;
270         fm ->Size    = size;
271         fm ->Pointer = 0;
272         iohandler -> ReportedSize = size;
273         break;
274
275     case 'w': 
276         fm = (FILEMEM*) _cmsMallocZero(ContextID, sizeof(FILEMEM));
277         if (fm == NULL) goto Error;
278
279         fm ->Block = (cmsUInt8Number*) Buffer;
280         fm ->FreeBlockOnClose = FALSE;
281         fm ->Size    = size;
282         fm ->Pointer = 0;     
283         iohandler -> ReportedSize = 0;
284         break;
285
286     default:
287         cmsSignalError(ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknown access mode '%c'", *AccessMode);
288         return NULL;
289     }
290
291     iohandler ->ContextID = ContextID;
292     iohandler ->stream  = (void*) fm;   
293     iohandler ->UsedSpace = 0;
294     iohandler ->PhysicalFile[0] = 0;
295
296     iohandler ->Read    = MemoryRead;
297     iohandler ->Seek    = MemorySeek;
298     iohandler ->Close   = MemoryClose;
299     iohandler ->Tell    = MemoryTell;
300     iohandler ->Write   = MemoryWrite;
301
302     return iohandler;
303
304 Error:
305     if (fm) _cmsFree(ContextID, fm);
306     if (iohandler) _cmsFree(ContextID, iohandler);
307     return NULL;
308 }
309
310 // File-based stream -------------------------------------------------------
311
312 // Read count elements of size bytes each. Return number of elements read
313 static
314 cmsUInt32Number FileRead(cmsIOHANDLER* iohandler, void *Buffer, cmsUInt32Number size, cmsUInt32Number count)
315 {
316     cmsUInt32Number nReaded = (cmsUInt32Number) fread(Buffer, size, count, (FILE*) iohandler->stream);
317
318     if (nReaded != count) {
319             cmsSignalError(iohandler ->ContextID, cmsERROR_FILE, "Read error. Got %d bytes, block should be of %d bytes", nReaded * size, count * size);
320             return 0;
321     }
322
323     return nReaded;
324 }
325
326 // Postion file pointer in the file
327 static
328 cmsBool  FileSeek(cmsIOHANDLER* iohandler, cmsUInt32Number offset)
329 {
330     if (fseek((FILE*) iohandler ->stream, (long) offset, SEEK_SET) != 0) {
331
332        cmsSignalError(iohandler ->ContextID, cmsERROR_FILE, "Seek error; probably corrupted file");
333        return FALSE;
334     }
335
336     return TRUE;
337 }
338
339 // Returns file pointer position
340 static
341 cmsUInt32Number FileTell(cmsIOHANDLER* iohandler)
342 {       
343     return ftell((FILE*)iohandler ->stream);
344 }
345
346 // Writes data to stream, also keeps used space for further reference. Returns TRUE on success, FALSE on error
347 static
348 cmsBool  FileWrite(cmsIOHANDLER* iohandler, cmsUInt32Number size, const void* Buffer)
349 {
350        if (size == 0) return TRUE;  // We allow to write 0 bytes, but nothing is written
351
352        iohandler->UsedSpace += size;
353        return (fwrite(Buffer, size, 1, (FILE*) iohandler->stream) == 1);
354 }
355
356 // Closes the file
357 static
358 cmsBool  FileClose(cmsIOHANDLER* iohandler)
359 {   
360     if (fclose((FILE*) iohandler ->stream) != 0) return FALSE;
361     _cmsFree(iohandler ->ContextID, iohandler);
362     return TRUE;
363 }
364
365 // Create a iohandler for disk based files. if FileName is NULL, then 'stream' member is also set
366 // to NULL and no real writting is performed. This only happens in writting access mode
367 cmsIOHANDLER* CMSEXPORT cmsOpenIOhandlerFromFile(cmsContext ContextID, const char* FileName, const char* AccessMode)
368 {
369     cmsIOHANDLER* iohandler = NULL;
370     FILE* fm = NULL;
371
372     iohandler = (cmsIOHANDLER*) _cmsMallocZero(ContextID, sizeof(cmsIOHANDLER));
373     if (iohandler == NULL) return NULL;
374
375     switch (*AccessMode) {
376
377     case 'r':
378         fm = fopen(FileName, "rb");
379         if (fm == NULL) {
380             _cmsFree(ContextID, iohandler);
381              cmsSignalError(ContextID, cmsERROR_FILE, "File '%s' not found", FileName);
382             return NULL;
383         }
384         iohandler -> ReportedSize = cmsfilelength(fm);
385         break;
386
387     case 'w':
388         fm = fopen(FileName, "wb");
389         if (fm == NULL) {
390             _cmsFree(ContextID, iohandler);
391              cmsSignalError(ContextID, cmsERROR_FILE, "Couldn't create '%s'", FileName);
392             return NULL;
393         }
394         iohandler -> ReportedSize = 0;
395         break;
396
397     default:
398         _cmsFree(ContextID, iohandler);
399          cmsSignalError(ContextID, cmsERROR_FILE, "Unknown access mode '%c'", *AccessMode);
400         return NULL;
401     }
402
403     iohandler ->ContextID = ContextID;
404     iohandler ->stream = (void*) fm;
405     iohandler ->UsedSpace = 0;
406
407     // Keep track of the original file
408     if (FileName != NULL)  {
409
410         strncpy(iohandler -> PhysicalFile, FileName, sizeof(iohandler -> PhysicalFile)-1);
411         iohandler -> PhysicalFile[sizeof(iohandler -> PhysicalFile)-1] = 0;
412     }
413
414     iohandler ->Read    = FileRead;
415     iohandler ->Seek    = FileSeek;
416     iohandler ->Close   = FileClose;
417     iohandler ->Tell    = FileTell;
418     iohandler ->Write   = FileWrite;
419
420     return iohandler;
421 }
422
423 // Create a iohandler for stream based files 
424 cmsIOHANDLER* CMSEXPORT cmsOpenIOhandlerFromStream(cmsContext ContextID, FILE* Stream)
425 {
426     cmsIOHANDLER* iohandler = NULL;
427     
428     iohandler = (cmsIOHANDLER*) _cmsMallocZero(ContextID, sizeof(cmsIOHANDLER));
429     if (iohandler == NULL) return NULL;
430
431     iohandler -> ContextID = ContextID;
432     iohandler -> stream = (void*) Stream;
433     iohandler -> UsedSpace = 0;
434     iohandler -> ReportedSize = cmsfilelength(Stream);
435     iohandler -> PhysicalFile[0] = 0;
436     
437     iohandler ->Read    = FileRead;
438     iohandler ->Seek    = FileSeek;
439     iohandler ->Close   = FileClose;
440     iohandler ->Tell    = FileTell;
441     iohandler ->Write   = FileWrite;
442
443     return iohandler;
444 }
445
446
447
448 // Close an open IO handler
449 cmsBool CMSEXPORT cmsCloseIOhandler(cmsIOHANDLER* io)
450 {
451     return io -> Close(io);
452 }
453
454 // -------------------------------------------------------------------------------------------------------
455
456 // Creates an empty structure holding all required parameters
457 cmsHPROFILE CMSEXPORT cmsCreateProfilePlaceholder(cmsContext ContextID)
458 {
459     time_t now = time(NULL);
460     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) _cmsMallocZero(ContextID, sizeof(_cmsICCPROFILE));
461     if (Icc == NULL) return NULL;
462
463     Icc ->ContextID = ContextID;
464
465     // Set it to empty
466     Icc -> TagCount   = 0;
467
468     // Set default version 
469     Icc ->Version =  0x02100000;
470
471     // Set creation date/time
472     memmove(&Icc ->Created, gmtime(&now), sizeof(Icc ->Created));
473
474     // Return the handle
475     return (cmsHPROFILE) Icc;
476 }
477
478 cmsContext CMSEXPORT cmsGetProfileContextID(cmsHPROFILE hProfile)
479 {
480      _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;  
481
482     if (Icc == NULL) return NULL;
483     return Icc -> ContextID;
484 }
485
486
487 // Return the number of tags
488 cmsInt32Number CMSEXPORT cmsGetTagCount(cmsHPROFILE hProfile)
489 {
490     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;  
491         if (Icc == NULL) return -1;
492
493     return  Icc->TagCount;
494 }
495
496 // Return the tag signature of a given tag number
497 cmsTagSignature CMSEXPORT cmsGetTagSignature(cmsHPROFILE hProfile, cmsUInt32Number n)
498 {
499     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;    
500
501     if (n > Icc->TagCount) return (cmsTagSignature) 0;  // Mark as not available     
502     if (n >= MAX_TABLE_TAG) return (cmsTagSignature) 0; // As double check
503
504     return Icc ->TagNames[n];
505 }
506
507
508 static
509 int SearchOneTag(_cmsICCPROFILE* Profile, cmsTagSignature sig)
510 {
511         cmsUInt32Number i;
512
513         for (i=0; i < Profile -> TagCount; i++) {
514
515                 if (sig == Profile -> TagNames[i])
516                         return i;
517         }
518
519         return -1;
520 }
521
522 // Search for a specific tag in tag dictionary. Returns position or -1 if tag not found.
523 // If followlinks is turned on, then the position of the linked tag is returned
524 int _cmsSearchTag(_cmsICCPROFILE* Icc, cmsTagSignature sig, cmsBool lFollowLinks)
525 {
526         int n;
527         cmsTagSignature LinkedSig;
528
529         do {
530
531                 // Search for given tag in ICC profile directory
532                 n = SearchOneTag(Icc, sig);
533                 if (n < 0) 
534                         return -1;        // Not found
535
536                 if (!lFollowLinks) 
537                         return n;         // Found, don't follow links
538
539                 // Is this a linked tag?
540                 LinkedSig = Icc ->TagLinked[n];
541
542                 // Yes, follow link
543                 if (LinkedSig != (cmsTagSignature) 0) {
544                         sig = LinkedSig;
545                 }
546
547         } while (LinkedSig != (cmsTagSignature) 0);
548
549         return n;
550 }
551
552
553 // Create a new tag entry
554
555 static
556 cmsBool _cmsNewTag(_cmsICCPROFILE* Icc, cmsTagSignature sig, int* NewPos)
557 {
558         int i;
559
560         // Search for the tag
561     i = _cmsSearchTag(Icc, sig, FALSE);
562
563     // Now let's do it easy. If the tag has been already written, that's an error
564     if (i >= 0) {
565         cmsSignalError(Icc ->ContextID, cmsERROR_ALREADY_DEFINED, "Tag '%x' already exists", sig);
566         return FALSE;
567     }
568     else  {
569
570         // New one
571         
572         if (Icc -> TagCount >= MAX_TABLE_TAG) {
573             cmsSignalError(Icc ->ContextID, cmsERROR_RANGE, "Too many tags (%d)", MAX_TABLE_TAG);
574             return FALSE;
575         }
576
577                 *NewPos = Icc ->TagCount;
578         Icc -> TagCount++;
579     }
580
581         return TRUE;
582 }
583
584
585 // Check existance
586 cmsBool CMSEXPORT cmsIsTag(cmsHPROFILE hProfile, cmsTagSignature sig)
587 {
588        _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) (void*) hProfile;
589        return _cmsSearchTag(Icc, sig, FALSE) >= 0;
590 }
591
592
593 // Read profile header and validate it
594 cmsBool _cmsReadHeader(_cmsICCPROFILE* Icc)
595 {
596     cmsTagEntry Tag;
597     cmsICCHeader Header;
598     cmsUInt32Number i, j;
599     cmsUInt32Number HeaderSize;
600     cmsIOHANDLER* io = Icc ->IOhandler;
601     cmsUInt32Number TagCount;
602
603
604     // Read the header
605     if (io -> Read(io, &Header, sizeof(cmsICCHeader), 1) != 1) {        
606         return FALSE; 
607     }
608
609     // Validate file as an ICC profile
610     if (_cmsAdjustEndianess32(Header.magic) != cmsMagicNumber) {
611         cmsSignalError(Icc ->ContextID, cmsERROR_BAD_SIGNATURE, "not an ICC profile, invalid signature");
612         return FALSE; 
613     }
614
615     // Adjust endianess of the used parameters
616     Icc -> DeviceClass     = (cmsProfileClassSignature) _cmsAdjustEndianess32(Header.deviceClass);
617     Icc -> ColorSpace      = (cmsColorSpaceSignature)   _cmsAdjustEndianess32(Header.colorSpace);
618     Icc -> PCS             = (cmsColorSpaceSignature)   _cmsAdjustEndianess32(Header.pcs);
619     Icc -> RenderingIntent = _cmsAdjustEndianess32(Header.renderingIntent);
620     Icc -> flags           = _cmsAdjustEndianess32(Header.flags);
621     Icc -> manufacturer    = _cmsAdjustEndianess32(Header.manufacturer);
622     Icc -> model           = _cmsAdjustEndianess32(Header.model);
623     _cmsAdjustEndianess64(&Icc -> attributes, Header.attributes);
624     Icc -> Version         = _cmsAdjustEndianess32(Header.version);
625
626     // Get size as reported in header
627     HeaderSize = _cmsAdjustEndianess32(Header.size);
628
629     // Make sure HeaderSize is lower than profile size
630     if (HeaderSize >= Icc ->IOhandler ->ReportedSize)
631             HeaderSize = Icc ->IOhandler ->ReportedSize;
632
633    
634     // Get creation date/time
635     _cmsDecodeDateTimeNumber(&Header.date, &Icc ->Created);
636
637     // The profile ID are 32 raw bytes
638     memmove(Icc ->ProfileID.ID32, Header.profileID.ID32, 16);
639
640
641     // Read tag directory
642     if (!_cmsReadUInt32Number(io, &TagCount)) return FALSE;                          
643     if (TagCount > MAX_TABLE_TAG) {
644
645         cmsSignalError(Icc ->ContextID, cmsERROR_RANGE, "Too many tags (%d)", TagCount);
646         return FALSE;
647     }
648
649
650     // Read tag directory
651     Icc -> TagCount = 0;
652     for (i=0; i < TagCount; i++) {
653
654         if (!_cmsReadUInt32Number(io, (cmsUInt32Number *) &Tag.sig)) return FALSE;
655         if (!_cmsReadUInt32Number(io, &Tag.offset)) return FALSE;
656         if (!_cmsReadUInt32Number(io, &Tag.size)) return FALSE;
657
658         // Perform some sanity check. Offset + size should fall inside file.
659         if (Tag.offset + Tag.size > HeaderSize ||
660             Tag.offset + Tag.size < Tag.offset)       
661                   continue;
662
663         Icc -> TagNames[Icc ->TagCount]   = Tag.sig;
664         Icc -> TagOffsets[Icc ->TagCount] = Tag.offset;
665         Icc -> TagSizes[Icc ->TagCount]   = Tag.size;
666
667        // Search for links
668         for (j=0; j < Icc ->TagCount; j++) {
669
670             if ((Icc ->TagOffsets[j] == Tag.offset) &&
671                 (Icc ->TagSizes[j]   == Tag.size)) {
672
673                 Icc ->TagLinked[Icc ->TagCount] = Icc ->TagNames[j];   
674             }
675
676         }
677
678         Icc ->TagCount++;
679     }
680   
681     return TRUE;
682 }
683
684 // Saves profile header
685 cmsBool _cmsWriteHeader(_cmsICCPROFILE* Icc, cmsUInt32Number UsedSpace)
686 {
687     cmsICCHeader Header;    
688     cmsUInt32Number i;
689     cmsTagEntry Tag;       
690     cmsInt32Number Count = 0;
691
692     Header.size        = _cmsAdjustEndianess32(UsedSpace);
693     Header.cmmId       = _cmsAdjustEndianess32(lcmsSignature);
694     Header.version     = _cmsAdjustEndianess32(Icc ->Version);
695
696     Header.deviceClass = (cmsProfileClassSignature) _cmsAdjustEndianess32(Icc -> DeviceClass);
697     Header.colorSpace  = (cmsColorSpaceSignature) _cmsAdjustEndianess32(Icc -> ColorSpace);
698     Header.pcs         = (cmsColorSpaceSignature) _cmsAdjustEndianess32(Icc -> PCS);
699
700     //   NOTE: in v4 Timestamp must be in UTC rather than in local time
701     _cmsEncodeDateTimeNumber(&Header.date, &Icc ->Created);
702
703     Header.magic       = _cmsAdjustEndianess32(cmsMagicNumber);
704
705 #ifdef CMS_IS_WINDOWS_
706     Header.platform    = (cmsPlatformSignature) _cmsAdjustEndianess32(cmsSigMicrosoft);  
707 #else
708     Header.platform    = (cmsPlatformSignature) _cmsAdjustEndianess32(cmsSigMacintosh);  
709 #endif
710
711     Header.flags        = _cmsAdjustEndianess32(Icc -> flags);
712     Header.manufacturer = _cmsAdjustEndianess32(Icc -> manufacturer);
713     Header.model        = _cmsAdjustEndianess32(Icc -> model);
714
715     _cmsAdjustEndianess64(&Header.attributes, Icc -> attributes);              
716     
717     // Rendering intent in the header (for embedded profiles)
718     Header.renderingIntent = _cmsAdjustEndianess32(Icc -> RenderingIntent);
719
720     // Illuminant is always D50
721     Header.illuminant.X = _cmsAdjustEndianess32(_cmsDoubleTo15Fixed16(cmsD50_XYZ()->X));
722     Header.illuminant.Y = _cmsAdjustEndianess32(_cmsDoubleTo15Fixed16(cmsD50_XYZ()->Y));
723     Header.illuminant.Z = _cmsAdjustEndianess32(_cmsDoubleTo15Fixed16(cmsD50_XYZ()->Z));
724
725     // Created by LittleCMS (that's me!)
726     Header.creator      = _cmsAdjustEndianess32(lcmsSignature);
727
728     memset(&Header.reserved, 0, sizeof(Header.reserved));
729
730     // Set profile ID. Endianess is always big endian   
731     memmove(&Header.profileID, &Icc ->ProfileID, 16);
732
733     // Dump the header
734     if (!Icc -> IOhandler->Write(Icc->IOhandler, sizeof(cmsICCHeader), &Header)) return FALSE;
735
736     // Saves Tag directory
737
738     // Get true count
739     for (i=0;  i < Icc -> TagCount; i++) {
740         if (Icc ->TagNames[i] != 0)
741             Count++;
742     }
743
744     // Store number of tags
745     if (!_cmsWriteUInt32Number(Icc ->IOhandler, Count)) return FALSE;   
746
747     for (i=0; i < Icc -> TagCount; i++) {
748
749         if (Icc ->TagNames[i] == 0) continue;   // It is just a placeholder
750
751         Tag.sig    = (cmsTagSignature) _cmsAdjustEndianess32((cmsInt32Number) Icc -> TagNames[i]);
752         Tag.offset = _cmsAdjustEndianess32((cmsInt32Number) Icc -> TagOffsets[i]);
753         Tag.size   = _cmsAdjustEndianess32((cmsInt32Number) Icc -> TagSizes[i]);
754
755         if (!Icc ->IOhandler -> Write(Icc-> IOhandler, sizeof(cmsTagEntry), &Tag)) return FALSE;
756     }
757
758     return TRUE;
759 }
760
761 // ----------------------------------------------------------------------- Set/Get several struct members
762
763
764 cmsUInt32Number CMSEXPORT cmsGetHeaderRenderingIntent(cmsHPROFILE hProfile)
765 {
766     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
767     return Icc -> RenderingIntent;
768 }
769
770 void CMSEXPORT cmsSetHeaderRenderingIntent(cmsHPROFILE hProfile, cmsUInt32Number RenderingIntent)
771 {
772     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
773     Icc -> RenderingIntent = RenderingIntent;
774 }
775
776 cmsUInt32Number CMSEXPORT cmsGetHeaderFlags(cmsHPROFILE hProfile)
777 {
778     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
779     return (cmsUInt32Number) Icc -> flags;
780 }
781
782 void CMSEXPORT cmsSetHeaderFlags(cmsHPROFILE hProfile, cmsUInt32Number Flags)
783 {
784     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
785     Icc -> flags = (cmsUInt32Number) Flags;
786 }
787
788 cmsUInt32Number CMSEXPORT cmsGetHeaderManufacturer(cmsHPROFILE hProfile)
789 {
790     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
791     return (cmsUInt32Number) Icc ->manufacturer;
792 }
793
794 void CMSEXPORT cmsSetHeaderManufacturer(cmsHPROFILE hProfile, cmsUInt32Number manufacturer)
795 {
796     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
797     Icc -> manufacturer = (cmsUInt32Number) manufacturer;
798 }
799
800 cmsUInt32Number CMSEXPORT cmsGetHeaderModel(cmsHPROFILE hProfile)
801 {
802     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
803     return (cmsUInt32Number) Icc ->model;
804 }
805
806 void CMSEXPORT cmsSetHeaderModel(cmsHPROFILE hProfile, cmsUInt32Number model)
807 {
808     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
809     Icc -> model = (cmsUInt32Number) model;
810 }
811
812
813 void CMSEXPORT cmsGetHeaderAttributes(cmsHPROFILE hProfile, cmsUInt64Number* Flags)
814 {
815     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
816     memmove(Flags, &Icc -> attributes, sizeof(cmsUInt64Number));
817 }
818
819 void CMSEXPORT cmsSetHeaderAttributes(cmsHPROFILE hProfile, cmsUInt64Number Flags)
820 {
821     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
822     memmove(&Icc -> attributes, &Flags, sizeof(cmsUInt64Number));
823 }
824
825 void CMSEXPORT cmsGetHeaderProfileID(cmsHPROFILE hProfile, cmsUInt8Number* ProfileID)
826 {
827     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;    
828     memmove(ProfileID, Icc ->ProfileID.ID8, 16);    
829 }
830
831 void CMSEXPORT cmsSetHeaderProfileID(cmsHPROFILE hProfile, cmsUInt8Number* ProfileID)
832 {
833     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
834     memmove(&Icc -> ProfileID, ProfileID, 16);
835 }
836
837 cmsBool  CMSEXPORT cmsGetHeaderCreationDateTime(cmsHPROFILE hProfile, struct tm *Dest)
838 {
839     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;    
840     memmove(Dest, &Icc ->Created, sizeof(struct tm));    
841     return TRUE;
842 }
843
844 cmsColorSpaceSignature CMSEXPORT cmsGetPCS(cmsHPROFILE hProfile)
845 {
846     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
847     return Icc -> PCS;
848 }
849
850 void CMSEXPORT cmsSetPCS(cmsHPROFILE hProfile, cmsColorSpaceSignature pcs)
851 {
852     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
853     Icc -> PCS = pcs;
854 }
855
856 cmsColorSpaceSignature CMSEXPORT cmsGetColorSpace(cmsHPROFILE hProfile)
857 {
858     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
859     return Icc -> ColorSpace;
860 }
861
862 void CMSEXPORT cmsSetColorSpace(cmsHPROFILE hProfile, cmsColorSpaceSignature sig)
863 {
864     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
865     Icc -> ColorSpace = sig;
866 }
867
868 cmsProfileClassSignature CMSEXPORT cmsGetDeviceClass(cmsHPROFILE hProfile)
869 {
870     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
871     return Icc -> DeviceClass;
872 }
873
874 void CMSEXPORT cmsSetDeviceClass(cmsHPROFILE hProfile, cmsProfileClassSignature sig)
875 {
876     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
877     Icc -> DeviceClass = sig;
878 }
879
880 cmsUInt32Number CMSEXPORT cmsGetEncodedICCversion(cmsHPROFILE hProfile)
881 {
882     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
883     return Icc -> Version;
884 }
885
886 void CMSEXPORT cmsSetEncodedICCversion(cmsHPROFILE hProfile, cmsUInt32Number Version)
887 {
888     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
889     Icc -> Version = Version;
890 }
891
892 // Get an hexadecimal number with same digits as v
893 static
894 cmsUInt32Number BaseToBase(cmsUInt32Number in, int BaseIn, int BaseOut)
895 {
896     char Buff[100];
897     int i, len;
898     cmsUInt32Number out;
899     
900     for (len=0; in > 0 && len < 100; len++) {
901     
902         Buff[len] = (char) (in % BaseIn);
903         in /= BaseIn;
904     }
905
906     for (i=len-1, out=0; i >= 0; --i) {
907         out = out * BaseOut + Buff[i];
908     }
909
910     return out;
911 }
912
913 void  CMSEXPORT cmsSetProfileVersion(cmsHPROFILE hProfile, cmsFloat64Number Version)
914 {
915     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
916
917     // 4.2 -> 0x4200000
918
919     Icc -> Version = BaseToBase((cmsUInt32Number) floor(Version * 100.0), 10, 16) << 16;
920 }
921
922 cmsFloat64Number CMSEXPORT cmsGetProfileVersion(cmsHPROFILE hProfile)
923 {
924     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
925     cmsUInt32Number n = Icc -> Version >> 16;
926
927     return BaseToBase(n, 16, 10) / 100.0;
928 }
929 // --------------------------------------------------------------------------------------------------------------
930
931
932 // Create profile from IOhandler
933 cmsHPROFILE CMSEXPORT cmsOpenProfileFromIOhandlerTHR(cmsContext ContextID, cmsIOHANDLER* io)
934 {
935     _cmsICCPROFILE* NewIcc;
936     cmsHPROFILE hEmpty = cmsCreateProfilePlaceholder(ContextID);
937
938     if (hEmpty == NULL) return NULL;
939
940     NewIcc = (_cmsICCPROFILE*) hEmpty;
941
942     NewIcc ->IOhandler = io;
943     if (!_cmsReadHeader(NewIcc)) goto Error;    
944     return hEmpty;
945
946 Error:
947     cmsCloseProfile(hEmpty);
948     return NULL;
949 }
950
951 // Create profile from disk file
952 cmsHPROFILE CMSEXPORT cmsOpenProfileFromFileTHR(cmsContext ContextID, const char *lpFileName, const char *sAccess)
953 {
954     _cmsICCPROFILE* NewIcc;
955     cmsHPROFILE hEmpty = cmsCreateProfilePlaceholder(ContextID);
956
957     if (hEmpty == NULL) return NULL;
958
959     NewIcc = (_cmsICCPROFILE*) hEmpty;
960
961     NewIcc ->IOhandler = cmsOpenIOhandlerFromFile(ContextID, lpFileName, sAccess);
962     if (NewIcc ->IOhandler == NULL) goto Error;
963
964     if (*sAccess == 'W' || *sAccess == 'w') {
965
966         NewIcc -> IsWrite = TRUE;
967         
968         return hEmpty;
969     }
970
971     if (!_cmsReadHeader(NewIcc)) goto Error;
972     return hEmpty;
973
974 Error:
975     cmsCloseProfile(hEmpty);
976     return NULL;
977 }
978
979
980 cmsHPROFILE CMSEXPORT cmsOpenProfileFromFile(const char *ICCProfile, const char *sAccess)
981 {
982     return cmsOpenProfileFromFileTHR(NULL, ICCProfile, sAccess);
983 }
984
985
986 cmsHPROFILE  CMSEXPORT cmsOpenProfileFromStreamTHR(cmsContext ContextID, FILE* ICCProfile, const char *sAccess)
987 {
988     _cmsICCPROFILE* NewIcc;
989     cmsHPROFILE hEmpty = cmsCreateProfilePlaceholder(ContextID);
990
991     if (hEmpty == NULL) return NULL;
992
993     NewIcc = (_cmsICCPROFILE*) hEmpty;
994
995     NewIcc ->IOhandler = cmsOpenIOhandlerFromStream(ContextID, ICCProfile);
996     if (NewIcc ->IOhandler == NULL) goto Error;
997
998     if (*sAccess == 'w') {
999
1000         NewIcc -> IsWrite = TRUE;       
1001         return hEmpty;
1002     }
1003
1004     if (!_cmsReadHeader(NewIcc)) goto Error;    
1005     return hEmpty;
1006
1007 Error:
1008     cmsCloseProfile(hEmpty);
1009     return NULL;
1010
1011 }
1012
1013 cmsHPROFILE  CMSEXPORT cmsOpenProfileFromStream(FILE* ICCProfile, const char *sAccess)
1014 {
1015     return cmsOpenProfileFromStreamTHR(NULL, ICCProfile, sAccess);
1016 }
1017
1018
1019 // Open from memory block
1020 cmsHPROFILE CMSEXPORT cmsOpenProfileFromMemTHR(cmsContext ContextID, const void* MemPtr, cmsUInt32Number dwSize)
1021 {
1022     _cmsICCPROFILE* NewIcc;
1023     cmsHPROFILE hEmpty;
1024
1025     hEmpty = cmsCreateProfilePlaceholder(ContextID);
1026     if (hEmpty == NULL) return NULL;
1027
1028     NewIcc = (_cmsICCPROFILE*) hEmpty;
1029
1030         // Ok, in this case const void* is casted to void* just because open IO handler 
1031         // shares read and writting modes. Don't abuse this feature!
1032     NewIcc ->IOhandler = cmsOpenIOhandlerFromMem(ContextID, (void*) MemPtr, dwSize, "r");
1033     if (NewIcc ->IOhandler == NULL) goto Error;
1034
1035     if (!_cmsReadHeader(NewIcc)) goto Error;
1036
1037     return hEmpty;
1038
1039 Error:
1040     cmsCloseProfile(hEmpty);
1041     return NULL;
1042 }
1043
1044 cmsHPROFILE CMSEXPORT cmsOpenProfileFromMem(const void* MemPtr, cmsUInt32Number dwSize)
1045 {
1046     return cmsOpenProfileFromMemTHR(NULL, MemPtr, dwSize);
1047 }
1048
1049
1050
1051 // Dump tag contents. If the profile is being modified, untouched tags are copied from FileOrig
1052 static
1053 cmsBool SaveTags(_cmsICCPROFILE* Icc, _cmsICCPROFILE* FileOrig)
1054 {
1055     cmsUInt8Number* Data;
1056     cmsUInt32Number i;
1057     cmsUInt32Number Begin;
1058     cmsIOHANDLER* io = Icc ->IOhandler;
1059     cmsTagDescriptor* TagDescriptor;
1060     cmsTagTypeSignature TypeBase;
1061     cmsTagTypeHandler* TypeHandler;
1062
1063
1064     for (i=0; i < Icc -> TagCount; i++) {
1065
1066        
1067         if (Icc ->TagNames[i] == 0) continue;
1068
1069         // Linked tags are not written
1070         if (Icc ->TagLinked[i] != (cmsTagSignature) 0) continue;
1071
1072         Icc -> TagOffsets[i] = Begin = io ->UsedSpace;
1073
1074         Data = (cmsUInt8Number*)  Icc -> TagPtrs[i];
1075
1076         if (!Data) {
1077
1078             // Reach here if we are copying a tag from a disk-based ICC profile which has not been modified by user. 
1079             // In this case a blind copy of the block data is performed
1080             if (FileOrig != NULL && Icc -> TagOffsets[i]) {
1081
1082                 cmsUInt32Number TagSize   = FileOrig -> TagSizes[i];
1083                 cmsUInt32Number TagOffset = FileOrig -> TagOffsets[i];
1084                 void* Mem;
1085
1086                 if (!FileOrig ->IOhandler->Seek(FileOrig ->IOhandler, TagOffset)) return FALSE;
1087
1088                 Mem = _cmsMalloc(Icc ->ContextID, TagSize);                  
1089                 if (Mem == NULL) return FALSE;
1090
1091                 if (FileOrig ->IOhandler->Read(FileOrig->IOhandler, Mem, TagSize, 1) != 1) return FALSE;
1092                 if (!io ->Write(io, TagSize, Mem)) return FALSE;
1093                 _cmsFree(Icc ->ContextID, Mem);
1094
1095                 Icc -> TagSizes[i] = (io ->UsedSpace - Begin);
1096                 
1097
1098                 // Align to 32 bit boundary.
1099                 if (! _cmsWriteAlignment(io)) 
1100                     return FALSE;                   
1101             }
1102
1103             continue;
1104         }
1105
1106
1107         // Should this tag be saved as RAW? If so, tagsizes should be specified in advance (no further cooking is done)
1108         if (Icc ->TagSaveAsRaw[i]) {
1109
1110             if (io -> Write(io, Icc ->TagSizes[i], Data) != 1) return FALSE;
1111         }
1112         else {
1113
1114             // Search for support on this tag
1115             TagDescriptor = _cmsGetTagDescriptor(Icc -> TagNames[i]);
1116             if (TagDescriptor == NULL) continue;                        // Unsupported, ignore it
1117
1118             TypeHandler = Icc ->TagTypeHandlers[i];
1119
1120             if (TypeHandler == NULL) {
1121                 cmsSignalError(Icc ->ContextID, cmsERROR_INTERNAL, "(Internal) no handler for tag %x", Icc -> TagNames[i]);
1122                 continue;
1123             }
1124
1125             TypeBase = TypeHandler ->Signature;
1126             if (!_cmsWriteTypeBase(io, TypeBase)) 
1127                 return FALSE;
1128
1129             TypeHandler ->ContextID  = Icc ->ContextID;
1130             TypeHandler ->ICCVersion = Icc ->Version;
1131             if (!TypeHandler ->WritePtr(TypeHandler, io, Data, TagDescriptor ->ElemCount)) {
1132
1133                                 char String[5];
1134
1135                                  _cmsTagSignature2String(String, (cmsTagSignature) TypeBase);
1136                 cmsSignalError(Icc ->ContextID, cmsERROR_WRITE, "Couldn't write type '%s'", String);
1137                 return FALSE;   
1138             }
1139         }
1140
1141
1142         Icc -> TagSizes[i] = (io ->UsedSpace - Begin);      
1143
1144         // Align to 32 bit boundary.
1145         if (! _cmsWriteAlignment(io)) 
1146             return FALSE;                   
1147     }
1148
1149
1150     return TRUE;
1151 }
1152
1153
1154 // Fill the offset and size fields for all linked tags
1155 static
1156 cmsBool SetLinks( _cmsICCPROFILE* Icc)
1157 {
1158     cmsUInt32Number i;
1159
1160     for (i=0; i < Icc -> TagCount; i++) {
1161
1162         cmsTagSignature lnk = Icc ->TagLinked[i];
1163         if (lnk != (cmsTagSignature) 0) {
1164
1165             int j = _cmsSearchTag(Icc, lnk, FALSE);
1166             if (j >= 0) {
1167
1168                 Icc ->TagOffsets[i] = Icc ->TagOffsets[j];
1169                 Icc ->TagSizes[i]   = Icc ->TagSizes[j];
1170             }
1171
1172         }
1173     }
1174
1175     return TRUE;
1176 }
1177
1178 // Low-level save to IOHANDLER. It returns the number of bytes used to
1179 // store the profile, or zero on error. io may be NULL and in this case
1180 // no data is written--only sizes are calculated
1181 cmsUInt32Number CMSEXPORT cmsSaveProfileToIOhandler(cmsHPROFILE hProfile, cmsIOHANDLER* io)
1182 {
1183     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1184     _cmsICCPROFILE Keep;              
1185     cmsIOHANDLER* PrevIO;
1186     cmsUInt32Number UsedSpace;
1187     cmsContext ContextID;
1188
1189     memmove(&Keep, Icc, sizeof(_cmsICCPROFILE));
1190
1191     ContextID = cmsGetProfileContextID(hProfile);
1192     PrevIO = Icc ->IOhandler = cmsOpenIOhandlerFromNULL(ContextID);
1193     if (PrevIO == NULL) return 0;
1194
1195     // Pass #1 does compute offsets
1196
1197     if (!_cmsWriteHeader(Icc, 0)) return 0;
1198     if (!SaveTags(Icc, &Keep)) return 0;
1199
1200     UsedSpace = PrevIO ->UsedSpace;
1201
1202     // Pass #2 does save to iohandler
1203
1204     if (io != NULL) {
1205         Icc ->IOhandler = io;     
1206         if (!SetLinks(Icc)) goto CleanUp;
1207         if (!_cmsWriteHeader(Icc, UsedSpace)) goto CleanUp;
1208         if (!SaveTags(Icc, &Keep)) goto CleanUp;
1209     }
1210
1211     memmove(Icc, &Keep, sizeof(_cmsICCPROFILE));
1212     if (!cmsCloseIOhandler(PrevIO)) return 0;
1213
1214     return UsedSpace;
1215
1216
1217 CleanUp:     
1218     cmsCloseIOhandler(PrevIO);      
1219     memmove(Icc, &Keep, sizeof(_cmsICCPROFILE));
1220     return 0;
1221 }
1222
1223
1224 // Low-level save to disk. 
1225 cmsBool  CMSEXPORT cmsSaveProfileToFile(cmsHPROFILE hProfile, const char* FileName)
1226 {   
1227     cmsContext ContextID = cmsGetProfileContextID(hProfile);
1228     cmsIOHANDLER* io = cmsOpenIOhandlerFromFile(ContextID, FileName, "w");
1229     cmsBool rc;
1230     
1231     if (io == NULL) return FALSE;
1232
1233     rc = (cmsSaveProfileToIOhandler(hProfile, io) != 0);
1234     rc &= cmsCloseIOhandler(io);
1235
1236     if (rc == FALSE) {          // remove() is C99 per 7.19.4.1
1237             remove(FileName);   // We have to IGNORE return value in this case
1238     }
1239     return rc;
1240 }
1241
1242 // Same as anterior, but for streams
1243 cmsBool CMSEXPORT cmsSaveProfileToStream(cmsHPROFILE hProfile, FILE* Stream)
1244 {
1245     cmsBool rc;
1246     cmsContext ContextID = cmsGetProfileContextID(hProfile);
1247     cmsIOHANDLER* io = cmsOpenIOhandlerFromStream(ContextID, Stream);
1248     
1249     if (io == NULL) return FALSE;
1250
1251     rc = (cmsSaveProfileToIOhandler(hProfile, io) != 0);
1252     rc &= cmsCloseIOhandler(io);
1253
1254     return rc;
1255 }
1256
1257
1258 // Same as anterior, but for memory blocks. In this case, a NULL as MemPtr means calculate needed space only
1259 cmsBool CMSEXPORT cmsSaveProfileToMem(cmsHPROFILE hProfile, void *MemPtr, cmsUInt32Number* BytesNeeded)
1260 {
1261     cmsBool rc;
1262     cmsIOHANDLER* io;
1263     cmsContext ContextID = cmsGetProfileContextID(hProfile);
1264     
1265     // Should we just calculate the needed space?
1266     if (MemPtr == NULL) {   
1267
1268            *BytesNeeded =  cmsSaveProfileToIOhandler(hProfile, NULL);
1269             return TRUE;
1270     }
1271
1272     // That is a real write operation
1273     io =  cmsOpenIOhandlerFromMem(ContextID, MemPtr, *BytesNeeded, "w");
1274     if (io == NULL) return FALSE;
1275
1276     rc = (cmsSaveProfileToIOhandler(hProfile, io) != 0);
1277     rc &= cmsCloseIOhandler(io);
1278
1279     return rc;
1280 }
1281
1282
1283
1284 // Closes a profile freeing any involved resources
1285 cmsBool  CMSEXPORT cmsCloseProfile(cmsHPROFILE hProfile)
1286 {
1287     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1288     cmsBool  rc = TRUE;
1289     cmsUInt32Number i;         
1290
1291     if (!Icc) return FALSE;
1292
1293     // Was open in write mode?   
1294     if (Icc ->IsWrite) {
1295
1296         Icc ->IsWrite = FALSE;      // Assure no further writting
1297         rc &= cmsSaveProfileToFile(hProfile, Icc ->IOhandler->PhysicalFile);        
1298     }
1299
1300     for (i=0; i < Icc -> TagCount; i++) {
1301
1302         if (Icc -> TagPtrs[i]) {
1303
1304             cmsTagTypeHandler* TypeHandler = Icc ->TagTypeHandlers[i];
1305
1306             if (TypeHandler != NULL) {
1307
1308                 TypeHandler ->ContextID = Icc ->ContextID;              // As an additional parameters
1309                 TypeHandler ->ICCVersion = Icc ->Version;
1310                 TypeHandler ->FreePtr(TypeHandler, Icc -> TagPtrs[i]);
1311             }
1312             else
1313                 _cmsFree(Icc ->ContextID, Icc ->TagPtrs[i]);
1314         }
1315     }
1316
1317     if (Icc ->IOhandler != NULL) {      
1318         rc &= cmsCloseIOhandler(Icc->IOhandler);   
1319     }       
1320
1321     _cmsFree(Icc ->ContextID, Icc);   // Free placeholder memory
1322
1323     return rc;
1324 }
1325
1326
1327 // -------------------------------------------------------------------------------------------------------------------
1328
1329
1330 // Returns TRUE if a given tag is supported by a plug-in
1331 static
1332 cmsBool IsTypeSupported(cmsTagDescriptor* TagDescriptor, cmsTagTypeSignature Type)
1333 {
1334     cmsUInt32Number i, nMaxTypes;
1335
1336     nMaxTypes = TagDescriptor->nSupportedTypes;
1337     if (nMaxTypes >= MAX_TYPES_IN_LCMS_PLUGIN)
1338         nMaxTypes = MAX_TYPES_IN_LCMS_PLUGIN;
1339     
1340     for (i=0; i < nMaxTypes; i++) {
1341         if (Type == TagDescriptor ->SupportedTypes[i]) return TRUE; 
1342     }
1343
1344     return FALSE;
1345 }
1346
1347
1348 // That's the main read function
1349 void* CMSEXPORT cmsReadTag(cmsHPROFILE hProfile, cmsTagSignature sig)
1350 {
1351     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile; 
1352     cmsIOHANDLER* io = Icc ->IOhandler;
1353     cmsTagTypeHandler* TypeHandler;
1354     cmsTagDescriptor*  TagDescriptor;
1355     cmsTagTypeSignature BaseType;
1356     cmsUInt32Number Offset, TagSize;
1357     cmsUInt32Number ElemCount;
1358     int n;
1359
1360         n = _cmsSearchTag(Icc, sig, TRUE);
1361         if (n < 0) return NULL;                 // Not found, return NULL
1362
1363
1364         // If the element is already in memory, return the pointer
1365         if (Icc -> TagPtrs[n]) {
1366
1367                 if (Icc ->TagSaveAsRaw[n]) return NULL;  // We don't support read raw tags as cooked
1368                 return Icc -> TagPtrs[n];
1369         }
1370
1371         // We need to read it. Get the offset and size to the file
1372     Offset    = Icc -> TagOffsets[n];
1373     TagSize   = Icc -> TagSizes[n]; 
1374     
1375     // Seek to its location
1376     if (!io -> Seek(io, Offset))
1377             return NULL;
1378
1379     // Search for support on this tag
1380     TagDescriptor = _cmsGetTagDescriptor(sig);
1381     if (TagDescriptor == NULL) return NULL;     // Unsupported. 
1382
1383     // if supported, get type and check if in list
1384     BaseType = _cmsReadTypeBase(io);
1385     if (BaseType == 0) return NULL;
1386
1387     if (!IsTypeSupported(TagDescriptor, BaseType)) return NULL;
1388
1389     TagSize  -= 8;                      // Alredy read by the type base logic
1390
1391     // Get type handler
1392     TypeHandler = _cmsGetTagTypeHandler(BaseType);
1393     if (TypeHandler == NULL) return NULL;
1394
1395
1396     // Read the tag
1397     Icc -> TagTypeHandlers[n] = TypeHandler;
1398
1399     TypeHandler ->ContextID = Icc ->ContextID;
1400     TypeHandler ->ICCVersion = Icc ->Version;
1401     Icc -> TagPtrs[n] = TypeHandler ->ReadPtr(TypeHandler, io, &ElemCount, TagSize);
1402
1403     // The tag type is supported, but something wrong happend and we cannot read the tag.
1404     // let know the user about this (although it is just a warning)
1405     if (Icc -> TagPtrs[n] == NULL) {
1406
1407         char String[5];
1408
1409         _cmsTagSignature2String(String, sig);
1410         cmsSignalError(Icc ->ContextID, cmsERROR_CORRUPTION_DETECTED, "Corrupted tag '%s'", String);
1411         return NULL;
1412     }
1413
1414     // This is a weird error that may be a symptom of something more serious, the number of
1415     // stored item is actually less than the number of required elements. 
1416     if (ElemCount < TagDescriptor ->ElemCount) {
1417
1418         char String[5];
1419
1420         _cmsTagSignature2String(String, sig);
1421         cmsSignalError(Icc ->ContextID, cmsERROR_CORRUPTION_DETECTED, "'%s' Inconsistent number of items: expected %d, got %d", 
1422                                                              String, TagDescriptor ->ElemCount, ElemCount);
1423     }
1424
1425     
1426     // Return the data
1427     return Icc -> TagPtrs[n];
1428 }
1429
1430
1431 // Get true type of data
1432 cmsTagTypeSignature _cmsGetTagTrueType(cmsHPROFILE hProfile, cmsTagSignature sig)
1433 {
1434         _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile; 
1435         cmsTagTypeHandler* TypeHandler; 
1436         int n;
1437
1438         // Search for given tag in ICC profile directory
1439         n = _cmsSearchTag(Icc, sig, TRUE);
1440         if (n < 0) return (cmsTagTypeSignature) 0;                // Not found, return NULL
1441
1442         // Get the handler. The true type is there
1443         TypeHandler =  Icc -> TagTypeHandlers[n];
1444         return TypeHandler ->Signature;
1445 }
1446
1447
1448 // Write a single tag. This just keeps track of the tak into a list of "to be written". If the tag is already
1449 // in that list, the previous version is deleted.
1450 cmsBool CMSEXPORT cmsWriteTag(cmsHPROFILE hProfile, cmsTagSignature sig, const void* data)
1451 {
1452     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;  
1453     cmsTagTypeHandler* TypeHandler = NULL;
1454     cmsTagDescriptor* TagDescriptor = NULL;
1455     cmsTagTypeSignature Type;
1456     int i;
1457     cmsFloat64Number Version;
1458     char TypeString[5], SigString[5];
1459
1460
1461     if (data == NULL) {
1462
1463          i = _cmsSearchTag(Icc, sig, FALSE);
1464          if (i >= 0) 
1465              Icc ->TagNames[i] = (cmsTagSignature) 0;
1466          // Unsupported by now, reserved for future ampliations (delete)      
1467          return FALSE;
1468     }
1469
1470     i = _cmsSearchTag(Icc, sig, FALSE);
1471     if (i >=0) {
1472
1473         if (Icc -> TagPtrs[i] != NULL) {
1474
1475             // Already exists. Free previous version
1476             if (Icc ->TagSaveAsRaw[i]) {
1477                 _cmsFree(Icc ->ContextID, Icc ->TagPtrs[i]);
1478             }
1479             else {
1480                 TypeHandler = Icc ->TagTypeHandlers[i];
1481
1482                 if (TypeHandler != NULL) {
1483
1484                     TypeHandler ->ContextID = Icc ->ContextID;              // As an additional parameter
1485                     TypeHandler ->ICCVersion = Icc ->Version;
1486                     TypeHandler->FreePtr(TypeHandler, Icc -> TagPtrs[i]);
1487                 }
1488             }
1489         }
1490     }
1491     else  {
1492         // New one
1493         i = Icc -> TagCount;
1494
1495         if (i >= MAX_TABLE_TAG) {
1496             cmsSignalError(Icc ->ContextID, cmsERROR_RANGE, "Too many tags (%d)", MAX_TABLE_TAG);
1497             return FALSE;
1498         }
1499
1500         Icc -> TagCount++;
1501     }
1502
1503     // This is not raw
1504     Icc ->TagSaveAsRaw[i] = FALSE;
1505
1506     // This is not a link
1507     Icc ->TagLinked[i] = (cmsTagSignature) 0;
1508
1509     // Get information about the TAG. 
1510     TagDescriptor = _cmsGetTagDescriptor(sig);
1511     if (TagDescriptor == NULL){
1512          cmsSignalError(Icc ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported tag '%x'", sig);
1513         return FALSE;
1514     }
1515
1516     
1517     // Now we need to know which type to use. It depends on the version. 
1518     Version = cmsGetProfileVersion(hProfile);
1519
1520     if (TagDescriptor ->DecideType != NULL) {
1521
1522         // Let the tag descriptor to decide the type base on depending on
1523         // the data. This is useful for example on parametric curves, where 
1524         // curves specified by a table cannot be saved as parametric and needs
1525         // to be revented to single v2-curves, even on v4 profiles.
1526
1527         Type = TagDescriptor ->DecideType(Version, data);
1528     }
1529     else {
1530
1531
1532         Type = TagDescriptor ->SupportedTypes[0];
1533     }
1534
1535     // Does the tag support this type?
1536     if (!IsTypeSupported(TagDescriptor, Type)) {
1537                
1538         _cmsTagSignature2String(TypeString, (cmsTagSignature) Type);
1539         _cmsTagSignature2String(SigString,  sig);
1540
1541         cmsSignalError(Icc ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported type '%s' for tag '%s'", TypeString, SigString);
1542         return FALSE;
1543     }
1544
1545     // Does we have a handler for this type?
1546     TypeHandler =  _cmsGetTagTypeHandler(Type);
1547     if (TypeHandler == NULL) {
1548
1549         _cmsTagSignature2String(TypeString, (cmsTagSignature) Type);
1550         _cmsTagSignature2String(SigString,  sig);
1551
1552         cmsSignalError(Icc ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported type '%s' for tag '%s'", TypeString, SigString);
1553         return FALSE;           // Should never happen
1554     }
1555
1556
1557     // Fill fields on icc structure
1558     Icc ->TagTypeHandlers[i]  = TypeHandler;
1559     Icc ->TagNames[i]         = sig;
1560     Icc ->TagSizes[i]         = 0;
1561     Icc ->TagOffsets[i]       = 0;
1562
1563     TypeHandler ->ContextID  = Icc ->ContextID;
1564     TypeHandler ->ICCVersion = Icc ->Version;
1565     Icc ->TagPtrs[i]         = TypeHandler ->DupPtr(TypeHandler, data, TagDescriptor ->ElemCount); 
1566
1567     if (Icc ->TagPtrs[i] == NULL)  {
1568         
1569         _cmsTagSignature2String(TypeString, (cmsTagSignature) Type);
1570         _cmsTagSignature2String(SigString,  sig);
1571         cmsSignalError(Icc ->ContextID, cmsERROR_CORRUPTION_DETECTED, "Malformed struct in type '%s' for tag '%s'", TypeString, SigString);
1572         
1573         return FALSE;
1574     }
1575     
1576     return TRUE;
1577 }
1578
1579 // Read and write raw data. The only way those function would work and keep consistence with normal read and write 
1580 // is to do an additional step of serialization. That means, readRaw would issue a normal read and then convert the obtained
1581 // data to raw bytes by using the "write" serialization logic. And vice-versa. I know this may end in situations where
1582 // raw data written does not exactly correspond with the raw data proposed to cmsWriteRaw data, but this approach allows
1583 // to write a tag as raw data and the read it as handled.
1584
1585 cmsInt32Number CMSEXPORT cmsReadRawTag(cmsHPROFILE hProfile, cmsTagSignature sig, void* data, cmsUInt32Number BufferSize)
1586 {
1587     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;  
1588     void *Object; 
1589     int i;
1590     cmsIOHANDLER* MemIO;
1591     cmsTagTypeHandler* TypeHandler = NULL;
1592     cmsTagDescriptor* TagDescriptor = NULL;
1593     cmsUInt32Number rc;
1594     cmsUInt32Number Offset, TagSize;
1595
1596         // Search for given tag in ICC profile directory
1597         i = _cmsSearchTag(Icc, sig, TRUE);
1598         if (i < 0) return 0;                 // Not found, return 0
1599
1600         // It is already read?
1601     if (Icc -> TagPtrs[i] == NULL) {
1602
1603         // No yet, get original position
1604         Offset   = Icc ->TagOffsets[i];
1605         TagSize  = Icc ->TagSizes[i];
1606
1607         
1608         // read the data directly, don't keep copy
1609                 if (data != NULL) {
1610
1611                         if (BufferSize < TagSize)
1612                  TagSize = BufferSize;
1613
1614             if (!Icc ->IOhandler ->Seek(Icc ->IOhandler, Offset)) return 0;
1615             if (!Icc ->IOhandler ->Read(Icc ->IOhandler, data, 1, TagSize)) return 0;
1616                 }
1617
1618         return Icc ->TagSizes[i];
1619     }
1620
1621     // The data has been already read, or written. But wait!, maybe the user choosed to save as
1622     // raw data. In this case, return the raw data directly
1623     if (Icc ->TagSaveAsRaw[i]) {
1624                
1625                 if (data != NULL)  {
1626
1627                          TagSize  = Icc ->TagSizes[i];
1628                         if (BufferSize < TagSize)
1629                        TagSize = BufferSize;
1630
1631             memmove(data, Icc ->TagPtrs[i], TagSize);
1632                 }
1633
1634         return Icc ->TagSizes[i];
1635     }
1636
1637     // Already readed, or previously set by cmsWriteTag(). We need to serialize that 
1638     // data to raw in order to maintain consistency.
1639     Object = cmsReadTag(hProfile, sig);
1640     if (Object == NULL) return 0;
1641
1642     // Now we need to serialize to a memory block: just use a memory iohandler
1643
1644         if (data == NULL) {
1645                   MemIO = cmsOpenIOhandlerFromNULL(cmsGetProfileContextID(hProfile));
1646         } else{
1647           MemIO = cmsOpenIOhandlerFromMem(cmsGetProfileContextID(hProfile), data, BufferSize, "w");
1648         }
1649     if (MemIO == NULL) return 0;
1650
1651     // Obtain type handling for the tag
1652     TypeHandler = Icc ->TagTypeHandlers[i];
1653     TagDescriptor = _cmsGetTagDescriptor(sig);
1654     if (TagDescriptor == NULL) {
1655          cmsCloseIOhandler(MemIO);      
1656          return 0;
1657     }
1658     
1659     // Serialize
1660     TypeHandler ->ContextID  = Icc ->ContextID;
1661     TypeHandler ->ICCVersion = Icc ->Version;
1662
1663     if (!_cmsWriteTypeBase(MemIO, TypeHandler ->Signature)) {
1664         cmsCloseIOhandler(MemIO);      
1665         return 0;    
1666     }
1667
1668     if (!TypeHandler ->WritePtr(TypeHandler, MemIO, Object, TagDescriptor ->ElemCount)) {
1669         cmsCloseIOhandler(MemIO);      
1670         return 0;
1671     }
1672
1673     // Get Size and close
1674     rc = MemIO ->Tell(MemIO);
1675     cmsCloseIOhandler(MemIO);      // Ignore return code this time
1676
1677     return rc;
1678 }
1679
1680 // Similar to the anterior. This function allows to write directly to the ICC profile any data, without
1681 // checking anything. As a rule, mixing Raw with cooked doesn't work, so writting a tag as raw and then reading 
1682 // it as cooked without serializing does result into an error. If that is wha you want, you will need to dump
1683 // the profile to memry or disk and then reopen it.
1684 cmsBool CMSEXPORT cmsWriteRawTag(cmsHPROFILE hProfile, cmsTagSignature sig, const void* data, cmsUInt32Number Size)
1685 {
1686     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;  
1687     int i;
1688
1689         if (!_cmsNewTag(Icc, sig, &i)) return FALSE;
1690
1691     // Mark the tag as being written as RAW
1692     Icc ->TagSaveAsRaw[i] = TRUE;
1693     Icc ->TagNames[i]     = sig;
1694     Icc ->TagLinked[i]    = (cmsTagSignature) 0;
1695
1696     // Keep a copy of the block
1697     Icc ->TagPtrs[i]  = _cmsDupMem(Icc ->ContextID, data, Size);
1698     Icc ->TagSizes[i] = Size;
1699
1700     return TRUE;
1701 }
1702
1703 // Using this function you can collapse several tag entries to the same block in the profile
1704 cmsBool CMSEXPORT cmsLinkTag(cmsHPROFILE hProfile, cmsTagSignature sig, cmsTagSignature dest)
1705 {
1706      _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;  
1707     int i;
1708
1709         if (!_cmsNewTag(Icc, sig, &i)) return FALSE;
1710
1711     // Keep necessary information
1712     Icc ->TagSaveAsRaw[i] = FALSE;
1713     Icc ->TagNames[i]     = sig;
1714     Icc ->TagLinked[i]    = dest;
1715     
1716     Icc ->TagPtrs[i]    = NULL;
1717     Icc ->TagSizes[i]   = 0;
1718     Icc ->TagOffsets[i] = 0;
1719
1720     return TRUE;
1721 }
1722
1723
1724 // Returns the tag linked to sig, in the case two tags are sharing same resource
1725 cmsTagSignature  CMSEXPORT cmsTagLinkedTo(cmsHPROFILE hProfile, cmsTagSignature sig)
1726 {
1727     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;  
1728     int i;
1729
1730     // Search for given tag in ICC profile directory
1731         i = _cmsSearchTag(Icc, sig, FALSE);
1732         if (i < 0) return (cmsTagSignature) 0;                 // Not found, return 0
1733
1734     return Icc -> TagLinked[i];
1735 }