Code

Avoid crashing when profile is missing. Addresses main symptom of bug #437927.
[inkscape.git] / src / color-profile.cpp
1 #ifdef HAVE_CONFIG_H
2 # include "config.h"
3 #endif
5 //#define DEBUG_LCMS
7 #include <glib/gstdio.h>
8 #include <sys/fcntl.h>
9 #include <gdkmm/color.h>
11 #ifdef DEBUG_LCMS
12 #include <gtk/gtkmessagedialog.h>
13 #endif // DEBUG_LCMS
15 #include <cstring>
16 #include <string>
18 #ifdef WIN32
19 #ifndef _WIN32_WINDOWS         // Allow use of features specific to Windows 98 or later. Required for correctly including icm.h
20 #define _WIN32_WINDOWS 0x0410
21 #endif
22 #include <windows.h>
23 #endif
25 #include "xml/repr.h"
26 #include "color-profile.h"
27 #include "color-profile-fns.h"
28 #include "attributes.h"
29 #include "inkscape.h"
30 #include "document.h"
31 #include "preferences.h"
33 #include "dom/uri.h"
34 #include "dom/util/digest.h"
36 #ifdef WIN32
37 #include <Icm.h>
38 #endif // WIN32
40 using Inkscape::ColorProfile;
41 using Inkscape::ColorProfileClass;
43 namespace Inkscape
44 {
45 #if ENABLE_LCMS
46 static cmsHPROFILE colorprofile_get_system_profile_handle();
47 static cmsHPROFILE colorprofile_get_proof_profile_handle();
48 #endif // ENABLE_LCMS
49 }
51 #ifdef DEBUG_LCMS
52 extern guint update_in_progress;
53 #define DEBUG_MESSAGE(key, ...) \
54 {\
55     Inkscape::Preferences *prefs = Inkscape::Preferences::get();\
56     bool dump = prefs->getBool(Glib::ustring("/options/scislac/") + #key);\
57     bool dumpD = prefs->getBool(Glib::ustring("/options/scislac/") + #key"D");\
58     bool dumpD2 = prefs->getBool(Glib::ustring("/options/scislac/") + #key"D2");\
59     dumpD &= ( (update_in_progress == 0) || dumpD2 );\
60     if ( dump )\
61     {\
62         g_message( __VA_ARGS__ );\
63 \
64     }\
65     if ( dumpD )\
66     {\
67         GtkWidget *dialog = gtk_message_dialog_new(NULL,\
68                                                    GTK_DIALOG_DESTROY_WITH_PARENT, \
69                                                    GTK_MESSAGE_INFO,    \
70                                                    GTK_BUTTONS_OK,      \
71                                                    __VA_ARGS__          \
72                                                    );\
73         g_signal_connect_swapped(dialog, "response",\
74                                  G_CALLBACK(gtk_widget_destroy),        \
75                                  dialog);                               \
76         gtk_widget_show_all( dialog );\
77     }\
78 }
79 #endif // DEBUG_LCMS
81 static SPObjectClass *cprof_parent_class;
83 #if ENABLE_LCMS
85 cmsHPROFILE ColorProfile::_sRGBProf = 0;
87 cmsHPROFILE ColorProfile::getSRGBProfile() {
88     if ( !_sRGBProf ) {
89         _sRGBProf = cmsCreate_sRGBProfile();
90     }
91     return _sRGBProf;
92 }
94 #endif // ENABLE_LCMS
96 /**
97  * Register ColorProfile class and return its type.
98  */
99 GType Inkscape::colorprofile_get_type()
101     return ColorProfile::getType();
104 GType ColorProfile::getType()
106     static GType type = 0;
107     if (!type) {
108         GTypeInfo info = {
109             sizeof(ColorProfileClass),
110             NULL, NULL,
111             (GClassInitFunc) ColorProfile::classInit,
112             NULL, NULL,
113             sizeof(ColorProfile),
114             16,
115             (GInstanceInitFunc) ColorProfile::init,
116             NULL,   /* value_table */
117         };
118         type = g_type_register_static( SP_TYPE_OBJECT, "ColorProfile", &info, static_cast<GTypeFlags>(0) );
119     }
120     return type;
123 /**
124  * ColorProfile vtable initialization.
125  */
126 void ColorProfile::classInit( ColorProfileClass *klass )
128     SPObjectClass *sp_object_class = reinterpret_cast<SPObjectClass *>(klass);
130     cprof_parent_class = static_cast<SPObjectClass*>(g_type_class_ref(SP_TYPE_OBJECT));
132     sp_object_class->release = ColorProfile::release;
133     sp_object_class->build = ColorProfile::build;
134     sp_object_class->set = ColorProfile::set;
135     sp_object_class->write = ColorProfile::write;
138 /**
139  * Callback for ColorProfile object initialization.
140  */
141 void ColorProfile::init( ColorProfile *cprof )
143     cprof->href = 0;
144     cprof->local = 0;
145     cprof->name = 0;
146     cprof->intentStr = 0;
147     cprof->rendering_intent = Inkscape::RENDERING_INTENT_UNKNOWN;
148 #if ENABLE_LCMS
149     cprof->profHandle = 0;
150     cprof->_profileClass = icSigInputClass;
151     cprof->_profileSpace = icSigRgbData;
152     cprof->_transf = 0;
153     cprof->_revTransf = 0;
154 #endif // ENABLE_LCMS
157 /**
158  * Callback: free object
159  */
160 void ColorProfile::release( SPObject *object )
162     // Unregister ourselves
163     SPDocument* document = SP_OBJECT_DOCUMENT(object);
164     if ( document ) {
165         sp_document_remove_resource (SP_OBJECT_DOCUMENT (object), "iccprofile", SP_OBJECT (object));
166     }
168     ColorProfile *cprof = COLORPROFILE(object);
169     if ( cprof->href ) {
170         g_free( cprof->href );
171         cprof->href = 0;
172     }
174     if ( cprof->local ) {
175         g_free( cprof->local );
176         cprof->local = 0;
177     }
179     if ( cprof->name ) {
180         g_free( cprof->name );
181         cprof->name = 0;
182     }
184     if ( cprof->intentStr ) {
185         g_free( cprof->intentStr );
186         cprof->intentStr = 0;
187     }
189 #if ENABLE_LCMS
190     cprof->_clearProfile();
191 #endif // ENABLE_LCMS
194 #if ENABLE_LCMS
195 void ColorProfile::_clearProfile()
197     _profileSpace = icSigRgbData;
199     if ( _transf ) {
200         cmsDeleteTransform( _transf );
201         _transf = 0;
202     }
203     if ( _revTransf ) {
204         cmsDeleteTransform( _revTransf );
205         _revTransf = 0;
206     }
207     if ( profHandle ) {
208         cmsCloseProfile( profHandle );
209         profHandle = 0;
210     }
212 #endif // ENABLE_LCMS
214 /**
215  * Callback: set attributes from associated repr.
216  */
217 void ColorProfile::build( SPObject *object, SPDocument *document, Inkscape::XML::Node *repr )
219     ColorProfile *cprof = COLORPROFILE(object);
220     g_assert(cprof->href == 0);
221     g_assert(cprof->local == 0);
222     g_assert(cprof->name == 0);
223     g_assert(cprof->intentStr == 0);
225     if (cprof_parent_class->build) {
226         (* cprof_parent_class->build)(object, document, repr);
227     }
228     sp_object_read_attr( object, "xlink:href" );
229     sp_object_read_attr( object, "local" );
230     sp_object_read_attr( object, "name" );
231     sp_object_read_attr( object, "rendering-intent" );
233     // Register
234     if ( document ) {
235         sp_document_add_resource( document, "iccprofile", object );
236     }
239 /**
240  * Callback: set attribute.
241  */
242 void ColorProfile::set( SPObject *object, unsigned key, gchar const *value )
244     ColorProfile *cprof = COLORPROFILE(object);
246     switch (key) {
247         case SP_ATTR_XLINK_HREF:
248             if ( cprof->href ) {
249                 g_free( cprof->href );
250                 cprof->href = 0;
251             }
252             if ( value ) {
253                 cprof->href = g_strdup( value );
254                 if ( *cprof->href ) {
255 #if ENABLE_LCMS
256                     cmsErrorAction( LCMS_ERROR_SHOW );
258                     // TODO open filename and URIs properly
259                     //FILE* fp = fopen_utf8name( filename, "r" );
260                     //LCMSAPI cmsHPROFILE   LCMSEXPORT cmsOpenProfileFromMem(LPVOID MemPtr, DWORD dwSize);
262                     // Try to open relative
263                     SPDocument *doc = SP_OBJECT_DOCUMENT(object);
264                     if (!doc) {
265                         doc = SP_ACTIVE_DOCUMENT;
266                         g_warning("object has no document.  using active");
267                     }
268                     //# 1.  Get complete URI of document
269                     gchar const *docbase = SP_DOCUMENT_URI( doc );
270                     if (!docbase)
271                     {
272                         // Normal for files that have not yet been saved.
273                         docbase = "";
274                     }
275                     //g_message("docbase:%s\n", docbase);
276                     org::w3c::dom::URI docUri(docbase);
277                     //# 2. Get href of icc file.  we don't care if it's rel or abs
278                     org::w3c::dom::URI hrefUri(cprof->href);
279                     //# 3.  Resolve the href according the docBase.  This follows
280                     //      the w3c specs.  All absolute and relative issues are considered
281                     org::w3c::dom::URI cprofUri = docUri.resolve(hrefUri);
282                     gchar* fullname = g_strdup((gchar *)cprofUri.getNativePath().c_str());
283                     cprof->_clearProfile();
284                     cprof->profHandle = cmsOpenProfileFromFile( fullname, "r" );
285                     if ( cprof->profHandle ) {
286                         cprof->_profileSpace = cmsGetColorSpace( cprof->profHandle );
287                         cprof->_profileClass = cmsGetDeviceClass( cprof->profHandle );
288                     }
289 #ifdef DEBUG_LCMS
290                     DEBUG_MESSAGE( lcmsOne, "cmsOpenProfileFromFile( '%s'...) = %p", fullname, (void*)cprof->profHandle );
291 #endif // DEBUG_LCMS
292                     g_free(fullname);
293 #endif // ENABLE_LCMS
294                 }
295             }
296             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
297             break;
299         case SP_ATTR_LOCAL:
300             if ( cprof->local ) {
301                 g_free( cprof->local );
302                 cprof->local = 0;
303             }
304             cprof->local = g_strdup( value );
305             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
306             break;
308         case SP_ATTR_NAME:
309             if ( cprof->name ) {
310                 g_free( cprof->name );
311                 cprof->name = 0;
312             }
313             cprof->name = g_strdup( value );
314 #ifdef DEBUG_LCMS
315             DEBUG_MESSAGE( lcmsTwo, "<color-profile> name set to '%s'", cprof->name );
316 #endif // DEBUG_LCMS
317             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
318             break;
320         case SP_ATTR_RENDERING_INTENT:
321             if ( cprof->intentStr ) {
322                 g_free( cprof->intentStr );
323                 cprof->intentStr = 0;
324             }
325             cprof->intentStr = g_strdup( value );
327             if ( value ) {
328                 if ( strcmp( value, "auto" ) == 0 ) {
329                     cprof->rendering_intent = RENDERING_INTENT_AUTO;
330                 } else if ( strcmp( value, "perceptual" ) == 0 ) {
331                     cprof->rendering_intent = RENDERING_INTENT_PERCEPTUAL;
332                 } else if ( strcmp( value, "relative-colorimetric" ) == 0 ) {
333                     cprof->rendering_intent = RENDERING_INTENT_RELATIVE_COLORIMETRIC;
334                 } else if ( strcmp( value, "saturation" ) == 0 ) {
335                     cprof->rendering_intent = RENDERING_INTENT_SATURATION;
336                 } else if ( strcmp( value, "absolute-colorimetric" ) == 0 ) {
337                     cprof->rendering_intent = RENDERING_INTENT_ABSOLUTE_COLORIMETRIC;
338                 } else {
339                     cprof->rendering_intent = RENDERING_INTENT_UNKNOWN;
340                 }
341             } else {
342                 cprof->rendering_intent = RENDERING_INTENT_UNKNOWN;
343             }
345             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
346             break;
348         default:
349             if (cprof_parent_class->set) {
350                 (* cprof_parent_class->set)(object, key, value);
351             }
352             break;
353     }
357 /**
358  * Callback: write attributes to associated repr.
359  */
360 Inkscape::XML::Node* ColorProfile::write( SPObject *object, Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags )
362     ColorProfile *cprof = COLORPROFILE(object);
364     if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) {
365         repr = xml_doc->createElement("svg:color-profile");
366     }
368     if ( (flags & SP_OBJECT_WRITE_ALL) || cprof->href ) {
369         repr->setAttribute( "xlink:href", cprof->href );
370     }
372     if ( (flags & SP_OBJECT_WRITE_ALL) || cprof->local ) {
373         repr->setAttribute( "local", cprof->local );
374     }
376     if ( (flags & SP_OBJECT_WRITE_ALL) || cprof->name ) {
377         repr->setAttribute( "name", cprof->name );
378     }
380     if ( (flags & SP_OBJECT_WRITE_ALL) || cprof->intentStr ) {
381         repr->setAttribute( "rendering-intent", cprof->intentStr );
382     }
384     if (cprof_parent_class->write) {
385         (* cprof_parent_class->write)(object, xml_doc, repr, flags);
386     }
388     return repr;
392 #if ENABLE_LCMS
394 struct MapMap {
395     icColorSpaceSignature space;
396     DWORD inForm;
397 };
399 DWORD ColorProfile::_getInputFormat( icColorSpaceSignature space )
401     MapMap possible[] = {
402         {icSigXYZData,   TYPE_XYZ_16},
403         {icSigLabData,   TYPE_Lab_16},
404         //icSigLuvData
405         {icSigYCbCrData, TYPE_YCbCr_16},
406         {icSigYxyData,   TYPE_Yxy_16},
407         {icSigRgbData,   TYPE_RGB_16},
408         {icSigGrayData,  TYPE_GRAY_16},
409         {icSigHsvData,   TYPE_HSV_16},
410         {icSigHlsData,   TYPE_HLS_16},
411         {icSigCmykData,  TYPE_CMYK_16},
412         {icSigCmyData,   TYPE_CMY_16},
413     };
415     int index = 0;
416     for ( guint i = 0; i < G_N_ELEMENTS(possible); i++ ) {
417         if ( possible[i].space == space ) {
418             index = i;
419             break;
420         }
421     }
423     return possible[index].inForm;
426 static int getLcmsIntent( guint svgIntent )
428     int intent = INTENT_PERCEPTUAL;
429     switch ( svgIntent ) {
430         case Inkscape::RENDERING_INTENT_RELATIVE_COLORIMETRIC:
431             intent = INTENT_RELATIVE_COLORIMETRIC;
432             break;
433         case Inkscape::RENDERING_INTENT_SATURATION:
434             intent = INTENT_SATURATION;
435             break;
436         case Inkscape::RENDERING_INTENT_ABSOLUTE_COLORIMETRIC:
437             intent = INTENT_ABSOLUTE_COLORIMETRIC;
438             break;
439         case Inkscape::RENDERING_INTENT_PERCEPTUAL:
440         case Inkscape::RENDERING_INTENT_UNKNOWN:
441         case Inkscape::RENDERING_INTENT_AUTO:
442         default:
443             intent = INTENT_PERCEPTUAL;
444     }
445     return intent;
448 static SPObject* bruteFind( SPDocument* document, gchar const* name )
450     SPObject* result = 0;
451     const GSList * current = sp_document_get_resource_list(document, "iccprofile");
452     while ( current && !result ) {
453         if ( IS_COLORPROFILE(current->data) ) {
454             ColorProfile* prof = COLORPROFILE(current->data);
455             if ( prof ) {
456                 if ( prof->name && (strcmp(prof->name, name) == 0) ) {
457                     result = SP_OBJECT(current->data);
458                     break;
459                 }
460             }
461         }
462         current = g_slist_next(current);
463     }
465     return result;
468 cmsHPROFILE Inkscape::colorprofile_get_handle( SPDocument* document, guint* intent, gchar const* name )
470     cmsHPROFILE prof = 0;
472     SPObject* thing = bruteFind( document, name );
473     if ( thing ) {
474         prof = COLORPROFILE(thing)->profHandle;
475     }
477     if ( intent ) {
478         *intent = thing ? COLORPROFILE(thing)->rendering_intent : (guint)RENDERING_INTENT_UNKNOWN;
479     }
481 #ifdef DEBUG_LCMS
482     DEBUG_MESSAGE( lcmsThree, "<color-profile> queried for profile of '%s'. Returning %p with intent of %d", name, prof, (intent? *intent:0) );
483 #endif // DEBUG_LCMS
485     return prof;
488 cmsHTRANSFORM ColorProfile::getTransfToSRGB8()
490     if ( !_transf && profHandle ) {
491         int intent = getLcmsIntent(rendering_intent);
492         _transf = cmsCreateTransform( profHandle, _getInputFormat(_profileSpace), getSRGBProfile(), TYPE_RGBA_8, intent, 0 );
493     }
494     return _transf;
497 cmsHTRANSFORM ColorProfile::getTransfFromSRGB8()
499     if ( !_revTransf && profHandle ) {
500         int intent = getLcmsIntent(rendering_intent);
501         _revTransf = cmsCreateTransform( getSRGBProfile(), TYPE_RGBA_8, profHandle, _getInputFormat(_profileSpace), intent, 0 );
502     }
503     return _revTransf;
507 #include <io/sys.h>
509 class ProfileInfo
511 public:
512     ProfileInfo( cmsHPROFILE, Glib::ustring const & path );
514     Glib::ustring const& getName() {return _name;}
515     Glib::ustring const& getPath() {return _path;}
516     icColorSpaceSignature getSpace() {return _profileSpace;}
517     icProfileClassSignature getClass() {return _profileClass;}
519 private:
520     Glib::ustring _path;
521     Glib::ustring _name;
522     icColorSpaceSignature _profileSpace;
523     icProfileClassSignature _profileClass;
524 };
527 ProfileInfo::ProfileInfo( cmsHPROFILE prof, Glib::ustring const & path )
529     _path = path;
530     _name = cmsTakeProductDesc(prof);
531     _profileSpace = cmsGetColorSpace( prof );
532     _profileClass = cmsGetDeviceClass( prof );
537 static std::vector<ProfileInfo> knownProfiles;
539 std::vector<Glib::ustring> Inkscape::colorprofile_get_display_names()
541     std::vector<Glib::ustring> result;
543     for ( std::vector<ProfileInfo>::iterator it = knownProfiles.begin(); it != knownProfiles.end(); ++it ) {
544         if ( it->getClass() == icSigDisplayClass && it->getSpace() == icSigRgbData ) {
545             result.push_back( it->getName() );
546         }
547     }
549     return result;
552 std::vector<Glib::ustring> Inkscape::colorprofile_get_softproof_names()
554     std::vector<Glib::ustring> result;
556     for ( std::vector<ProfileInfo>::iterator it = knownProfiles.begin(); it != knownProfiles.end(); ++it ) {
557         if ( it->getClass() == icSigOutputClass ) {
558             result.push_back( it->getName() );
559         }
560     }
562     return result;
565 Glib::ustring Inkscape::get_path_for_profile(Glib::ustring const& name)
567     Glib::ustring result;
569     for ( std::vector<ProfileInfo>::iterator it = knownProfiles.begin(); it != knownProfiles.end(); ++it ) {
570         if ( name == it->getName() ) {
571             result = it->getPath();
572             break;
573         }
574     }
576     return result;
578 #endif // ENABLE_LCMS
580 std::list<Glib::ustring> ColorProfile::getProfileDirs() {
581     std::list<Glib::ustring> sources;
583     gchar* base = profile_path("XXX");
584     {
585         gchar* base2 = g_path_get_dirname(base);
586         g_free(base);
587         base = base2;
588         base2 = g_path_get_dirname(base);
589         g_free(base);
590         base = base2;
591     }
593     // first try user's local dir
594     sources.push_back( g_build_filename(g_get_user_data_dir(), "color", "icc", NULL) );
597     const gchar* const * dataDirs = g_get_system_data_dirs();
598     for ( int i = 0; dataDirs[i]; i++ ) {
599         gchar* path = g_build_filename(dataDirs[i], "color", "icc", NULL);
600         sources.push_back(path);
601         g_free(path);
602     }
604     // On OS X:
605     if ( g_file_test("/Library/ColorSync/Profiles", G_FILE_TEST_EXISTS)  && g_file_test("/Library/ColorSync/Profiles", G_FILE_TEST_IS_DIR) ) {
606         sources.push_back("/Library/ColorSync/Profiles");
608         gchar* path = g_build_filename(g_get_home_dir(), "Library", "ColorSync", "Profiles", NULL);
609         if ( g_file_test(path, G_FILE_TEST_EXISTS)  && g_file_test(path, G_FILE_TEST_IS_DIR) ) {
610             sources.push_back(path);
611         }
612         g_free(path);
613     }
616 #ifdef WIN32
617     wchar_t pathBuf[MAX_PATH + 1];
618     pathBuf[0] = 0;
619     DWORD pathSize = sizeof(pathBuf);
620     g_assert(sizeof(wchar_t) == sizeof(gunichar2));
621     if ( GetColorDirectoryW( NULL, pathBuf, &pathSize ) ) {
622         gchar * utf8Path = g_utf16_to_utf8( (gunichar2*)(&pathBuf[0]), -1, NULL, NULL, NULL );
623         if ( !g_utf8_validate(utf8Path, -1, NULL) ) {
624             g_warning( "GetColorDirectoryW() resulted in invalid UTF-8" );
625         } else {
626             sources.push_back(utf8Path);
627         }
628         g_free( utf8Path );
629     }
630 #endif // WIN32
632     return sources;
635 #if ENABLE_LCMS
636 static void findThings() {
637     std::list<Glib::ustring> sources = ColorProfile::getProfileDirs();
639     for ( std::list<Glib::ustring>::const_iterator it = sources.begin(); it != sources.end(); ++it ) {
640         if ( g_file_test( it->c_str(), G_FILE_TEST_EXISTS ) && g_file_test( it->c_str(), G_FILE_TEST_IS_DIR ) ) {
641             GError *err = 0;
642             GDir *dir = g_dir_open(it->c_str(), 0, &err);
644             if (dir) {
645                 for (gchar const *file = g_dir_read_name(dir); file != NULL; file = g_dir_read_name(dir)) {
646                     gchar *filepath = g_build_filename(it->c_str(), file, NULL);
649                     if ( g_file_test( filepath, G_FILE_TEST_IS_DIR ) ) {
650                         sources.push_back(g_strdup(filepath));
651                     } else {
652                         bool isIccFile = false;
653                         struct stat st;
654                         if ( g_stat(filepath, &st) == 0 && (st.st_size > 128) ) {
655                             //0-3 == size
656                             //36-39 == 'acsp' 0x61637370
657                             int fd = g_open( filepath, O_RDONLY, S_IRWXU);
658                             if ( fd != -1 ) {
659                                 guchar scratch[40] = {0};
660                                 size_t len = sizeof(scratch);
662                                 //size_t left = 40;
663                                 ssize_t got = read(fd, scratch, len);
664                                 if ( got != -1 ) {
665                                     size_t calcSize = (scratch[0] << 24) | (scratch[1] << 16) | (scratch[2] << 8) | scratch[3];
666                                     if ( calcSize > 128 && calcSize <= static_cast<size_t>(st.st_size) ) {
667                                         isIccFile = (scratch[36] == 'a') && (scratch[37] == 'c') && (scratch[38] == 's') && (scratch[39] == 'p');
668                                     }
669                                 }
671                                 close(fd);
672                             }
673                         }
675                         if ( isIccFile ) {
676                             cmsHPROFILE prof = cmsOpenProfileFromFile( filepath, "r" );
677                             if ( prof ) {
678                                 ProfileInfo info( prof, Glib::filename_to_utf8( filepath ) );
679                                 cmsCloseProfile( prof );
681                                 bool sameName = false;
682                                 for ( std::vector<ProfileInfo>::iterator it = knownProfiles.begin(); it != knownProfiles.end(); ++it ) {
683                                     if ( it->getName() == info.getName() ) {
684                                         sameName = true;
685                                         break;
686                                     }
687                                 }
689                                 if ( !sameName ) {
690                                     knownProfiles.push_back(info);
691                                 }
692                             }
693                         }
694                     }
696                     g_free(filepath);
697                 }
698             }
699         }
700     }
703 int errorHandlerCB(int ErrorCode, const char *ErrorText)
705     g_message("lcms: Error %d; %s", ErrorCode, ErrorText);
707     return 1;
710 static bool gamutWarn = false;
711 static Gdk::Color lastGamutColor("#808080");
712 static bool lastBPC = false;
713 #if defined(cmsFLAGS_PRESERVEBLACK)
714 static bool lastPreserveBlack = false;
715 #endif // defined(cmsFLAGS_PRESERVEBLACK)
716 static int lastIntent = INTENT_PERCEPTUAL;
717 static int lastProofIntent = INTENT_PERCEPTUAL;
718 static cmsHTRANSFORM transf = 0;
720 cmsHPROFILE Inkscape::colorprofile_get_system_profile_handle()
722     static cmsHPROFILE theOne = 0;
723     static Glib::ustring lastURI;
725     static bool init = false;
726     if ( !init ) {
727         cmsSetErrorHandler(errorHandlerCB);
729         findThings();
730         init = true;
731     }
733     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
734     Glib::ustring uri = prefs->getString("/options/displayprofile/uri");
736     if ( !uri.empty() ) {
737         if ( uri != lastURI ) {
738             lastURI.clear();
739             if ( theOne ) {
740                 cmsCloseProfile( theOne );
741             }
742             if ( transf ) {
743                 cmsDeleteTransform( transf );
744                 transf = 0;
745             }
746             theOne = cmsOpenProfileFromFile( uri.data(), "r" );
747             if ( theOne ) {
748                 // a display profile must have the proper stuff
749                 icColorSpaceSignature space = cmsGetColorSpace(theOne);
750                 icProfileClassSignature profClass = cmsGetDeviceClass(theOne);
752                 if ( profClass != icSigDisplayClass ) {
753                     g_warning("Not a display profile");
754                     cmsCloseProfile( theOne );
755                     theOne = 0;
756                 } else if ( space != icSigRgbData ) {
757                     g_warning("Not an RGB profile");
758                     cmsCloseProfile( theOne );
759                     theOne = 0;
760                 } else {
761                     lastURI = uri;
762                 }
763             }
764         }
765     } else if ( theOne ) {
766         cmsCloseProfile( theOne );
767         theOne = 0;
768         lastURI.clear();
769         if ( transf ) {
770             cmsDeleteTransform( transf );
771             transf = 0;
772         }
773     }
775     return theOne;
779 cmsHPROFILE Inkscape::colorprofile_get_proof_profile_handle()
781     static cmsHPROFILE theOne = 0;
782     static Glib::ustring lastURI;
784     static bool init = false;
785     if ( !init ) {
786         cmsSetErrorHandler(errorHandlerCB);
788         findThings();
789         init = true;
790     }
792     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
793     bool which = prefs->getBool( "/options/softproof/enable");
794     Glib::ustring uri = prefs->getString("/options/softproof/uri");
796     if ( which && !uri.empty() ) {
797         if ( lastURI != uri ) {
798             lastURI.clear();
799             if ( theOne ) {
800                 cmsCloseProfile( theOne );
801             }
802             if ( transf ) {
803                 cmsDeleteTransform( transf );
804                 transf = 0;
805             }
806             theOne = cmsOpenProfileFromFile( uri.data(), "r" );
807             if ( theOne ) {
808                 // a display profile must have the proper stuff
809                 icColorSpaceSignature space = cmsGetColorSpace(theOne);
810                 icProfileClassSignature profClass = cmsGetDeviceClass(theOne);
812                 (void)space;
813                 (void)profClass;
814 /*
815                 if ( profClass != icSigDisplayClass ) {
816                     g_warning("Not a display profile");
817                     cmsCloseProfile( theOne );
818                     theOne = 0;
819                 } else if ( space != icSigRgbData ) {
820                     g_warning("Not an RGB profile");
821                     cmsCloseProfile( theOne );
822                     theOne = 0;
823                 } else {
824 */
825                     lastURI = uri;
826 /*
827                 }
828 */
829             }
830         }
831     } else if ( theOne ) {
832         cmsCloseProfile( theOne );
833         theOne = 0;
834         lastURI.clear();
835         if ( transf ) {
836             cmsDeleteTransform( transf );
837             transf = 0;
838         }
839     }
841     return theOne;
844 static void free_transforms();
846 cmsHTRANSFORM Inkscape::colorprofile_get_display_transform()
848     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
849     bool fromDisplay = prefs->getBool( "/options/displayprofile/from_display");
850     if ( fromDisplay ) {
851         if ( transf ) {
852             cmsDeleteTransform(transf);
853             transf = 0;
854         }
855         return 0;
856     }
858     bool warn = prefs->getBool( "/options/softproof/gamutwarn");
859     int intent = prefs->getIntLimited( "/options/displayprofile/intent", 0, 0, 3 );
860     int proofIntent = prefs->getIntLimited( "/options/softproof/intent", 0, 0, 3 );
861     bool bpc = prefs->getBool( "/options/softproof/bpc");
862 #if defined(cmsFLAGS_PRESERVEBLACK)
863     bool preserveBlack = prefs->getBool( "/options/softproof/preserveblack");
864 #endif //defined(cmsFLAGS_PRESERVEBLACK)
865     Glib::ustring colorStr = prefs->getString("/options/softproof/gamutcolor");
866     Gdk::Color gamutColor( colorStr.empty() ? "#808080" : colorStr );
868     if ( (warn != gamutWarn)
869          || (lastIntent != intent)
870          || (lastProofIntent != proofIntent)
871          || (bpc != lastBPC)
872 #if defined(cmsFLAGS_PRESERVEBLACK)
873          || (preserveBlack != lastPreserveBlack)
874 #endif // defined(cmsFLAGS_PRESERVEBLACK)
875          || (gamutColor != lastGamutColor)
876         ) {
877         gamutWarn = warn;
878         free_transforms();
879         lastIntent = intent;
880         lastProofIntent = proofIntent;
881         lastBPC = bpc;
882 #if defined(cmsFLAGS_PRESERVEBLACK)
883         lastPreserveBlack = preserveBlack;
884 #endif // defined(cmsFLAGS_PRESERVEBLACK)
885         lastGamutColor = gamutColor;
886     }
888     // Fetch these now, as they might clear the transform as a side effect.
889     cmsHPROFILE hprof = Inkscape::colorprofile_get_system_profile_handle();
890     cmsHPROFILE proofProf = hprof ? Inkscape::colorprofile_get_proof_profile_handle() : 0;
892     if ( !transf ) {
893         if ( hprof && proofProf ) {
894             DWORD dwFlags = cmsFLAGS_SOFTPROOFING;
895             if ( gamutWarn ) {
896                 dwFlags |= cmsFLAGS_GAMUTCHECK;
897                 cmsSetAlarmCodes(gamutColor.get_red() >> 8, gamutColor.get_green() >> 8, gamutColor.get_blue() >> 8);
898             }
899             if ( bpc ) {
900                 dwFlags |= cmsFLAGS_BLACKPOINTCOMPENSATION;
901             }
902 #if defined(cmsFLAGS_PRESERVEBLACK)
903             if ( preserveBlack ) {
904                 dwFlags |= cmsFLAGS_PRESERVEBLACK;
905             }
906 #endif // defined(cmsFLAGS_PRESERVEBLACK)
907             transf = cmsCreateProofingTransform( ColorProfile::getSRGBProfile(), TYPE_RGBA_8, hprof, TYPE_RGBA_8, proofProf, intent, proofIntent, dwFlags );
908         } else if ( hprof ) {
909             transf = cmsCreateTransform( ColorProfile::getSRGBProfile(), TYPE_RGBA_8, hprof, TYPE_RGBA_8, intent, 0 );
910         }
911     }
913     return transf;
917 class MemProfile {
918 public:
919     MemProfile();
920     ~MemProfile();
922     std::string id;
923     cmsHPROFILE hprof;
924     cmsHTRANSFORM transf;
925 };
927 MemProfile::MemProfile() :
928     id(),
929     hprof(0),
930     transf(0)
934 MemProfile::~MemProfile()
938 static std::vector< std::vector<MemProfile> > perMonitorProfiles;
940 void free_transforms()
942     if ( transf ) {
943         cmsDeleteTransform(transf);
944         transf = 0;
945     }
947     for ( std::vector< std::vector<MemProfile> >::iterator it = perMonitorProfiles.begin(); it != perMonitorProfiles.end(); ++it ) {
948         for ( std::vector<MemProfile>::iterator it2 = it->begin(); it2 != it->end(); ++it2 ) {
949             if ( it2->transf ) {
950                 cmsDeleteTransform(it2->transf);
951                 it2->transf = 0;
952             }
953         }
954     }
957 Glib::ustring Inkscape::colorprofile_get_display_id( int screen, int monitor )
959     Glib::ustring id;
961     if ( screen >= 0 && screen < static_cast<int>(perMonitorProfiles.size()) ) {
962         std::vector<MemProfile>& row = perMonitorProfiles[screen];
963         if ( monitor >= 0 && monitor < static_cast<int>(row.size()) ) {
964             MemProfile& item = row[monitor];
965             id = item.id;
966         }
967     }
969     return id;
972 Glib::ustring Inkscape::colorprofile_set_display_per( gpointer buf, guint bufLen, int screen, int monitor )
974     Glib::ustring id;
976     while ( static_cast<int>(perMonitorProfiles.size()) <= screen ) {
977         std::vector<MemProfile> tmp;
978         perMonitorProfiles.push_back(tmp);
979     }
980     std::vector<MemProfile>& row = perMonitorProfiles[screen];
981     while ( static_cast<int>(row.size()) <= monitor ) {
982         MemProfile tmp;
983         row.push_back(tmp);
984     }
985     MemProfile& item = row[monitor];
987     if ( item.hprof ) {
988         cmsCloseProfile( item.hprof );
989         item.hprof = 0;
990     }
991     id.clear();
993     if ( buf && bufLen ) {
994         id = Digest::hashHex(Digest::HASH_MD5,
995                    reinterpret_cast<unsigned char*>(buf), bufLen);
997         // Note: if this is not a valid profile, item.hprof will be set to null.
998         item.hprof = cmsOpenProfileFromMem(buf, bufLen);
999     }
1000     item.id = id;
1002     return id;
1005 cmsHTRANSFORM Inkscape::colorprofile_get_display_per( Glib::ustring const& id )
1007     cmsHTRANSFORM result = 0;
1008     if ( id.empty() ) {
1009         return 0;
1010     }
1012     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1013     bool found = false;
1014     for ( std::vector< std::vector<MemProfile> >::iterator it = perMonitorProfiles.begin(); it != perMonitorProfiles.end() && !found; ++it ) {
1015         for ( std::vector<MemProfile>::iterator it2 = it->begin(); it2 != it->end() && !found; ++it2 ) {
1016             if ( id == it2->id ) {
1017                 MemProfile& item = *it2;
1019                 bool warn = prefs->getBool( "/options/softproof/gamutwarn");
1020                 int intent = prefs->getIntLimited( "/options/displayprofile/intent", 0, 0, 3 );
1021                 int proofIntent = prefs->getIntLimited( "/options/softproof/intent", 0, 0, 3 );
1022                 bool bpc = prefs->getBool( "/options/softproof/bpc");
1023 #if defined(cmsFLAGS_PRESERVEBLACK)
1024                 bool preserveBlack = prefs->getBool( "/options/softproof/preserveblack");
1025 #endif //defined(cmsFLAGS_PRESERVEBLACK)
1026                 Glib::ustring colorStr = prefs->getString("/options/softproof/gamutcolor");
1027                 Gdk::Color gamutColor( colorStr.empty() ? "#808080" : colorStr );
1029                 if ( (warn != gamutWarn)
1030                      || (lastIntent != intent)
1031                      || (lastProofIntent != proofIntent)
1032                      || (bpc != lastBPC)
1033 #if defined(cmsFLAGS_PRESERVEBLACK)
1034                      || (preserveBlack != lastPreserveBlack)
1035 #endif // defined(cmsFLAGS_PRESERVEBLACK)
1036                      || (gamutColor != lastGamutColor)
1037                     ) {
1038                     gamutWarn = warn;
1039                     free_transforms();
1040                     lastIntent = intent;
1041                     lastProofIntent = proofIntent;
1042                     lastBPC = bpc;
1043 #if defined(cmsFLAGS_PRESERVEBLACK)
1044                     lastPreserveBlack = preserveBlack;
1045 #endif // defined(cmsFLAGS_PRESERVEBLACK)
1046                     lastGamutColor = gamutColor;
1047                 }
1049                 // Fetch these now, as they might clear the transform as a side effect.
1050                 cmsHPROFILE proofProf = item.hprof ? Inkscape::colorprofile_get_proof_profile_handle() : 0;
1052                 if ( !item.transf ) {
1053                     if ( item.hprof && proofProf ) {
1054                         DWORD dwFlags = cmsFLAGS_SOFTPROOFING;
1055                         if ( gamutWarn ) {
1056                             dwFlags |= cmsFLAGS_GAMUTCHECK;
1057                             cmsSetAlarmCodes(gamutColor.get_red() >> 8, gamutColor.get_green() >> 8, gamutColor.get_blue() >> 8);
1058                         }
1059                         if ( bpc ) {
1060                             dwFlags |= cmsFLAGS_BLACKPOINTCOMPENSATION;
1061                         }
1062 #if defined(cmsFLAGS_PRESERVEBLACK)
1063                         if ( preserveBlack ) {
1064                             dwFlags |= cmsFLAGS_PRESERVEBLACK;
1065                         }
1066 #endif // defined(cmsFLAGS_PRESERVEBLACK)
1067                         item.transf = cmsCreateProofingTransform( ColorProfile::getSRGBProfile(), TYPE_RGBA_8, item.hprof, TYPE_RGBA_8, proofProf, intent, proofIntent, dwFlags );
1068                     } else if ( item.hprof ) {
1069                         item.transf = cmsCreateTransform( ColorProfile::getSRGBProfile(), TYPE_RGBA_8, item.hprof, TYPE_RGBA_8, intent, 0 );
1070                     }
1071                 }
1073                 result = item.transf;
1074                 found = true;
1075             }
1076         }
1077     }
1079     return result;
1084 #endif // ENABLE_LCMS
1086 /*
1087   Local Variables:
1088   mode:c++
1089   c-file-style:"stroustrup"
1090   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1091   indent-tabs-mode:nil
1092   fill-column:99
1093   End:
1094 */
1095 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :