Code

Fixed include to ensure file compiles with lcms disabled
[inkscape.git] / src / color-profile.cpp
1 #ifdef HAVE_CONFIG_H
2 # include "config.h"
3 #endif
5 #define noDEBUG_LCMS
7 #include <glib/gstdio.h>
8 #include <sys/fcntl.h>
9 #include <gdkmm/color.h>
10 #include <glib/gi18n.h>
12 #ifdef DEBUG_LCMS
13 #include <gtk/gtkmessagedialog.h>
14 #endif // DEBUG_LCMS
16 #include <cstring>
17 #include <string>
18 #include <io/sys.h>
20 #ifdef WIN32
21 #ifndef _WIN32_WINDOWS         // Allow use of features specific to Windows 98 or later. Required for correctly including icm.h
22 #define _WIN32_WINDOWS 0x0410
23 #endif
24 #include <windows.h>
25 #endif
27 #include "xml/repr.h"
28 #include "color.h"
29 #include "color-profile.h"
30 #include "color-profile-fns.h"
31 #include "attributes.h"
32 #include "inkscape.h"
33 #include "document.h"
34 #include "preferences.h"
36 #include "dom/uri.h"
37 #include "dom/util/digest.h"
39 #ifdef WIN32
40 #include <icm.h>
41 #endif // WIN32
43 using Inkscape::ColorProfile;
44 using Inkscape::ColorProfileClass;
46 namespace Inkscape
47 {
48 #if ENABLE_LCMS
49 static cmsHPROFILE colorprofile_get_system_profile_handle();
50 static cmsHPROFILE colorprofile_get_proof_profile_handle();
51 #endif // ENABLE_LCMS
52 }
54 #ifdef DEBUG_LCMS
55 extern guint update_in_progress;
56 #define DEBUG_MESSAGE_SCISLAC(key, ...) \
57 {\
58     Inkscape::Preferences *prefs = Inkscape::Preferences::get();\
59     bool dump = prefs->getBool(Glib::ustring("/options/scislac/") + #key);\
60     bool dumpD = prefs->getBool(Glib::ustring("/options/scislac/") + #key"D");\
61     bool dumpD2 = prefs->getBool(Glib::ustring("/options/scislac/") + #key"D2");\
62     dumpD &= ( (update_in_progress == 0) || dumpD2 );\
63     if ( dump )\
64     {\
65         g_message( __VA_ARGS__ );\
66 \
67     }\
68     if ( dumpD )\
69     {\
70         GtkWidget *dialog = gtk_message_dialog_new(NULL,\
71                                                    GTK_DIALOG_DESTROY_WITH_PARENT, \
72                                                    GTK_MESSAGE_INFO,    \
73                                                    GTK_BUTTONS_OK,      \
74                                                    __VA_ARGS__          \
75                                                    );\
76         g_signal_connect_swapped(dialog, "response",\
77                                  G_CALLBACK(gtk_widget_destroy),        \
78                                  dialog);                               \
79         gtk_widget_show_all( dialog );\
80     }\
81 }
84 #define DEBUG_MESSAGE(key, ...)\
85 {\
86     g_message( __VA_ARGS__ );\
87 }
89 #endif // DEBUG_LCMS
91 static SPObjectClass *cprof_parent_class;
93 #if ENABLE_LCMS
95 cmsHPROFILE ColorProfile::_sRGBProf = 0;
97 cmsHPROFILE ColorProfile::getSRGBProfile() {
98     if ( !_sRGBProf ) {
99         _sRGBProf = cmsCreate_sRGBProfile();
100     }
101     return _sRGBProf;
104 cmsHPROFILE ColorProfile::_NullProf = 0;
106 cmsHPROFILE ColorProfile::getNULLProfile() {
107     if ( !_NullProf ) {
108         _NullProf = cmsCreateNULLProfile();
109     }
110     return _NullProf;
113 #endif // ENABLE_LCMS
115 /**
116  * Register ColorProfile class and return its type.
117  */
118 GType Inkscape::colorprofile_get_type()
120     return ColorProfile::getType();
123 GType ColorProfile::getType()
125     static GType type = 0;
126     if (!type) {
127         GTypeInfo info = {
128             sizeof(ColorProfileClass),
129             NULL, NULL,
130             (GClassInitFunc) ColorProfile::classInit,
131             NULL, NULL,
132             sizeof(ColorProfile),
133             16,
134             (GInstanceInitFunc) ColorProfile::init,
135             NULL,   /* value_table */
136         };
137         type = g_type_register_static( SP_TYPE_OBJECT, "ColorProfile", &info, static_cast<GTypeFlags>(0) );
138     }
139     return type;
142 /**
143  * ColorProfile vtable initialization.
144  */
145 void ColorProfile::classInit( ColorProfileClass *klass )
147     SPObjectClass *sp_object_class = reinterpret_cast<SPObjectClass *>(klass);
149     cprof_parent_class = static_cast<SPObjectClass*>(g_type_class_ref(SP_TYPE_OBJECT));
151     sp_object_class->release = ColorProfile::release;
152     sp_object_class->build = ColorProfile::build;
153     sp_object_class->set = ColorProfile::set;
154     sp_object_class->write = ColorProfile::write;
157 /**
158  * Callback for ColorProfile object initialization.
159  */
160 void ColorProfile::init( ColorProfile *cprof )
162     cprof->href = 0;
163     cprof->local = 0;
164     cprof->name = 0;
165     cprof->intentStr = 0;
166     cprof->rendering_intent = Inkscape::RENDERING_INTENT_UNKNOWN;
167 #if ENABLE_LCMS
168     cprof->profHandle = 0;
169     cprof->_profileClass = icSigInputClass;
170     cprof->_profileSpace = icSigRgbData;
171     cprof->_transf = 0;
172     cprof->_revTransf = 0;
173     cprof->_gamutTransf = 0;
174 #endif // ENABLE_LCMS
177 /**
178  * Callback: free object
179  */
180 void ColorProfile::release( SPObject *object )
182     // Unregister ourselves
183     SPDocument* document = SP_OBJECT_DOCUMENT(object);
184     if ( document ) {
185         sp_document_remove_resource (SP_OBJECT_DOCUMENT (object), "iccprofile", SP_OBJECT (object));
186     }
188     ColorProfile *cprof = COLORPROFILE(object);
189     if ( cprof->href ) {
190         g_free( cprof->href );
191         cprof->href = 0;
192     }
194     if ( cprof->local ) {
195         g_free( cprof->local );
196         cprof->local = 0;
197     }
199     if ( cprof->name ) {
200         g_free( cprof->name );
201         cprof->name = 0;
202     }
204     if ( cprof->intentStr ) {
205         g_free( cprof->intentStr );
206         cprof->intentStr = 0;
207     }
209 #if ENABLE_LCMS
210     cprof->_clearProfile();
211 #endif // ENABLE_LCMS
214 #if ENABLE_LCMS
215 void ColorProfile::_clearProfile()
217     _profileSpace = icSigRgbData;
219     if ( _transf ) {
220         cmsDeleteTransform( _transf );
221         _transf = 0;
222     }
223     if ( _revTransf ) {
224         cmsDeleteTransform( _revTransf );
225         _revTransf = 0;
226     }
227     if ( _gamutTransf ) {
228         cmsDeleteTransform( _gamutTransf );
229         _gamutTransf = 0;
230     }
231     if ( profHandle ) {
232         cmsCloseProfile( profHandle );
233         profHandle = 0;
234     }
236 #endif // ENABLE_LCMS
238 /**
239  * Callback: set attributes from associated repr.
240  */
241 void ColorProfile::build( SPObject *object, SPDocument *document, Inkscape::XML::Node *repr )
243     ColorProfile *cprof = COLORPROFILE(object);
244     g_assert(cprof->href == 0);
245     g_assert(cprof->local == 0);
246     g_assert(cprof->name == 0);
247     g_assert(cprof->intentStr == 0);
249     if (cprof_parent_class->build) {
250         (* cprof_parent_class->build)(object, document, repr);
251     }
252     sp_object_read_attr( object, "xlink:href" );
253     sp_object_read_attr( object, "local" );
254     sp_object_read_attr( object, "name" );
255     sp_object_read_attr( object, "rendering-intent" );
257     // Register
258     if ( document ) {
259         sp_document_add_resource( document, "iccprofile", object );
260     }
263 /**
264  * Callback: set attribute.
265  */
266 void ColorProfile::set( SPObject *object, unsigned key, gchar const *value )
268     ColorProfile *cprof = COLORPROFILE(object);
270     switch (key) {
271         case SP_ATTR_XLINK_HREF:
272             if ( cprof->href ) {
273                 g_free( cprof->href );
274                 cprof->href = 0;
275             }
276             if ( value ) {
277                 cprof->href = g_strdup( value );
278                 if ( *cprof->href ) {
279 #if ENABLE_LCMS
280                     cmsErrorAction( LCMS_ERROR_SHOW );
282                     // TODO open filename and URIs properly
283                     //FILE* fp = fopen_utf8name( filename, "r" );
284                     //LCMSAPI cmsHPROFILE   LCMSEXPORT cmsOpenProfileFromMem(LPVOID MemPtr, DWORD dwSize);
286                     // Try to open relative
287                     SPDocument *doc = SP_OBJECT_DOCUMENT(object);
288                     if (!doc) {
289                         doc = SP_ACTIVE_DOCUMENT;
290                         g_warning("object has no document.  using active");
291                     }
292                     //# 1.  Get complete URI of document
293                     gchar const *docbase = SP_DOCUMENT_URI( doc );
294                     if (!docbase)
295                     {
296                         // Normal for files that have not yet been saved.
297                         docbase = "";
298                     }
300                     gchar* escaped = g_uri_escape_string(cprof->href, "!*'();:@=+$,/?#[]", TRUE);
302                     //g_message("docbase:%s\n", docbase);
303                     org::w3c::dom::URI docUri(docbase);
304                     //# 2. Get href of icc file.  we don't care if it's rel or abs
305                     org::w3c::dom::URI hrefUri(escaped);
306                     //# 3.  Resolve the href according the docBase.  This follows
307                     //      the w3c specs.  All absolute and relative issues are considered
308                     org::w3c::dom::URI cprofUri = docUri.resolve(hrefUri);
309                     gchar* fullname = g_uri_unescape_string(cprofUri.getNativePath().c_str(), "");
310                     cprof->_clearProfile();
311                     cprof->profHandle = cmsOpenProfileFromFile( fullname, "r" );
312                     if ( cprof->profHandle ) {
313                         cprof->_profileSpace = cmsGetColorSpace( cprof->profHandle );
314                         cprof->_profileClass = cmsGetDeviceClass( cprof->profHandle );
315                     }
316 #ifdef DEBUG_LCMS
317                     DEBUG_MESSAGE( lcmsOne, "cmsOpenProfileFromFile( '%s'...) = %p", fullname, (void*)cprof->profHandle );
318 #endif // DEBUG_LCMS
319                     g_free(escaped);
320                     escaped = 0;
321                     g_free(fullname);
322 #endif // ENABLE_LCMS
323                 }
324             }
325             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
326             break;
328         case SP_ATTR_LOCAL:
329             if ( cprof->local ) {
330                 g_free( cprof->local );
331                 cprof->local = 0;
332             }
333             cprof->local = g_strdup( value );
334             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
335             break;
337         case SP_ATTR_NAME:
338             if ( cprof->name ) {
339                 g_free( cprof->name );
340                 cprof->name = 0;
341             }
342             cprof->name = g_strdup( value );
343 #ifdef DEBUG_LCMS
344             DEBUG_MESSAGE( lcmsTwo, "<color-profile> name set to '%s'", cprof->name );
345 #endif // DEBUG_LCMS
346             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
347             break;
349         case SP_ATTR_RENDERING_INTENT:
350             if ( cprof->intentStr ) {
351                 g_free( cprof->intentStr );
352                 cprof->intentStr = 0;
353             }
354             cprof->intentStr = g_strdup( value );
356             if ( value ) {
357                 if ( strcmp( value, "auto" ) == 0 ) {
358                     cprof->rendering_intent = RENDERING_INTENT_AUTO;
359                 } else if ( strcmp( value, "perceptual" ) == 0 ) {
360                     cprof->rendering_intent = RENDERING_INTENT_PERCEPTUAL;
361                 } else if ( strcmp( value, "relative-colorimetric" ) == 0 ) {
362                     cprof->rendering_intent = RENDERING_INTENT_RELATIVE_COLORIMETRIC;
363                 } else if ( strcmp( value, "saturation" ) == 0 ) {
364                     cprof->rendering_intent = RENDERING_INTENT_SATURATION;
365                 } else if ( strcmp( value, "absolute-colorimetric" ) == 0 ) {
366                     cprof->rendering_intent = RENDERING_INTENT_ABSOLUTE_COLORIMETRIC;
367                 } else {
368                     cprof->rendering_intent = RENDERING_INTENT_UNKNOWN;
369                 }
370             } else {
371                 cprof->rendering_intent = RENDERING_INTENT_UNKNOWN;
372             }
374             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
375             break;
377         default:
378             if (cprof_parent_class->set) {
379                 (* cprof_parent_class->set)(object, key, value);
380             }
381             break;
382     }
386 /**
387  * Callback: write attributes to associated repr.
388  */
389 Inkscape::XML::Node* ColorProfile::write( SPObject *object, Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags )
391     ColorProfile *cprof = COLORPROFILE(object);
393     if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) {
394         repr = xml_doc->createElement("svg:color-profile");
395     }
397     if ( (flags & SP_OBJECT_WRITE_ALL) || cprof->href ) {
398         repr->setAttribute( "xlink:href", cprof->href );
399     }
401     if ( (flags & SP_OBJECT_WRITE_ALL) || cprof->local ) {
402         repr->setAttribute( "local", cprof->local );
403     }
405     if ( (flags & SP_OBJECT_WRITE_ALL) || cprof->name ) {
406         repr->setAttribute( "name", cprof->name );
407     }
409     if ( (flags & SP_OBJECT_WRITE_ALL) || cprof->intentStr ) {
410         repr->setAttribute( "rendering-intent", cprof->intentStr );
411     }
413     if (cprof_parent_class->write) {
414         (* cprof_parent_class->write)(object, xml_doc, repr, flags);
415     }
417     return repr;
421 #if ENABLE_LCMS
423 struct MapMap {
424     icColorSpaceSignature space;
425     DWORD inForm;
426 };
428 DWORD ColorProfile::_getInputFormat( icColorSpaceSignature space )
430     MapMap possible[] = {
431         {icSigXYZData,   TYPE_XYZ_16},
432         {icSigLabData,   TYPE_Lab_16},
433         //icSigLuvData
434         {icSigYCbCrData, TYPE_YCbCr_16},
435         {icSigYxyData,   TYPE_Yxy_16},
436         {icSigRgbData,   TYPE_RGB_16},
437         {icSigGrayData,  TYPE_GRAY_16},
438         {icSigHsvData,   TYPE_HSV_16},
439         {icSigHlsData,   TYPE_HLS_16},
440         {icSigCmykData,  TYPE_CMYK_16},
441         {icSigCmyData,   TYPE_CMY_16},
442     };
444     int index = 0;
445     for ( guint i = 0; i < G_N_ELEMENTS(possible); i++ ) {
446         if ( possible[i].space == space ) {
447             index = i;
448             break;
449         }
450     }
452     return possible[index].inForm;
455 static int getLcmsIntent( guint svgIntent )
457     int intent = INTENT_PERCEPTUAL;
458     switch ( svgIntent ) {
459         case Inkscape::RENDERING_INTENT_RELATIVE_COLORIMETRIC:
460             intent = INTENT_RELATIVE_COLORIMETRIC;
461             break;
462         case Inkscape::RENDERING_INTENT_SATURATION:
463             intent = INTENT_SATURATION;
464             break;
465         case Inkscape::RENDERING_INTENT_ABSOLUTE_COLORIMETRIC:
466             intent = INTENT_ABSOLUTE_COLORIMETRIC;
467             break;
468         case Inkscape::RENDERING_INTENT_PERCEPTUAL:
469         case Inkscape::RENDERING_INTENT_UNKNOWN:
470         case Inkscape::RENDERING_INTENT_AUTO:
471         default:
472             intent = INTENT_PERCEPTUAL;
473     }
474     return intent;
477 static SPObject* bruteFind( SPDocument* document, gchar const* name )
479     SPObject* result = 0;
480     const GSList * current = sp_document_get_resource_list(document, "iccprofile");
481     while ( current && !result ) {
482         if ( IS_COLORPROFILE(current->data) ) {
483             ColorProfile* prof = COLORPROFILE(current->data);
484             if ( prof ) {
485                 if ( prof->name && (strcmp(prof->name, name) == 0) ) {
486                     result = SP_OBJECT(current->data);
487                     break;
488                 }
489             }
490         }
491         current = g_slist_next(current);
492     }
494     return result;
497 cmsHPROFILE Inkscape::colorprofile_get_handle( SPDocument* document, guint* intent, gchar const* name )
499     cmsHPROFILE prof = 0;
501     SPObject* thing = bruteFind( document, name );
502     if ( thing ) {
503         prof = COLORPROFILE(thing)->profHandle;
504     }
506     if ( intent ) {
507         *intent = thing ? COLORPROFILE(thing)->rendering_intent : (guint)RENDERING_INTENT_UNKNOWN;
508     }
510 #ifdef DEBUG_LCMS
511     DEBUG_MESSAGE( lcmsThree, "<color-profile> queried for profile of '%s'. Returning %p with intent of %d", name, prof, (intent? *intent:0) );
512 #endif // DEBUG_LCMS
514     return prof;
517 cmsHTRANSFORM ColorProfile::getTransfToSRGB8()
519     if ( !_transf && profHandle ) {
520         int intent = getLcmsIntent(rendering_intent);
521         _transf = cmsCreateTransform( profHandle, _getInputFormat(_profileSpace), getSRGBProfile(), TYPE_RGBA_8, intent, 0 );
522     }
523     return _transf;
526 cmsHTRANSFORM ColorProfile::getTransfFromSRGB8()
528     if ( !_revTransf && profHandle ) {
529         int intent = getLcmsIntent(rendering_intent);
530         _revTransf = cmsCreateTransform( getSRGBProfile(), TYPE_RGBA_8, profHandle, _getInputFormat(_profileSpace), intent, 0 );
531     }
532     return _revTransf;
535 cmsHTRANSFORM ColorProfile::getTransfGamutCheck()
537     if ( !_gamutTransf ) {
538         _gamutTransf = cmsCreateProofingTransform(getSRGBProfile(), TYPE_RGBA_8, getNULLProfile(), TYPE_GRAY_8, profHandle, INTENT_RELATIVE_COLORIMETRIC, INTENT_RELATIVE_COLORIMETRIC, (cmsFLAGS_GAMUTCHECK|cmsFLAGS_SOFTPROOFING));
539     }
540     return _gamutTransf;
543 bool ColorProfile::GamutCheck(SPColor color){
544     BYTE outofgamut = 0;
545     
546     guint32 val = color.toRGBA32(0);
547     guchar check_color[4] = {
548         SP_RGBA32_R_U(val),
549         SP_RGBA32_G_U(val),
550         SP_RGBA32_B_U(val),
551         255};
553     int alarm_r, alarm_g, alarm_b;
554     cmsGetAlarmCodes(&alarm_r, &alarm_g, &alarm_b);
555     cmsSetAlarmCodes(255, 255, 255);
556     cmsDoTransform(ColorProfile::getTransfGamutCheck(), &check_color, &outofgamut, 1);
557     cmsSetAlarmCodes(alarm_r, alarm_g, alarm_b);
558     return (outofgamut == 255);
561 class ProfileInfo
563 public:
564     ProfileInfo( cmsHPROFILE, Glib::ustring const & path );
566     Glib::ustring const& getName() {return _name;}
567     Glib::ustring const& getPath() {return _path;}
568     icColorSpaceSignature getSpace() {return _profileSpace;}
569     icProfileClassSignature getClass() {return _profileClass;}
571 private:
572     Glib::ustring _path;
573     Glib::ustring _name;
574     icColorSpaceSignature _profileSpace;
575     icProfileClassSignature _profileClass;
576 };
579 ProfileInfo::ProfileInfo( cmsHPROFILE prof, Glib::ustring const & path )
581     _path = path;
582     _name = cmsTakeProductDesc(prof);
583     _profileSpace = cmsGetColorSpace( prof );
584     _profileClass = cmsGetDeviceClass( prof );
589 static std::vector<ProfileInfo> knownProfiles;
591 std::vector<Glib::ustring> Inkscape::colorprofile_get_display_names()
593     std::vector<Glib::ustring> result;
595     for ( std::vector<ProfileInfo>::iterator it = knownProfiles.begin(); it != knownProfiles.end(); ++it ) {
596         if ( it->getClass() == icSigDisplayClass && it->getSpace() == icSigRgbData ) {
597             result.push_back( it->getName() );
598         }
599     }
601     return result;
604 std::vector<Glib::ustring> Inkscape::colorprofile_get_softproof_names()
606     std::vector<Glib::ustring> result;
608     for ( std::vector<ProfileInfo>::iterator it = knownProfiles.begin(); it != knownProfiles.end(); ++it ) {
609         if ( it->getClass() == icSigOutputClass ) {
610             result.push_back( it->getName() );
611         }
612     }
614     return result;
617 Glib::ustring Inkscape::get_path_for_profile(Glib::ustring const& name)
619     Glib::ustring result;
621     for ( std::vector<ProfileInfo>::iterator it = knownProfiles.begin(); it != knownProfiles.end(); ++it ) {
622         if ( name == it->getName() ) {
623             result = it->getPath();
624             break;
625         }
626     }
628     return result;
630 #endif // ENABLE_LCMS
632 std::list<Glib::ustring> ColorProfile::getBaseProfileDirs() {
633 #if ENABLE_LCMS
634     static bool warnSet = false;
635     if (!warnSet) {
636         cmsErrorAction( LCMS_ERROR_SHOW );
637         warnSet = true;
638     }
639 #endif // ENABLE_LCMS
640     std::list<Glib::ustring> sources;
642     gchar* base = profile_path("XXX");
643     {
644         gchar* base2 = g_path_get_dirname(base);
645         g_free(base);
646         base = base2;
647         base2 = g_path_get_dirname(base);
648         g_free(base);
649         base = base2;
650     }
652     // first try user's local dir
653     sources.push_back( g_build_filename(g_get_user_data_dir(), "color", "icc", NULL) );
656     const gchar* const * dataDirs = g_get_system_data_dirs();
657     for ( int i = 0; dataDirs[i]; i++ ) {
658         gchar* path = g_build_filename(dataDirs[i], "color", "icc", NULL);
659         sources.push_back(path);
660         g_free(path);
661     }
663     // On OS X:
664     {
665         bool onOSX = false;
666         std::list<Glib::ustring> possible;
667         possible.push_back("/System/Library/ColorSync/Profiles");
668         possible.push_back("/Library/ColorSync/Profiles");
669         for ( std::list<Glib::ustring>::const_iterator it = possible.begin(); it != possible.end(); ++it ) {
670             if ( g_file_test(it->c_str(), G_FILE_TEST_EXISTS)  && g_file_test(it->c_str(), G_FILE_TEST_IS_DIR) ) {
671                 sources.push_back(it->c_str());
672                 onOSX = true;
673             }
674         }
675         if ( onOSX ) {
676             gchar* path = g_build_filename(g_get_home_dir(), "Library", "ColorSync", "Profiles", NULL);
677             if ( g_file_test(path, G_FILE_TEST_EXISTS)  && g_file_test(path, G_FILE_TEST_IS_DIR) ) {
678                 sources.push_back(path);
679             }
680             g_free(path);
681         }
682     }
684 #ifdef WIN32
685     wchar_t pathBuf[MAX_PATH + 1];
686     pathBuf[0] = 0;
687     DWORD pathSize = sizeof(pathBuf);
688     g_assert(sizeof(wchar_t) == sizeof(gunichar2));
689     if ( GetColorDirectoryW( NULL, pathBuf, &pathSize ) ) {
690         gchar * utf8Path = g_utf16_to_utf8( (gunichar2*)(&pathBuf[0]), -1, NULL, NULL, NULL );
691         if ( !g_utf8_validate(utf8Path, -1, NULL) ) {
692             g_warning( "GetColorDirectoryW() resulted in invalid UTF-8" );
693         } else {
694             sources.push_back(utf8Path);
695         }
696         g_free( utf8Path );
697     }
698 #endif // WIN32
700     return sources;
703 static bool isIccFile( gchar const *filepath )
705     bool isIccFile = false;
706     struct stat st;
707     if ( g_stat(filepath, &st) == 0 && (st.st_size > 128) ) {
708         //0-3 == size
709         //36-39 == 'acsp' 0x61637370
710         int fd = g_open( filepath, O_RDONLY, S_IRWXU);
711         if ( fd != -1 ) {
712             guchar scratch[40] = {0};
713             size_t len = sizeof(scratch);
715             //size_t left = 40;
716             ssize_t got = read(fd, scratch, len);
717             if ( got != -1 ) {
718                 size_t calcSize = (scratch[0] << 24) | (scratch[1] << 16) | (scratch[2] << 8) | scratch[3];
719                 if ( calcSize > 128 && calcSize <= static_cast<size_t>(st.st_size) ) {
720                     isIccFile = (scratch[36] == 'a') && (scratch[37] == 'c') && (scratch[38] == 's') && (scratch[39] == 'p');
721                 }
722             }
724             close(fd);
725         }
726     }
727     return isIccFile;
730 std::list<Glib::ustring> ColorProfile::getProfileFiles()
732     std::list<Glib::ustring> files;
734     std::list<Glib::ustring> sources = ColorProfile::getBaseProfileDirs();
735     for ( std::list<Glib::ustring>::const_iterator it = sources.begin(); it != sources.end(); ++it ) {
736         if ( g_file_test( it->c_str(), G_FILE_TEST_EXISTS ) && g_file_test( it->c_str(), G_FILE_TEST_IS_DIR ) ) {
737             GError *err = 0;
738             GDir *dir = g_dir_open(it->c_str(), 0, &err);
740             if (dir) {
741                 for (gchar const *file = g_dir_read_name(dir); file != NULL; file = g_dir_read_name(dir)) {
742                     gchar *filepath = g_build_filename(it->c_str(), file, NULL);
743                     if ( g_file_test( filepath, G_FILE_TEST_IS_DIR ) ) {
744                         sources.push_back(g_strdup(filepath));
745                     } else {
746                         if ( isIccFile( filepath ) ) {
747                             files.push_back( filepath );
748                         }
749                     }
751                     g_free(filepath);
752                 }
753                 g_dir_close(dir);
754                 dir = 0;
755             } else {
756                 gchar *safeDir = Inkscape::IO::sanitizeString(it->c_str());
757                 g_warning(_("Color profiles directory (%s) is unavailable."), safeDir);
758                 g_free(safeDir);
759             }
760         }
761     }
763     return files;
766 #if ENABLE_LCMS
767 static void findThings() {
768     std::list<Glib::ustring> files = ColorProfile::getProfileFiles();
770     for ( std::list<Glib::ustring>::const_iterator it = files.begin(); it != files.end(); ++it ) {
771         cmsHPROFILE prof = cmsOpenProfileFromFile( it->c_str(), "r" );
772         if ( prof ) {
773             ProfileInfo info( prof, Glib::filename_to_utf8( it->c_str() ) );
774             cmsCloseProfile( prof );
776             bool sameName = false;
777             for ( std::vector<ProfileInfo>::iterator it = knownProfiles.begin(); it != knownProfiles.end(); ++it ) {
778                 if ( it->getName() == info.getName() ) {
779                     sameName = true;
780                     break;
781                 }
782             }
784             if ( !sameName ) {
785                 knownProfiles.push_back(info);
786             }
787         }
788     }
791 int errorHandlerCB(int ErrorCode, const char *ErrorText)
793     g_message("lcms: Error %d; %s", ErrorCode, ErrorText);
795     return 1;
798 static bool gamutWarn = false;
799 static Gdk::Color lastGamutColor("#808080");
800 static bool lastBPC = false;
801 #if defined(cmsFLAGS_PRESERVEBLACK)
802 static bool lastPreserveBlack = false;
803 #endif // defined(cmsFLAGS_PRESERVEBLACK)
804 static int lastIntent = INTENT_PERCEPTUAL;
805 static int lastProofIntent = INTENT_PERCEPTUAL;
806 static cmsHTRANSFORM transf = 0;
808 cmsHPROFILE Inkscape::colorprofile_get_system_profile_handle()
810     static cmsHPROFILE theOne = 0;
811     static Glib::ustring lastURI;
813     static bool init = false;
814     if ( !init ) {
815         cmsSetErrorHandler(errorHandlerCB);
817         findThings();
818         init = true;
819     }
821     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
822     Glib::ustring uri = prefs->getString("/options/displayprofile/uri");
824     if ( !uri.empty() ) {
825         if ( uri != lastURI ) {
826             lastURI.clear();
827             if ( theOne ) {
828                 cmsCloseProfile( theOne );
829             }
830             if ( transf ) {
831                 cmsDeleteTransform( transf );
832                 transf = 0;
833             }
834             theOne = cmsOpenProfileFromFile( uri.data(), "r" );
835             if ( theOne ) {
836                 // a display profile must have the proper stuff
837                 icColorSpaceSignature space = cmsGetColorSpace(theOne);
838                 icProfileClassSignature profClass = cmsGetDeviceClass(theOne);
840                 if ( profClass != icSigDisplayClass ) {
841                     g_warning("Not a display profile");
842                     cmsCloseProfile( theOne );
843                     theOne = 0;
844                 } else if ( space != icSigRgbData ) {
845                     g_warning("Not an RGB profile");
846                     cmsCloseProfile( theOne );
847                     theOne = 0;
848                 } else {
849                     lastURI = uri;
850                 }
851             }
852         }
853     } else if ( theOne ) {
854         cmsCloseProfile( theOne );
855         theOne = 0;
856         lastURI.clear();
857         if ( transf ) {
858             cmsDeleteTransform( transf );
859             transf = 0;
860         }
861     }
863     return theOne;
867 cmsHPROFILE Inkscape::colorprofile_get_proof_profile_handle()
869     static cmsHPROFILE theOne = 0;
870     static Glib::ustring lastURI;
872     static bool init = false;
873     if ( !init ) {
874         cmsSetErrorHandler(errorHandlerCB);
876         findThings();
877         init = true;
878     }
880     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
881     bool which = prefs->getBool( "/options/softproof/enable");
882     Glib::ustring uri = prefs->getString("/options/softproof/uri");
884     if ( which && !uri.empty() ) {
885         if ( lastURI != uri ) {
886             lastURI.clear();
887             if ( theOne ) {
888                 cmsCloseProfile( theOne );
889             }
890             if ( transf ) {
891                 cmsDeleteTransform( transf );
892                 transf = 0;
893             }
894             theOne = cmsOpenProfileFromFile( uri.data(), "r" );
895             if ( theOne ) {
896                 // a display profile must have the proper stuff
897                 icColorSpaceSignature space = cmsGetColorSpace(theOne);
898                 icProfileClassSignature profClass = cmsGetDeviceClass(theOne);
900                 (void)space;
901                 (void)profClass;
902 /*
903                 if ( profClass != icSigDisplayClass ) {
904                     g_warning("Not a display profile");
905                     cmsCloseProfile( theOne );
906                     theOne = 0;
907                 } else if ( space != icSigRgbData ) {
908                     g_warning("Not an RGB profile");
909                     cmsCloseProfile( theOne );
910                     theOne = 0;
911                 } else {
912 */
913                     lastURI = uri;
914 /*
915                 }
916 */
917             }
918         }
919     } else if ( theOne ) {
920         cmsCloseProfile( theOne );
921         theOne = 0;
922         lastURI.clear();
923         if ( transf ) {
924             cmsDeleteTransform( transf );
925             transf = 0;
926         }
927     }
929     return theOne;
932 static void free_transforms();
934 cmsHTRANSFORM Inkscape::colorprofile_get_display_transform()
936     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
937     bool fromDisplay = prefs->getBool( "/options/displayprofile/from_display");
938     if ( fromDisplay ) {
939         if ( transf ) {
940             cmsDeleteTransform(transf);
941             transf = 0;
942         }
943         return 0;
944     }
946     bool warn = prefs->getBool( "/options/softproof/gamutwarn");
947     int intent = prefs->getIntLimited( "/options/displayprofile/intent", 0, 0, 3 );
948     int proofIntent = prefs->getIntLimited( "/options/softproof/intent", 0, 0, 3 );
949     bool bpc = prefs->getBool( "/options/softproof/bpc");
950 #if defined(cmsFLAGS_PRESERVEBLACK)
951     bool preserveBlack = prefs->getBool( "/options/softproof/preserveblack");
952 #endif //defined(cmsFLAGS_PRESERVEBLACK)
953     Glib::ustring colorStr = prefs->getString("/options/softproof/gamutcolor");
954     Gdk::Color gamutColor( colorStr.empty() ? "#808080" : colorStr );
956     if ( (warn != gamutWarn)
957          || (lastIntent != intent)
958          || (lastProofIntent != proofIntent)
959          || (bpc != lastBPC)
960 #if defined(cmsFLAGS_PRESERVEBLACK)
961          || (preserveBlack != lastPreserveBlack)
962 #endif // defined(cmsFLAGS_PRESERVEBLACK)
963          || (gamutColor != lastGamutColor)
964         ) {
965         gamutWarn = warn;
966         free_transforms();
967         lastIntent = intent;
968         lastProofIntent = proofIntent;
969         lastBPC = bpc;
970 #if defined(cmsFLAGS_PRESERVEBLACK)
971         lastPreserveBlack = preserveBlack;
972 #endif // defined(cmsFLAGS_PRESERVEBLACK)
973         lastGamutColor = gamutColor;
974     }
976     // Fetch these now, as they might clear the transform as a side effect.
977     cmsHPROFILE hprof = Inkscape::colorprofile_get_system_profile_handle();
978     cmsHPROFILE proofProf = hprof ? Inkscape::colorprofile_get_proof_profile_handle() : 0;
980     if ( !transf ) {
981         if ( hprof && proofProf ) {
982             DWORD dwFlags = cmsFLAGS_SOFTPROOFING;
983             if ( gamutWarn ) {
984                 dwFlags |= cmsFLAGS_GAMUTCHECK;
985                 cmsSetAlarmCodes(gamutColor.get_red() >> 8, gamutColor.get_green() >> 8, gamutColor.get_blue() >> 8);
986             }
987             if ( bpc ) {
988                 dwFlags |= cmsFLAGS_BLACKPOINTCOMPENSATION;
989             }
990 #if defined(cmsFLAGS_PRESERVEBLACK)
991             if ( preserveBlack ) {
992                 dwFlags |= cmsFLAGS_PRESERVEBLACK;
993             }
994 #endif // defined(cmsFLAGS_PRESERVEBLACK)
995             transf = cmsCreateProofingTransform( ColorProfile::getSRGBProfile(), TYPE_RGBA_8, hprof, TYPE_RGBA_8, proofProf, intent, proofIntent, dwFlags );
996         } else if ( hprof ) {
997             transf = cmsCreateTransform( ColorProfile::getSRGBProfile(), TYPE_RGBA_8, hprof, TYPE_RGBA_8, intent, 0 );
998         }
999     }
1001     return transf;
1005 class MemProfile {
1006 public:
1007     MemProfile();
1008     ~MemProfile();
1010     std::string id;
1011     cmsHPROFILE hprof;
1012     cmsHTRANSFORM transf;
1013 };
1015 MemProfile::MemProfile() :
1016     id(),
1017     hprof(0),
1018     transf(0)
1022 MemProfile::~MemProfile()
1026 static std::vector< std::vector<MemProfile> > perMonitorProfiles;
1028 void free_transforms()
1030     if ( transf ) {
1031         cmsDeleteTransform(transf);
1032         transf = 0;
1033     }
1035     for ( std::vector< std::vector<MemProfile> >::iterator it = perMonitorProfiles.begin(); it != perMonitorProfiles.end(); ++it ) {
1036         for ( std::vector<MemProfile>::iterator it2 = it->begin(); it2 != it->end(); ++it2 ) {
1037             if ( it2->transf ) {
1038                 cmsDeleteTransform(it2->transf);
1039                 it2->transf = 0;
1040             }
1041         }
1042     }
1045 Glib::ustring Inkscape::colorprofile_get_display_id( int screen, int monitor )
1047     Glib::ustring id;
1049     if ( screen >= 0 && screen < static_cast<int>(perMonitorProfiles.size()) ) {
1050         std::vector<MemProfile>& row = perMonitorProfiles[screen];
1051         if ( monitor >= 0 && monitor < static_cast<int>(row.size()) ) {
1052             MemProfile& item = row[monitor];
1053             id = item.id;
1054         }
1055     }
1057     return id;
1060 Glib::ustring Inkscape::colorprofile_set_display_per( gpointer buf, guint bufLen, int screen, int monitor )
1062     Glib::ustring id;
1064     while ( static_cast<int>(perMonitorProfiles.size()) <= screen ) {
1065         std::vector<MemProfile> tmp;
1066         perMonitorProfiles.push_back(tmp);
1067     }
1068     std::vector<MemProfile>& row = perMonitorProfiles[screen];
1069     while ( static_cast<int>(row.size()) <= monitor ) {
1070         MemProfile tmp;
1071         row.push_back(tmp);
1072     }
1073     MemProfile& item = row[monitor];
1075     if ( item.hprof ) {
1076         cmsCloseProfile( item.hprof );
1077         item.hprof = 0;
1078     }
1079     id.clear();
1081     if ( buf && bufLen ) {
1082         id = Digest::hashHex(Digest::HASH_MD5,
1083                    reinterpret_cast<unsigned char*>(buf), bufLen);
1085         // Note: if this is not a valid profile, item.hprof will be set to null.
1086         item.hprof = cmsOpenProfileFromMem(buf, bufLen);
1087     }
1088     item.id = id;
1090     return id;
1093 cmsHTRANSFORM Inkscape::colorprofile_get_display_per( Glib::ustring const& id )
1095     cmsHTRANSFORM result = 0;
1096     if ( id.empty() ) {
1097         return 0;
1098     }
1100     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1101     bool found = false;
1102     for ( std::vector< std::vector<MemProfile> >::iterator it = perMonitorProfiles.begin(); it != perMonitorProfiles.end() && !found; ++it ) {
1103         for ( std::vector<MemProfile>::iterator it2 = it->begin(); it2 != it->end() && !found; ++it2 ) {
1104             if ( id == it2->id ) {
1105                 MemProfile& item = *it2;
1107                 bool warn = prefs->getBool( "/options/softproof/gamutwarn");
1108                 int intent = prefs->getIntLimited( "/options/displayprofile/intent", 0, 0, 3 );
1109                 int proofIntent = prefs->getIntLimited( "/options/softproof/intent", 0, 0, 3 );
1110                 bool bpc = prefs->getBool( "/options/softproof/bpc");
1111 #if defined(cmsFLAGS_PRESERVEBLACK)
1112                 bool preserveBlack = prefs->getBool( "/options/softproof/preserveblack");
1113 #endif //defined(cmsFLAGS_PRESERVEBLACK)
1114                 Glib::ustring colorStr = prefs->getString("/options/softproof/gamutcolor");
1115                 Gdk::Color gamutColor( colorStr.empty() ? "#808080" : colorStr );
1117                 if ( (warn != gamutWarn)
1118                      || (lastIntent != intent)
1119                      || (lastProofIntent != proofIntent)
1120                      || (bpc != lastBPC)
1121 #if defined(cmsFLAGS_PRESERVEBLACK)
1122                      || (preserveBlack != lastPreserveBlack)
1123 #endif // defined(cmsFLAGS_PRESERVEBLACK)
1124                      || (gamutColor != lastGamutColor)
1125                     ) {
1126                     gamutWarn = warn;
1127                     free_transforms();
1128                     lastIntent = intent;
1129                     lastProofIntent = proofIntent;
1130                     lastBPC = bpc;
1131 #if defined(cmsFLAGS_PRESERVEBLACK)
1132                     lastPreserveBlack = preserveBlack;
1133 #endif // defined(cmsFLAGS_PRESERVEBLACK)
1134                     lastGamutColor = gamutColor;
1135                 }
1137                 // Fetch these now, as they might clear the transform as a side effect.
1138                 cmsHPROFILE proofProf = item.hprof ? Inkscape::colorprofile_get_proof_profile_handle() : 0;
1140                 if ( !item.transf ) {
1141                     if ( item.hprof && proofProf ) {
1142                         DWORD dwFlags = cmsFLAGS_SOFTPROOFING;
1143                         if ( gamutWarn ) {
1144                             dwFlags |= cmsFLAGS_GAMUTCHECK;
1145                             cmsSetAlarmCodes(gamutColor.get_red() >> 8, gamutColor.get_green() >> 8, gamutColor.get_blue() >> 8);
1146                         }
1147                         if ( bpc ) {
1148                             dwFlags |= cmsFLAGS_BLACKPOINTCOMPENSATION;
1149                         }
1150 #if defined(cmsFLAGS_PRESERVEBLACK)
1151                         if ( preserveBlack ) {
1152                             dwFlags |= cmsFLAGS_PRESERVEBLACK;
1153                         }
1154 #endif // defined(cmsFLAGS_PRESERVEBLACK)
1155                         item.transf = cmsCreateProofingTransform( ColorProfile::getSRGBProfile(), TYPE_RGBA_8, item.hprof, TYPE_RGBA_8, proofProf, intent, proofIntent, dwFlags );
1156                     } else if ( item.hprof ) {
1157                         item.transf = cmsCreateTransform( ColorProfile::getSRGBProfile(), TYPE_RGBA_8, item.hprof, TYPE_RGBA_8, intent, 0 );
1158                     }
1159                 }
1161                 result = item.transf;
1162                 found = true;
1163             }
1164         }
1165     }
1167     return result;
1172 #endif // ENABLE_LCMS
1174 /*
1175   Local Variables:
1176   mode:c++
1177   c-file-style:"stroustrup"
1178   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1179   indent-tabs-mode:nil
1180   fill-column:99
1181   End:
1182 */
1183 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :