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