1 #define __SP_FILE_C__
3 /*
4 * File/Print operations
5 *
6 * Authors:
7 * Lauris Kaplinski <lauris@kaplinski.com>
8 * Chema Celorio <chema@celorio.com>
9 * bulia byak <buliabyak@users.sf.net>
10 *
11 * Copyright (C) 1999-2005 Authors
12 * Copyright (C) 2001-2002 Ximian, Inc.
13 * Copyright (C) 2004 David Turner
14 *
15 * Released under GNU GPL, read the file 'COPYING' for more information
16 */
18 /**
19 * Note: This file needs to be cleaned up extensively.
20 * What it probably needs is to have one .h file for
21 * the API, and two or more .cpp files for the implementations.
22 */
24 #ifdef HAVE_CONFIG_H
25 # include "config.h"
26 #endif
28 #include <glib/gmem.h>
29 #include <libnr/nr-pixops.h>
31 #include "document-private.h"
32 #include "selection-chemistry.h"
33 #include "ui/view/view-widget.h"
34 #include "dir-util.h"
35 #include "helper/png-write.h"
36 #include "dialogs/export.h"
37 #include <glibmm/i18n.h>
38 #include "inkscape.h"
39 #include "desktop.h"
40 #include "selection.h"
41 #include "interface.h"
42 #include "style.h"
43 #include "print.h"
44 #include "file.h"
45 #include "message-stack.h"
46 #include "ui/dialog/filedialog.h"
47 #include "prefs-utils.h"
48 #include "path-prefix.h"
50 #include "sp-namedview.h"
51 #include "desktop-handles.h"
53 #include "extension/db.h"
54 #include "extension/input.h"
55 #include "extension/output.h"
56 /* #include "extension/menu.h" */
57 #include "extension/system.h"
59 #include "io/sys.h"
60 #include "application/application.h"
61 #include "application/editor.h"
62 #include "inkscape.h"
63 #include "uri.h"
65 #ifdef WITH_INKBOARD
66 #include "jabber_whiteboard/session-manager.h"
67 #endif
69 /**
70 * 'Current' paths. Used to remember which directory
71 * had the last file accessed.
72 * Static globals are evil. This will be gone soon
73 * as C++ification continues
74 */
75 static gchar *import_path = NULL;
77 //#define INK_DUMP_FILENAME_CONV 1
78 #undef INK_DUMP_FILENAME_CONV
80 //#define INK_DUMP_FOPEN 1
81 #undef INK_DUMP_FOPEN
83 void dump_str(gchar const *str, gchar const *prefix);
84 void dump_ustr(Glib::ustring const &ustr);
87 /*######################
88 ## N E W
89 ######################*/
91 /**
92 * Create a blank document and add it to the desktop
93 */
94 SPDesktop*
95 sp_file_new(gchar const *templ)
96 {
97 SPDocument *doc = sp_document_new(templ, TRUE, true);
98 g_return_val_if_fail(doc != NULL, NULL);
100 SPDesktop *dt;
101 if (Inkscape::NSApplication::Application::getNewGui())
102 {
103 dt = Inkscape::NSApplication::Editor::createDesktop (doc);
104 } else {
105 SPViewWidget *dtw = sp_desktop_widget_new(sp_document_namedview(doc, NULL));
106 g_return_val_if_fail(dtw != NULL, NULL);
107 sp_document_unref(doc);
109 sp_create_window(dtw, TRUE);
110 dt = static_cast<SPDesktop*>(dtw->view);
111 sp_namedview_window_from_document(dt);
112 }
113 return dt;
114 }
116 SPDesktop*
117 sp_file_new_default()
118 {
119 std::list<gchar *> sources;
120 sources.push_back( profile_path("templates") ); // first try user's local dir
121 sources.push_back( g_strdup(INKSCAPE_TEMPLATESDIR) ); // then the system templates dir
123 while (!sources.empty()) {
124 gchar *dirname = sources.front();
125 if ( Inkscape::IO::file_test( dirname, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR) ) ) {
127 // TRANSLATORS: default.svg is localizable - this is the name of the default document
128 // template. This way you can localize the default pagesize, translate the name of
129 // the default layer, etc. If you wish to localize this file, please create a
130 // localized share/templates/default.xx.svg file, where xx is your language code.
131 char *default_template = g_build_filename(dirname, _("default.svg"), NULL);
132 if (Inkscape::IO::file_test(default_template, G_FILE_TEST_IS_REGULAR)) {
133 return sp_file_new(default_template);
134 }
135 }
136 g_free(dirname);
137 sources.pop_front();
138 }
140 return sp_file_new(NULL);
141 }
144 /*######################
145 ## D E L E T E
146 ######################*/
148 /**
149 * Perform document closures preceding an exit()
150 */
151 void
152 sp_file_exit()
153 {
154 sp_ui_close_all();
155 // no need to call inkscape_exit here; last document being closed will take care of that
156 }
159 /*######################
160 ## O P E N
161 ######################*/
163 /**
164 * Open a file, add the document to the desktop
165 *
166 * \param replace_empty if true, and the current desktop is empty, this document
167 * will replace the empty one.
168 */
169 bool
170 sp_file_open(gchar const *uri, Inkscape::Extension::Extension *key, bool add_to_recent, bool replace_empty)
171 {
172 SPDocument *doc;
173 try {
174 doc = Inkscape::Extension::open(key, uri);
175 } catch (Inkscape::Extension::Input::no_extension_found &e) {
176 doc = NULL;
177 } catch (Inkscape::Extension::Input::open_failed &e) {
178 doc = NULL;
179 }
181 if (doc) {
182 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
183 SPDocument *existing = desktop ? sp_desktop_document(desktop) : NULL;
185 if (existing && existing->virgin && replace_empty) {
186 // If the current desktop is empty, open the document there
187 sp_document_ensure_up_to_date (doc);
188 desktop->change_document(doc);
189 sp_document_resized_signal_emit (doc, sp_document_width(doc), sp_document_height(doc));
190 } else {
191 if (!Inkscape::NSApplication::Application::getNewGui()) {
192 // create a whole new desktop and window
193 SPViewWidget *dtw = sp_desktop_widget_new(sp_document_namedview(doc, NULL));
194 sp_create_window(dtw, TRUE);
195 desktop = static_cast<SPDesktop*>(dtw->view);
196 } else {
197 desktop = Inkscape::NSApplication::Editor::createDesktop (doc);
198 }
199 }
201 doc->virgin = FALSE;
202 // everyone who cares now has a reference, get rid of ours
203 sp_document_unref(doc);
204 // resize the window to match the document properties
205 // (this may be redundant for new windows... if so, move to the "virgin"
206 // section above)
207 sp_namedview_window_from_document(desktop);
209 if (add_to_recent) {
210 prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
211 }
213 return TRUE;
214 } else {
215 gchar *safeUri = Inkscape::IO::sanitizeString(uri);
216 gchar *text = g_strdup_printf(_("Failed to load the requested file %s"), safeUri);
217 sp_ui_error_dialog(text);
218 g_free(text);
219 g_free(safeUri);
220 return FALSE;
221 }
222 }
224 /**
225 * Handle prompting user for "do you want to revert"? Revert on "OK"
226 */
227 void
228 sp_file_revert_dialog()
229 {
230 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
231 g_assert(desktop != NULL);
233 SPDocument *doc = sp_desktop_document(desktop);
234 g_assert(doc != NULL);
236 Inkscape::XML::Node *repr = sp_document_repr_root(doc);
237 g_assert(repr != NULL);
239 gchar const *uri = doc->uri;
240 if (!uri) {
241 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved yet. Cannot revert."));
242 return;
243 }
245 bool do_revert = true;
246 if (repr->attribute("sodipodi:modified") != NULL) {
247 gchar *text = g_strdup_printf(_("Changes will be lost! Are you sure you want to reload document %s?"), uri);
249 bool response = desktop->warnDialog (text);
250 g_free(text);
252 if (!response) {
253 do_revert = false;
254 }
255 }
257 bool reverted;
258 if (do_revert) {
259 // Allow overwriting of current document.
260 doc->virgin = TRUE;
261 reverted = sp_file_open(uri,NULL);
262 } else {
263 reverted = false;
264 }
266 if (reverted) {
267 desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Document reverted."));
268 } else {
269 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not reverted."));
270 }
271 }
273 void dump_str(gchar const *str, gchar const *prefix)
274 {
275 Glib::ustring tmp;
276 tmp = prefix;
277 tmp += " [";
278 size_t const total = strlen(str);
279 for (unsigned i = 0; i < total; i++) {
280 gchar *const tmp2 = g_strdup_printf(" %02x", (0x0ff & str[i]));
281 tmp += tmp2;
282 g_free(tmp2);
283 }
285 tmp += "]";
286 g_message(tmp.c_str());
287 }
289 void dump_ustr(Glib::ustring const &ustr)
290 {
291 char const *cstr = ustr.c_str();
292 char const *data = ustr.data();
293 Glib::ustring::size_type const byteLen = ustr.bytes();
294 Glib::ustring::size_type const dataLen = ustr.length();
295 Glib::ustring::size_type const cstrLen = strlen(cstr);
297 g_message(" size: %lu\n length: %lu\n bytes: %lu\n clen: %lu",
298 gulong(ustr.size()), gulong(dataLen), gulong(byteLen), gulong(cstrLen) );
299 g_message( " ASCII? %s", (ustr.is_ascii() ? "yes":"no") );
300 g_message( " UTF-8? %s", (ustr.validate() ? "yes":"no") );
302 try {
303 Glib::ustring tmp;
304 for (Glib::ustring::size_type i = 0; i < ustr.bytes(); i++) {
305 tmp = " ";
306 if (i < dataLen) {
307 Glib::ustring::value_type val = ustr.at(i);
308 gchar* tmp2 = g_strdup_printf( (((val & 0xff00) == 0) ? " %02x" : "%04x"), val );
309 tmp += tmp2;
310 g_free( tmp2 );
311 } else {
312 tmp += " ";
313 }
315 if (i < byteLen) {
316 int val = (0x0ff & data[i]);
317 gchar *tmp2 = g_strdup_printf(" %02x", val);
318 tmp += tmp2;
319 g_free( tmp2 );
320 if ( val > 32 && val < 127 ) {
321 tmp2 = g_strdup_printf( " '%c'", (gchar)val );
322 tmp += tmp2;
323 g_free( tmp2 );
324 } else {
325 tmp += " . ";
326 }
327 } else {
328 tmp += " ";
329 }
331 if ( i < cstrLen ) {
332 int val = (0x0ff & cstr[i]);
333 gchar* tmp2 = g_strdup_printf(" %02x", val);
334 tmp += tmp2;
335 g_free(tmp2);
336 if ( val > 32 && val < 127 ) {
337 tmp2 = g_strdup_printf(" '%c'", (gchar) val);
338 tmp += tmp2;
339 g_free( tmp2 );
340 } else {
341 tmp += " . ";
342 }
343 } else {
344 tmp += " ";
345 }
347 g_message( tmp.c_str() );
348 }
349 } catch (...) {
350 g_message("XXXXXXXXXXXXXXXXXX Exception" );
351 }
352 g_message("---------------");
353 }
355 static Inkscape::UI::Dialog::FileOpenDialog *openDialogInstance = NULL;
357 /**
358 * Display an file Open selector. Open a document if OK is pressed.
359 * Can select single or multiple files for opening.
360 */
361 void
362 sp_file_open_dialog(gpointer object, gpointer data)
363 {
364 gchar *open_path2 = NULL;
366 gchar *open_path = g_strdup(prefs_get_string_attribute("dialogs.open", "path"));
367 if (open_path != NULL && open_path[0] == '\0') {
368 g_free(open_path);
369 open_path = NULL;
370 }
371 if (open_path && !Inkscape::IO::file_test(open_path, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) {
372 g_free(open_path);
373 open_path = NULL;
374 }
375 if (open_path == NULL)
376 open_path = g_strconcat(g_get_home_dir(), G_DIR_SEPARATOR_S, NULL);
378 if (!openDialogInstance) {
379 openDialogInstance =
380 Inkscape::UI::Dialog::FileOpenDialog::create(
381 (char const *)open_path,
382 Inkscape::UI::Dialog::SVG_TYPES,
383 (char const *)_("Select file to open"));
384 }
385 bool const success = openDialogInstance->show();
386 gchar *fileName = ( success
387 ? g_strdup(openDialogInstance->getFilename())
388 : NULL );
389 Inkscape::Extension::Extension *selection =
390 openDialogInstance->getSelectionType();
391 g_free(open_path);
393 if (!success) return;
395 // Code to check & open iff multiple files.
396 Glib::SListHandle<Glib::ustring> flist=openDialogInstance->getFilenames();
397 GSList *list=flist.data();
399 if(g_slist_length(list)>1)
400 {
401 gchar *fileName=NULL;
403 while(list!=NULL)
404 {
406 #ifdef INK_DUMP_FILENAME_CONV
407 g_message(" FileName: %s",(const char *)list->data);
408 #endif
410 fileName=(gchar *)g_strdup((gchar *)list->data);
412 if (fileName && !g_file_test(fileName,G_FILE_TEST_IS_DIR)) {
413 gsize bytesRead = 0;
414 gsize bytesWritten = 0;
415 GError *error = NULL;
416 #ifdef INK_DUMP_FILENAME_CONV
417 dump_str( fileName, "A file pre is " );
418 #endif
419 gchar *newFileName = g_filename_to_utf8(fileName,
420 -1,
421 &bytesRead,
422 &bytesWritten,
423 &error);
424 if ( newFileName != NULL ) {
425 g_free(fileName);
426 fileName = newFileName;
427 #ifdef INK_DUMP_FILENAME_CONV
428 dump_str( fileName, "A file post is " );
429 #endif
430 } else {
431 // TODO: bulia, please look over
432 g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
433 }
435 #ifdef INK_DUMP_FILENAME_CONV
436 g_message("Opening File %s\n",fileName);
437 #endif
439 sp_file_open(fileName, selection);
440 g_free(fileName);
441 }
442 else
443 {
444 g_message("Cannot Open Directory %s\n",fileName);
445 }
447 list=list->next;
448 }
450 return;
451 }
454 if (fileName) {
455 gsize bytesRead = 0;
456 gsize bytesWritten = 0;
457 GError *error = NULL;
458 #ifdef INK_DUMP_FILENAME_CONV
459 dump_str( fileName, "A file pre is " );
460 #endif
461 gchar *newFileName = g_filename_to_utf8(fileName,
462 -1,
463 &bytesRead,
464 &bytesWritten,
465 &error);
466 if ( newFileName != NULL ) {
467 g_free(fileName);
468 fileName = newFileName;
469 #ifdef INK_DUMP_FILENAME_CONV
470 dump_str( fileName, "A file post is " );
471 #endif
472 } else {
473 // TODO: bulia, please look over
474 g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
475 }
478 if ( !g_utf8_validate(fileName, -1, NULL) ) {
479 // TODO: bulia, please look over
480 g_warning( "INPUT FILENAME IS NOT UTF-8" );
481 }
484 open_path = g_dirname(fileName);
485 open_path2 = g_strconcat(open_path, G_DIR_SEPARATOR_S, NULL);
486 prefs_set_string_attribute("dialogs.open", "path", open_path2);
487 g_free(open_path);
488 g_free(open_path2);
490 sp_file_open(fileName, selection);
491 g_free(fileName);
492 }
494 return;
495 }
498 /*######################
499 ## V A C U U M
500 ######################*/
502 /**
503 * Remove unreferenced defs from the defs section of the document.
504 */
507 void
508 sp_file_vacuum()
509 {
510 SPDocument *doc = SP_ACTIVE_DOCUMENT;
512 unsigned int diff = vacuum_document (doc);
514 sp_document_done(doc, SP_VERB_FILE_VACUUM,
515 /* TODO: annotate */ "file.cpp:515");
517 SPDesktop *dt = SP_ACTIVE_DESKTOP;
518 if (diff > 0) {
519 dt->messageStack()->flashF(Inkscape::NORMAL_MESSAGE,
520 ngettext("Removed <b>%i</b> unused definition in <defs>.",
521 "Removed <b>%i</b> unused definitions in <defs>.",
522 diff),
523 diff);
524 } else {
525 dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("No unused definitions in <defs>."));
526 }
527 }
531 /*######################
532 ## S A V E
533 ######################*/
535 /**
536 * This 'save' function called by the others below
537 */
538 static bool
539 file_save(SPDocument *doc, gchar const *uri, Inkscape::Extension::Extension *key, bool saveas)
540 {
541 if (!doc || !uri) //Safety check
542 return FALSE;
544 try {
545 Inkscape::Extension::save(key, doc, uri,
546 saveas && prefs_get_int_attribute("dialogs.save_as", "append_extension", 1),
547 saveas, TRUE); // save officially, with inkscape: attributes set
548 } catch (Inkscape::Extension::Output::no_extension_found &e) {
549 gchar *safeUri = Inkscape::IO::sanitizeString(uri);
550 gchar *text = g_strdup_printf(_("No Inkscape extension found to save document (%s). This may have been caused by an unknown filename extension."), safeUri);
551 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved."));
552 sp_ui_error_dialog(text);
553 g_free(text);
554 g_free(safeUri);
555 return FALSE;
556 } catch (Inkscape::Extension::Output::save_failed &e) {
557 gchar *safeUri = Inkscape::IO::sanitizeString(uri);
558 gchar *text = g_strdup_printf(_("File %s could not be saved."), safeUri);
559 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved."));
560 sp_ui_error_dialog(text);
561 g_free(text);
562 g_free(safeUri);
563 return FALSE;
564 } catch (Inkscape::Extension::Output::no_overwrite &e) {
565 return sp_file_save_dialog(doc);
566 }
568 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Document saved."));
569 return TRUE;
570 }
572 static Inkscape::UI::Dialog::FileSaveDialog *saveDialogInstance = NULL;
574 /**
575 * Display a SaveAs dialog. Save the document if OK pressed.
576 */
577 gboolean
578 sp_file_save_dialog(SPDocument *doc)
579 {
580 Inkscape::XML::Node *repr = sp_document_repr_root(doc);
581 gchar const *default_extension = NULL;
582 gchar *save_loc;
583 Inkscape::Extension::Output *extension;
584 gchar *save_path = NULL;
586 default_extension = repr->attribute("inkscape:output_extension");
587 if (default_extension == NULL) {
588 default_extension = prefs_get_string_attribute("dialogs.save_as", "default");
589 }
590 //g_warning("%s: extension name: '%s'", __FUNCTION__, default_extension);
592 if (doc->uri == NULL) {
593 int i = 1;
594 char const *filename_extension;
595 char *temp_filename;
597 extension = dynamic_cast<Inkscape::Extension::Output *>(Inkscape::Extension::db.get(default_extension));
598 //g_warning("%s: extension ptr: 0x%x", __FUNCTION__, (unsigned int)extension);
599 if (extension == NULL) {
600 filename_extension = ".svg";
601 } else {
602 filename_extension = extension->get_extension();
603 }
605 save_path = g_strdup(prefs_get_string_attribute("dialogs.save_as", "path"));
606 if (save_path != NULL && save_path[0] == '\0') {
607 g_free(save_path);
608 save_path = NULL;
609 }
610 if (save_path && !Inkscape::IO::file_test(save_path, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) {
611 g_free(save_path);
612 save_path = NULL;
613 }
614 if (save_path == NULL)
615 save_path = g_strdup(g_get_home_dir());
616 temp_filename = g_strdup_printf(_("drawing%s"), filename_extension);
617 save_loc = g_build_filename(save_path, temp_filename, NULL);
618 g_free(temp_filename);
620 while (Inkscape::IO::file_test(save_loc, G_FILE_TEST_EXISTS)) {
621 g_free(save_loc);
622 temp_filename = g_strdup_printf(_("drawing-%d%s"), i++, filename_extension);
623 save_loc = g_build_filename(save_path, temp_filename, NULL);
624 g_free(temp_filename);
625 }
626 } else {
627 save_loc = g_path_get_dirname(doc->uri); /* \todo should use a getter */
628 }
630 { // convert save_loc from utf-8 to locale
631 // is this needed any more, now that everything is handled in
632 // Inkscape::IO?
633 gsize bytesRead = 0;
634 gsize bytesWritten = 0;
635 GError* error = NULL;
636 #ifdef INK_DUMP_FILENAME_CONV
637 dump_str( save_loc, "B file pre is " );
638 #endif
639 gchar* save_loc_local = g_filename_from_utf8( save_loc, -1, &bytesRead, &bytesWritten, &error);
641 if ( save_loc_local != NULL ) {
642 g_free(save_loc);
643 save_loc = save_loc_local;
644 #ifdef INK_DUMP_FILENAME_CONV
645 dump_str( save_loc, "B file post is " );
646 #endif
647 } else {
648 //g_warning( "Error converting save filename stored in the file to locale encoding.");
649 }
650 }
652 if (!saveDialogInstance) {
653 saveDialogInstance =
654 Inkscape::UI::Dialog::FileSaveDialog::create(
655 (char const *) save_loc,
656 Inkscape::UI::Dialog::SVG_TYPES,
657 (char const *) _("Select file to save to"),
658 default_extension
659 );
660 } // FIXME: else (i.e. if reshowing an already shown dialog) save_loc is not used, it thus always displays the previously opened dir
661 bool success = saveDialogInstance->show();
662 char *fileName = ( success
663 ? g_strdup(saveDialogInstance->getFilename())
664 : NULL );
665 Inkscape::Extension::Extension *selectionType =
666 saveDialogInstance->getSelectionType();
667 g_free(save_loc);
668 g_free(save_path);
669 if (!success) {
670 return success;
671 }
673 if (fileName && *fileName) {
674 gsize bytesRead = 0;
675 gsize bytesWritten = 0;
676 GError *error = NULL;
677 #ifdef INK_DUMP_FILENAME_CONV
678 dump_str( fileName, "C file pre is " );
679 #endif
680 gchar *newFileName = g_filename_to_utf8(fileName,
681 -1,
682 &bytesRead,
683 &bytesWritten,
684 &error);
685 if ( newFileName != NULL ) {
686 g_free(fileName);
687 fileName = newFileName;
688 #ifdef INK_DUMP_FILENAME_CONV
689 dump_str( fileName, "C file post is " );
690 #endif
691 } else {
692 g_warning( "Error converting save filename to UTF-8." );
693 }
695 if (!g_utf8_validate(fileName, -1, NULL)) {
696 // TODO: bulia, please look over
697 g_warning( "The filename is not UTF-8." );
698 }
700 success = file_save(doc, fileName, selectionType, TRUE);
702 if (success) {
703 prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
704 }
706 save_path = g_dirname(fileName);
707 prefs_set_string_attribute("dialogs.save_as", "path", save_path);
708 g_free(save_path);
710 g_free(fileName);
711 return success;
712 } else {
713 return FALSE;
714 }
715 }
718 /**
719 * Save a document, displaying a SaveAs dialog if necessary.
720 */
721 gboolean
722 sp_file_save_document(SPDocument *doc)
723 {
724 gboolean success = TRUE;
726 Inkscape::XML::Node *repr = sp_document_repr_root(doc);
728 gchar const *fn = repr->attribute("sodipodi:modified");
729 if (fn != NULL) {
730 if (doc->uri == NULL
731 || repr->attribute("inkscape:output_extension") == NULL)
732 {
733 return sp_file_save_dialog(doc);
734 } else {
735 fn = g_strdup(doc->uri);
736 gchar const *ext = repr->attribute("inkscape:output_extension");
737 success = file_save(doc, fn, Inkscape::Extension::db.get(ext), FALSE);
738 g_free((void *) fn);
739 }
740 } else {
741 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No changes need to be saved."));
742 success = TRUE;
743 }
745 return success;
746 }
749 /**
750 * Save a document.
751 */
752 bool
753 sp_file_save(gpointer object, gpointer data)
754 {
755 if (!SP_ACTIVE_DOCUMENT)
756 return false;
757 sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
758 return sp_file_save_document(SP_ACTIVE_DOCUMENT);
759 }
762 /**
763 * Save a document, always displaying the SaveAs dialog.
764 */
765 bool
766 sp_file_save_as(gpointer object, gpointer data)
767 {
768 if (!SP_ACTIVE_DOCUMENT)
769 return false;
770 sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
771 return sp_file_save_dialog(SP_ACTIVE_DOCUMENT);
772 }
777 /*######################
778 ## I M P O R T
779 ######################*/
781 /**
782 * Import a resource. Called by sp_file_import()
783 */
784 void
785 file_import(SPDocument *in_doc, gchar const *uri, Inkscape::Extension::Extension *key)
786 {
787 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
789 //DEBUG_MESSAGE( fileImport, "file_import( in_doc:%p uri:[%s], key:%p", in_doc, uri, key );
790 SPDocument *doc;
791 try {
792 doc = Inkscape::Extension::open(key, uri);
793 } catch (Inkscape::Extension::Input::no_extension_found &e) {
794 doc = NULL;
795 } catch (Inkscape::Extension::Input::open_failed &e) {
796 doc = NULL;
797 }
799 if (doc != NULL) {
800 // the import extension has passed us a document, now we need to embed it into our document
801 if ( 0 ) {
802 // const gchar *docbase = (sp_repr_document_root( sp_repr_document( repr ))->attribute("sodipodi:docbase" );
803 g_message(" settings uri [%s]", doc->uri );
804 g_message(" base [%s]", doc->base );
805 g_message(" name [%s]", doc->name );
806 Inkscape::IO::fixupHrefs( doc, doc->base, TRUE );
807 g_message(" mid-fixup");
808 Inkscape::IO::fixupHrefs( doc, in_doc->base, TRUE );
809 }
811 // move imported defs to our document's defs
812 SPObject *in_defs = SP_DOCUMENT_DEFS(in_doc);
813 SPObject *defs = SP_DOCUMENT_DEFS(doc);
814 Inkscape::XML::Node *last_def = SP_OBJECT_REPR(in_defs)->lastChild();
815 for (SPObject *child = sp_object_first_child(defs);
816 child != NULL; child = SP_OBJECT_NEXT(child))
817 {
818 // FIXME: in case of id conflict, newly added thing will be re-ided and thus likely break a reference to it from imported stuff
819 SP_OBJECT_REPR(in_defs)->addChild(SP_OBJECT_REPR(child)->duplicate(), last_def);
820 }
822 guint items_count = 0;
823 for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc));
824 child != NULL; child = SP_OBJECT_NEXT(child)) {
825 if (SP_IS_ITEM(child))
826 items_count ++;
827 }
828 SPCSSAttr *style = sp_css_attr_from_object (SP_DOCUMENT_ROOT (doc));
830 SPObject *new_obj = NULL;
832 if ((style && style->firstChild()) || items_count > 1) {
833 // create group
834 Inkscape::XML::Node *newgroup = sp_repr_new("svg:g");
835 sp_repr_css_set (newgroup, style, "style");
837 for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc)); child != NULL; child = SP_OBJECT_NEXT(child) ) {
838 if (SP_IS_ITEM(child)) {
839 Inkscape::XML::Node *newchild = SP_OBJECT_REPR(child)->duplicate();
841 // convert layers to groups; FIXME: add "preserve layers" mode where each layer
842 // from impot is copied to the same-named layer in host
843 newchild->setAttribute("inkscape:groupmode", NULL);
845 newgroup->appendChild(newchild);
846 }
847 }
849 if (desktop) {
850 // Add it to the current layer
851 new_obj = desktop->currentLayer()->appendChildRepr(newgroup);
852 } else {
853 // There's no desktop (command line run?)
854 // FIXME: For such cases we need a document:: method to return the current layer
855 new_obj = SP_DOCUMENT_ROOT(in_doc)->appendChildRepr(newgroup);
856 }
858 Inkscape::GC::release(newgroup);
859 } else {
860 // just add one item
861 for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc)); child != NULL; child = SP_OBJECT_NEXT(child) ) {
862 if (SP_IS_ITEM(child)) {
863 Inkscape::XML::Node *newitem = SP_OBJECT_REPR(child)->duplicate();
864 newitem->setAttribute("inkscape:groupmode", NULL);
866 if (desktop) {
867 // Add it to the current layer
868 new_obj = desktop->currentLayer()->appendChildRepr(newitem);
869 } else {
870 // There's no desktop (command line run?)
871 // FIXME: For such cases we need a document:: method to return the current layer
872 new_obj = SP_DOCUMENT_ROOT(in_doc)->appendChildRepr(newitem);
873 }
875 }
876 }
877 }
879 if (style) sp_repr_css_attr_unref (style);
881 // select and move the imported item
882 if (new_obj && SP_IS_ITEM(new_obj)) {
883 Inkscape::Selection *selection = sp_desktop_selection(desktop);
884 selection->set(SP_ITEM(new_obj));
886 // To move the imported object, we must temporarily set the "transform pattern with
887 // object" option.
888 {
889 int const saved_pref = prefs_get_int_attribute("options.transform", "pattern", 1);
890 prefs_set_int_attribute("options.transform", "pattern", 1);
891 sp_document_ensure_up_to_date(sp_desktop_document(desktop));
892 NR::Point m( desktop->point() - selection->bounds().midpoint() );
893 sp_selection_move_relative(selection, m);
894 prefs_set_int_attribute("options.transform", "pattern", saved_pref);
895 }
896 }
898 sp_document_unref(doc);
899 sp_document_done(in_doc, SP_VERB_FILE_IMPORT,
900 /* TODO: annotate */ "file.cpp:900");
902 } else {
903 gchar *text = g_strdup_printf(_("Failed to load the requested file %s"), uri);
904 sp_ui_error_dialog(text);
905 g_free(text);
906 }
908 return;
909 }
912 static Inkscape::UI::Dialog::FileOpenDialog *importDialogInstance = NULL;
914 /**
915 * Display an Open dialog, import a resource if OK pressed.
916 */
917 void
918 sp_file_import(GtkWidget *widget)
919 {
920 SPDocument *doc = SP_ACTIVE_DOCUMENT;
921 if (!doc)
922 return;
924 if (!importDialogInstance) {
925 importDialogInstance =
926 Inkscape::UI::Dialog::FileOpenDialog::create(
927 (char const *)import_path,
928 Inkscape::UI::Dialog::IMPORT_TYPES,
929 (char const *)_("Select file to import"));
930 }
931 bool success = importDialogInstance->show();
932 char *fileName = ( success
933 ? g_strdup(importDialogInstance->getFilename())
934 : NULL );
935 Inkscape::Extension::Extension *selection =
936 importDialogInstance->getSelectionType();
938 if (!success) return;
939 if (fileName) {
940 gsize bytesRead = 0;
941 gsize bytesWritten = 0;
942 GError *error = NULL;
943 #ifdef INK_DUMP_FILENAME_CONV
944 dump_str( fileName, "D file pre is " );
945 #endif
946 gchar *newFileName = g_filename_to_utf8( fileName,
947 -1,
948 &bytesRead,
949 &bytesWritten,
950 &error);
951 if ( newFileName != NULL ) {
952 g_free(fileName);
953 fileName = newFileName;
954 #ifdef INK_DUMP_FILENAME_CONV
955 dump_str( fileName, "D file post is " );
956 #endif
957 } else {
958 // TODO: bulia, please look over
959 g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
960 }
963 if (!g_utf8_validate(fileName, -1, NULL)) {
964 // TODO: bulia, please look over
965 g_warning( "INPUT FILENAME IS NOT UTF-8" );
966 }
968 g_free(import_path);
969 import_path = g_dirname(fileName);
970 if (import_path) import_path = g_strconcat(import_path, G_DIR_SEPARATOR_S, NULL);
972 file_import(doc, fileName, selection);
973 g_free(fileName);
974 }
976 return;
977 }
981 /*######################
982 ## E X P O R T
983 ######################*/
985 /**
986 *
987 */
988 void
989 sp_file_export_dialog(void *widget)
990 {
991 sp_export_dialog();
992 }
994 #include <display/nr-arena-item.h>
995 #include <display/nr-arena.h>
997 struct SPEBP {
998 int width, height, sheight;
999 guchar r, g, b, a;
1000 NRArenaItem *root; // the root arena item to show; it is assumed that all unneeded items are hidden
1001 guchar *px;
1002 unsigned (*status)(float, void *);
1003 void *data;
1004 };
1007 /**
1008 *
1009 */
1010 static int
1011 sp_export_get_rows(guchar const **rows, int row, int num_rows, void *data)
1012 {
1013 struct SPEBP *ebp = (struct SPEBP *) data;
1015 if (ebp->status) {
1016 if (!ebp->status((float) row / ebp->height, ebp->data)) return 0;
1017 }
1019 num_rows = MIN(num_rows, ebp->sheight);
1020 num_rows = MIN(num_rows, ebp->height - row);
1022 /* Set area of interest */
1023 NRRectL bbox;
1024 bbox.x0 = 0;
1025 bbox.y0 = row;
1026 bbox.x1 = ebp->width;
1027 bbox.y1 = row + num_rows;
1028 /* Update to renderable state */
1029 NRGC gc(NULL);
1030 nr_matrix_set_identity(&gc.transform);
1032 nr_arena_item_invoke_update(ebp->root, &bbox, &gc, NR_ARENA_ITEM_STATE_ALL, NR_ARENA_ITEM_STATE_NONE);
1034 NRPixBlock pb;
1035 nr_pixblock_setup_extern(&pb, NR_PIXBLOCK_MODE_R8G8B8A8N,
1036 bbox.x0, bbox.y0, bbox.x1, bbox.y1,
1037 ebp->px, 4 * ebp->width, FALSE, FALSE);
1039 for (int r = 0; r < num_rows; r++) {
1040 guchar *p = NR_PIXBLOCK_PX(&pb) + r * pb.rs;
1041 for (int c = 0; c < ebp->width; c++) {
1042 *p++ = ebp->r;
1043 *p++ = ebp->g;
1044 *p++ = ebp->b;
1045 *p++ = ebp->a;
1046 }
1047 }
1049 /* Render */
1050 nr_arena_item_invoke_render(ebp->root, &bbox, &pb, 0);
1052 for (int r = 0; r < num_rows; r++) {
1053 rows[r] = NR_PIXBLOCK_PX(&pb) + r * pb.rs;
1054 }
1056 nr_pixblock_release(&pb);
1058 return num_rows;
1059 }
1061 /**
1062 Hide all items which are not listed in list, recursively, skipping groups and defs
1063 */
1064 void
1065 hide_other_items_recursively(SPObject *o, GSList *list, unsigned dkey)
1066 {
1067 if (SP_IS_ITEM(o)
1068 && !SP_IS_DEFS(o)
1069 && !SP_IS_ROOT(o)
1070 && !SP_IS_GROUP(o)
1071 && !g_slist_find(list, o))
1072 {
1073 sp_item_invoke_hide(SP_ITEM(o), dkey);
1074 }
1076 // recurse
1077 if (!g_slist_find(list, o)) {
1078 for (SPObject *child = sp_object_first_child(o) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
1079 hide_other_items_recursively(child, list, dkey);
1080 }
1081 }
1082 }
1085 /**
1086 * Render the SVG drawing onto a PNG raster image, then save to
1087 * a file. Returns TRUE if succeeded in writing the file,
1088 * FALSE otherwise.
1089 */
1090 int
1091 sp_export_png_file(SPDocument *doc, gchar const *filename,
1092 double x0, double y0, double x1, double y1,
1093 unsigned width, unsigned height, double xdpi, double ydpi,
1094 unsigned long bgcolor,
1095 unsigned (*status)(float, void *),
1096 void *data, bool force_overwrite,
1097 GSList *items_only)
1098 {
1099 int write_status = TRUE;
1100 g_return_val_if_fail(doc != NULL, FALSE);
1101 g_return_val_if_fail(filename != NULL, FALSE);
1102 g_return_val_if_fail(width >= 1, FALSE);
1103 g_return_val_if_fail(height >= 1, FALSE);
1105 if (!force_overwrite && !sp_ui_overwrite_file(filename)) {
1106 return FALSE;
1107 }
1109 sp_document_ensure_up_to_date(doc);
1111 /* Go to document coordinates */
1112 gdouble t = y0;
1113 y0 = sp_document_height(doc) - y1;
1114 y1 = sp_document_height(doc) - t;
1116 /*
1117 * 1) a[0] * x0 + a[2] * y1 + a[4] = 0.0
1118 * 2) a[1] * x0 + a[3] * y1 + a[5] = 0.0
1119 * 3) a[0] * x1 + a[2] * y1 + a[4] = width
1120 * 4) a[1] * x0 + a[3] * y0 + a[5] = height
1121 * 5) a[1] = 0.0;
1122 * 6) a[2] = 0.0;
1123 *
1124 * (1,3) a[0] * x1 - a[0] * x0 = width
1125 * a[0] = width / (x1 - x0)
1126 * (2,4) a[3] * y0 - a[3] * y1 = height
1127 * a[3] = height / (y0 - y1)
1128 * (1) a[4] = -a[0] * x0
1129 * (2) a[5] = -a[3] * y1
1130 */
1132 NRMatrix affine;
1133 affine.c[0] = width / (x1 - x0);
1134 affine.c[1] = 0.0;
1135 affine.c[2] = 0.0;
1136 affine.c[3] = height / (y1 - y0);
1137 affine.c[4] = -affine.c[0] * x0;
1138 affine.c[5] = -affine.c[3] * y0;
1140 //SP_PRINT_MATRIX("SVG2PNG", &affine);
1142 struct SPEBP ebp;
1143 ebp.width = width;
1144 ebp.height = height;
1145 ebp.r = NR_RGBA32_R(bgcolor);
1146 ebp.g = NR_RGBA32_G(bgcolor);
1147 ebp.b = NR_RGBA32_B(bgcolor);
1148 ebp.a = NR_RGBA32_A(bgcolor);
1150 /* Create new arena */
1151 NRArena *arena = NRArena::create();
1152 unsigned dkey = sp_item_display_key_new(1);
1154 /* Create ArenaItems and set transform */
1155 ebp.root = sp_item_invoke_show(SP_ITEM(sp_document_root(doc)), arena, dkey, SP_ITEM_SHOW_DISPLAY);
1156 nr_arena_item_set_transform(NR_ARENA_ITEM(ebp.root), NR::Matrix(&affine));
1158 // We show all and then hide all items we don't want, instead of showing only requested items,
1159 // because that would not work if the shown item references something in defs
1160 if (items_only) {
1161 hide_other_items_recursively(sp_document_root(doc), items_only, dkey);
1162 }
1164 ebp.status = status;
1165 ebp.data = data;
1167 if ((width < 256) || ((width * height) < 32768)) {
1168 ebp.px = nr_pixelstore_64K_new(FALSE, 0);
1169 ebp.sheight = 65536 / (4 * width);
1170 write_status = sp_png_write_rgba_striped(filename, width, height, xdpi, ydpi, sp_export_get_rows, &ebp);
1171 nr_pixelstore_64K_free(ebp.px);
1172 } else {
1173 ebp.px = g_new(guchar, 4 * 64 * width);
1174 ebp.sheight = 64;
1175 write_status = sp_png_write_rgba_striped(filename, width, height, xdpi, ydpi, sp_export_get_rows, &ebp);
1176 g_free(ebp.px);
1177 }
1179 // Hide items
1180 sp_item_invoke_hide(SP_ITEM(sp_document_root(doc)), dkey);
1182 /* Free Arena and ArenaItem */
1183 nr_arena_item_unref(ebp.root);
1184 nr_object_unref((NRObject *) arena);
1185 return write_status;
1186 }
1189 /*######################
1190 ## P R I N T
1191 ######################*/
1194 /**
1195 * Print the current document, if any.
1196 */
1197 void
1198 sp_file_print()
1199 {
1200 SPDocument *doc = SP_ACTIVE_DOCUMENT;
1201 if (doc)
1202 sp_print_document(doc, FALSE);
1203 }
1206 /**
1207 * Print the current document, if any. Do not use
1208 * the machine's print drivers.
1209 */
1210 void
1211 sp_file_print_direct()
1212 {
1213 SPDocument *doc = SP_ACTIVE_DOCUMENT;
1214 if (doc)
1215 sp_print_document(doc, TRUE);
1216 }
1219 /**
1220 * Display what the drawing would look like, if
1221 * printed.
1222 */
1223 void
1224 sp_file_print_preview(gpointer object, gpointer data)
1225 {
1227 SPDocument *doc = SP_ACTIVE_DOCUMENT;
1228 if (doc)
1229 sp_print_preview_document(doc);
1231 }
1233 void Inkscape::IO::fixupHrefs( SPDocument *doc, const gchar *base, gboolean spns )
1234 {
1235 //g_message("Inkscape::IO::fixupHrefs( , [%s], )", base );
1237 if ( 0 ) {
1238 gchar const* things[] = {
1239 "data:foo,bar",
1240 "http://www.google.com/image.png",
1241 "ftp://ssd.com/doo",
1242 "/foo/dee/bar.svg",
1243 "foo.svg",
1244 "file:/foo/dee/bar.svg",
1245 "file:///foo/dee/bar.svg",
1246 "file:foo.svg",
1247 "/foo/bar\xe1\x84\x92.svg",
1248 "file:///foo/bar\xe1\x84\x92.svg",
1249 "file:///foo/bar%e1%84%92.svg",
1250 "/foo/bar%e1%84%92.svg",
1251 "bar\xe1\x84\x92.svg",
1252 "bar%e1%84%92.svg",
1253 NULL
1254 };
1255 g_message("+------");
1256 for ( int i = 0; things[i]; i++ )
1257 {
1258 try
1259 {
1260 URI uri(things[i]);
1261 gboolean isAbs = g_path_is_absolute( things[i] );
1262 gchar *str = uri.toString();
1263 g_message( "abs:%d isRel:%d scheme:[%s] path:[%s][%s] uri[%s] / [%s]", (int)isAbs,
1264 (int)uri.isRelative(),
1265 uri.getScheme(),
1266 uri.getPath(),
1267 uri.getOpaque(),
1268 things[i],
1269 str );
1270 g_free(str);
1271 }
1272 catch ( MalformedURIException err )
1273 {
1274 dump_str( things[i], "MalformedURIException" );
1275 xmlChar *redo = xmlURIEscape((xmlChar const *)things[i]);
1276 g_message(" gone from [%s] to [%s]", things[i], redo );
1277 if ( redo == NULL )
1278 {
1279 URI again = URI::fromUtf8( things[i] );
1280 gboolean isAbs = g_path_is_absolute( things[i] );
1281 gchar *str = again.toString();
1282 g_message( "abs:%d isRel:%d scheme:[%s] path:[%s][%s] uri[%s] / [%s]", (int)isAbs,
1283 (int)again.isRelative(),
1284 again.getScheme(),
1285 again.getPath(),
1286 again.getOpaque(),
1287 things[i],
1288 str );
1289 g_free(str);
1290 g_message(" ----");
1291 }
1292 }
1293 }
1294 g_message("+------");
1295 }
1297 GSList const *images = sp_document_get_resource_list(doc, "image");
1298 for (GSList const *l = images; l != NULL; l = l->next) {
1299 Inkscape::XML::Node *ir = SP_OBJECT_REPR(l->data);
1301 const gchar *href = ir->attribute("xlink:href");
1303 // First try to figure out an absolute path to the asset
1304 //g_message("image href [%s]", href );
1305 if (spns && !g_path_is_absolute(href)) {
1306 const gchar *absref = ir->attribute("sodipodi:absref");
1307 const gchar *base_href = g_build_filename(base, href, NULL);
1308 //g_message(" absr [%s]", absref );
1310 if ( absref && Inkscape::IO::file_test(absref, G_FILE_TEST_EXISTS) && !Inkscape::IO::file_test(base_href, G_FILE_TEST_EXISTS))
1311 {
1312 // only switch over if the absref is valid while href is not
1313 href = absref;
1314 //g_message(" copied absref to href");
1315 }
1316 }
1318 // Once we have an absolute path, convert it relative to the new location
1319 if (href && g_path_is_absolute(href)) {
1320 const gchar *relname = sp_relative_path_from_path(href, base);
1321 //g_message(" setting to [%s]", relname );
1322 ir->setAttribute("xlink:href", relname);
1323 }
1324 // TODO next refinement is to make the first choice keeping the relative path as-is if
1325 // based on the new location it gives us a valid file.
1326 }
1327 }
1330 /*
1331 Local Variables:
1332 mode:c++
1333 c-file-style:"stroustrup"
1334 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1335 indent-tabs-mode:nil
1336 fill-column:99
1337 End:
1338 */
1339 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :