1 /** @file
2 * @brief Open Clip Art Library integration dialogs - implementation
3 */
4 /* Authors:
5 * Bruno Dilly
6 * Other dudes from The Inkscape Organization
7 *
8 * Copyright (C) 2007 Bruno Dilly <bruno.dilly@gmail.com>
9 *
10 * Released under GNU GPL, read the file 'COPYING' for more information
11 */
13 #ifdef HAVE_CONFIG_H
14 # include <config.h>
15 #endif
17 #include <stdio.h> // rename()
18 #include <unistd.h> // close()
19 #include <errno.h> // errno
20 #include <string.h> // strerror()
22 #include "ocaldialogs.h"
23 #include "filedialogimpl-gtkmm.h"
24 #include "interface.h"
25 #include "gc-core.h"
26 #include <dialogs/dialog-events.h>
27 #include "io/sys.h"
28 #include "preferences.h"
30 namespace Inkscape
31 {
32 namespace UI
33 {
34 namespace Dialog
35 {
37 //########################################################################
38 //# F I L E E X P O R T T O O C A L
39 //########################################################################
41 /**
42 * Callback for fileNameEntry widget
43 */
44 /*
45 void FileExportToOCALDialog::fileNameEntryChangedCallback()
46 {
47 if (!fileNameEntry)
48 return;
50 Glib::ustring fileName = fileNameEntry->get_text();
51 if (!Glib::get_charset()) //If we are not utf8
52 fileName = Glib::filename_to_utf8(fileName);
54 myFilename = fileName;
55 response(Gtk::RESPONSE_OK);
56 }
57 */
58 /**
59 * Constructor
60 */
61 /*
62 FileExportToOCALDialog::FileExportToOCALDialog(Gtk::Window &parentWindow,
63 FileDialogType fileTypes,
64 const Glib::ustring &title) :
65 FileDialogOCALBase(title, parentWindow)
66 {
67 */
68 /*
69 * Start Taking the vertical Box and putting a Label
70 * and a Entry to take the filename
71 * Later put the extension selection and checkbox (?)
72 */
73 /* Initalize to Autodetect */
74 /*
75 extension = NULL;
76 */
77 /* No filename to start out with */
78 /*
79 myFilename = "";
80 */
81 /* Set our dialog type (save, export, etc...)*/
82 /*
83 dialogType = fileTypes;
84 Gtk::VBox *vbox = get_vbox();
86 Gtk::Label *fileLabel = new Gtk::Label(_("File"));
88 fileNameEntry = new Gtk::Entry();
89 fileNameEntry->set_text(myFilename);
90 fileNameEntry->set_max_length(252); // I am giving the extension approach.
91 fileBox.pack_start(*fileLabel);
92 fileBox.pack_start(*fileNameEntry, Gtk::PACK_EXPAND_WIDGET, 3);
93 vbox->pack_start(fileBox);
95 //Let's do some customization
96 fileNameEntry = NULL;
97 Gtk::Container *cont = get_toplevel();
98 std::vector<Gtk::Entry *> entries;
99 findEntryWidgets(cont, entries);
100 if (entries.size() >=1 )
101 {
102 //Catch when user hits [return] on the text field
103 fileNameEntry = entries[0];
104 fileNameEntry->signal_activate().connect(
105 sigc::mem_fun(*this, &FileExportToOCALDialog::fileNameEntryChangedCallback) );
106 }
108 add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
109 set_default(*add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK));
111 show_all_children();
112 }
113 */
114 /**
115 * Destructor
116 */
117 /*
118 FileExportToOCALDialog::~FileExportToOCALDialog()
119 {
120 }
121 */
122 /**
123 * Show this dialog modally. Return true if user hits [OK]
124 */
125 /*
126 bool
127 FileExportToOCALDialog::show()
128 {
129 set_modal (TRUE); //Window
130 sp_transientize((GtkWidget *)gobj()); //Make transient
131 gint b = run(); //Dialog
132 hide();
134 if (b == Gtk::RESPONSE_OK)
135 {
136 return TRUE;
137 }
138 else
139 {
140 return FALSE;
141 }
142 }
143 */
144 /**
145 * Get the file name chosen by the user. Valid after an [OK]
146 */
147 /*
148 Glib::ustring
149 FileExportToOCALDialog::getFilename()
150 {
151 myFilename = fileNameEntry->get_text();
152 if (!Glib::get_charset()) //If we are not utf8
153 myFilename = Glib::filename_to_utf8(myFilename);
155 return myFilename;
156 }
159 void
160 FileExportToOCALDialog::change_title(const Glib::ustring& title)
161 {
162 this->set_title(title);
163 }
164 */
166 //########################################################################
167 //# F I L E E X P O R T T O O C A L P A S S W O R D
168 //########################################################################
171 /**
172 * Constructor
173 */
174 /*
175 FileExportToOCALPasswordDialog::FileExportToOCALPasswordDialog(Gtk::Window &parentWindow,
176 const Glib::ustring &title) : FileDialogOCALBase(title, parentWindow)
177 {
178 */
179 /*
180 * Start Taking the vertical Box and putting 2 Labels
181 * and 2 Entries to take the username and password
182 */
183 /* No username and password to start out with */
184 /*
185 myUsername = "";
186 myPassword = "";
188 Gtk::VBox *vbox = get_vbox();
190 Gtk::Label *userLabel = new Gtk::Label(_("Username:"));
191 Gtk::Label *passLabel = new Gtk::Label(_("Password:"));
193 usernameEntry = new Gtk::Entry();
194 usernameEntry->set_text(myUsername);
195 usernameEntry->set_max_length(255);
197 passwordEntry = new Gtk::Entry();
198 passwordEntry->set_text(myPassword);
199 passwordEntry->set_max_length(255);
200 passwordEntry->set_invisible_char('*');
201 passwordEntry->set_visibility(false);
202 passwordEntry->set_activates_default(true);
204 userBox.pack_start(*userLabel);
205 userBox.pack_start(*usernameEntry, Gtk::PACK_EXPAND_WIDGET, 3);
206 vbox->pack_start(userBox);
208 passBox.pack_start(*passLabel);
209 passBox.pack_start(*passwordEntry, Gtk::PACK_EXPAND_WIDGET, 3);
210 vbox->pack_start(passBox);
212 add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
213 set_default(*add_button(Gtk::Stock::OK, Gtk::RESPONSE_OK));
215 show_all_children();
216 }
217 */
219 /**
220 * Destructor
221 */
222 /*
223 FileExportToOCALPasswordDialog::~FileExportToOCALPasswordDialog()
224 {
225 }
226 */
227 /**
228 * Show this dialog modally. Return true if user hits [OK]
229 */
230 /*
231 bool
232 FileExportToOCALPasswordDialog::show()
233 {
234 set_modal (TRUE); //Window
235 sp_transientize((GtkWidget *)gobj()); //Make transient
236 gint b = run(); //Dialog
237 hide();
239 if (b == Gtk::RESPONSE_OK)
240 {
241 return TRUE;
242 }
243 else
244 {
245 return FALSE;
246 }
247 }
248 */
249 /**
250 * Get the username. Valid after an [OK]
251 */
252 /*
253 Glib::ustring
254 FileExportToOCALPasswordDialog::getUsername()
255 {
256 myUsername = usernameEntry->get_text();
257 return myUsername;
258 }
259 */
260 /**
261 * Get the password. Valid after an [OK]
262 */
263 /*
264 Glib::ustring
265 FileExportToOCALPasswordDialog::getPassword()
266 {
267 myPassword = passwordEntry->get_text();
268 return myPassword;
269 }
271 void
272 FileExportToOCALPasswordDialog::change_title(const Glib::ustring& title)
273 {
274 this->set_title(title);
275 }
276 */
278 //#########################################################################
279 //### F I L E I M P O R T F R O M O C A L
280 //#########################################################################
282 /*
283 * Calalback for cursor chage
284 */
285 void FileListViewText::on_cursor_changed()
286 {
287 std::vector<Gtk::TreeModel::Path> pathlist;
288 pathlist = this->get_selection()->get_selected_rows();
289 std::vector<int> posArray(1);
290 posArray = pathlist[0].get_indices();
292 #ifdef WITH_GNOME_VFS
293 gnome_vfs_init();
294 GnomeVFSHandle *from_handle = NULL;
295 GnomeVFSHandle *to_handle = NULL;
296 GnomeVFSFileSize bytes_read;
297 GnomeVFSFileSize bytes_written;
298 GnomeVFSResult result;
299 guint8 buffer[8192];
300 Glib::ustring fileUrl;
302 // FIXME: this would be better as a per-user OCAL cache of files
303 // instead of filling /tmp with downloads.
304 //
305 // create file path
306 const std::string tmptemplate = "ocal-";
307 std::string tmpname;
308 int fd = Inkscape::IO::file_open_tmp(tmpname, tmptemplate);
309 if (fd<0) {
310 g_warning("Error creating temp file");
311 return;
312 }
313 close(fd);
314 // make sure we don't collide with other users on the same machine
315 myFilename = tmpname;
316 myFilename.append("-");
317 myFilename.append(get_text(posArray[0], 2));
318 // rename based on original image's name, retaining extension
319 if (rename(tmpname.c_str(),myFilename.c_str())<0) {
320 unlink(tmpname.c_str());
321 g_warning("Error creating destination file '%s': %s", myFilename.c_str(), strerror(errno));
322 goto failquit;
323 }
325 //get file url
326 fileUrl = get_text(posArray[0], 1); //http url
328 //Inkscape::Preferences *prefs = Inkscape::Preferences::get();
329 //Glib::ustring fileUrl = "dav://"; //dav url
330 //fileUrl.append(prefs->getString("/options/ocalurl/str"));
331 //fileUrl.append("/dav.php/");
332 //fileUrl.append(get_text(posArray[0], 3)); //author dir
333 //fileUrl.append("/");
334 //fileUrl.append(get_text(posArray[0], 2)); //filename
336 if (!Glib::get_charset()) //If we are not utf8
337 fileUrl = Glib::filename_to_utf8(fileUrl);
339 {
340 // open the temp file to receive
341 result = gnome_vfs_open (&to_handle, myFilename.c_str(), GNOME_VFS_OPEN_WRITE);
342 if (result == GNOME_VFS_ERROR_NOT_FOUND){
343 result = gnome_vfs_create (&to_handle, myFilename.c_str(), GNOME_VFS_OPEN_WRITE, FALSE, GNOME_VFS_PERM_USER_ALL);
344 }
345 if (result != GNOME_VFS_OK) {
346 g_warning("Error creating temp file '%s': %s", myFilename.c_str(), gnome_vfs_result_to_string(result));
347 goto fail;
348 }
349 result = gnome_vfs_open (&from_handle, fileUrl.c_str(), GNOME_VFS_OPEN_READ);
350 if (result != GNOME_VFS_OK) {
351 g_warning("Could not find the file in Open Clip Art Library.");
352 goto fail;
353 }
354 // copy the file
355 while (1) {
356 result = gnome_vfs_read (from_handle, buffer, 8192, &bytes_read);
357 if ((result == GNOME_VFS_ERROR_EOF) &&(!bytes_read)){
358 result = gnome_vfs_close (from_handle);
359 result = gnome_vfs_close (to_handle);
360 break;
361 }
362 if (result != GNOME_VFS_OK) {
363 g_warning("%s", gnome_vfs_result_to_string(result));
364 goto fail;
365 }
366 result = gnome_vfs_write (to_handle, buffer, bytes_read, &bytes_written);
367 if (result != GNOME_VFS_OK) {
368 g_warning("%s", gnome_vfs_result_to_string(result));
369 goto fail;
370 }
371 if (bytes_read != bytes_written){
372 g_warning("Bytes read not equal to bytes written");
373 goto fail;
374 }
375 }
376 }
377 myPreview->showImage(myFilename);
378 myLabel->set_text(get_text(posArray[0], 4));
379 #endif
380 return;
381 fail:
382 unlink(myFilename.c_str());
383 failquit:
384 myFilename = "";
385 }
388 /*
389 * Callback for row activated
390 */
391 void FileListViewText::on_row_activated(const Gtk::TreeModel::Path& /*path*/, Gtk::TreeViewColumn* /*column*/)
392 {
393 this->on_cursor_changed();
394 myButton->activate();
395 }
398 /*
399 * Returns the selected filename
400 */
401 Glib::ustring FileListViewText::getFilename()
402 {
403 return myFilename;
404 }
407 #ifdef WITH_GNOME_VFS
408 /**
409 * Read callback for xmlReadIO(), used below
410 */
411 static int vfs_read_callback (GnomeVFSHandle *handle, char* buf, int nb)
412 {
413 GnomeVFSFileSize ndone;
414 GnomeVFSResult result;
416 result = gnome_vfs_read (handle, buf, nb, &ndone);
418 if (result == GNOME_VFS_OK) {
419 return (int)ndone;
420 } else {
421 if (result != GNOME_VFS_ERROR_EOF) {
422 sp_ui_error_dialog(_("Error while reading the Open Clip Art RSS feed"));
423 g_warning("%s\n", gnome_vfs_result_to_string(result));
424 }
425 return -1;
426 }
427 }
428 #endif
431 /**
432 * Callback for user input into searchTagEntry
433 */
434 void FileImportFromOCALDialog::searchTagEntryChangedCallback()
435 {
436 if (!searchTagEntry)
437 return;
439 notFoundLabel->hide();
440 descriptionLabel->set_text("");
441 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
443 Glib::ustring searchTag = searchTagEntry->get_text();
444 // create the ocal uri to get rss feed
445 Glib::ustring uri = "http://";
446 uri.append(prefs->getString("/options/ocalurl/str"));
447 uri.append("/media/feed/rss/");
448 uri.append(searchTag);
449 if (!Glib::get_charset()) //If we are not utf8
450 uri = Glib::filename_to_utf8(uri);
452 #ifdef WITH_GNOME_VFS
454 // open the rss feed
455 gnome_vfs_init();
456 GnomeVFSHandle *from_handle = NULL;
457 GnomeVFSResult result;
459 result = gnome_vfs_open (&from_handle, uri.c_str(), GNOME_VFS_OPEN_READ);
460 if (result != GNOME_VFS_OK) {
461 sp_ui_error_dialog(_("Failed to receive the Open Clip Art Library RSS feed. Verify if the server name is correct in Configuration->Import/Export (e.g.: openclipart.org)"));
462 return;
463 }
465 // create the resulting xml document tree
466 // this initialize the library and test mistakes between compiled and shared library used
467 LIBXML_TEST_VERSION
468 xmlDoc *doc = NULL;
469 xmlNode *root_element = NULL;
471 doc = xmlReadIO ((xmlInputReadCallback) vfs_read_callback,
472 (xmlInputCloseCallback) gnome_vfs_close, from_handle, uri.c_str(), NULL,
473 XML_PARSE_RECOVER);
474 if (doc == NULL) {
475 sp_ui_error_dialog(_("Server supplied malformed Clip Art feed"));
476 g_warning("Failed to parse %s\n", uri.c_str());
477 return;
478 }
480 // get the root element node
481 root_element = xmlDocGetRootElement(doc);
483 // clear the fileslist
484 filesList->clear_items();
485 filesList->set_sensitive(false);
487 // print all xml the element names
488 print_xml_element_names(root_element);
490 if (filesList->size() == 0)
491 {
492 notFoundLabel->show();
493 filesList->set_sensitive(false);
494 }
495 else
496 filesList->set_sensitive(true);
498 // free the document
499 xmlFreeDoc(doc);
500 // free the global variables that may have been allocated by the parser
501 xmlCleanupParser();
502 return;
503 #endif
504 }
507 /**
508 * Prints the names of the all the xml elements
509 * that are siblings or children of a given xml node
510 */
511 void FileImportFromOCALDialog::print_xml_element_names(xmlNode * a_node)
512 {
513 xmlNode *cur_node = NULL;
514 guint row_num = 0;
515 for (cur_node = a_node; cur_node; cur_node = cur_node->next) {
516 // get itens information
517 if (strcmp((const char*)cur_node->name, "rss")) //avoid the root
518 if (cur_node->type == XML_ELEMENT_NODE && !strcmp((const char*)cur_node->parent->name, "item"))
519 {
520 if (!strcmp((const char*)cur_node->name, "title"))
521 {
522 xmlChar *title = xmlNodeGetContent(cur_node);
523 row_num = filesList->append_text((const char*)title);
524 xmlFree(title);
525 }
526 #ifdef WITH_GNOME_VFS
527 else if (!strcmp((const char*)cur_node->name, "enclosure"))
528 {
529 xmlChar *urlattribute = xmlGetProp(cur_node, (xmlChar*)"url");
530 filesList->set_text(row_num, 1, (const char*)urlattribute);
531 gchar *tmp_file;
532 tmp_file = gnome_vfs_uri_extract_short_path_name(gnome_vfs_uri_new((const char*)urlattribute));
533 filesList->set_text(row_num, 2, (const char*)tmp_file);
534 xmlFree(urlattribute);
535 }
536 else if (!strcmp((const char*)cur_node->name, "creator"))
537 {
538 filesList->set_text(row_num, 3, (const char*)xmlNodeGetContent(cur_node));
539 }
540 else if (!strcmp((const char*)cur_node->name, "description"))
541 {
542 filesList->set_text(row_num, 4, (const char*)xmlNodeGetContent(cur_node));
543 }
544 #endif
545 }
546 print_xml_element_names(cur_node->children);
547 }
548 }
550 /**
551 * Constructor. Not called directly. Use the factory.
552 */
553 FileImportFromOCALDialog::FileImportFromOCALDialog(Gtk::Window& parentWindow,
554 const Glib::ustring &/*dir*/,
555 FileDialogType fileTypes,
556 const Glib::ustring &title) :
557 FileDialogOCALBase(title, parentWindow)
558 {
559 // Initalize to Autodetect
560 extension = NULL;
561 // No filename to start out with
562 Glib::ustring searchTag = "";
564 dialogType = fileTypes;
565 Gtk::VBox *vbox = get_vbox();
566 Gtk::Label *tagLabel = new Gtk::Label(_("Search for:"));
567 notFoundLabel = new Gtk::Label(_("No files matched your search"));
568 descriptionLabel = new Gtk::Label();
569 descriptionLabel->set_max_width_chars(260);
570 descriptionLabel->set_size_request(500, -1);
571 descriptionLabel->set_single_line_mode(false);
572 descriptionLabel->set_line_wrap(true);
573 messageBox.pack_start(*notFoundLabel);
574 descriptionBox.pack_start(*descriptionLabel);
575 searchTagEntry = new Gtk::Entry();
576 searchTagEntry->set_text(searchTag);
577 searchTagEntry->set_max_length(255);
578 searchButton = new Gtk::Button(_("Search"));
579 tagBox.pack_start(*tagLabel);
580 tagBox.pack_start(*searchTagEntry, Gtk::PACK_EXPAND_WIDGET, 3);
581 tagBox.pack_start(*searchButton);
582 filesPreview = new SVGPreview();
583 filesPreview->showNoPreview();
584 // add the buttons in the bottom of the dialog
585 add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
586 okButton = add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);
587 // sets the okbutton to default
588 set_default(*okButton);
589 filesList = new FileListViewText(5, *filesPreview, *descriptionLabel, *okButton);
590 filesList->set_sensitive(false);
591 // add the listview inside a ScrolledWindow
592 listScrolledWindow.add(*filesList);
593 // only show the scrollbars when they are necessary:
594 listScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
595 filesList->set_column_title(0, _("Files found"));
596 listScrolledWindow.set_size_request(400, 180);
597 filesList->get_column(1)->set_visible(false); // file url
598 filesList->get_column(2)->set_visible(false); // tmp file path
599 filesList->get_column(3)->set_visible(false); // author dir
600 filesList->get_column(4)->set_visible(false); // file description
601 filesBox.pack_start(listScrolledWindow);
602 filesBox.pack_start(*filesPreview);
603 vbox->pack_start(tagBox, false, false);
604 vbox->pack_start(messageBox);
605 vbox->pack_start(filesBox);
606 vbox->pack_start(descriptionBox);
608 //Let's do some customization
609 searchTagEntry = NULL;
610 Gtk::Container *cont = get_toplevel();
611 std::vector<Gtk::Entry *> entries;
612 findEntryWidgets(cont, entries);
613 if (entries.size() >=1 )
614 {
615 //Catch when user hits [return] on the text field
616 searchTagEntry = entries[0];
617 searchTagEntry->signal_activate().connect(
618 sigc::mem_fun(*this, &FileImportFromOCALDialog::searchTagEntryChangedCallback));
619 }
621 searchButton->signal_clicked().connect(
622 sigc::mem_fun(*this, &FileImportFromOCALDialog::searchTagEntryChangedCallback));
624 show_all_children();
625 notFoundLabel->hide();
626 }
628 /**
629 * Destructor
630 */
631 FileImportFromOCALDialog::~FileImportFromOCALDialog()
632 {
634 }
636 /**
637 * Show this dialog modally. Return true if user hits [OK]
638 */
639 bool
640 FileImportFromOCALDialog::show()
641 {
642 set_modal (TRUE); //Window
643 sp_transientize((GtkWidget *)gobj()); //Make transient
644 gint b = run(); //Dialog
645 hide();
647 if (b == Gtk::RESPONSE_OK)
648 {
649 return TRUE;
650 }
651 else
652 {
653 return FALSE;
654 }
655 }
658 /**
659 * Get the file extension type that was selected by the user. Valid after an [OK]
660 */
661 Inkscape::Extension::Extension *
662 FileImportFromOCALDialog::getSelectionType()
663 {
664 return extension;
665 }
668 /**
669 * Get the file name chosen by the user. Valid after an [OK]
670 */
671 Glib::ustring
672 FileImportFromOCALDialog::getFilename (void)
673 {
674 return filesList->getFilename();
675 }
678 } //namespace Dialog
679 } //namespace UI
680 } //namespace Inkscape
684 /*
685 Local Variables:
686 mode:c++
687 c-file-style:"stroustrup"
688 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
689 indent-tabs-mode:nil
690 fill-column:99
691 End:
692 */
693 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :