Code

fixups for previous OCAL tempfile wranglings
[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];
281     // FIXME: this would be better as a per-user OCAL cache of files
282     // instead of filling /tmp with downloads.
283     //
284     // create file path
285     const std::string tmptemplate = "ocal-";
286     std::string tmpname;
287     int fd = Glib::file_open_tmp(tmpname, tmptemplate);
288     if (fd<0) return;
289     close(fd);
290     // make sure we don't collide with other users on the same machine
291     Glib::ustring myFilename = tmpname;
292     myFilename.append("-");
293     myFilename.append(get_text(posArray[0], 2));
294     // rename based on original image's name, retaining extension
295     if (rename(tmpname.c_str(),myFilename.c_str())<0) {
296         unlink(tmpname.c_str());
297         g_warning("Error creating destination file '%s': %s", myFilename.c_str(), strerror(errno));
298         return;
299     }
301     //get file url
302     Glib::ustring fileUrl = get_text(posArray[0], 1); //http url
304     //Glib::ustring fileUrl = "dav://"; //dav url
305     //fileUrl.append(prefs_get_string_attribute("options.ocalurl", "str"));
306     //fileUrl.append("/dav.php/");
307     //fileUrl.append(get_text(posArray[0], 3)); //author dir
308     //fileUrl.append("/");
309     //fileUrl.append(get_text(posArray[0], 2)); //filename
311     if (!Glib::get_charset()) //If we are not utf8
312         fileUrl = Glib::filename_to_utf8(fileUrl);
314     {
315         // open the temp file to receive
316         result = gnome_vfs_open (&to_handle, myFilename.c_str(), GNOME_VFS_OPEN_WRITE);
317         if (result == GNOME_VFS_ERROR_NOT_FOUND){
318             result = gnome_vfs_create (&to_handle, myFilename.c_str(), GNOME_VFS_OPEN_WRITE, FALSE, GNOME_VFS_PERM_USER_ALL);
319         }
320         if (result != GNOME_VFS_OK) {
321             g_warning("Error creating temp file '%s': %s", myFilename.c_str(), gnome_vfs_result_to_string(result));
322             return;
323         }
324         result = gnome_vfs_open (&from_handle, fileUrl.c_str(), GNOME_VFS_OPEN_READ);
325         if (result != GNOME_VFS_OK) {
326             g_warning("Could not find the file in Open Clip Art Library.");
327             return;
328         }
329         // copy the file
330         while (1) {
331             result = gnome_vfs_read (from_handle, buffer, 8192, &bytes_read);
332             if ((result == GNOME_VFS_ERROR_EOF) &&(!bytes_read)){
333                 result = gnome_vfs_close (from_handle);
334                 result = gnome_vfs_close (to_handle);
335                 break;
336             }
337             if (result != GNOME_VFS_OK) {
338                 g_warning("%s", gnome_vfs_result_to_string(result));
339                 return;
340             }
341             result = gnome_vfs_write (to_handle, buffer, bytes_read, &bytes_written);
342             if (result != GNOME_VFS_OK) {
343                 g_warning("%s", gnome_vfs_result_to_string(result));
344                 return;
345             }
346             if (bytes_read != bytes_written){
347                 g_warning("Bytes read not equal to bytes written");
348                 return;
349             }
350         }
351     }
352     myPreview->showImage(myFilename);
353     myLabel->set_text(get_text(posArray[0], 4));
354 #endif
358 /*
359  * Callback for row activated
360  */
361 void FileListViewText::on_row_activated(const Gtk::TreeModel::Path& path, Gtk::TreeViewColumn* column)
363     this->on_cursor_changed();
364     myButton->activate();
368 /*
369  * Returns the selected filename
370  */
371 Glib::ustring FileListViewText::getFilename()
373     return myFilename;
376 /**
377  * Read callback for xmlReadIO(), used below
378  */
379 static int vfs_read_callback (GnomeVFSHandle *handle, char* buf, int nb)
381     GnomeVFSFileSize ndone;
382     GnomeVFSResult    result;
384     result = gnome_vfs_read (handle, buf, nb, &ndone);
386     if (result == GNOME_VFS_OK) {
387         return (int)ndone;
388     } else {
389         if (result != GNOME_VFS_ERROR_EOF) {
390             sp_ui_error_dialog(_("Error while reading the Open Clip Art RSS feed"));
391             g_warning("%s\n", gnome_vfs_result_to_string(result));
392         }
393         return -1;
394     }
397 /**
398  * Callback for user input into searchTagEntry
399  */
400 void FileImportFromOCALDialog::searchTagEntryChangedCallback()
402     if (!searchTagEntry)
403         return;
405     notFoundLabel->hide();
406     descriptionLabel->set_text("");
408     Glib::ustring searchTag = searchTagEntry->get_text();
409     // create the ocal uri to get rss feed
410     Glib::ustring uri = "http://";
411     uri.append(prefs_get_string_attribute("options.ocalurl", "str"));
412     uri.append("/media/feed/rss/");
413     uri.append(searchTag);
414     if (!Glib::get_charset()) //If we are not utf8
415         uri = Glib::filename_to_utf8(uri);
417 #ifdef WITH_GNOME_VFS
419     // open the rss feed
420     gnome_vfs_init();
421     GnomeVFSHandle    *from_handle = NULL;
422     GnomeVFSResult    result;
424     result = gnome_vfs_open (&from_handle, uri.c_str(), GNOME_VFS_OPEN_READ);
425     if (result != GNOME_VFS_OK) {
426         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)"));
427         return;
428     }
430     // create the resulting xml document tree
431     // this initialize the library and test mistakes between compiled and shared library used
432     LIBXML_TEST_VERSION 
433     xmlDoc *doc = NULL;
434     xmlNode *root_element = NULL;
436     doc = xmlReadIO ((xmlInputReadCallback) vfs_read_callback,
437         (xmlInputCloseCallback) gnome_vfs_close, from_handle, uri.c_str(), NULL,
438         XML_PARSE_RECOVER);
439     if (doc == NULL) {
440         sp_ui_error_dialog(_("Server supplied malformed Clip Art feed"));
441         g_warning("Failed to parse %s\n", uri.c_str());
442         return;
443     }
444     
445     // get the root element node
446     root_element = xmlDocGetRootElement(doc);
448     // clear the fileslist
449     filesList->clear_items();
450     filesList->set_sensitive(false);
452     // print all xml the element names
453     print_xml_element_names(root_element);
455     if (filesList->size() == 0)
456     {
457         notFoundLabel->show();
458         filesList->set_sensitive(false);
459     }
460     else
461         filesList->set_sensitive(true);
463     // free the document
464     xmlFreeDoc(doc);
465     // free the global variables that may have been allocated by the parser
466     xmlCleanupParser();
467     return;
468 #endif    
471 /**
472  * Prints the names of the all the xml elements 
473  * that are siblings or children of a given xml node
474  */
475 void FileImportFromOCALDialog::print_xml_element_names(xmlNode * a_node)
477     xmlNode *cur_node = NULL;
478     guint row_num = 0;
479     for (cur_node = a_node; cur_node; cur_node = cur_node->next) {
480         // get itens information
481         if (strcmp((const char*)cur_node->name, "rss")) //avoid the root
482             if (cur_node->type == XML_ELEMENT_NODE && !strcmp((const char*)cur_node->parent->name, "item"))
483             {
484                 if (!strcmp((const char*)cur_node->name, "title"))
485                 {
486                     xmlChar *title = xmlNodeGetContent(cur_node);
487                     row_num = filesList->append_text((const char*)title);
488                     xmlFree(title);
489                 }
490 #ifdef WITH_GNOME_VFS
491                 else if (!strcmp((const char*)cur_node->name, "enclosure"))
492                 {
493                     xmlChar *urlattribute = xmlGetProp(cur_node, (xmlChar*)"url");
494                     filesList->set_text(row_num, 1, (const char*)urlattribute);
495                     gchar *tmp_file;
496                     tmp_file = gnome_vfs_uri_extract_short_path_name(gnome_vfs_uri_new((const char*)urlattribute));
497                     filesList->set_text(row_num, 2, (const char*)tmp_file);
498                     xmlFree(urlattribute);
499                 }
500                 else if (!strcmp((const char*)cur_node->name, "creator"))
501                 {
502                     filesList->set_text(row_num, 3, (const char*)xmlNodeGetContent(cur_node));
503                 }
504                 else if (!strcmp((const char*)cur_node->name, "description"))
505                 {
506                     filesList->set_text(row_num, 4, (const char*)xmlNodeGetContent(cur_node));
507                 }
508 #endif
509             }
510         print_xml_element_names(cur_node->children);
511     }
514 /**
515  * Constructor.  Not called directly.  Use the factory.
516  */
517 FileImportFromOCALDialog::FileImportFromOCALDialog(Gtk::Window& parentWindow, 
518                                        const Glib::ustring &dir,
519                                        FileDialogType fileTypes,
520                                        const Glib::ustring &title) :
521      FileDialogOCALBase(title, parentWindow)
523     // Initalize to Autodetect
524     extension = NULL;
525     // No filename to start out with
526     Glib::ustring searchTag = "";
528     dialogType = fileTypes;
529     Gtk::VBox *vbox = get_vbox();
530     Gtk::Label *tagLabel = new Gtk::Label(_("Search Tag"));
531     notFoundLabel = new Gtk::Label(_("No files matched your search"));
532     descriptionLabel = new Gtk::Label();
533     descriptionLabel->set_max_width_chars(60);
534     descriptionLabel->set_single_line_mode(false);
535     messageBox.pack_start(*notFoundLabel);
536     descriptionBox.pack_start(*descriptionLabel);
537     searchTagEntry = new Gtk::Entry();
538     searchTagEntry->set_text(searchTag);
539     searchTagEntry->set_max_length(255);
540     searchButton = new Gtk::Button(_("Search"));
541     tagBox.pack_start(*tagLabel);
542     tagBox.pack_start(*searchTagEntry, Gtk::PACK_EXPAND_WIDGET, 3);
543     tagBox.pack_start(*searchButton);
544     filesPreview = new SVGPreview();
545     filesPreview->showNoPreview();
546     // add the buttons in the bottom of the dialog
547     add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
548     okButton = add_button(Gtk::Stock::OPEN,   Gtk::RESPONSE_OK);
549     // sets the okbutton to default
550     set_default(*okButton);
551     filesList = new FileListViewText(5, *filesPreview, *descriptionLabel, *okButton);
552     filesList->set_sensitive(false);
553     // add the listview inside a ScrolledWindow
554     listScrolledWindow.add(*filesList);
555     // only show the scrollbars when they are necessary:
556     listScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
557     filesList->set_column_title(0, _("Files Found"));
558     listScrolledWindow.set_size_request(400, 180);
559     filesList->get_column(1)->set_visible(false); // file url
560     filesList->get_column(2)->set_visible(false); // tmp file path
561     filesList->get_column(3)->set_visible(false); // author dir
562     filesList->get_column(4)->set_visible(false); // file description
563     filesBox.pack_start(listScrolledWindow);
564     filesBox.pack_start(*filesPreview);
565     vbox->pack_start(tagBox);
566     vbox->pack_start(messageBox);
567     vbox->pack_start(filesBox);
568     vbox->pack_start(descriptionBox);
570     //Let's do some customization
571     searchTagEntry = NULL;
572     Gtk::Container *cont = get_toplevel();
573     std::vector<Gtk::Entry *> entries;
574     findEntryWidgets(cont, entries);
575     if (entries.size() >=1 )
576     {
577     //Catch when user hits [return] on the text field
578         searchTagEntry = entries[0];
579         searchTagEntry->signal_activate().connect(
580               sigc::mem_fun(*this, &FileImportFromOCALDialog::searchTagEntryChangedCallback));
581     }
583     searchButton->signal_clicked().connect(
584             sigc::mem_fun(*this, &FileImportFromOCALDialog::searchTagEntryChangedCallback));
586     show_all_children();
587     notFoundLabel->hide();
590 /**
591  * Destructor
592  */
593 FileImportFromOCALDialog::~FileImportFromOCALDialog()
598 /**
599  * Show this dialog modally.  Return true if user hits [OK]
600  */
601 bool
602 FileImportFromOCALDialog::show()
604     set_modal (TRUE);                      //Window
605     sp_transientize((GtkWidget *)gobj());  //Make transient
606     gint b = run();                        //Dialog
607     hide();
609     if (b == Gtk::RESPONSE_OK)
610     {
611         return TRUE;
612     }
613     else
614     {
615         return FALSE;
616     }
620 /**
621  * Get the file extension type that was selected by the user. Valid after an [OK]
622  */
623 Inkscape::Extension::Extension *
624 FileImportFromOCALDialog::getSelectionType()
626     return extension;
630 /**
631  * Get the file name chosen by the user.   Valid after an [OK]
632  */
633 Glib::ustring
634 FileImportFromOCALDialog::getFilename (void)
636     return filesList->getFilename();
640 } //namespace Dialog
641 } //namespace UI
642 } //namespace Inkscape
646 /*
647   Local Variables:
648   mode:c++
649   c-file-style:"stroustrup"
650   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
651   indent-tabs-mode:nil
652   fill-column:99
653   End:
654 */
655 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :