Code

wrap vfs_read_callback() callback in #ifdef WITH_GNOME_VFS
[inkscape.git] / src / ui / dialog / ocaldialogs.cpp
1 /**
2  * Implementation of the ocal dialog interfaces defined in ocaldialog.h
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>
28 namespace Inkscape
29 {
30 namespace UI
31 {
32 namespace Dialog
33 {
35 //########################################################################
36 //# F I L E    E X P O R T   T O   O C A L
37 //########################################################################
39 /**
40  * Callback for fileNameEntry widget
41  */
42 void FileExportToOCALDialog::fileNameEntryChangedCallback()
43 {
44     if (!fileNameEntry)
45         return;
47     Glib::ustring fileName = fileNameEntry->get_text();
48     if (!Glib::get_charset()) //If we are not utf8
49         fileName = Glib::filename_to_utf8(fileName);
51     myFilename = fileName;
52     response(Gtk::RESPONSE_OK);
53 }
55 /**
56  * Constructor
57  */
58 FileExportToOCALDialog::FileExportToOCALDialog(Gtk::Window &parentWindow,
59             FileDialogType fileTypes,
60             const Glib::ustring &title) :
61     FileDialogOCALBase(title, parentWindow)
62 {
63     /*
64      * Start Taking the vertical Box and putting a Label
65      * and a Entry to take the filename
66      * Later put the extension selection and checkbox (?)
67      */
68     /* Initalize to Autodetect */
69     extension = NULL;
70     /* No filename to start out with */
71     myFilename = "";
72     /* Set our dialog type (save, export, etc...)*/
73     dialogType = fileTypes;
74     Gtk::VBox *vbox = get_vbox();
75     
76     Gtk::Label *fileLabel = new Gtk::Label(_("File"));
78     fileNameEntry = new Gtk::Entry();
79     fileNameEntry->set_text(myFilename);
80     fileNameEntry->set_max_length(252); // I am giving the extension approach.
81     fileBox.pack_start(*fileLabel);
82     fileBox.pack_start(*fileNameEntry, Gtk::PACK_EXPAND_WIDGET, 3);
83     vbox->pack_start(fileBox);
85     //Let's do some customization
86     fileNameEntry = NULL;
87     Gtk::Container *cont = get_toplevel();
88     std::vector<Gtk::Entry *> entries;
89     findEntryWidgets(cont, entries);
90     if (entries.size() >=1 )
91         {
92         //Catch when user hits [return] on the text field
93         fileNameEntry = entries[0];
94         fileNameEntry->signal_activate().connect(
95              sigc::mem_fun(*this, &FileExportToOCALDialog::fileNameEntryChangedCallback) );
96         }
98     add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
99     set_default(*add_button(Gtk::Stock::SAVE,   Gtk::RESPONSE_OK));
101     show_all_children();
104 /**
105  * Destructor
106  */
107 FileExportToOCALDialog::~FileExportToOCALDialog()
111 /**
112  * Show this dialog modally.  Return true if user hits [OK]
113  */
114 bool
115 FileExportToOCALDialog::show()
117     set_modal (TRUE);                      //Window
118     sp_transientize((GtkWidget *)gobj());  //Make transient
119     gint b = run();                        //Dialog
120     hide();
122     if (b == Gtk::RESPONSE_OK)
123     {
124         return TRUE;
125         }
126     else
127         {
128         return FALSE;
129         }
132 /**
133  * Get the file name chosen by the user.   Valid after an [OK]
134  */
135 Glib::ustring
136 FileExportToOCALDialog::getFilename()
138     myFilename = fileNameEntry->get_text();
139     if (!Glib::get_charset()) //If we are not utf8
140         myFilename = Glib::filename_to_utf8(myFilename);
142     return myFilename;
146 void
147 FileExportToOCALDialog::change_title(const Glib::ustring& title)
149     this->set_title(title);
153 //########################################################################
154 //# F I L E    E X P O R T   T O   O C A L   P A S S W O R D
155 //########################################################################
158 /**
159  * Constructor
160  */
161 FileExportToOCALPasswordDialog::FileExportToOCALPasswordDialog(Gtk::Window &parentWindow,
162                              const Glib::ustring &title) : FileDialogOCALBase(title, parentWindow)
164     /*
165      * Start Taking the vertical Box and putting 2 Labels
166      * and 2 Entries to take the username and password
167      */
168     /* No username and password to start out with */
169     myUsername = "";
170     myPassword = "";
172     Gtk::VBox *vbox = get_vbox();
174     Gtk::Label *userLabel = new Gtk::Label(_("Username:"));
175     Gtk::Label *passLabel = new Gtk::Label(_("Password:"));
177     usernameEntry = new Gtk::Entry();
178     usernameEntry->set_text(myUsername);
179     usernameEntry->set_max_length(255);
181     passwordEntry = new Gtk::Entry();
182     passwordEntry->set_text(myPassword);
183     passwordEntry->set_max_length(255);
184     passwordEntry->set_invisible_char('*');
185     passwordEntry->set_visibility(false);
186     passwordEntry->set_activates_default(true);
188     userBox.pack_start(*userLabel);
189     userBox.pack_start(*usernameEntry, Gtk::PACK_EXPAND_WIDGET, 3);
190     vbox->pack_start(userBox);
192     passBox.pack_start(*passLabel);
193     passBox.pack_start(*passwordEntry, Gtk::PACK_EXPAND_WIDGET, 3);
194     vbox->pack_start(passBox);
195     
196     add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
197     set_default(*add_button(Gtk::Stock::OK,   Gtk::RESPONSE_OK));
199     show_all_children();
203 /**
204  * Destructor
205  */
206 FileExportToOCALPasswordDialog::~FileExportToOCALPasswordDialog()
210 /**
211  * Show this dialog modally.  Return true if user hits [OK]
212  */
213 bool
214 FileExportToOCALPasswordDialog::show()
216     set_modal (TRUE);                      //Window
217     sp_transientize((GtkWidget *)gobj());  //Make transient
218     gint b = run();                        //Dialog
219     hide();
221     if (b == Gtk::RESPONSE_OK)
222     {
223         return TRUE;
224     }
225     else
226     {
227         return FALSE;
228     }
231 /**
232  * Get the username.   Valid after an [OK]
233  */
234 Glib::ustring
235 FileExportToOCALPasswordDialog::getUsername()
237     myUsername = usernameEntry->get_text();
238     return myUsername;
241 /**
242  * Get the password.   Valid after an [OK]
243  */
244 Glib::ustring
245 FileExportToOCALPasswordDialog::getPassword()
247     myPassword = passwordEntry->get_text();
248     return myPassword;
251 void
252 FileExportToOCALPasswordDialog::change_title(const Glib::ustring& title)
254     this->set_title(title);
258 //#########################################################################
259 //### F I L E   I M P O R T   F R O M   O C A L
260 //#########################################################################
262 /*
263  * Calalback for cursor chage
264  */
265 void FileListViewText::on_cursor_changed()
267     std::vector<Gtk::TreeModel::Path> pathlist;
268     pathlist = this->get_selection()->get_selected_rows();
269     std::vector<int> posArray(1);
270     posArray = pathlist[0].get_indices();
272 #ifdef WITH_GNOME_VFS
273     gnome_vfs_init();
274     GnomeVFSHandle    *from_handle = NULL;
275     GnomeVFSHandle    *to_handle = NULL;
276     GnomeVFSFileSize  bytes_read;
277     GnomeVFSFileSize  bytes_written;
278     GnomeVFSResult    result;
279     guint8 buffer[8192];
280     Glib::ustring fileUrl;
282     // FIXME: this would be better as a per-user OCAL cache of files
283     // instead of filling /tmp with downloads.
284     //
285     // create file path
286     const std::string tmptemplate = "ocal-";
287     std::string tmpname;
288     int fd = Glib::file_open_tmp(tmpname, tmptemplate);
289     if (fd<0) {
290         g_warning("Error creating temp file");
291         return;
292     }
293     close(fd);
294     // make sure we don't collide with other users on the same machine
295     myFilename = tmpname;
296     myFilename.append("-");
297     myFilename.append(get_text(posArray[0], 2));
298     // rename based on original image's name, retaining extension
299     if (rename(tmpname.c_str(),myFilename.c_str())<0) {
300         unlink(tmpname.c_str());
301         g_warning("Error creating destination file '%s': %s", myFilename.c_str(), strerror(errno));
302         goto failquit;
303     }
305     //get file url
306     fileUrl = get_text(posArray[0], 1); //http url
308     //Glib::ustring fileUrl = "dav://"; //dav url
309     //fileUrl.append(prefs_get_string_attribute("options.ocalurl", "str"));
310     //fileUrl.append("/dav.php/");
311     //fileUrl.append(get_text(posArray[0], 3)); //author dir
312     //fileUrl.append("/");
313     //fileUrl.append(get_text(posArray[0], 2)); //filename
315     if (!Glib::get_charset()) //If we are not utf8
316         fileUrl = Glib::filename_to_utf8(fileUrl);
318     {
319         // open the temp file to receive
320         result = gnome_vfs_open (&to_handle, myFilename.c_str(), GNOME_VFS_OPEN_WRITE);
321         if (result == GNOME_VFS_ERROR_NOT_FOUND){
322             result = gnome_vfs_create (&to_handle, myFilename.c_str(), GNOME_VFS_OPEN_WRITE, FALSE, GNOME_VFS_PERM_USER_ALL);
323         }
324         if (result != GNOME_VFS_OK) {
325             g_warning("Error creating temp file '%s': %s", myFilename.c_str(), gnome_vfs_result_to_string(result));
326             goto fail;
327         }
328         result = gnome_vfs_open (&from_handle, fileUrl.c_str(), GNOME_VFS_OPEN_READ);
329         if (result != GNOME_VFS_OK) {
330             g_warning("Could not find the file in Open Clip Art Library.");
331             goto fail;
332         }
333         // copy the file
334         while (1) {
335             result = gnome_vfs_read (from_handle, buffer, 8192, &bytes_read);
336             if ((result == GNOME_VFS_ERROR_EOF) &&(!bytes_read)){
337                 result = gnome_vfs_close (from_handle);
338                 result = gnome_vfs_close (to_handle);
339                 break;
340             }
341             if (result != GNOME_VFS_OK) {
342                 g_warning("%s", gnome_vfs_result_to_string(result));
343                 goto fail;
344             }
345             result = gnome_vfs_write (to_handle, buffer, bytes_read, &bytes_written);
346             if (result != GNOME_VFS_OK) {
347                 g_warning("%s", gnome_vfs_result_to_string(result));
348                 goto fail;
349             }
350             if (bytes_read != bytes_written){
351                 g_warning("Bytes read not equal to bytes written");
352                 goto fail;
353             }
354         }
355     }
356     myPreview->showImage(myFilename);
357     myLabel->set_text(get_text(posArray[0], 4));
358 #endif
359     return;
360 fail:
361     unlink(myFilename.c_str());
362 failquit:
363     myFilename = "";
367 /*
368  * Callback for row activated
369  */
370 void FileListViewText::on_row_activated(const Gtk::TreeModel::Path& path, Gtk::TreeViewColumn* column)
372     this->on_cursor_changed();
373     myButton->activate();
377 /*
378  * Returns the selected filename
379  */
380 Glib::ustring FileListViewText::getFilename()
382     return myFilename;
386 #ifdef WITH_GNOME_VFS
387 /**
388  * Read callback for xmlReadIO(), used below
389  */
390 static int vfs_read_callback (GnomeVFSHandle *handle, char* buf, int nb)
392     GnomeVFSFileSize ndone;
393     GnomeVFSResult    result;
395     result = gnome_vfs_read (handle, buf, nb, &ndone);
397     if (result == GNOME_VFS_OK) {
398         return (int)ndone;
399     } else {
400         if (result != GNOME_VFS_ERROR_EOF) {
401             sp_ui_error_dialog(_("Error while reading the Open Clip Art RSS feed"));
402             g_warning("%s\n", gnome_vfs_result_to_string(result));
403         }
404         return -1;
405     }
407 #endif
410 /**
411  * Callback for user input into searchTagEntry
412  */
413 void FileImportFromOCALDialog::searchTagEntryChangedCallback()
415     if (!searchTagEntry)
416         return;
418     notFoundLabel->hide();
419     descriptionLabel->set_text("");
421     Glib::ustring searchTag = searchTagEntry->get_text();
422     // create the ocal uri to get rss feed
423     Glib::ustring uri = "http://";
424     uri.append(prefs_get_string_attribute("options.ocalurl", "str"));
425     uri.append("/media/feed/rss/");
426     uri.append(searchTag);
427     if (!Glib::get_charset()) //If we are not utf8
428         uri = Glib::filename_to_utf8(uri);
430 #ifdef WITH_GNOME_VFS
432     // open the rss feed
433     gnome_vfs_init();
434     GnomeVFSHandle    *from_handle = NULL;
435     GnomeVFSResult    result;
437     result = gnome_vfs_open (&from_handle, uri.c_str(), GNOME_VFS_OPEN_READ);
438     if (result != GNOME_VFS_OK) {
439         sp_ui_error_dialog(_("Failed to receive the Open Clip Art Library RSS feed. Verify if the server name is correct in Configuration->Misc (e.g.: openclipart.org)"));
440         return;
441     }
443     // create the resulting xml document tree
444     // this initialize the library and test mistakes between compiled and shared library used
445     LIBXML_TEST_VERSION 
446     xmlDoc *doc = NULL;
447     xmlNode *root_element = NULL;
449     doc = xmlReadIO ((xmlInputReadCallback) vfs_read_callback,
450         (xmlInputCloseCallback) gnome_vfs_close, from_handle, uri.c_str(), NULL,
451         XML_PARSE_RECOVER);
452     if (doc == NULL) {
453         sp_ui_error_dialog(_("Server supplied malformed Clip Art feed"));
454         g_warning("Failed to parse %s\n", uri.c_str());
455         return;
456     }
457     
458     // get the root element node
459     root_element = xmlDocGetRootElement(doc);
461     // clear the fileslist
462     filesList->clear_items();
463     filesList->set_sensitive(false);
465     // print all xml the element names
466     print_xml_element_names(root_element);
468     if (filesList->size() == 0)
469     {
470         notFoundLabel->show();
471         filesList->set_sensitive(false);
472     }
473     else
474         filesList->set_sensitive(true);
476     // free the document
477     xmlFreeDoc(doc);
478     // free the global variables that may have been allocated by the parser
479     xmlCleanupParser();
480     return;
481 #endif    
485 /**
486  * Prints the names of the all the xml elements 
487  * that are siblings or children of a given xml node
488  */
489 void FileImportFromOCALDialog::print_xml_element_names(xmlNode * a_node)
491     xmlNode *cur_node = NULL;
492     guint row_num = 0;
493     for (cur_node = a_node; cur_node; cur_node = cur_node->next) {
494         // get itens information
495         if (strcmp((const char*)cur_node->name, "rss")) //avoid the root
496             if (cur_node->type == XML_ELEMENT_NODE && !strcmp((const char*)cur_node->parent->name, "item"))
497             {
498                 if (!strcmp((const char*)cur_node->name, "title"))
499                 {
500                     xmlChar *title = xmlNodeGetContent(cur_node);
501                     row_num = filesList->append_text((const char*)title);
502                     xmlFree(title);
503                 }
504 #ifdef WITH_GNOME_VFS
505                 else if (!strcmp((const char*)cur_node->name, "enclosure"))
506                 {
507                     xmlChar *urlattribute = xmlGetProp(cur_node, (xmlChar*)"url");
508                     filesList->set_text(row_num, 1, (const char*)urlattribute);
509                     gchar *tmp_file;
510                     tmp_file = gnome_vfs_uri_extract_short_path_name(gnome_vfs_uri_new((const char*)urlattribute));
511                     filesList->set_text(row_num, 2, (const char*)tmp_file);
512                     xmlFree(urlattribute);
513                 }
514                 else if (!strcmp((const char*)cur_node->name, "creator"))
515                 {
516                     filesList->set_text(row_num, 3, (const char*)xmlNodeGetContent(cur_node));
517                 }
518                 else if (!strcmp((const char*)cur_node->name, "description"))
519                 {
520                     filesList->set_text(row_num, 4, (const char*)xmlNodeGetContent(cur_node));
521                 }
522 #endif
523             }
524         print_xml_element_names(cur_node->children);
525     }
528 /**
529  * Constructor.  Not called directly.  Use the factory.
530  */
531 FileImportFromOCALDialog::FileImportFromOCALDialog(Gtk::Window& parentWindow, 
532                                        const Glib::ustring &dir,
533                                        FileDialogType fileTypes,
534                                        const Glib::ustring &title) :
535      FileDialogOCALBase(title, parentWindow)
537     // Initalize to Autodetect
538     extension = NULL;
539     // No filename to start out with
540     Glib::ustring searchTag = "";
542     dialogType = fileTypes;
543     Gtk::VBox *vbox = get_vbox();
544     Gtk::Label *tagLabel = new Gtk::Label(_("Search for:"));
545     notFoundLabel = new Gtk::Label(_("No files matched your search"));
546     descriptionLabel = new Gtk::Label();
547     descriptionLabel->set_max_width_chars(260);
548     descriptionLabel->set_size_request(500, -1);
549     descriptionLabel->set_single_line_mode(false);
550     descriptionLabel->set_line_wrap(true);
551     messageBox.pack_start(*notFoundLabel);
552     descriptionBox.pack_start(*descriptionLabel);
553     searchTagEntry = new Gtk::Entry();
554     searchTagEntry->set_text(searchTag);
555     searchTagEntry->set_max_length(255);
556     searchButton = new Gtk::Button(_("Search"));
557     tagBox.pack_start(*tagLabel);
558     tagBox.pack_start(*searchTagEntry, Gtk::PACK_EXPAND_WIDGET, 3);
559     tagBox.pack_start(*searchButton);
560     filesPreview = new SVGPreview();
561     filesPreview->showNoPreview();
562     // add the buttons in the bottom of the dialog
563     add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
564     okButton = add_button(Gtk::Stock::OPEN,   Gtk::RESPONSE_OK);
565     // sets the okbutton to default
566     set_default(*okButton);
567     filesList = new FileListViewText(5, *filesPreview, *descriptionLabel, *okButton);
568     filesList->set_sensitive(false);
569     // add the listview inside a ScrolledWindow
570     listScrolledWindow.add(*filesList);
571     // only show the scrollbars when they are necessary:
572     listScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
573     filesList->set_column_title(0, _("Files found"));
574     listScrolledWindow.set_size_request(400, 180);
575     filesList->get_column(1)->set_visible(false); // file url
576     filesList->get_column(2)->set_visible(false); // tmp file path
577     filesList->get_column(3)->set_visible(false); // author dir
578     filesList->get_column(4)->set_visible(false); // file description
579     filesBox.pack_start(listScrolledWindow);
580     filesBox.pack_start(*filesPreview);
581     vbox->pack_start(tagBox, false, false);
582     vbox->pack_start(messageBox);
583     vbox->pack_start(filesBox);
584     vbox->pack_start(descriptionBox);
586     //Let's do some customization
587     searchTagEntry = NULL;
588     Gtk::Container *cont = get_toplevel();
589     std::vector<Gtk::Entry *> entries;
590     findEntryWidgets(cont, entries);
591     if (entries.size() >=1 )
592     {
593     //Catch when user hits [return] on the text field
594         searchTagEntry = entries[0];
595         searchTagEntry->signal_activate().connect(
596               sigc::mem_fun(*this, &FileImportFromOCALDialog::searchTagEntryChangedCallback));
597     }
599     searchButton->signal_clicked().connect(
600             sigc::mem_fun(*this, &FileImportFromOCALDialog::searchTagEntryChangedCallback));
602     show_all_children();
603     notFoundLabel->hide();
606 /**
607  * Destructor
608  */
609 FileImportFromOCALDialog::~FileImportFromOCALDialog()
614 /**
615  * Show this dialog modally.  Return true if user hits [OK]
616  */
617 bool
618 FileImportFromOCALDialog::show()
620     set_modal (TRUE);                      //Window
621     sp_transientize((GtkWidget *)gobj());  //Make transient
622     gint b = run();                        //Dialog
623     hide();
625     if (b == Gtk::RESPONSE_OK)
626     {
627         return TRUE;
628     }
629     else
630     {
631         return FALSE;
632     }
636 /**
637  * Get the file extension type that was selected by the user. Valid after an [OK]
638  */
639 Inkscape::Extension::Extension *
640 FileImportFromOCALDialog::getSelectionType()
642     return extension;
646 /**
647  * Get the file name chosen by the user.   Valid after an [OK]
648  */
649 Glib::ustring
650 FileImportFromOCALDialog::getFilename (void)
652     return filesList->getFilename();
656 } //namespace Dialog
657 } //namespace UI
658 } //namespace Inkscape
662 /*
663   Local Variables:
664   mode:c++
665   c-file-style:"stroustrup"
666   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
667   indent-tabs-mode:nil
668   fill-column:99
669   End:
670 */
671 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :