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;
102 }
104 cmsHPROFILE ColorProfile::_NullProf = 0;
106 cmsHPROFILE ColorProfile::getNULLProfile() {
107 if ( !_NullProf ) {
108 _NullProf = cmsCreateNULLProfile();
109 }
110 return _NullProf;
111 }
113 #endif // ENABLE_LCMS
115 /**
116 * Register ColorProfile class and return its type.
117 */
118 GType Inkscape::colorprofile_get_type()
119 {
120 return ColorProfile::getType();
121 }
123 GType ColorProfile::getType()
124 {
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;
140 }
142 /**
143 * ColorProfile vtable initialization.
144 */
145 void ColorProfile::classInit( ColorProfileClass *klass )
146 {
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;
155 }
157 /**
158 * Callback for ColorProfile object initialization.
159 */
160 void ColorProfile::init( ColorProfile *cprof )
161 {
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
175 }
177 /**
178 * Callback: free object
179 */
180 void ColorProfile::release( SPObject *object )
181 {
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
212 }
214 #if ENABLE_LCMS
215 void ColorProfile::_clearProfile()
216 {
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 }
235 }
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 )
242 {
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 }
261 }
263 /**
264 * Callback: set attribute.
265 */
266 void ColorProfile::set( SPObject *object, unsigned key, gchar const *value )
267 {
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 }
384 }
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 )
390 {
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;
418 }
421 #if ENABLE_LCMS
423 struct MapMap {
424 icColorSpaceSignature space;
425 DWORD inForm;
426 };
428 DWORD ColorProfile::_getInputFormat( icColorSpaceSignature space )
429 {
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;
453 }
455 static int getLcmsIntent( guint svgIntent )
456 {
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;
475 }
477 static SPObject* bruteFind( SPDocument* document, gchar const* name )
478 {
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;
495 }
497 cmsHPROFILE Inkscape::colorprofile_get_handle( SPDocument* document, guint* intent, gchar const* name )
498 {
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;
515 }
517 cmsHTRANSFORM ColorProfile::getTransfToSRGB8()
518 {
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;
524 }
526 cmsHTRANSFORM ColorProfile::getTransfFromSRGB8()
527 {
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;
533 }
535 cmsHTRANSFORM ColorProfile::getTransfGamutCheck()
536 {
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;
541 }
543 bool ColorProfile::GamutCheck(SPColor color){
544 BYTE outofgamut = 0;
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);
559 }
561 class ProfileInfo
562 {
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 )
580 {
581 _path = path;
582 _name = cmsTakeProductDesc(prof);
583 _profileSpace = cmsGetColorSpace( prof );
584 _profileClass = cmsGetDeviceClass( prof );
585 }
589 static std::vector<ProfileInfo> knownProfiles;
591 std::vector<Glib::ustring> Inkscape::colorprofile_get_display_names()
592 {
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;
602 }
604 std::vector<Glib::ustring> Inkscape::colorprofile_get_softproof_names()
605 {
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;
615 }
617 Glib::ustring Inkscape::get_path_for_profile(Glib::ustring const& name)
618 {
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;
629 }
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;
701 }
703 static bool isIccFile( gchar const *filepath )
704 {
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 #if ENABLE_LCMS
726 if (isIccFile) {
727 cmsHPROFILE prof = cmsOpenProfileFromFile( filepath, "r" );
728 if ( prof ) {
729 icProfileClassSignature profClass = cmsGetDeviceClass(prof);
730 if ( profClass == icSigNamedColorClass ) {
731 isIccFile = false; // Ignore named color profiles for now.
732 }
733 cmsCloseProfile( prof );
734 }
735 }
736 #endif // ENABLE_LCMS
737 }
738 }
739 return isIccFile;
740 }
742 std::list<Glib::ustring> ColorProfile::getProfileFiles()
743 {
744 std::list<Glib::ustring> files;
746 std::list<Glib::ustring> sources = ColorProfile::getBaseProfileDirs();
747 for ( std::list<Glib::ustring>::const_iterator it = sources.begin(); it != sources.end(); ++it ) {
748 if ( g_file_test( it->c_str(), G_FILE_TEST_EXISTS ) && g_file_test( it->c_str(), G_FILE_TEST_IS_DIR ) ) {
749 GError *err = 0;
750 GDir *dir = g_dir_open(it->c_str(), 0, &err);
752 if (dir) {
753 for (gchar const *file = g_dir_read_name(dir); file != NULL; file = g_dir_read_name(dir)) {
754 gchar *filepath = g_build_filename(it->c_str(), file, NULL);
755 if ( g_file_test( filepath, G_FILE_TEST_IS_DIR ) ) {
756 sources.push_back(g_strdup(filepath));
757 } else {
758 if ( isIccFile( filepath ) ) {
759 files.push_back( filepath );
760 }
761 }
763 g_free(filepath);
764 }
765 g_dir_close(dir);
766 dir = 0;
767 } else {
768 gchar *safeDir = Inkscape::IO::sanitizeString(it->c_str());
769 g_warning(_("Color profiles directory (%s) is unavailable."), safeDir);
770 g_free(safeDir);
771 }
772 }
773 }
775 return files;
776 }
778 #if ENABLE_LCMS
779 static void findThings() {
780 std::list<Glib::ustring> files = ColorProfile::getProfileFiles();
782 for ( std::list<Glib::ustring>::const_iterator it = files.begin(); it != files.end(); ++it ) {
783 cmsHPROFILE prof = cmsOpenProfileFromFile( it->c_str(), "r" );
784 if ( prof ) {
785 ProfileInfo info( prof, Glib::filename_to_utf8( it->c_str() ) );
786 cmsCloseProfile( prof );
788 bool sameName = false;
789 for ( std::vector<ProfileInfo>::iterator it = knownProfiles.begin(); it != knownProfiles.end(); ++it ) {
790 if ( it->getName() == info.getName() ) {
791 sameName = true;
792 break;
793 }
794 }
796 if ( !sameName ) {
797 knownProfiles.push_back(info);
798 }
799 }
800 }
801 }
803 int errorHandlerCB(int ErrorCode, const char *ErrorText)
804 {
805 g_message("lcms: Error %d; %s", ErrorCode, ErrorText);
807 return 1;
808 }
810 static bool gamutWarn = false;
811 static Gdk::Color lastGamutColor("#808080");
812 static bool lastBPC = false;
813 #if defined(cmsFLAGS_PRESERVEBLACK)
814 static bool lastPreserveBlack = false;
815 #endif // defined(cmsFLAGS_PRESERVEBLACK)
816 static int lastIntent = INTENT_PERCEPTUAL;
817 static int lastProofIntent = INTENT_PERCEPTUAL;
818 static cmsHTRANSFORM transf = 0;
820 cmsHPROFILE Inkscape::colorprofile_get_system_profile_handle()
821 {
822 static cmsHPROFILE theOne = 0;
823 static Glib::ustring lastURI;
825 static bool init = false;
826 if ( !init ) {
827 cmsSetErrorHandler(errorHandlerCB);
829 findThings();
830 init = true;
831 }
833 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
834 Glib::ustring uri = prefs->getString("/options/displayprofile/uri");
836 if ( !uri.empty() ) {
837 if ( uri != lastURI ) {
838 lastURI.clear();
839 if ( theOne ) {
840 cmsCloseProfile( theOne );
841 }
842 if ( transf ) {
843 cmsDeleteTransform( transf );
844 transf = 0;
845 }
846 theOne = cmsOpenProfileFromFile( uri.data(), "r" );
847 if ( theOne ) {
848 // a display profile must have the proper stuff
849 icColorSpaceSignature space = cmsGetColorSpace(theOne);
850 icProfileClassSignature profClass = cmsGetDeviceClass(theOne);
852 if ( profClass != icSigDisplayClass ) {
853 g_warning("Not a display profile");
854 cmsCloseProfile( theOne );
855 theOne = 0;
856 } else if ( space != icSigRgbData ) {
857 g_warning("Not an RGB profile");
858 cmsCloseProfile( theOne );
859 theOne = 0;
860 } else {
861 lastURI = uri;
862 }
863 }
864 }
865 } else if ( theOne ) {
866 cmsCloseProfile( theOne );
867 theOne = 0;
868 lastURI.clear();
869 if ( transf ) {
870 cmsDeleteTransform( transf );
871 transf = 0;
872 }
873 }
875 return theOne;
876 }
879 cmsHPROFILE Inkscape::colorprofile_get_proof_profile_handle()
880 {
881 static cmsHPROFILE theOne = 0;
882 static Glib::ustring lastURI;
884 static bool init = false;
885 if ( !init ) {
886 cmsSetErrorHandler(errorHandlerCB);
888 findThings();
889 init = true;
890 }
892 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
893 bool which = prefs->getBool( "/options/softproof/enable");
894 Glib::ustring uri = prefs->getString("/options/softproof/uri");
896 if ( which && !uri.empty() ) {
897 if ( lastURI != uri ) {
898 lastURI.clear();
899 if ( theOne ) {
900 cmsCloseProfile( theOne );
901 }
902 if ( transf ) {
903 cmsDeleteTransform( transf );
904 transf = 0;
905 }
906 theOne = cmsOpenProfileFromFile( uri.data(), "r" );
907 if ( theOne ) {
908 // a display profile must have the proper stuff
909 icColorSpaceSignature space = cmsGetColorSpace(theOne);
910 icProfileClassSignature profClass = cmsGetDeviceClass(theOne);
912 (void)space;
913 (void)profClass;
914 /*
915 if ( profClass != icSigDisplayClass ) {
916 g_warning("Not a display profile");
917 cmsCloseProfile( theOne );
918 theOne = 0;
919 } else if ( space != icSigRgbData ) {
920 g_warning("Not an RGB profile");
921 cmsCloseProfile( theOne );
922 theOne = 0;
923 } else {
924 */
925 lastURI = uri;
926 /*
927 }
928 */
929 }
930 }
931 } else if ( theOne ) {
932 cmsCloseProfile( theOne );
933 theOne = 0;
934 lastURI.clear();
935 if ( transf ) {
936 cmsDeleteTransform( transf );
937 transf = 0;
938 }
939 }
941 return theOne;
942 }
944 static void free_transforms();
946 cmsHTRANSFORM Inkscape::colorprofile_get_display_transform()
947 {
948 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
949 bool fromDisplay = prefs->getBool( "/options/displayprofile/from_display");
950 if ( fromDisplay ) {
951 if ( transf ) {
952 cmsDeleteTransform(transf);
953 transf = 0;
954 }
955 return 0;
956 }
958 bool warn = prefs->getBool( "/options/softproof/gamutwarn");
959 int intent = prefs->getIntLimited( "/options/displayprofile/intent", 0, 0, 3 );
960 int proofIntent = prefs->getIntLimited( "/options/softproof/intent", 0, 0, 3 );
961 bool bpc = prefs->getBool( "/options/softproof/bpc");
962 #if defined(cmsFLAGS_PRESERVEBLACK)
963 bool preserveBlack = prefs->getBool( "/options/softproof/preserveblack");
964 #endif //defined(cmsFLAGS_PRESERVEBLACK)
965 Glib::ustring colorStr = prefs->getString("/options/softproof/gamutcolor");
966 Gdk::Color gamutColor( colorStr.empty() ? "#808080" : colorStr );
968 if ( (warn != gamutWarn)
969 || (lastIntent != intent)
970 || (lastProofIntent != proofIntent)
971 || (bpc != lastBPC)
972 #if defined(cmsFLAGS_PRESERVEBLACK)
973 || (preserveBlack != lastPreserveBlack)
974 #endif // defined(cmsFLAGS_PRESERVEBLACK)
975 || (gamutColor != lastGamutColor)
976 ) {
977 gamutWarn = warn;
978 free_transforms();
979 lastIntent = intent;
980 lastProofIntent = proofIntent;
981 lastBPC = bpc;
982 #if defined(cmsFLAGS_PRESERVEBLACK)
983 lastPreserveBlack = preserveBlack;
984 #endif // defined(cmsFLAGS_PRESERVEBLACK)
985 lastGamutColor = gamutColor;
986 }
988 // Fetch these now, as they might clear the transform as a side effect.
989 cmsHPROFILE hprof = Inkscape::colorprofile_get_system_profile_handle();
990 cmsHPROFILE proofProf = hprof ? Inkscape::colorprofile_get_proof_profile_handle() : 0;
992 if ( !transf ) {
993 if ( hprof && proofProf ) {
994 DWORD dwFlags = cmsFLAGS_SOFTPROOFING;
995 if ( gamutWarn ) {
996 dwFlags |= cmsFLAGS_GAMUTCHECK;
997 cmsSetAlarmCodes(gamutColor.get_red() >> 8, gamutColor.get_green() >> 8, gamutColor.get_blue() >> 8);
998 }
999 if ( bpc ) {
1000 dwFlags |= cmsFLAGS_BLACKPOINTCOMPENSATION;
1001 }
1002 #if defined(cmsFLAGS_PRESERVEBLACK)
1003 if ( preserveBlack ) {
1004 dwFlags |= cmsFLAGS_PRESERVEBLACK;
1005 }
1006 #endif // defined(cmsFLAGS_PRESERVEBLACK)
1007 transf = cmsCreateProofingTransform( ColorProfile::getSRGBProfile(), TYPE_RGBA_8, hprof, TYPE_RGBA_8, proofProf, intent, proofIntent, dwFlags );
1008 } else if ( hprof ) {
1009 transf = cmsCreateTransform( ColorProfile::getSRGBProfile(), TYPE_RGBA_8, hprof, TYPE_RGBA_8, intent, 0 );
1010 }
1011 }
1013 return transf;
1014 }
1017 class MemProfile {
1018 public:
1019 MemProfile();
1020 ~MemProfile();
1022 std::string id;
1023 cmsHPROFILE hprof;
1024 cmsHTRANSFORM transf;
1025 };
1027 MemProfile::MemProfile() :
1028 id(),
1029 hprof(0),
1030 transf(0)
1031 {
1032 }
1034 MemProfile::~MemProfile()
1035 {
1036 }
1038 static std::vector< std::vector<MemProfile> > perMonitorProfiles;
1040 void free_transforms()
1041 {
1042 if ( transf ) {
1043 cmsDeleteTransform(transf);
1044 transf = 0;
1045 }
1047 for ( std::vector< std::vector<MemProfile> >::iterator it = perMonitorProfiles.begin(); it != perMonitorProfiles.end(); ++it ) {
1048 for ( std::vector<MemProfile>::iterator it2 = it->begin(); it2 != it->end(); ++it2 ) {
1049 if ( it2->transf ) {
1050 cmsDeleteTransform(it2->transf);
1051 it2->transf = 0;
1052 }
1053 }
1054 }
1055 }
1057 Glib::ustring Inkscape::colorprofile_get_display_id( int screen, int monitor )
1058 {
1059 Glib::ustring id;
1061 if ( screen >= 0 && screen < static_cast<int>(perMonitorProfiles.size()) ) {
1062 std::vector<MemProfile>& row = perMonitorProfiles[screen];
1063 if ( monitor >= 0 && monitor < static_cast<int>(row.size()) ) {
1064 MemProfile& item = row[monitor];
1065 id = item.id;
1066 }
1067 }
1069 return id;
1070 }
1072 Glib::ustring Inkscape::colorprofile_set_display_per( gpointer buf, guint bufLen, int screen, int monitor )
1073 {
1074 Glib::ustring id;
1076 while ( static_cast<int>(perMonitorProfiles.size()) <= screen ) {
1077 std::vector<MemProfile> tmp;
1078 perMonitorProfiles.push_back(tmp);
1079 }
1080 std::vector<MemProfile>& row = perMonitorProfiles[screen];
1081 while ( static_cast<int>(row.size()) <= monitor ) {
1082 MemProfile tmp;
1083 row.push_back(tmp);
1084 }
1085 MemProfile& item = row[monitor];
1087 if ( item.hprof ) {
1088 cmsCloseProfile( item.hprof );
1089 item.hprof = 0;
1090 }
1091 id.clear();
1093 if ( buf && bufLen ) {
1094 id = Digest::hashHex(Digest::HASH_MD5,
1095 reinterpret_cast<unsigned char*>(buf), bufLen);
1097 // Note: if this is not a valid profile, item.hprof will be set to null.
1098 item.hprof = cmsOpenProfileFromMem(buf, bufLen);
1099 }
1100 item.id = id;
1102 return id;
1103 }
1105 cmsHTRANSFORM Inkscape::colorprofile_get_display_per( Glib::ustring const& id )
1106 {
1107 cmsHTRANSFORM result = 0;
1108 if ( id.empty() ) {
1109 return 0;
1110 }
1112 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1113 bool found = false;
1114 for ( std::vector< std::vector<MemProfile> >::iterator it = perMonitorProfiles.begin(); it != perMonitorProfiles.end() && !found; ++it ) {
1115 for ( std::vector<MemProfile>::iterator it2 = it->begin(); it2 != it->end() && !found; ++it2 ) {
1116 if ( id == it2->id ) {
1117 MemProfile& item = *it2;
1119 bool warn = prefs->getBool( "/options/softproof/gamutwarn");
1120 int intent = prefs->getIntLimited( "/options/displayprofile/intent", 0, 0, 3 );
1121 int proofIntent = prefs->getIntLimited( "/options/softproof/intent", 0, 0, 3 );
1122 bool bpc = prefs->getBool( "/options/softproof/bpc");
1123 #if defined(cmsFLAGS_PRESERVEBLACK)
1124 bool preserveBlack = prefs->getBool( "/options/softproof/preserveblack");
1125 #endif //defined(cmsFLAGS_PRESERVEBLACK)
1126 Glib::ustring colorStr = prefs->getString("/options/softproof/gamutcolor");
1127 Gdk::Color gamutColor( colorStr.empty() ? "#808080" : colorStr );
1129 if ( (warn != gamutWarn)
1130 || (lastIntent != intent)
1131 || (lastProofIntent != proofIntent)
1132 || (bpc != lastBPC)
1133 #if defined(cmsFLAGS_PRESERVEBLACK)
1134 || (preserveBlack != lastPreserveBlack)
1135 #endif // defined(cmsFLAGS_PRESERVEBLACK)
1136 || (gamutColor != lastGamutColor)
1137 ) {
1138 gamutWarn = warn;
1139 free_transforms();
1140 lastIntent = intent;
1141 lastProofIntent = proofIntent;
1142 lastBPC = bpc;
1143 #if defined(cmsFLAGS_PRESERVEBLACK)
1144 lastPreserveBlack = preserveBlack;
1145 #endif // defined(cmsFLAGS_PRESERVEBLACK)
1146 lastGamutColor = gamutColor;
1147 }
1149 // Fetch these now, as they might clear the transform as a side effect.
1150 cmsHPROFILE proofProf = item.hprof ? Inkscape::colorprofile_get_proof_profile_handle() : 0;
1152 if ( !item.transf ) {
1153 if ( item.hprof && proofProf ) {
1154 DWORD dwFlags = cmsFLAGS_SOFTPROOFING;
1155 if ( gamutWarn ) {
1156 dwFlags |= cmsFLAGS_GAMUTCHECK;
1157 cmsSetAlarmCodes(gamutColor.get_red() >> 8, gamutColor.get_green() >> 8, gamutColor.get_blue() >> 8);
1158 }
1159 if ( bpc ) {
1160 dwFlags |= cmsFLAGS_BLACKPOINTCOMPENSATION;
1161 }
1162 #if defined(cmsFLAGS_PRESERVEBLACK)
1163 if ( preserveBlack ) {
1164 dwFlags |= cmsFLAGS_PRESERVEBLACK;
1165 }
1166 #endif // defined(cmsFLAGS_PRESERVEBLACK)
1167 item.transf = cmsCreateProofingTransform( ColorProfile::getSRGBProfile(), TYPE_RGBA_8, item.hprof, TYPE_RGBA_8, proofProf, intent, proofIntent, dwFlags );
1168 } else if ( item.hprof ) {
1169 item.transf = cmsCreateTransform( ColorProfile::getSRGBProfile(), TYPE_RGBA_8, item.hprof, TYPE_RGBA_8, intent, 0 );
1170 }
1171 }
1173 result = item.transf;
1174 found = true;
1175 }
1176 }
1177 }
1179 return result;
1180 }
1184 #endif // ENABLE_LCMS
1186 /*
1187 Local Variables:
1188 mode:c++
1189 c-file-style:"stroustrup"
1190 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1191 indent-tabs-mode:nil
1192 fill-column:99
1193 End:
1194 */
1195 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :