Code

cosmetics, copyedit
[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;
385 /**
386  * Read callback for xmlReadIO(), used below
387  */
388 static int vfs_read_callback (GnomeVFSHandle *handle, char* buf, int nb)
390     GnomeVFSFileSize ndone;
391     GnomeVFSResult    result;
393     result = gnome_vfs_read (handle, buf, nb, &ndone);
395     if (result == GNOME_VFS_OK) {
396         return (int)ndone;
397     } else {
398         if (result != GNOME_VFS_ERROR_EOF) {
399             sp_ui_error_dialog(_("Error while reading the Open Clip Art RSS feed"));
400             g_warning("%s\n", gnome_vfs_result_to_string(result));
401         }
402         return -1;
403     }
406 /**
407  * Callback for user input into searchTagEntry
408  */
409 void FileImportFromOCALDialog::searchTagEntryChangedCallback()
411     if (!searchTagEntry)
412         return;
414     notFoundLabel->hide();
415     descriptionLabel->set_text("");
417     Glib::ustring searchTag = searchTagEntry->get_text();
418     // create the ocal uri to get rss feed
419     Glib::ustring uri = "http://";
420     uri.append(prefs_get_string_attribute("options.ocalurl", "str"));
421     uri.append("/media/feed/rss/");
422     uri.append(searchTag);
423     if (!Glib::get_charset()) //If we are not utf8
424         uri = Glib::filename_to_utf8(uri);
426 #ifdef WITH_GNOME_VFS
428     // open the rss feed
429     gnome_vfs_init();
430     GnomeVFSHandle    *from_handle = NULL;
431     GnomeVFSResult    result;
433     result = gnome_vfs_open (&from_handle, uri.c_str(), GNOME_VFS_OPEN_READ);
434     if (result != GNOME_VFS_OK) {
435         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)"));
436         return;
437     }
439     // create the resulting xml document tree
440     // this initialize the library and test mistakes between compiled and shared library used
441     LIBXML_TEST_VERSION 
442     xmlDoc *doc = NULL;
443     xmlNode *root_element = NULL;
445     doc = xmlReadIO ((xmlInputReadCallback) vfs_read_callback,
446         (xmlInputCloseCallback) gnome_vfs_close, from_handle, uri.c_str(), NULL,
447         XML_PARSE_RECOVER);
448     if (doc == NULL) {
449         sp_ui_error_dialog(_("Server supplied malformed Clip Art feed"));
450         g_warning("Failed to parse %s\n", uri.c_str());
451         return;
452     }
453     
454     // get the root element node
455     root_element = xmlDocGetRootElement(doc);
457     // clear the fileslist
458     filesList->clear_items();
459     filesList->set_sensitive(false);
461     // print all xml the element names
462     print_xml_element_names(root_element);
464     if (filesList->size() == 0)
465     {
466         notFoundLabel->show();
467         filesList->set_sensitive(false);
468     }
469     else
470         filesList->set_sensitive(true);
472     // free the document
473     xmlFreeDoc(doc);
474     // free the global variables that may have been allocated by the parser
475     xmlCleanupParser();
476     return;
477 #endif    
480 /**
481  * Prints the names of the all the xml elements 
482  * that are siblings or children of a given xml node
483  */
484 void FileImportFromOCALDialog::print_xml_element_names(xmlNode * a_node)
486     xmlNode *cur_node = NULL;
487     guint row_num = 0;
488     for (cur_node = a_node; cur_node; cur_node = cur_node->next) {
489         // get itens information
490         if (strcmp((const char*)cur_node->name, "rss")) //avoid the root
491             if (cur_node->type == XML_ELEMENT_NODE && !strcmp((const char*)cur_node->parent->name, "item"))
492             {
493                 if (!strcmp((const char*)cur_node->name, "title"))
494                 {
495                     xmlChar *title = xmlNodeGetContent(cur_node);
496                     row_num = filesList->append_text((const char*)title);
497                     xmlFree(title);
498                 }
499 #ifdef WITH_GNOME_VFS
500                 else if (!strcmp((const char*)cur_node->name, "enclosure"))
501                 {
502                     xmlChar *urlattribute = xmlGetProp(cur_node, (xmlChar*)"url");
503                     filesList->set_text(row_num, 1, (const char*)urlattribute);
504                     gchar *tmp_file;
505                     tmp_file = gnome_vfs_uri_extract_short_path_name(gnome_vfs_uri_new((const char*)urlattribute));
506                     filesList->set_text(row_num, 2, (const char*)tmp_file);
507                     xmlFree(urlattribute);
508                 }
509                 else if (!strcmp((const char*)cur_node->name, "creator"))
510                 {
511                     filesList->set_text(row_num, 3, (const char*)xmlNodeGetContent(cur_node));
512                 }
513                 else if (!strcmp((const char*)cur_node->name, "description"))
514                 {
515                     filesList->set_text(row_num, 4, (const char*)xmlNodeGetContent(cur_node));
516                 }
517 #endif
518             }
519         print_xml_element_names(cur_node->children);
520     }
523 /**
524  * Constructor.  Not called directly.  Use the factory.
525  */
526 FileImportFromOCALDialog::FileImportFromOCALDialog(Gtk::Window& parentWindow, 
527                                        const Glib::ustring &dir,
528                                        FileDialogType fileTypes,
529                                        const Glib::ustring &title) :
530      FileDialogOCALBase(title, parentWindow)
532     // Initalize to Autodetect
533     extension = NULL;
534     // No filename to start out with
535     Glib::ustring searchTag = "";
537     dialogType = fileTypes;
538     Gtk::VBox *vbox = get_vbox();
539     Gtk::Label *tagLabel = new Gtk::Label(_("Search for:"));
540     notFoundLabel = new Gtk::Label(_("No files matched your search"));
541     descriptionLabel = new Gtk::Label();
542     descriptionLabel->set_max_width_chars(260);
543     descriptionLabel->set_size_request(500, -1);
544     descriptionLabel->set_single_line_mode(false);
545     descriptionLabel->set_line_wrap(true);
546     messageBox.pack_start(*notFoundLabel);
547     descriptionBox.pack_start(*descriptionLabel);
548     searchTagEntry = new Gtk::Entry();
549     searchTagEntry->set_text(searchTag);
550     searchTagEntry->set_max_length(255);
551     searchButton = new Gtk::Button(_("Search"));
552     tagBox.pack_start(*tagLabel);
553     tagBox.pack_start(*searchTagEntry, Gtk::PACK_EXPAND_WIDGET, 3);
554     tagBox.pack_start(*searchButton);
555     filesPreview = new SVGPreview();
556     filesPreview->showNoPreview();
557     // add the buttons in the bottom of the dialog
558     add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
559     okButton = add_button(Gtk::Stock::OPEN,   Gtk::RESPONSE_OK);
560     // sets the okbutton to default
561     set_default(*okButton);
562     filesList = new FileListViewText(5, *filesPreview, *descriptionLabel, *okButton);
563     filesList->set_sensitive(false);
564     // add the listview inside a ScrolledWindow
565     listScrolledWindow.add(*filesList);
566     // only show the scrollbars when they are necessary:
567     listScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
568     filesList->set_column_title(0, _("Files found"));
569     listScrolledWindow.set_size_request(400, 180);
570     filesList->get_column(1)->set_visible(false); // file url
571     filesList->get_column(2)->set_visible(false); // tmp file path
572     filesList->get_column(3)->set_visible(false); // author dir
573     filesList->get_column(4)->set_visible(false); // file description
574     filesBox.pack_start(listScrolledWindow);
575     filesBox.pack_start(*filesPreview);
576     vbox->pack_start(tagBox, false, false);
577     vbox->pack_start(messageBox);
578     vbox->pack_start(filesBox);
579     vbox->pack_start(descriptionBox);
581     //Let's do some customization
582     searchTagEntry = NULL;
583     Gtk::Container *cont = get_toplevel();
584     std::vector<Gtk::Entry *> entries;
585     findEntryWidgets(cont, entries);
586     if (entries.size() >=1 )
587     {
588     //Catch when user hits [return] on the text field
589         searchTagEntry = entries[0];
590         searchTagEntry->signal_activate().connect(
591               sigc::mem_fun(*this, &FileImportFromOCALDialog::searchTagEntryChangedCallback));
592     }
594     searchButton->signal_clicked().connect(
595             sigc::mem_fun(*this, &FileImportFromOCALDialog::searchTagEntryChangedCallback));
597     show_all_children();
598     notFoundLabel->hide();
601 /**
602  * Destructor
603  */
604 FileImportFromOCALDialog::~FileImportFromOCALDialog()
609 /**
610  * Show this dialog modally.  Return true if user hits [OK]
611  */
612 bool
613 FileImportFromOCALDialog::show()
615     set_modal (TRUE);                      //Window
616     sp_transientize((GtkWidget *)gobj());  //Make transient
617     gint b = run();                        //Dialog
618     hide();
620     if (b == Gtk::RESPONSE_OK)
621     {
622         return TRUE;
623     }
624     else
625     {
626         return FALSE;
627     }
631 /**
632  * Get the file extension type that was selected by the user. Valid after an [OK]
633  */
634 Inkscape::Extension::Extension *
635 FileImportFromOCALDialog::getSelectionType()
637     return extension;
641 /**
642  * Get the file name chosen by the user.   Valid after an [OK]
643  */
644 Glib::ustring
645 FileImportFromOCALDialog::getFilename (void)
647     return filesList->getFilename();
651 } //namespace Dialog
652 } //namespace UI
653 } //namespace Inkscape
657 /*
658   Local Variables:
659   mode:c++
660   c-file-style:"stroustrup"
661   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
662   indent-tabs-mode:nil
663   fill-column:99
664   End:
665 */
666 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :