1 // Copyright 2005 Ben Hutchings <ben@decadentplace.org.uk>.
2 // See the file "COPYING" for licence details.
18 #include <boost/shared_ptr.hpp>
20 #include <gdkmm/pixbuf.h>
21 #include <glibmm/convert.h>
22 #include <glibmm/spawn.h>
23 #include <gtkmm/main.h>
24 #include <gtkmm/window.h>
26 #include <imglib2/ImageErrors.h>
27 #include <nsGUIEvent.h>
28 #include <nsIBoxObject.h>
29 #include <nsIContent.h>
30 #include <nsIDocShell.h>
31 #include <nsIDOMAbstractView.h>
32 #include <nsIDOMBarProp.h>
33 #include <nsIDOMDocumentEvent.h>
34 #include <nsIDOMDocumentView.h>
35 #include <nsIDOMElement.h>
36 #include <nsIDOMEventTarget.h>
37 #include <nsIDOMHTMLDocument.h>
38 #include <nsIDOMMouseEvent.h>
39 #include <nsIDOMNSDocument.h>
40 #include <nsIDOMWindow.h>
41 #include <nsIEventStateManager.h>
42 #include <nsIInterfaceRequestorUtils.h>
43 #include <nsIURI.h> // required before nsILink.h
45 #include <nsIPrefBranch.h>
46 #include <nsIPrefService.h>
47 #include <nsIPresContext.h>
48 #include <nsIPresShell.h>
49 #include <nsIServiceManagerUtils.h>
50 #include <nsIWebBrowser.h>
53 #include "browserwidget.hpp"
54 #include "childiterator.hpp"
56 #include "framebuffer.hpp"
57 #include "linkiterator.hpp"
58 #include "pixbufs.hpp"
59 #include "stylesheets.hpp"
60 #include "temp_file.hpp"
62 #include "xpcom_support.hpp"
64 using xpcom_support::check;
70 int left, top; // inclusive
71 int right, bottom; // exclusive
73 rectangle operator|=(const rectangle & other)
77 // use current extents unchanged
86 // find rectangle enclosing both extents
87 left = std::min(left, other.left);
88 top = std::min(top, other.top);
89 right = std::max(right, other.right);
90 bottom = std::max(bottom, other.bottom);
96 rectangle operator&=(const rectangle & other)
98 // find rectangle enclosed in both extents
99 left = std::max(left, other.left);
100 top = std::max(top, other.top);
101 right = std::max(left, std::min(right, other.right));
102 bottom = std::max(top, std::min(bottom, other.bottom));
108 return left == right || bottom == top;
112 rectangle get_elem_rect(nsIDOMNSDocument * ns_doc,
113 nsIDOMElement * elem)
117 // Start with this element's bounding box
118 nsCOMPtr<nsIBoxObject> box;
119 check(ns_doc->GetBoxObjectFor(elem, getter_AddRefs(box)));
121 check(box->GetScreenX(&result.left));
122 check(box->GetScreenY(&result.top));
123 check(box->GetWidth(&width));
124 check(box->GetHeight(&height));
125 result.right = result.left + width;
126 result.bottom = result.top + height;
128 // Merge bounding boxes of all child elements
129 for (ChildIterator it = ChildIterator(elem), end; it != end; ++it)
131 nsCOMPtr<nsIDOMNode> child_node(*it);
133 if (check(child_node->GetNodeType(&child_type)),
134 child_type == nsIDOMNode::ELEMENT_NODE)
136 nsCOMPtr<nsIDOMElement> child_elem(
137 do_QueryInterface(child_node));
138 result |= get_elem_rect(ns_doc, child_elem);
145 class WebDvdWindow : public Gtk::Window
149 const video::frame_params & frame_params,
150 const std::string & main_page_uri,
151 const std::string & output_dir);
154 void add_page(const std::string & uri);
155 void add_video(const std::string & uri);
156 void load_next_page();
157 void on_net_state_change(const char * uri, gint flags, guint status);
159 void save_screenshot();
160 void process_links(nsIPresShell * pres_shell,
161 nsIPresContext * pres_context,
162 nsIDOMWindow * dom_window);
165 enum ResourceType { page_resource, video_resource };
166 typedef std::pair<ResourceType, int> ResourceEntry;
167 video::frame_params frame_params_;
168 std::string output_dir_;
169 BrowserWidget browser_widget_;
170 nsCOMPtr<nsIStyleSheet> stylesheet_;
171 std::queue<std::string> page_queue_;
172 std::map<std::string, ResourceEntry> resource_map_;
173 std::vector<std::vector<std::string> > page_links_;
174 std::vector<std::string> video_paths_;
175 bool pending_window_update_;
176 int pending_req_count_;
177 bool have_tweaked_page_;
178 std::auto_ptr<temp_file> background_temp_;
180 std::auto_ptr<page_state> page_state_;
181 std::vector<boost::shared_ptr<temp_file> > page_temp_files_;
184 WebDvdWindow::WebDvdWindow(
185 const video::frame_params & frame_params,
186 const std::string & main_page_uri,
187 const std::string & output_dir)
188 : frame_params_(frame_params),
189 output_dir_(output_dir),
190 stylesheet_(load_css("file://" WEBDVD_LIB_DIR "/webdvd.css")),
191 pending_window_update_(false),
192 pending_req_count_(0),
193 have_tweaked_page_(false)
195 set_size_request(frame_params_.width, frame_params_.height);
196 set_resizable(false);
198 add(browser_widget_);
199 browser_widget_.show();
200 browser_widget_.signal_net_state().connect(
201 SigC::slot(*this, &WebDvdWindow::on_net_state_change));
203 add_page(main_page_uri);
207 void WebDvdWindow::add_page(const std::string & uri)
209 if (resource_map_.insert(
210 std::make_pair(uri, ResourceEntry(page_resource, 0)))
213 page_queue_.push(uri);
217 void WebDvdWindow::add_video(const std::string & uri)
219 if (resource_map_.insert(
220 std::make_pair(uri, ResourceEntry(video_resource,
221 video_paths_.size() + 1)))
224 Glib::ustring hostname;
225 std::string filename(Glib::filename_from_uri(uri, hostname));
226 // FIXME: Should check the hostname
227 if (!Glib::file_test(filename, Glib::FILE_TEST_IS_REGULAR))
228 throw std::runtime_error(
229 filename + " is missing or not a regular file");
230 video_paths_.push_back(filename);
234 void WebDvdWindow::load_next_page()
236 assert(!page_queue_.empty());
237 const std::string & uri = page_queue_.front();
238 std::cout << "loading " << uri << std::endl;
240 std::size_t page_count = page_links_.size();
241 resource_map_[uri].second = ++page_count;
242 page_links_.resize(page_count);
244 browser_widget_.load_uri(uri);
247 void WebDvdWindow::on_net_state_change(const char * uri,
248 gint flags, guint status)
250 # ifdef DEBUG_ON_NET_STATE_CHANGE
251 std::cout << "WebDvdWindow::on_net_state_change(";
253 std::cout << '"' << uri << '"';
258 gint flags_left = flags;
259 static const struct {
263 { GTK_MOZ_EMBED_FLAG_START, "STATE_START" },
264 { GTK_MOZ_EMBED_FLAG_REDIRECTING, "STATE_REDIRECTING" },
265 { GTK_MOZ_EMBED_FLAG_TRANSFERRING, "STATE_TRANSFERRING" },
266 { GTK_MOZ_EMBED_FLAG_NEGOTIATING, "STATE_NEGOTIATING" },
267 { GTK_MOZ_EMBED_FLAG_STOP, "STATE_STOP" },
268 { GTK_MOZ_EMBED_FLAG_IS_REQUEST, "STATE_IS_REQUEST" },
269 { GTK_MOZ_EMBED_FLAG_IS_DOCUMENT, "STATE_IS_DOCUMENT" },
270 { GTK_MOZ_EMBED_FLAG_IS_NETWORK, "STATE_IS_NETWORK" },
271 { GTK_MOZ_EMBED_FLAG_IS_WINDOW, "STATE_IS_WINDOW" }
273 for (int i = 0; i != sizeof(flag_names)/sizeof(flag_names[0]); ++i)
275 if (flags & flag_names[i].value)
277 std::cout << flag_names[i].name;
278 flags_left -= flag_names[i].value;
284 std::cout << "0x" << std::setbase(16) << flags_left;
286 std::cout << ", " << "0x" << std::setbase(16) << status << ")\n";
287 # endif // DEBUG_ON_NET_STATE_CHANGE
289 if (flags & GTK_MOZ_EMBED_FLAG_IS_REQUEST)
291 if (flags & GTK_MOZ_EMBED_FLAG_START)
292 ++pending_req_count_;
294 if (flags & GTK_MOZ_EMBED_FLAG_STOP)
296 assert(pending_req_count_ != 0);
297 --pending_req_count_;
301 if (flags & GTK_MOZ_EMBED_FLAG_IS_DOCUMENT
302 && flags & GTK_MOZ_EMBED_FLAG_START)
304 pending_window_update_ = true;
305 have_tweaked_page_ = false;
308 if (flags & GTK_MOZ_EMBED_FLAG_IS_WINDOW
309 && flags & GTK_MOZ_EMBED_FLAG_STOP)
311 // Check whether the load was successful, ignoring this
313 if (status != NS_IMAGELIB_ERROR_LOAD_ABORTED)
316 pending_window_update_ = false;
319 if (pending_req_count_ == 0 && !pending_window_update_)
326 catch (std::exception & e)
328 std::cerr << "Fatal error";
329 if (!page_queue_.empty())
330 std::cerr << " while processing <" << page_queue_.front()
332 std::cerr << ": " << e.what() << "\n";
338 bool WebDvdWindow::process_page()
340 assert(!page_queue_.empty());
342 nsCOMPtr<nsIWebBrowser> browser(browser_widget_.get_browser());
343 nsCOMPtr<nsIDocShell> doc_shell(do_GetInterface(browser));
345 nsCOMPtr<nsIPresShell> pres_shell;
346 check(doc_shell->GetPresShell(getter_AddRefs(pres_shell)));
347 nsCOMPtr<nsIPresContext> pres_context;
348 check(doc_shell->GetPresContext(getter_AddRefs(pres_context)));
349 nsCOMPtr<nsIDOMWindow> dom_window;
350 check(browser->GetContentDOMWindow(getter_AddRefs(dom_window)));
352 // If we haven't done so already, apply the stylesheet and
353 // disable scrollbars.
354 if (!have_tweaked_page_)
356 apply_style_sheet(stylesheet_, pres_shell);
358 // This actually only needs to be done once.
359 nsCOMPtr<nsIDOMBarProp> dom_bar_prop;
360 check(dom_window->GetScrollbars(getter_AddRefs(dom_bar_prop)));
361 check(dom_bar_prop->SetVisible(false));
363 have_tweaked_page_ = true;
365 // Might need to wait a while for things to load or more
366 // likely for a re-layout.
367 if (pending_req_count_ > 0)
371 // All further work should only be done if we're not in preview mode.
372 if (!output_dir_.empty())
374 // If we haven't already started work on this page, save a
375 // screenshot of its normal appearance.
376 if (!page_state_.get())
379 // Start or continue processing links.
380 process_links(pres_shell, pres_context, dom_window);
382 // If we've finished work on the links, move on to the
383 // next page, if any, or else generate the DVD filesystem.
384 if (!page_state_.get())
387 if (page_queue_.empty())
402 void WebDvdWindow::save_screenshot()
404 Glib::RefPtr<Gdk::Window> window(get_window());
406 window->process_updates(true);
408 background_temp_.reset(new temp_file("webdvd-back-"));
409 background_temp_->close();
410 std::cout << "saving " << background_temp_->get_name() << std::endl;
411 Gdk::Pixbuf::create(Glib::RefPtr<Gdk::Drawable>(window),
412 window->get_colormap(),
414 frame_params_.width, frame_params_.height)
415 ->save(background_temp_->get_name(), "png");
418 struct WebDvdWindow::page_state
420 page_state(nsIDOMDocument * doc, int width, int height)
421 : diff_pixbuf(Gdk::Pixbuf::create(
423 true, 8, // has_alpha, bits_per_sample
425 spumux_temp("webdvd-spumux-"),
426 links_temp("webdvd-links-"),
435 Glib::RefPtr<Gdk::Pixbuf> diff_pixbuf;
437 temp_file spumux_temp;
438 std::ofstream spumux_file;
440 temp_file links_temp;
443 LinkIterator links_it, links_end;
447 Glib::RefPtr<Gdk::Pixbuf> norm_pixbuf;
450 void WebDvdWindow::process_links(nsIPresShell * pres_shell,
451 nsIPresContext * pres_context,
452 nsIDOMWindow * dom_window)
454 Glib::RefPtr<Gdk::Window> window(get_window());
457 nsCOMPtr<nsIDOMDocument> basic_doc;
458 check(dom_window->GetDocument(getter_AddRefs(basic_doc)));
459 nsCOMPtr<nsIDOMNSDocument> ns_doc(do_QueryInterface(basic_doc));
461 nsCOMPtr<nsIEventStateManager> event_state_man(
462 pres_context->EventStateManager()); // does not AddRef
463 assert(event_state_man);
464 nsCOMPtr<nsIDOMDocumentEvent> event_factory(
465 do_QueryInterface(basic_doc));
466 assert(event_factory);
467 nsCOMPtr<nsIDOMDocumentView> doc_view(do_QueryInterface(basic_doc));
469 nsCOMPtr<nsIDOMAbstractView> view;
470 check(doc_view->GetDefaultView(getter_AddRefs(view)));
472 // Set up or recover our iteration state.
473 std::auto_ptr<page_state> state(page_state_);
478 basic_doc, frame_params_.width, frame_params_.height));
480 state->spumux_file.open(state->spumux_temp.get_name().c_str());
481 state->spumux_file <<
484 " <spu force='yes' start='00:00:00.00'\n"
485 " highlight='" << state->links_temp.get_name() << "'\n"
486 " select='" << state->links_temp.get_name() << "'>\n";
489 rectangle window_rect = {
490 0, 0, frame_params_.width, frame_params_.height
493 for (/* no initialisation */;
494 state->links_it != state->links_end;
497 nsCOMPtr<nsIDOMNode> node(*state->links_it);
499 // Find the link URI.
500 nsCOMPtr<nsILink> link(do_QueryInterface(node));
502 nsCOMPtr<nsIURI> uri;
503 check(link->GetHrefURI(getter_AddRefs(uri)));
504 std::string uri_string;
506 nsCString uri_ns_string;
507 check(uri->GetSpec(uri_ns_string));
508 uri_string.assign(uri_ns_string.BeginReading(),
509 uri_ns_string.EndReading());
511 std::string uri_sans_fragment(uri_string, 0, uri_string.find('#'));
513 // Is this a new link?
514 if (!state->link_changing)
516 // Find a rectangle enclosing the link and clip it to the
518 nsCOMPtr<nsIDOMElement> elem(do_QueryInterface(node));
520 state->link_rect = get_elem_rect(ns_doc, elem);
521 state->link_rect &= window_rect;
523 if (state->link_rect.empty())
525 std::cerr << "Ignoring invisible link to "
526 << uri_string << "\n";
532 if (state->link_num >= dvd::menu_buttons_max)
534 if (state->link_num == dvd::menu_buttons_max)
535 std::cerr << "No more than " << dvd::menu_buttons_max
536 << " buttons can be placed on a page\n";
537 std::cerr << "Ignoring link to " << uri_string << "\n";
541 // Check whether this is a link to a video or a page then
542 // add it to the known resources if not already seen.
544 check(uri->GetPath(path));
545 // FIXME: This is a bit of a hack. Perhaps we could decide
546 // later based on the MIME type determined by Mozilla?
547 if ((path.Length() > 4
548 && std::strcmp(path.EndReading() - 4, ".vob") == 0)
549 || (path.Length() > 8
550 && std::strcmp(path.EndReading() - 8, ".voblist")
554 check(uri->SchemeIs("file", &is_file));
557 std::cerr << "Links to video must use the file:"
561 add_video(uri_sans_fragment);
565 add_page(uri_sans_fragment);
568 nsCOMPtr<nsIContent> content(do_QueryInterface(node));
570 nsCOMPtr<nsIDOMEventTarget> event_target(
571 do_QueryInterface(node));
572 assert(event_target);
574 state->norm_pixbuf = Gdk::Pixbuf::create(
575 Glib::RefPtr<Gdk::Drawable>(window),
576 window->get_colormap(),
577 state->link_rect.left,
578 state->link_rect.top,
581 state->link_rect.right - state->link_rect.left,
582 state->link_rect.bottom - state->link_rect.top);
584 nsCOMPtr<nsIDOMEvent> event;
585 check(event_factory->CreateEvent(
586 NS_ConvertASCIItoUTF16("MouseEvents"),
587 getter_AddRefs(event)));
588 nsCOMPtr<nsIDOMMouseEvent> mouse_event(
589 do_QueryInterface(event));
591 check(mouse_event->InitMouseEvent(
592 NS_ConvertASCIItoUTF16("mouseover"),
596 0, // detail: mouse click count
597 state->link_rect.left, // screenX
598 state->link_rect.top, // screenY
599 state->link_rect.left, // clientX
600 state->link_rect.top, // clientY
601 false, false, false, false, // qualifiers
602 0, // button: left (or primary)
603 0)); // related target
605 check(event_target->DispatchEvent(mouse_event,
607 check(event_state_man->SetContentState(content,
608 NS_EVENT_STATE_HOVER));
610 pres_shell->FlushPendingNotifications(true);
612 // We may have to exit and wait for image loading
613 // to complete, at which point we will be called
615 if (pending_req_count_ > 0)
617 state->link_changing = true;
623 window->process_updates(true);
625 Glib::RefPtr<Gdk::Pixbuf> changed_pixbuf(
627 Glib::RefPtr<Gdk::Drawable>(window),
628 window->get_colormap(),
629 state->link_rect.left,
630 state->link_rect.top,
633 state->link_rect.right - state->link_rect.left,
634 state->link_rect.bottom - state->link_rect.top));
639 state->link_rect.left,
640 state->link_rect.top,
641 state->link_rect.right - state->link_rect.left,
642 state->link_rect.bottom - state->link_rect.top);
644 state->spumux_file <<
645 " <button x0='" << state->link_rect.left << "'"
646 " y0='" << state->link_rect.top << "'"
647 " x1='" << state->link_rect.right - 1 << "'"
648 " y1='" << state->link_rect.bottom - 1 << "'/>\n";
650 // Add to the page's links, ignoring any fragment (for now).
651 page_links_.back().push_back(uri_sans_fragment);
654 quantise_rgba_pixbuf(state->diff_pixbuf, dvd::button_n_colours);
656 std::cout << "saving " << state->links_temp.get_name()
658 state->diff_pixbuf->save(state->links_temp.get_name(), "png");
660 state->spumux_file <<
665 state->spumux_file.close();
667 // TODO: if (!state->spumux_file) throw ...
670 boost::shared_ptr<temp_file> vob_temp(
671 new temp_file("webdvd-vob-"));
672 std::ostringstream command_stream;
673 command_stream << "pngtopnm "
674 << background_temp_->get_name()
675 << " | ppmtoy4m -v0 -n1 -F"
676 << frame_params_.rate_numer
677 << ":" << frame_params_.rate_denom
678 << " -A" << frame_params_.pixel_ratio_width
679 << ":" << frame_params_.pixel_ratio_height
680 << (" -Ip -S420_mpeg2"
681 " | mpeg2enc -v0 -f8 -a2 -o/dev/stdout"
682 " | mplex -v0 -f8 -o/dev/stdout /dev/stdin"
683 " | spumux -v0 -mdvd ")
684 << state->spumux_temp.get_name()
685 << " > " << vob_temp->get_name();
686 std::string command(command_stream.str());
687 const char * argv[] = {
688 "/bin/sh", "-c", command.c_str(), 0
690 std::cout << "running " << argv[2] << std::endl;
692 Glib::spawn_sync(".",
693 Glib::ArrayHandle<std::string>(
694 argv, sizeof(argv)/sizeof(argv[0]),
695 Glib::OWNERSHIP_NONE),
696 Glib::SPAWN_STDOUT_TO_DEV_NULL,
700 if (command_result != 0)
701 throw std::runtime_error("spumux pipeline failed");
703 page_temp_files_.push_back(vob_temp);
707 void generate_page_dispatch(std::ostream &, int indent,
708 int first_page, int last_page);
710 void WebDvdWindow::generate_dvd()
712 temp_file temp("webdvd-dvdauthor-");
714 std::ofstream file(temp.get_name().c_str());
716 // We generate code that uses registers in the following way:
718 // g0: link destination (when jumping to menu 1), then scratch
719 // g1: current location
720 // g2-g11: location history (g2 = most recent)
721 // g12: location that last linked to a video
723 // All locations are divided into two bitfields: the least
724 // significant 10 bits are a page/menu number and the most
725 // significant 6 bits are a link/button number. This is
726 // chosen for compatibility with the encoding of the s8
727 // (button) register.
729 static const int link_mult = dvd::reg_s8_button_mult;
730 static const int page_mask = link_mult - 1;
731 static const int link_mask = (1 << dvd::reg_bits) - link_mult;
738 for (std::size_t page_num = 1;
739 page_num <= page_links_.size();
742 std::vector<std::string> & page_links =
743 page_links_[page_num - 1];
747 // This is the first page (root menu) which needs to
748 // include initialisation and dispatch code.
751 " <pgc entry='title'>\n"
753 // Has the location been set yet?
756 // Initialise the current location to first link on
758 " g1 = " << 1 * link_mult + 1 << ";\n"
762 // Has the user selected a link?
765 // First update the history.
766 // Does link go to the last page in the history?
767 " if (((g0 ^ g2) & " << page_mask
769 // It does; we treat this as going back and pop the old
770 // location off the history stack into the current
771 // location. Clear the free stack slot.
773 " g1 = g2; g2 = g3; g3 = g4; g4 = g5;\n"
774 " g5 = g6; g6 = g7; g7 = g8; g8 = g9;\n"
775 " g9 = g10; g10 = g11; g11 = 0;\n"
778 // Link goes to some other page, so push current
779 // location onto the history stack and set the current
780 // location to be exactly the target location.
782 " g11 = g10; g10 = g9; g9 = g8; g8 = g7;\n"
783 " g7 = g6; g6 = g5; g5 = g4; g4 = g3;\n"
784 " g3 = g2; g2 = g1; g1 = g0;\n"
787 // Find the target page number.
788 " g0 = g1 & " << page_mask << ";\n";
789 // There seems to be no way to perform a computed jump,
790 // so we generate all possible jumps and a binary search
791 // to select the correct one.
792 generate_page_dispatch(file, 12, 1, page_links_.size());
796 else // page_num != 1
804 // Clear link indicator and highlight the
805 // appropriate link/button.
806 " g0 = 0; s8 = g1 & " << link_mask << ";\n"
809 << page_temp_files_[page_num - 1]->get_name() << "'/>\n";
811 for (std::size_t link_num = 1;
812 link_num <= page_links.size();
817 // Update current location.
818 " g1 = " << link_num * link_mult + page_num << ";";
820 // Jump to appropriate resource.
821 const ResourceEntry & resource_loc =
822 resource_map_[page_links[link_num - 1]];
823 if (resource_loc.first == page_resource)
825 " g0 = " << 1 * link_mult + resource_loc.second << ";"
827 else if (resource_loc.first == video_resource)
828 file << " jump title " << resource_loc.second << ";";
830 file << " </button>\n";
840 // Generate a titleset for each video. This appears to make
841 // jumping to titles a whole lot simpler.
842 for (std::size_t video_num = 1;
843 video_num <= video_paths_.size();
848 // Generate a dummy menu so that the menu button on the
849 // remote control will work.
851 " <pgc entry='root'>\n"
852 " <pre> jump vmgm menu; </pre>\n"
857 // Record calling page/menu.
858 " <pre> g12 = g1; </pre>\n";
860 // Write a reference to a linked VOB file, or the contents
861 // of a linked VOB list file.
862 const std::string & video_path = video_paths_[video_num - 1];
863 if (video_path.compare(video_path.size() - 4, 4, ".vob") == 0)
865 // FIXME: Should XML-escape the path
866 file << " <vob file='" << video_path << "'/>\n";
870 assert(video_path.compare(video_path.size() - 8, 8,
872 // TODO: Validate the file contents;
873 file << Glib::file_get_contents(video_path);
877 // If page/menu location has not been changed during the
878 // video, change the location to be the following
879 // link/button when returning to it. In any case,
880 // return to a page/menu.
881 " <post> if (g1 eq g12) g1 = g1 + " << link_mult
882 << "; call menu; </post>\n"
894 const char * argv[] = {
896 "-o", output_dir_.c_str(),
897 "-x", temp.get_name().c_str(),
901 Glib::spawn_sync(".",
902 Glib::ArrayHandle<std::string>(
903 argv, sizeof(argv)/sizeof(argv[0]),
904 Glib::OWNERSHIP_NONE),
905 Glib::SPAWN_SEARCH_PATH
906 | Glib::SPAWN_STDOUT_TO_DEV_NULL,
910 if (command_result != 0)
911 throw std::runtime_error("dvdauthor failed");
915 void generate_page_dispatch(std::ostream & file, int indent,
916 int first_page, int last_page)
918 if (first_page == 1 && last_page == 1)
920 // The dispatch code is *on* page 1 so we must not dispatch to
921 // page 1 since that would cause an infinite loop. This case
922 // should be unreachable if there is more than one page due
923 // to the following case.
925 else if (first_page == 1 && last_page == 2)
927 // dvdauthor doesn't allow empty blocks or null statements so
928 // when selecting between pages 1 and 2 we don't use an "else"
929 // part. We must use braces so that a following "else" will
930 // match the right "if".
931 file << std::setw(indent) << "" << "{\n"
932 << std::setw(indent) << "" << "if (g0 eq 2)\n"
933 << std::setw(indent + 2) << "" << "jump menu 2;\n"
934 << std::setw(indent) << "" << "}\n";
936 else if (first_page == last_page)
938 file << std::setw(indent) << ""
939 << "jump menu " << first_page << ";\n";
943 int middle = (first_page + last_page) / 2;
944 file << std::setw(indent) << "" << "if (g0 le " << middle << ")\n";
945 generate_page_dispatch(file, indent + 2, first_page, middle);
946 file << std::setw(indent) << "" << "else\n";
947 generate_page_dispatch(file, indent + 2, middle + 1, last_page);
951 const video::frame_params & lookup_frame_params(const char * str)
954 static const struct { const char * str; bool is_ntsc; }
960 // For DVD purposes, SECAM can be treated identically to PAL.
964 for (std::size_t i = 0;
965 i != sizeof(known_strings)/sizeof(known_strings[0]);
967 if (std::strcmp(str, known_strings[i].str) == 0)
968 return known_strings[i].is_ntsc ?
969 video::ntsc_params : video::pal_params;
970 throw std::runtime_error(
971 std::string("Invalid video standard: ").append(str));
974 void print_usage(std::ostream & stream, const char * command_name)
976 stream << "Usage: " << command_name
977 << (" [gtk-options] [--video-std std-name]"
978 " [--preview] menu-url [output-dir]\n");
981 void set_browser_preferences()
983 // Disable IE-compatibility kluge that causes backgrounds to
984 // sometimes/usually be missing from snapshots. This is only
985 // effective from Mozilla 1.8 onward.
986 # if MOZ_VERSION_MAJOR > 1 \
987 || (MOZ_VERSION_MAJOR == 1 && MOZ_VERSION_MINOR >= 8)
988 nsCOMPtr<nsIPrefService> pref_service;
989 static const nsCID pref_service_cid = NS_PREFSERVICE_CID;
990 check(CallGetService<nsIPrefService>(pref_service_cid,
991 getter_AddRefs(pref_service)));
992 nsCOMPtr<nsIPrefBranch> pref_branch;
993 check(pref_service->GetDefaultBranch("layout",
994 getter_AddRefs(pref_branch)));
995 check(pref_branch->SetBoolPref(
996 "fire_onload_after_image_background_loads",
1000 // TODO: Set display resolution? Unfortunately Mozilla doesn't
1001 // support non-square pixels (and neither do fontconfig or Xft
1007 int main(int argc, char ** argv)
1011 video::frame_params frame_params = video::pal_params;
1012 bool preview_mode = false;
1013 std::string menu_url;
1014 std::string output_dir;
1016 // Do initial option parsing. We have to do this before
1017 // letting Gtk parse the arguments since we may need to spawn
1020 while (argi != argc)
1022 if (std::strcmp(argv[argi], "--") == 0)
1026 else if (std::strcmp(argv[argi], "--help") == 0)
1028 print_usage(std::cout, argv[0]);
1029 return EXIT_SUCCESS;
1031 else if (std::strcmp(argv[argi], "--preview") == 0)
1033 preview_mode = true;
1036 else if (std::strcmp(argv[argi], "--video-std") == 0)
1038 if (argi + 1 == argc)
1040 std::cerr << "Missing argument to --video-std\n";
1041 print_usage(std::cerr, argv[0]);
1042 return EXIT_FAILURE;
1044 frame_params = lookup_frame_params(argv[argi + 1]);
1053 std::auto_ptr<FrameBuffer> fb;
1056 // Spawn Xvfb and set env variables so that Xlib will use it
1057 // Use 8 bits each for RGB components, which should translate into
1058 // "enough" bits for YUV components.
1059 fb.reset(new FrameBuffer(frame_params.width, frame_params.height,
1061 setenv("XAUTHORITY", fb->get_x_authority().c_str(), true);
1062 setenv("DISPLAY", fb->get_x_display().c_str(), true);
1066 Gtk::Main kit(argc, argv);
1068 // Complete option parsing with Gtk's options out of the way.
1070 while (argi != argc)
1072 if (std::strcmp(argv[argi], "--") == 0)
1077 else if (std::strcmp(argv[argi], "--preview") == 0)
1081 else if (std::strcmp(argv[argi], "--video-std") == 0)
1085 else if (argv[argi][0] == '-')
1087 std::cerr << "Invalid option: " << argv[argi] << "\n";
1088 print_usage(std::cerr, argv[0]);
1089 return EXIT_FAILURE;
1097 // Look for a starting URL or filename and (except in preview
1098 // mode) an output directory after the options.
1099 if (argc - argi != (preview_mode ? 1 : 2))
1101 print_usage(std::cerr, argv[0]);
1102 return EXIT_FAILURE;
1104 if (std::strstr(argv[argi], "://"))
1106 // It appears to be an absolute URL, so use it as-is.
1107 menu_url = argv[argi];
1111 // Assume it's a filename. Resolve it to an absolute URL.
1112 std::string path(argv[argi]);
1113 if (!Glib::path_is_absolute(path))
1114 path = Glib::build_filename(Glib::get_current_dir(), path);
1115 menu_url = Glib::filename_to_uri(path);
1118 output_dir = argv[argi + 1];
1120 // Initialise Mozilla
1121 BrowserWidget::Initialiser browser_init;
1122 set_browser_preferences();
1124 // Run the browser/converter
1125 WebDvdWindow window(frame_params, menu_url, output_dir);
1126 Gtk::Main::run(window);
1128 catch (std::exception & e)
1130 std::cerr << "Fatal error: " << e.what() << "\n";
1131 return EXIT_FAILURE;
1134 return EXIT_SUCCESS;