Code

Revert recent refactoring changes by johnce because they break the build, which canno...
[inkscape.git] / src / color-profile.cpp
3 //#define DEBUG_LCMS
5 #include <glib/gstdio.h>
6 #include <sys/fcntl.h>
7 #include <gdkmm/color.h>
9 #ifdef DEBUG_LCMS
10 #include <gtk/gtkmessagedialog.h>
11 #endif // DEBUG_LCMS
13 #include <cstring>
14 #include <string>
15 // #ifdef WIN32
16 // #include <windows.h>
17 // #include <Icm.h>
18 // #endif
19 #include "xml/repr.h"
20 #include "color-profile.h"
21 #include "color-profile-fns.h"
22 #include "attributes.h"
23 #include "inkscape.h"
24 #include "document.h"
25 #include "preferences.h"
27 #include "dom/uri.h"
28 #include "dom/util/digest.h"
31 using Inkscape::ColorProfile;
32 using Inkscape::ColorProfileClass;
34 namespace Inkscape
35 {
36 #if ENABLE_LCMS
37 static cmsHPROFILE colorprofile_get_system_profile_handle();
38 static cmsHPROFILE colorprofile_get_proof_profile_handle();
39 #endif // ENABLE_LCMS
40 }
42 #ifdef DEBUG_LCMS
43 extern guint update_in_progress;
44 #define DEBUG_MESSAGE(key, ...) \
45 {\
46     Inkscape::Preferences *prefs = Inkscape::Preferences::get();\
47     bool dump = prefs->getBool(Glib::ustring("/options/scislac/") + #key);\
48     bool dumpD = prefs->getBool(Glib::ustring("/options/scislac/") + #key"D");\
49     bool dumpD2 = prefs->getBool(Glib::ustring("/options/scislac/") + #key"D2");\
50     dumpD &= ( (update_in_progress == 0) || dumpD2 );\
51     if ( dump )\
52     {\
53         g_message( __VA_ARGS__ );\
54 \
55     }\
56     if ( dumpD )\
57     {\
58         GtkWidget *dialog = gtk_message_dialog_new(NULL,\
59                                                    GTK_DIALOG_DESTROY_WITH_PARENT, \
60                                                    GTK_MESSAGE_INFO,    \
61                                                    GTK_BUTTONS_OK,      \
62                                                    __VA_ARGS__          \
63                                                    );\
64         g_signal_connect_swapped(dialog, "response",\
65                                  G_CALLBACK(gtk_widget_destroy),        \
66                                  dialog);                               \
67         gtk_widget_show_all( dialog );\
68     }\
69 }
70 #endif // DEBUG_LCMS
72 static SPObjectClass *cprof_parent_class;
74 #if ENABLE_LCMS
76 cmsHPROFILE ColorProfile::_sRGBProf = 0;
78 cmsHPROFILE ColorProfile::getSRGBProfile() {
79     if ( !_sRGBProf ) {
80         _sRGBProf = cmsCreate_sRGBProfile();
81     }
82     return _sRGBProf;
83 }
85 #endif // ENABLE_LCMS
87 /**
88  * Register ColorProfile class and return its type.
89  */
90 GType Inkscape::colorprofile_get_type()
91 {
92     return ColorProfile::getType();
93 }
95 GType ColorProfile::getType()
96 {
97     static GType type = 0;
98     if (!type) {
99         GTypeInfo info = {
100             sizeof(ColorProfileClass),
101             NULL, NULL,
102             (GClassInitFunc) ColorProfile::classInit,
103             NULL, NULL,
104             sizeof(ColorProfile),
105             16,
106             (GInstanceInitFunc) ColorProfile::init,
107             NULL,   /* value_table */
108         };
109         type = g_type_register_static( SP_TYPE_OBJECT, "ColorProfile", &info, static_cast<GTypeFlags>(0) );
110     }
111     return type;
114 /**
115  * ColorProfile vtable initialization.
116  */
117 void ColorProfile::classInit( ColorProfileClass *klass )
119     SPObjectClass *sp_object_class = reinterpret_cast<SPObjectClass *>(klass);
121     cprof_parent_class = static_cast<SPObjectClass*>(g_type_class_ref(SP_TYPE_OBJECT));
123     sp_object_class->release = ColorProfile::release;
124     sp_object_class->build = ColorProfile::build;
125     sp_object_class->set = ColorProfile::set;
126     sp_object_class->write = ColorProfile::write;
129 /**
130  * Callback for ColorProfile object initialization.
131  */
132 void ColorProfile::init( ColorProfile *cprof )
134     cprof->href = 0;
135     cprof->local = 0;
136     cprof->name = 0;
137     cprof->intentStr = 0;
138     cprof->rendering_intent = Inkscape::RENDERING_INTENT_UNKNOWN;
139 #if ENABLE_LCMS
140     cprof->profHandle = 0;
141     cprof->_profileClass = icSigInputClass;
142     cprof->_profileSpace = icSigRgbData;
143     cprof->_transf = 0;
144     cprof->_revTransf = 0;
145 #endif // ENABLE_LCMS
148 /**
149  * Callback: free object
150  */
151 void ColorProfile::release( SPObject *object )
153     // Unregister ourselves
154     SPDocument* document = SP_OBJECT_DOCUMENT(object);
155     if ( document ) {
156         sp_document_remove_resource (SP_OBJECT_DOCUMENT (object), "iccprofile", SP_OBJECT (object));
157     }
159     ColorProfile *cprof = COLORPROFILE(object);
160     if ( cprof->href ) {
161         g_free( cprof->href );
162         cprof->href = 0;
163     }
165     if ( cprof->local ) {
166         g_free( cprof->local );
167         cprof->local = 0;
168     }
170     if ( cprof->name ) {
171         g_free( cprof->name );
172         cprof->name = 0;
173     }
175     if ( cprof->intentStr ) {
176         g_free( cprof->intentStr );
177         cprof->intentStr = 0;
178     }
180 #if ENABLE_LCMS
181     cprof->_clearProfile();
182 #endif // ENABLE_LCMS
185 #if ENABLE_LCMS
186 void ColorProfile::_clearProfile()
188     _profileSpace = icSigRgbData;
190     if ( _transf ) {
191         cmsDeleteTransform( _transf );
192         _transf = 0;
193     }
194     if ( _revTransf ) {
195         cmsDeleteTransform( _revTransf );
196         _revTransf = 0;
197     }
198     if ( profHandle ) {
199         cmsCloseProfile( profHandle );
200         profHandle = 0;
201     }
203 #endif // ENABLE_LCMS
205 /**
206  * Callback: set attributes from associated repr.
207  */
208 void ColorProfile::build( SPObject *object, SPDocument *document, Inkscape::XML::Node *repr )
210     ColorProfile *cprof = COLORPROFILE(object);
211     g_assert(cprof->href == 0);
212     g_assert(cprof->local == 0);
213     g_assert(cprof->name == 0);
214     g_assert(cprof->intentStr == 0);
216     if (cprof_parent_class->build) {
217         (* cprof_parent_class->build)(object, document, repr);
218     }
219     sp_object_read_attr( object, "xlink:href" );
220     sp_object_read_attr( object, "local" );
221     sp_object_read_attr( object, "name" );
222     sp_object_read_attr( object, "rendering-intent" );
224     // Register
225     if ( document ) {
226         sp_document_add_resource( document, "iccprofile", object );
227     }
230 /**
231  * Callback: set attribute.
232  */
233 void ColorProfile::set( SPObject *object, unsigned key, gchar const *value )
235     ColorProfile *cprof = COLORPROFILE(object);
237     switch (key) {
238         case SP_ATTR_XLINK_HREF:
239             if ( cprof->href ) {
240                 g_free( cprof->href );
241                 cprof->href = 0;
242             }
243             if ( value ) {
244                 cprof->href = g_strdup( value );
245                 if ( *cprof->href ) {
246 #if ENABLE_LCMS
247                     cmsErrorAction( LCMS_ERROR_SHOW );
249                     // TODO open filename and URIs properly
250                     //FILE* fp = fopen_utf8name( filename, "r" );
251                     //LCMSAPI cmsHPROFILE   LCMSEXPORT cmsOpenProfileFromMem(LPVOID MemPtr, DWORD dwSize);
253                     // Try to open relative
254                     SPDocument *doc = SP_OBJECT_DOCUMENT(object);
255                     if (!doc) {
256                         doc = SP_ACTIVE_DOCUMENT;
257                         g_warning("object has no document.  using active");
258                     }
259                     //# 1.  Get complete URI of document
260                     gchar const *docbase = SP_DOCUMENT_URI( doc );
261                     if (!docbase)
262                     {
263                         // Normal for files that have not yet been saved.
264                         docbase = "";
265                     }
266                     //g_message("docbase:%s\n", docbase);
267                     org::w3c::dom::URI docUri(docbase);
268                     //# 2. Get href of icc file.  we don't care if it's rel or abs
269                     org::w3c::dom::URI hrefUri(cprof->href);
270                     //# 3.  Resolve the href according the docBase.  This follows
271                     //      the w3c specs.  All absolute and relative issues are considered
272                     org::w3c::dom::URI cprofUri = docUri.resolve(hrefUri);
273                     gchar* fullname = g_strdup((gchar *)cprofUri.getNativePath().c_str());
274                     cprof->_clearProfile();
275                     cprof->profHandle = cmsOpenProfileFromFile( fullname, "r" );
276                     if ( cprof->profHandle ) {
277                         cprof->_profileSpace = cmsGetColorSpace( cprof->profHandle );
278                         cprof->_profileClass = cmsGetDeviceClass( cprof->profHandle );
279                     }
280 #ifdef DEBUG_LCMS
281                     DEBUG_MESSAGE( lcmsOne, "cmsOpenProfileFromFile( '%s'...) = %p", fullname, (void*)cprof->profHandle );
282 #endif // DEBUG_LCMS
283                     g_free(fullname);
284 #endif // ENABLE_LCMS
285                 }
286             }
287             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
288             break;
290         case SP_ATTR_LOCAL:
291             if ( cprof->local ) {
292                 g_free( cprof->local );
293                 cprof->local = 0;
294             }
295             cprof->local = g_strdup( value );
296             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
297             break;
299         case SP_ATTR_NAME:
300             if ( cprof->name ) {
301                 g_free( cprof->name );
302                 cprof->name = 0;
303             }
304             cprof->name = g_strdup( value );
305 #ifdef DEBUG_LCMS
306             DEBUG_MESSAGE( lcmsTwo, "<color-profile> name set to '%s'", cprof->name );
307 #endif // DEBUG_LCMS
308             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
309             break;
311         case SP_ATTR_RENDERING_INTENT:
312             if ( cprof->intentStr ) {
313                 g_free( cprof->intentStr );
314                 cprof->intentStr = 0;
315             }
316             cprof->intentStr = g_strdup( value );
318             if ( value ) {
319                 if ( strcmp( value, "auto" ) == 0 ) {
320                     cprof->rendering_intent = RENDERING_INTENT_AUTO;
321                 } else if ( strcmp( value, "perceptual" ) == 0 ) {
322                     cprof->rendering_intent = RENDERING_INTENT_PERCEPTUAL;
323                 } else if ( strcmp( value, "relative-colorimetric" ) == 0 ) {
324                     cprof->rendering_intent = RENDERING_INTENT_RELATIVE_COLORIMETRIC;
325                 } else if ( strcmp( value, "saturation" ) == 0 ) {
326                     cprof->rendering_intent = RENDERING_INTENT_SATURATION;
327                 } else if ( strcmp( value, "absolute-colorimetric" ) == 0 ) {
328                     cprof->rendering_intent = RENDERING_INTENT_ABSOLUTE_COLORIMETRIC;
329                 } else {
330                     cprof->rendering_intent = RENDERING_INTENT_UNKNOWN;
331                 }
332             } else {
333                 cprof->rendering_intent = RENDERING_INTENT_UNKNOWN;
334             }
336             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
337             break;
339         default:
340             if (cprof_parent_class->set) {
341                 (* cprof_parent_class->set)(object, key, value);
342             }
343             break;
344     }
348 /**
349  * Callback: write attributes to associated repr.
350  */
351 Inkscape::XML::Node* ColorProfile::write( SPObject *object, Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags )
353     ColorProfile *cprof = COLORPROFILE(object);
355     if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) {
356         repr = xml_doc->createElement("svg:color-profile");
357     }
359     if ( (flags & SP_OBJECT_WRITE_ALL) || cprof->href ) {
360         repr->setAttribute( "xlink:href", cprof->href );
361     }
363     if ( (flags & SP_OBJECT_WRITE_ALL) || cprof->local ) {
364         repr->setAttribute( "local", cprof->local );
365     }
367     if ( (flags & SP_OBJECT_WRITE_ALL) || cprof->name ) {
368         repr->setAttribute( "name", cprof->name );
369     }
371     if ( (flags & SP_OBJECT_WRITE_ALL) || cprof->intentStr ) {
372         repr->setAttribute( "rendering-intent", cprof->intentStr );
373     }
375     if (cprof_parent_class->write) {
376         (* cprof_parent_class->write)(object, xml_doc, repr, flags);
377     }
379     return repr;
383 #if ENABLE_LCMS
385 struct MapMap {
386     icColorSpaceSignature space;
387     DWORD inForm;
388 };
390 DWORD ColorProfile::_getInputFormat( icColorSpaceSignature space )
392     MapMap possible[] = {
393         {icSigXYZData,   TYPE_XYZ_16},
394         {icSigLabData,   TYPE_Lab_16},
395         //icSigLuvData
396         {icSigYCbCrData, TYPE_YCbCr_16},
397         {icSigYxyData,   TYPE_Yxy_16},
398         {icSigRgbData,   TYPE_RGB_16},
399         {icSigGrayData,  TYPE_GRAY_16},
400         {icSigHsvData,   TYPE_HSV_16},
401         {icSigHlsData,   TYPE_HLS_16},
402         {icSigCmykData,  TYPE_CMYK_16},
403         {icSigCmyData,   TYPE_CMY_16},
404     };
406     int index = 0;
407     for ( guint i = 0; i < G_N_ELEMENTS(possible); i++ ) {
408         if ( possible[i].space == space ) {
409             index = i;
410             break;
411         }
412     }
414     return possible[index].inForm;
417 static int getLcmsIntent( guint svgIntent )
419     int intent = INTENT_PERCEPTUAL;
420     switch ( svgIntent ) {
421         case Inkscape::RENDERING_INTENT_RELATIVE_COLORIMETRIC:
422             intent = INTENT_RELATIVE_COLORIMETRIC;
423             break;
424         case Inkscape::RENDERING_INTENT_SATURATION:
425             intent = INTENT_SATURATION;
426             break;
427         case Inkscape::RENDERING_INTENT_ABSOLUTE_COLORIMETRIC:
428             intent = INTENT_ABSOLUTE_COLORIMETRIC;
429             break;
430         case Inkscape::RENDERING_INTENT_PERCEPTUAL:
431         case Inkscape::RENDERING_INTENT_UNKNOWN:
432         case Inkscape::RENDERING_INTENT_AUTO:
433         default:
434             intent = INTENT_PERCEPTUAL;
435     }
436     return intent;
439 static SPObject* bruteFind( SPDocument* document, gchar const* name )
441     SPObject* result = 0;
442     const GSList * current = sp_document_get_resource_list(document, "iccprofile");
443     while ( current && !result ) {
444         if ( IS_COLORPROFILE(current->data) ) {
445             ColorProfile* prof = COLORPROFILE(current->data);
446             if ( prof ) {
447                 if ( prof->name && (strcmp(prof->name, name) == 0) ) {
448                     result = SP_OBJECT(current->data);
449                     break;
450                 }
451             }
452         }
453         current = g_slist_next(current);
454     }
456     return result;
459 cmsHPROFILE Inkscape::colorprofile_get_handle( SPDocument* document, guint* intent, gchar const* name )
461     cmsHPROFILE prof = 0;
463     SPObject* thing = bruteFind( document, name );
464     if ( thing ) {
465         prof = COLORPROFILE(thing)->profHandle;
466     }
468     if ( intent ) {
469         *intent = thing ? COLORPROFILE(thing)->rendering_intent : (guint)RENDERING_INTENT_UNKNOWN;
470     }
472 #ifdef DEBUG_LCMS
473     DEBUG_MESSAGE( lcmsThree, "<color-profile> queried for profile of '%s'. Returning %p with intent of %d", name, prof, (intent? *intent:0) );
474 #endif // DEBUG_LCMS
476     return prof;
479 cmsHTRANSFORM ColorProfile::getTransfToSRGB8()
481     if ( !_transf ) {
482         int intent = getLcmsIntent(rendering_intent);
483         _transf = cmsCreateTransform( profHandle, _getInputFormat(_profileSpace), getSRGBProfile(), TYPE_RGBA_8, intent, 0 );
484     }
485     return _transf;
488 cmsHTRANSFORM ColorProfile::getTransfFromSRGB8()
490     if ( !_revTransf ) {
491         int intent = getLcmsIntent(rendering_intent);
492         _revTransf = cmsCreateTransform( getSRGBProfile(), TYPE_RGBA_8, profHandle, _getInputFormat(_profileSpace), intent, 0 );
493     }
494     return _revTransf;
498 #include <io/sys.h>
500 class ProfileInfo
502 public:
503     ProfileInfo( cmsHPROFILE, Glib::ustring const & path );
505     Glib::ustring const& getName() {return _name;}
506     Glib::ustring const& getPath() {return _path;}
507     icColorSpaceSignature getSpace() {return _profileSpace;}
508     icProfileClassSignature getClass() {return _profileClass;}
510 private:
511     Glib::ustring _path;
512     Glib::ustring _name;
513     icColorSpaceSignature _profileSpace;
514     icProfileClassSignature _profileClass;
515 };
518 ProfileInfo::ProfileInfo( cmsHPROFILE prof, Glib::ustring const & path )
520     _path = path;
521     _name = cmsTakeProductDesc(prof);
522     _profileSpace = cmsGetColorSpace( prof );
523     _profileClass = cmsGetDeviceClass( prof );
528 static std::vector<ProfileInfo> knownProfiles;
530 std::vector<Glib::ustring> Inkscape::colorprofile_get_display_names()
532     std::vector<Glib::ustring> result;
534     for ( std::vector<ProfileInfo>::iterator it = knownProfiles.begin(); it != knownProfiles.end(); ++it ) {
535         if ( it->getClass() == icSigDisplayClass && it->getSpace() == icSigRgbData ) {
536             result.push_back( it->getName() );
537         }
538     }
540     return result;
543 std::vector<Glib::ustring> Inkscape::colorprofile_get_softproof_names()
545     std::vector<Glib::ustring> result;
547     for ( std::vector<ProfileInfo>::iterator it = knownProfiles.begin(); it != knownProfiles.end(); ++it ) {
548         if ( it->getClass() == icSigOutputClass ) {
549             result.push_back( it->getName() );
550         }
551     }
553     return result;
556 Glib::ustring Inkscape::get_path_for_profile(Glib::ustring const& name)
558     Glib::ustring result;
560     for ( std::vector<ProfileInfo>::iterator it = knownProfiles.begin(); it != knownProfiles.end(); ++it ) {
561         if ( name == it->getName() ) {
562             result = it->getPath();
563             break;
564         }
565     }
567     return result;
569 #endif // ENABLE_LCMS
571 std::list<Glib::ustring> ColorProfile::getProfileDirs() {
572     std::list<Glib::ustring> sources;
574     gchar* base = profile_path("XXX");
575     {
576         gchar* base2 = g_path_get_dirname(base);
577         g_free(base);
578         base = base2;
579         base2 = g_path_get_dirname(base);
580         g_free(base);
581         base = base2;
582     }
584     // first try user's local dir
585     sources.push_back( g_build_filename(g_get_user_data_dir(), "color", "icc", NULL) );
588     const gchar* const * dataDirs = g_get_system_data_dirs();
589     for ( int i = 0; dataDirs[i]; i++ ) {
590         gchar* path = g_build_filename(dataDirs[i], "color", "icc", NULL);
591         sources.push_back(path);
592         g_free(path);
593     }
595     // On OS X:
596     if ( g_file_test("/Library/ColorSync/Profiles", G_FILE_TEST_EXISTS)  && g_file_test("/Library/ColorSync/Profiles", G_FILE_TEST_IS_DIR) ) {
597         sources.push_back("/Library/ColorSync/Profiles");
599         gchar* path = g_build_filename(g_get_home_dir(), "Library", "ColorSync", "Profiles", NULL);
600         if ( g_file_test(path, G_FILE_TEST_EXISTS)  && g_file_test(path, G_FILE_TEST_IS_DIR) ) {
601             sources.push_back(path);
602         }
603         g_free(path);
604     }
607 // #ifdef WIN32
608 //     wchar_t pathBuf[MAX_PATH + 1];
609 //     pathBuf[0] = 0;
610 //     DWORD pathSize = sizeof(pathBuf);
611 //     g_assert(sizeof(wchar_t) == sizeof(gunichar2));
612 //     if ( GetColorDirectoryW( NULL, &pathBuf, &pathSize ) ) {
613 //         gchar * utf8Path = g_utf16_to_utf8( (gunichar2*)(&pathBuf[0]), -1, NULL, NULL, NULL );
614 //         if ( !g_utf8_validate(utf8Path, -1, NULL) ) {
615 //             g_warning( "GetColorDirectoryW() resulted in invalid UTF-8" );
616 //         } else {
617 //             sources.pushback(utf8Path);
618 //         }
619 //         g_free( utf8Path );
620 //     }
621 // #endif // WIN32
623     return sources;
626 #if ENABLE_LCMS
627 static void findThings() {
628     std::list<Glib::ustring> sources = ColorProfile::getProfileDirs();
630     for ( std::list<Glib::ustring>::const_iterator it = sources.begin(); it != sources.end(); ++it ) {
631         if ( g_file_test( it->c_str(), G_FILE_TEST_EXISTS ) && g_file_test( it->c_str(), G_FILE_TEST_IS_DIR ) ) {
632             GError *err = 0;
633             GDir *dir = g_dir_open(it->c_str(), 0, &err);
635             if (dir) {
636                 for (gchar const *file = g_dir_read_name(dir); file != NULL; file = g_dir_read_name(dir)) {
637                     gchar *filepath = g_build_filename(it->c_str(), file, NULL);
640                     if ( g_file_test( filepath, G_FILE_TEST_IS_DIR ) ) {
641                         sources.push_back(g_strdup(filepath));
642                     } else {
643                         bool isIccFile = false;
644                         struct stat st;
645                         if ( g_stat(filepath, &st) == 0 && (st.st_size > 128) ) {
646                             //0-3 == size
647                             //36-39 == 'acsp' 0x61637370
648                             int fd = g_open( filepath, O_RDONLY, S_IRWXU);
649                             if ( fd != -1 ) {
650                                 guchar scratch[40] = {0};
651                                 size_t len = sizeof(scratch);
653                                 //size_t left = 40;
654                                 ssize_t got = read(fd, scratch, len);
655                                 if ( got != -1 ) {
656                                     size_t calcSize = (scratch[0] << 24) | (scratch[1] << 16) | (scratch[2] << 8) | scratch[3];
657                                     if ( calcSize > 128 && calcSize <= static_cast<size_t>(st.st_size) ) {
658                                         isIccFile = (scratch[36] == 'a') && (scratch[37] == 'c') && (scratch[38] == 's') && (scratch[39] == 'p');
659                                     }
660                                 }
662                                 close(fd);
663                             }
664                         }
666                         if ( isIccFile ) {
667                             cmsHPROFILE prof = cmsOpenProfileFromFile( filepath, "r" );
668                             if ( prof ) {
669                                 ProfileInfo info( prof, Glib::filename_to_utf8( filepath ) );
670                                 cmsCloseProfile( prof );
672                                 bool sameName = false;
673                                 for ( std::vector<ProfileInfo>::iterator it = knownProfiles.begin(); it != knownProfiles.end(); ++it ) {
674                                     if ( it->getName() == info.getName() ) {
675                                         sameName = true;
676                                         break;
677                                     }
678                                 }
680                                 if ( !sameName ) {
681                                     knownProfiles.push_back(info);
682                                 }
683                             }
684                         }
685                     }
687                     g_free(filepath);
688                 }
689             }
690         }
691     }
694 int errorHandlerCB(int ErrorCode, const char *ErrorText)
696     g_message("lcms: Error %d; %s", ErrorCode, ErrorText);
698     return 1;
701 static bool gamutWarn = false;
702 static Gdk::Color lastGamutColor("#808080");
703 static bool lastBPC = false;
704 #if defined(cmsFLAGS_PRESERVEBLACK)
705 static bool lastPreserveBlack = false;
706 #endif // defined(cmsFLAGS_PRESERVEBLACK)
707 static int lastIntent = INTENT_PERCEPTUAL;
708 static int lastProofIntent = INTENT_PERCEPTUAL;
709 static cmsHTRANSFORM transf = 0;
711 cmsHPROFILE Inkscape::colorprofile_get_system_profile_handle()
713     static cmsHPROFILE theOne = 0;
714     static Glib::ustring lastURI;
716     static bool init = false;
717     if ( !init ) {
718         cmsSetErrorHandler(errorHandlerCB);
720         findThings();
721         init = true;
722     }
724     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
725     Glib::ustring uri = prefs->getString("/options/displayprofile/uri");
727     if ( !uri.empty() ) {
728         if ( uri != lastURI ) {
729             lastURI.clear();
730             if ( theOne ) {
731                 cmsCloseProfile( theOne );
732             }
733             if ( transf ) {
734                 cmsDeleteTransform( transf );
735                 transf = 0;
736             }
737             theOne = cmsOpenProfileFromFile( uri.data(), "r" );
738             if ( theOne ) {
739                 // a display profile must have the proper stuff
740                 icColorSpaceSignature space = cmsGetColorSpace(theOne);
741                 icProfileClassSignature profClass = cmsGetDeviceClass(theOne);
743                 if ( profClass != icSigDisplayClass ) {
744                     g_warning("Not a display profile");
745                     cmsCloseProfile( theOne );
746                     theOne = 0;
747                 } else if ( space != icSigRgbData ) {
748                     g_warning("Not an RGB profile");
749                     cmsCloseProfile( theOne );
750                     theOne = 0;
751                 } else {
752                     lastURI = uri;
753                 }
754             }
755         }
756     } else if ( theOne ) {
757         cmsCloseProfile( theOne );
758         theOne = 0;
759         lastURI.clear();
760         if ( transf ) {
761             cmsDeleteTransform( transf );
762             transf = 0;
763         }
764     }
766     return theOne;
770 cmsHPROFILE Inkscape::colorprofile_get_proof_profile_handle()
772     static cmsHPROFILE theOne = 0;
773     static Glib::ustring lastURI;
775     static bool init = false;
776     if ( !init ) {
777         cmsSetErrorHandler(errorHandlerCB);
779         findThings();
780         init = true;
781     }
783     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
784     bool which = prefs->getBool( "/options/softproof/enable");
785     Glib::ustring uri = prefs->getString("/options/softproof/uri");
787     if ( which && !uri.empty() ) {
788         if ( lastURI != uri ) {
789             lastURI.clear();
790             if ( theOne ) {
791                 cmsCloseProfile( theOne );
792             }
793             if ( transf ) {
794                 cmsDeleteTransform( transf );
795                 transf = 0;
796             }
797             theOne = cmsOpenProfileFromFile( uri.data(), "r" );
798             if ( theOne ) {
799                 // a display profile must have the proper stuff
800                 icColorSpaceSignature space = cmsGetColorSpace(theOne);
801                 icProfileClassSignature profClass = cmsGetDeviceClass(theOne);
803                 (void)space;
804                 (void)profClass;
805 /*
806                 if ( profClass != icSigDisplayClass ) {
807                     g_warning("Not a display profile");
808                     cmsCloseProfile( theOne );
809                     theOne = 0;
810                 } else if ( space != icSigRgbData ) {
811                     g_warning("Not an RGB profile");
812                     cmsCloseProfile( theOne );
813                     theOne = 0;
814                 } else {
815 */
816                     lastURI = uri;
817 /*
818                 }
819 */
820             }
821         }
822     } else if ( theOne ) {
823         cmsCloseProfile( theOne );
824         theOne = 0;
825         lastURI.clear();
826         if ( transf ) {
827             cmsDeleteTransform( transf );
828             transf = 0;
829         }
830     }
832     return theOne;
835 static void free_transforms();
837 cmsHTRANSFORM Inkscape::colorprofile_get_display_transform()
839     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
840     bool fromDisplay = prefs->getBool( "/options/displayprofile/from_display");
841     if ( fromDisplay ) {
842         if ( transf ) {
843             cmsDeleteTransform(transf);
844             transf = 0;
845         }
846         return 0;
847     }
849     bool warn = prefs->getBool( "/options/softproof/gamutwarn");
850     int intent = prefs->getIntLimited( "/options/displayprofile/intent", 0, 0, 3 );
851     int proofIntent = prefs->getIntLimited( "/options/softproof/intent", 0, 0, 3 );
852     bool bpc = prefs->getBool( "/options/softproof/bpc");
853 #if defined(cmsFLAGS_PRESERVEBLACK)
854     bool preserveBlack = prefs->getBool( "/options/softproof/preserveblack");
855 #endif //defined(cmsFLAGS_PRESERVEBLACK)
856     Glib::ustring colorStr = prefs->getString("/options/softproof/gamutcolor");
857     Gdk::Color gamutColor( colorStr.empty() ? "#808080" : colorStr );
859     if ( (warn != gamutWarn)
860          || (lastIntent != intent)
861          || (lastProofIntent != proofIntent)
862          || (bpc != lastBPC)
863 #if defined(cmsFLAGS_PRESERVEBLACK)
864          || (preserveBlack != lastPreserveBlack)
865 #endif // defined(cmsFLAGS_PRESERVEBLACK)
866          || (gamutColor != lastGamutColor)
867         ) {
868         gamutWarn = warn;
869         free_transforms();
870         lastIntent = intent;
871         lastProofIntent = proofIntent;
872         lastBPC = bpc;
873 #if defined(cmsFLAGS_PRESERVEBLACK)
874         lastPreserveBlack = preserveBlack;
875 #endif // defined(cmsFLAGS_PRESERVEBLACK)
876         lastGamutColor = gamutColor;
877     }
879     // Fetch these now, as they might clear the transform as a side effect.
880     cmsHPROFILE hprof = Inkscape::colorprofile_get_system_profile_handle();
881     cmsHPROFILE proofProf = hprof ? Inkscape::colorprofile_get_proof_profile_handle() : 0;
883     if ( !transf ) {
884         if ( hprof && proofProf ) {
885             DWORD dwFlags = cmsFLAGS_SOFTPROOFING;
886             if ( gamutWarn ) {
887                 dwFlags |= cmsFLAGS_GAMUTCHECK;
888                 cmsSetAlarmCodes(gamutColor.get_red() >> 8, gamutColor.get_green() >> 8, gamutColor.get_blue() >> 8);
889             }
890             if ( bpc ) {
891                 dwFlags |= cmsFLAGS_BLACKPOINTCOMPENSATION;
892             }
893 #if defined(cmsFLAGS_PRESERVEBLACK)
894             if ( preserveBlack ) {
895                 dwFlags |= cmsFLAGS_PRESERVEBLACK;
896             }
897 #endif // defined(cmsFLAGS_PRESERVEBLACK)
898             transf = cmsCreateProofingTransform( ColorProfile::getSRGBProfile(), TYPE_RGBA_8, hprof, TYPE_RGBA_8, proofProf, intent, proofIntent, dwFlags );
899         } else if ( hprof ) {
900             transf = cmsCreateTransform( ColorProfile::getSRGBProfile(), TYPE_RGBA_8, hprof, TYPE_RGBA_8, intent, 0 );
901         }
902     }
904     return transf;
908 class MemProfile {
909 public:
910     MemProfile();
911     ~MemProfile();
913     std::string id;
914     cmsHPROFILE hprof;
915     cmsHTRANSFORM transf;
916 };
918 MemProfile::MemProfile() :
919     id(),
920     hprof(0),
921     transf(0)
925 MemProfile::~MemProfile()
929 static std::vector< std::vector<MemProfile> > perMonitorProfiles;
931 void free_transforms()
933     if ( transf ) {
934         cmsDeleteTransform(transf);
935         transf = 0;
936     }
938     for ( std::vector< std::vector<MemProfile> >::iterator it = perMonitorProfiles.begin(); it != perMonitorProfiles.end(); ++it ) {
939         for ( std::vector<MemProfile>::iterator it2 = it->begin(); it2 != it->end(); ++it2 ) {
940             if ( it2->transf ) {
941                 cmsDeleteTransform(it2->transf);
942                 it2->transf = 0;
943             }
944         }
945     }
948 Glib::ustring Inkscape::colorprofile_get_display_id( int screen, int monitor )
950     Glib::ustring id;
952     if ( screen >= 0 && screen < static_cast<int>(perMonitorProfiles.size()) ) {
953         std::vector<MemProfile>& row = perMonitorProfiles[screen];
954         if ( monitor >= 0 && monitor < static_cast<int>(row.size()) ) {
955             MemProfile& item = row[monitor];
956             id = item.id;
957         }
958     }
960     return id;
963 Glib::ustring Inkscape::colorprofile_set_display_per( gpointer buf, guint bufLen, int screen, int monitor )
965     Glib::ustring id;
967     while ( static_cast<int>(perMonitorProfiles.size()) <= screen ) {
968         std::vector<MemProfile> tmp;
969         perMonitorProfiles.push_back(tmp);
970     }
971     std::vector<MemProfile>& row = perMonitorProfiles[screen];
972     while ( static_cast<int>(row.size()) <= monitor ) {
973         MemProfile tmp;
974         row.push_back(tmp);
975     }
976     MemProfile& item = row[monitor];
978     if ( item.hprof ) {
979         cmsCloseProfile( item.hprof );
980         item.hprof = 0;
981     }
982     id.clear();
984     if ( buf && bufLen ) {
985         id = Digest::hashHex(Digest::HASH_MD5,
986                    reinterpret_cast<unsigned char*>(buf), bufLen);
988         // Note: if this is not a valid profile, item.hprof will be set to null.
989         item.hprof = cmsOpenProfileFromMem(buf, bufLen);
990     }
991     item.id = id;
993     return id;
996 cmsHTRANSFORM Inkscape::colorprofile_get_display_per( Glib::ustring const& id )
998     cmsHTRANSFORM result = 0;
999     if ( id.empty() ) {
1000         return 0;
1001     }
1003     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1004     bool found = false;
1005     for ( std::vector< std::vector<MemProfile> >::iterator it = perMonitorProfiles.begin(); it != perMonitorProfiles.end() && !found; ++it ) {
1006         for ( std::vector<MemProfile>::iterator it2 = it->begin(); it2 != it->end() && !found; ++it2 ) {
1007             if ( id == it2->id ) {
1008                 MemProfile& item = *it2;
1010                 bool warn = prefs->getBool( "/options/softproof/gamutwarn");
1011                 int intent = prefs->getIntLimited( "/options/displayprofile/intent", 0, 0, 3 );
1012                 int proofIntent = prefs->getIntLimited( "/options/softproof/intent", 0, 0, 3 );
1013                 bool bpc = prefs->getBool( "/options/softproof/bpc");
1014 #if defined(cmsFLAGS_PRESERVEBLACK)
1015                 bool preserveBlack = prefs->getBool( "/options/softproof/preserveblack");
1016 #endif //defined(cmsFLAGS_PRESERVEBLACK)
1017                 Glib::ustring colorStr = prefs->getString("/options/softproof/gamutcolor");
1018                 Gdk::Color gamutColor( colorStr.empty() ? "#808080" : colorStr );
1020                 if ( (warn != gamutWarn)
1021                      || (lastIntent != intent)
1022                      || (lastProofIntent != proofIntent)
1023                      || (bpc != lastBPC)
1024 #if defined(cmsFLAGS_PRESERVEBLACK)
1025                      || (preserveBlack != lastPreserveBlack)
1026 #endif // defined(cmsFLAGS_PRESERVEBLACK)
1027                      || (gamutColor != lastGamutColor)
1028                     ) {
1029                     gamutWarn = warn;
1030                     free_transforms();
1031                     lastIntent = intent;
1032                     lastProofIntent = proofIntent;
1033                     lastBPC = bpc;
1034 #if defined(cmsFLAGS_PRESERVEBLACK)
1035                     lastPreserveBlack = preserveBlack;
1036 #endif // defined(cmsFLAGS_PRESERVEBLACK)
1037                     lastGamutColor = gamutColor;
1038                 }
1040                 // Fetch these now, as they might clear the transform as a side effect.
1041                 cmsHPROFILE proofProf = item.hprof ? Inkscape::colorprofile_get_proof_profile_handle() : 0;
1043                 if ( !item.transf ) {
1044                     if ( item.hprof && proofProf ) {
1045                         DWORD dwFlags = cmsFLAGS_SOFTPROOFING;
1046                         if ( gamutWarn ) {
1047                             dwFlags |= cmsFLAGS_GAMUTCHECK;
1048                             cmsSetAlarmCodes(gamutColor.get_red() >> 8, gamutColor.get_green() >> 8, gamutColor.get_blue() >> 8);
1049                         }
1050                         if ( bpc ) {
1051                             dwFlags |= cmsFLAGS_BLACKPOINTCOMPENSATION;
1052                         }
1053 #if defined(cmsFLAGS_PRESERVEBLACK)
1054                         if ( preserveBlack ) {
1055                             dwFlags |= cmsFLAGS_PRESERVEBLACK;
1056                         }
1057 #endif // defined(cmsFLAGS_PRESERVEBLACK)
1058                         item.transf = cmsCreateProofingTransform( ColorProfile::getSRGBProfile(), TYPE_RGBA_8, item.hprof, TYPE_RGBA_8, proofProf, intent, proofIntent, dwFlags );
1059                     } else if ( item.hprof ) {
1060                         item.transf = cmsCreateTransform( ColorProfile::getSRGBProfile(), TYPE_RGBA_8, item.hprof, TYPE_RGBA_8, intent, 0 );
1061                     }
1062                 }
1064                 result = item.transf;
1065                 found = true;
1066             }
1067         }
1068     }
1070     return result;
1075 #endif // ENABLE_LCMS
1077 /*
1078   Local Variables:
1079   mode:c++
1080   c-file-style:"stroustrup"
1081   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1082   indent-tabs-mode:nil
1083   fill-column:99
1084   End:
1085 */
1086 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :