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 "browser_widget.hpp"
54 #include "child_iterator.hpp"
56 #include "link_iterator.hpp"
57 #include "pixbufs.hpp"
58 #include "style_sheets.hpp"
59 #include "temp_file.hpp"
61 #include "x_frame_buffer.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 (child_iterator it = child_iterator(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);
147 enum pgc_type { menu_pgc, title_pgc };
148 typedef std::pair<pgc_type, int> pgc_ref;
153 : vob_temp(new temp_file("webdvd-vob-"))
158 boost::shared_ptr<temp_file> vob_temp;
159 std::vector<pgc_ref> entries;
164 explicit title(const std::string & vob_list)
168 std::string vob_list;
171 std::vector<menu> menus;
172 std::vector<title> titles;
175 class webdvd_window : public Gtk::Window
179 const video::frame_params & frame_params,
180 const std::string & main_page_uri,
181 const std::string & output_dir);
184 dvd_contents::pgc_ref add_menu(const std::string & uri);
185 dvd_contents::pgc_ref add_title(const std::string & uri);
186 void load_next_page();
187 void on_net_state_change(const char * uri, gint flags, guint status);
189 void save_screenshot();
190 void process_links(nsIPresShell * pres_shell,
191 nsIPresContext * pres_context,
192 nsIDOMWindow * dom_window);
195 video::frame_params frame_params_;
196 std::string output_dir_;
197 browser_widget browser_widget_;
198 nsCOMPtr<nsIStyleSheet> stylesheet_;
200 dvd_contents contents_;
201 typedef std::map<std::string, dvd_contents::pgc_ref> resource_map_type;
202 resource_map_type resource_map_;
204 std::queue<std::string> page_queue_;
205 bool pending_window_update_;
206 int pending_req_count_;
207 bool have_tweaked_page_;
208 std::auto_ptr<temp_file> background_temp_;
210 std::auto_ptr<page_state> page_state_;
213 webdvd_window::webdvd_window(
214 const video::frame_params & frame_params,
215 const std::string & main_page_uri,
216 const std::string & output_dir)
217 : frame_params_(frame_params),
218 output_dir_(output_dir),
219 stylesheet_(load_css("file://" WEBDVD_LIB_DIR "/webdvd.css")),
220 pending_window_update_(false),
221 pending_req_count_(0),
222 have_tweaked_page_(false)
224 set_size_request(frame_params_.width, frame_params_.height);
225 set_resizable(false);
227 add(browser_widget_);
228 browser_widget_.show();
229 browser_widget_.signal_net_state().connect(
230 SigC::slot(*this, &webdvd_window::on_net_state_change));
232 add_menu(main_page_uri);
236 dvd_contents::pgc_ref webdvd_window::add_menu(const std::string & uri)
238 dvd_contents::pgc_ref next_menu(dvd_contents::menu_pgc,
239 contents_.menus.size());
240 std::pair<resource_map_type::iterator, bool> insert_result(
241 resource_map_.insert(std::make_pair(uri, next_menu)));
243 if (!insert_result.second)
245 return insert_result.first->second;
249 page_queue_.push(uri);
250 contents_.menus.resize(contents_.menus.size() + 1);
255 dvd_contents::pgc_ref webdvd_window::add_title(const std::string & uri)
257 dvd_contents::pgc_ref next_title(dvd_contents::title_pgc,
258 contents_.titles.size());
259 std::pair<resource_map_type::iterator, bool> insert_result(
260 resource_map_.insert(std::make_pair(uri, next_title)));
262 if (!insert_result.second)
264 return insert_result.first->second;
268 Glib::ustring hostname;
269 std::string filename(Glib::filename_from_uri(uri, hostname));
270 // FIXME: Should check the hostname
272 std::string vob_list;
274 // Store a reference to a linked VOB file, or the contents
275 // of a linked VOB list file.
276 if (filename.compare(filename.size() - 4, 4, ".vob") == 0)
278 if (!Glib::file_test(filename, Glib::FILE_TEST_IS_REGULAR))
279 throw std::runtime_error(
280 filename + " is missing or not a regular file");
282 .append("<vob file='")
283 // FIXME: Should XML-escape the path
289 assert(filename.compare(filename.size() - 8, 8, ".voblist")
291 // TODO: Validate the file contents
292 vob_list.assign(Glib::file_get_contents(filename));
295 contents_.titles.push_back(dvd_contents::title(vob_list));
300 void webdvd_window::load_next_page()
302 assert(!page_queue_.empty());
303 const std::string & uri = page_queue_.front();
304 std::cout << "loading " << uri << std::endl;
306 browser_widget_.load_uri(uri);
309 void webdvd_window::on_net_state_change(const char * uri,
310 gint flags, guint status)
312 # ifdef DEBUG_ON_NET_STATE_CHANGE
313 std::cout << "webdvd_window::on_net_state_change(";
315 std::cout << '"' << uri << '"';
320 gint flags_left = flags;
321 static const struct {
325 { GTK_MOZ_EMBED_FLAG_START, "STATE_START" },
326 { GTK_MOZ_EMBED_FLAG_REDIRECTING, "STATE_REDIRECTING" },
327 { GTK_MOZ_EMBED_FLAG_TRANSFERRING, "STATE_TRANSFERRING" },
328 { GTK_MOZ_EMBED_FLAG_NEGOTIATING, "STATE_NEGOTIATING" },
329 { GTK_MOZ_EMBED_FLAG_STOP, "STATE_STOP" },
330 { GTK_MOZ_EMBED_FLAG_IS_REQUEST, "STATE_IS_REQUEST" },
331 { GTK_MOZ_EMBED_FLAG_IS_DOCUMENT, "STATE_IS_DOCUMENT" },
332 { GTK_MOZ_EMBED_FLAG_IS_NETWORK, "STATE_IS_NETWORK" },
333 { GTK_MOZ_EMBED_FLAG_IS_WINDOW, "STATE_IS_WINDOW" }
335 for (int i = 0; i != sizeof(flag_names)/sizeof(flag_names[0]); ++i)
337 if (flags & flag_names[i].value)
339 std::cout << flag_names[i].name;
340 flags_left -= flag_names[i].value;
346 std::cout << "0x" << std::setbase(16) << flags_left;
348 std::cout << ", " << "0x" << std::setbase(16) << status << ")\n";
349 # endif // DEBUG_ON_NET_STATE_CHANGE
351 if (flags & GTK_MOZ_EMBED_FLAG_IS_REQUEST)
353 if (flags & GTK_MOZ_EMBED_FLAG_START)
354 ++pending_req_count_;
356 if (flags & GTK_MOZ_EMBED_FLAG_STOP)
358 assert(pending_req_count_ != 0);
359 --pending_req_count_;
363 if (flags & GTK_MOZ_EMBED_FLAG_IS_DOCUMENT
364 && flags & GTK_MOZ_EMBED_FLAG_START)
366 pending_window_update_ = true;
367 have_tweaked_page_ = false;
370 if (flags & GTK_MOZ_EMBED_FLAG_IS_WINDOW
371 && flags & GTK_MOZ_EMBED_FLAG_STOP)
373 // Check whether the load was successful, ignoring this
375 if (status != NS_IMAGELIB_ERROR_LOAD_ABORTED)
378 pending_window_update_ = false;
381 if (pending_req_count_ == 0 && !pending_window_update_)
388 catch (std::exception & e)
390 std::cerr << "Fatal error";
391 if (!page_queue_.empty())
392 std::cerr << " while processing <" << page_queue_.front()
394 std::cerr << ": " << e.what() << "\n";
400 bool webdvd_window::process_page()
402 assert(!page_queue_.empty());
404 nsCOMPtr<nsIWebBrowser> browser(browser_widget_.get_browser());
405 nsCOMPtr<nsIDocShell> doc_shell(do_GetInterface(browser));
407 nsCOMPtr<nsIPresShell> pres_shell;
408 check(doc_shell->GetPresShell(getter_AddRefs(pres_shell)));
409 nsCOMPtr<nsIPresContext> pres_context;
410 check(doc_shell->GetPresContext(getter_AddRefs(pres_context)));
411 nsCOMPtr<nsIDOMWindow> dom_window;
412 check(browser->GetContentDOMWindow(getter_AddRefs(dom_window)));
414 // If we haven't done so already, apply the stylesheet and
415 // disable scrollbars.
416 if (!have_tweaked_page_)
418 apply_style_sheet(stylesheet_, pres_shell);
420 // This actually only needs to be done once.
421 nsCOMPtr<nsIDOMBarProp> dom_bar_prop;
422 check(dom_window->GetScrollbars(getter_AddRefs(dom_bar_prop)));
423 check(dom_bar_prop->SetVisible(false));
425 have_tweaked_page_ = true;
427 // Might need to wait a while for things to load or more
428 // likely for a re-layout.
429 if (pending_req_count_ > 0)
433 // All further work should only be done if we're not in preview mode.
434 if (!output_dir_.empty())
436 // If we haven't already started work on this menu, save a
437 // screenshot of its normal appearance.
438 if (!page_state_.get())
441 // Start or continue processing links.
442 process_links(pres_shell, pres_context, dom_window);
444 // If we've finished work on the links, move on to the
445 // next page, if any, or else generate the DVD filesystem.
446 if (!page_state_.get())
449 if (page_queue_.empty())
464 void webdvd_window::save_screenshot()
466 Glib::RefPtr<Gdk::Window> window(get_window());
468 window->process_updates(true);
470 background_temp_.reset(new temp_file("webdvd-back-"));
471 background_temp_->close();
472 std::cout << "saving " << background_temp_->get_name() << std::endl;
473 Gdk::Pixbuf::create(Glib::RefPtr<Gdk::Drawable>(window),
474 window->get_colormap(),
476 frame_params_.width, frame_params_.height)
477 ->save(background_temp_->get_name(), "png");
480 struct webdvd_window::page_state
482 page_state(nsIDOMDocument * doc, int width, int height)
483 : diff_pixbuf(Gdk::Pixbuf::create(
485 true, 8, // has_alpha, bits_per_sample
487 spumux_temp("webdvd-spumux-"),
488 links_temp("webdvd-links-"),
497 Glib::RefPtr<Gdk::Pixbuf> diff_pixbuf;
499 temp_file spumux_temp;
500 std::ofstream spumux_file;
502 temp_file links_temp;
505 link_iterator links_it, links_end;
509 Glib::RefPtr<Gdk::Pixbuf> norm_pixbuf;
512 void webdvd_window::process_links(nsIPresShell * pres_shell,
513 nsIPresContext * pres_context,
514 nsIDOMWindow * dom_window)
516 Glib::RefPtr<Gdk::Window> window(get_window());
519 nsCOMPtr<nsIDOMDocument> basic_doc;
520 check(dom_window->GetDocument(getter_AddRefs(basic_doc)));
521 nsCOMPtr<nsIDOMNSDocument> ns_doc(do_QueryInterface(basic_doc));
523 nsCOMPtr<nsIEventStateManager> event_state_man(
524 pres_context->EventStateManager()); // does not AddRef
525 assert(event_state_man);
526 nsCOMPtr<nsIDOMDocumentEvent> event_factory(
527 do_QueryInterface(basic_doc));
528 assert(event_factory);
529 nsCOMPtr<nsIDOMDocumentView> doc_view(do_QueryInterface(basic_doc));
531 nsCOMPtr<nsIDOMAbstractView> view;
532 check(doc_view->GetDefaultView(getter_AddRefs(view)));
534 // Set up or recover our iteration state.
535 std::auto_ptr<page_state> state(page_state_);
540 basic_doc, frame_params_.width, frame_params_.height));
542 state->spumux_file.open(state->spumux_temp.get_name().c_str());
543 state->spumux_file <<
546 " <spu force='yes' start='00:00:00.00'\n"
547 " highlight='" << state->links_temp.get_name() << "'\n"
548 " select='" << state->links_temp.get_name() << "'>\n";
551 rectangle window_rect = {
552 0, 0, frame_params_.width, frame_params_.height
555 int menu_num = resource_map_[page_queue_.front()].second;
557 for (/* no initialisation */;
558 state->links_it != state->links_end;
561 nsCOMPtr<nsIDOMNode> node(*state->links_it);
563 // Find the link URI.
564 nsCOMPtr<nsILink> link(do_QueryInterface(node));
566 nsCOMPtr<nsIURI> uri;
567 check(link->GetHrefURI(getter_AddRefs(uri)));
568 std::string uri_string;
570 nsCString uri_ns_string;
571 check(uri->GetSpec(uri_ns_string));
572 uri_string.assign(uri_ns_string.BeginReading(),
573 uri_ns_string.EndReading());
575 std::string uri_sans_fragment(uri_string, 0, uri_string.find('#'));
577 // Is this a new link?
578 if (!state->link_changing)
580 // Find a rectangle enclosing the link and clip it to the
582 nsCOMPtr<nsIDOMElement> elem(do_QueryInterface(node));
584 state->link_rect = get_elem_rect(ns_doc, elem);
585 state->link_rect &= window_rect;
587 if (state->link_rect.empty())
589 std::cerr << "Ignoring invisible link to "
590 << uri_string << "\n";
596 if (state->link_num >= dvd::menu_buttons_max)
598 if (state->link_num == dvd::menu_buttons_max)
599 std::cerr << "No more than " << dvd::menu_buttons_max
600 << " buttons can be placed on a menu\n";
601 std::cerr << "Ignoring link to " << uri_string << "\n";
605 state->spumux_file <<
606 " <button x0='" << state->link_rect.left << "'"
607 " y0='" << state->link_rect.top << "'"
608 " x1='" << state->link_rect.right - 1 << "'"
609 " y1='" << state->link_rect.bottom - 1 << "'/>\n";
611 // Check whether this is a link to a video or a page then
612 // add it to the known resources if not already seen; then
613 // add it to the menu entries.
615 check(uri->GetPath(path));
616 dvd_contents::pgc_ref dest_pgc;
617 // FIXME: This is a bit of a hack. Perhaps we could decide
618 // later based on the MIME type determined by Mozilla?
619 if ((path.Length() > 4
620 && std::strcmp(path.EndReading() - 4, ".vob") == 0)
621 || (path.Length() > 8
622 && std::strcmp(path.EndReading() - 8, ".voblist")
626 check(uri->SchemeIs("file", &is_file));
629 std::cerr << "Links to video must use the file:"
633 dest_pgc = add_title(uri_sans_fragment);
637 dest_pgc = add_menu(uri_sans_fragment);
639 contents_.menus[menu_num].entries.push_back(dest_pgc);
641 nsCOMPtr<nsIContent> content(do_QueryInterface(node));
643 nsCOMPtr<nsIDOMEventTarget> event_target(
644 do_QueryInterface(node));
645 assert(event_target);
647 state->norm_pixbuf = Gdk::Pixbuf::create(
648 Glib::RefPtr<Gdk::Drawable>(window),
649 window->get_colormap(),
650 state->link_rect.left,
651 state->link_rect.top,
654 state->link_rect.right - state->link_rect.left,
655 state->link_rect.bottom - state->link_rect.top);
657 nsCOMPtr<nsIDOMEvent> event;
658 check(event_factory->CreateEvent(
659 NS_ConvertASCIItoUTF16("MouseEvents"),
660 getter_AddRefs(event)));
661 nsCOMPtr<nsIDOMMouseEvent> mouse_event(
662 do_QueryInterface(event));
664 check(mouse_event->InitMouseEvent(
665 NS_ConvertASCIItoUTF16("mouseover"),
669 0, // detail: mouse click count
670 state->link_rect.left, // screenX
671 state->link_rect.top, // screenY
672 state->link_rect.left, // clientX
673 state->link_rect.top, // clientY
674 false, false, false, false, // qualifiers
675 0, // button: left (or primary)
676 0)); // related target
678 check(event_target->DispatchEvent(mouse_event,
680 check(event_state_man->SetContentState(content,
681 NS_EVENT_STATE_HOVER));
683 pres_shell->FlushPendingNotifications(true);
685 // We may have to exit and wait for image loading
686 // to complete, at which point we will be called
688 if (pending_req_count_ > 0)
690 state->link_changing = true;
696 window->process_updates(true);
698 Glib::RefPtr<Gdk::Pixbuf> changed_pixbuf(
700 Glib::RefPtr<Gdk::Drawable>(window),
701 window->get_colormap(),
702 state->link_rect.left,
703 state->link_rect.top,
706 state->link_rect.right - state->link_rect.left,
707 state->link_rect.bottom - state->link_rect.top));
712 state->link_rect.left,
713 state->link_rect.top,
714 state->link_rect.right - state->link_rect.left,
715 state->link_rect.bottom - state->link_rect.top);
718 quantise_rgba_pixbuf(state->diff_pixbuf, dvd::button_n_colours);
720 std::cout << "saving " << state->links_temp.get_name()
722 state->diff_pixbuf->save(state->links_temp.get_name(), "png");
724 state->spumux_file <<
729 state->spumux_file.close();
731 // TODO: if (!state->spumux_file) throw ...
734 std::ostringstream command_stream;
735 command_stream << "pngtopnm "
736 << background_temp_->get_name()
737 << " | ppmtoy4m -v0 -n1 -F"
738 << frame_params_.rate_numer
739 << ":" << frame_params_.rate_denom
740 << " -A" << frame_params_.pixel_ratio_width
741 << ":" << frame_params_.pixel_ratio_height
742 << (" -Ip -S420_mpeg2"
743 " | mpeg2enc -v0 -f8 -a2 -o/dev/stdout"
744 " | mplex -v0 -f8 -o/dev/stdout /dev/stdin"
745 " | spumux -v0 -mdvd ")
746 << state->spumux_temp.get_name()
748 << contents_.menus[menu_num].vob_temp->get_name();
749 std::string command(command_stream.str());
750 const char * argv[] = {
751 "/bin/sh", "-c", command.c_str(), 0
753 std::cout << "running " << argv[2] << std::endl;
755 Glib::spawn_sync(".",
756 Glib::ArrayHandle<std::string>(
757 argv, sizeof(argv)/sizeof(argv[0]),
758 Glib::OWNERSHIP_NONE),
759 Glib::SPAWN_STDOUT_TO_DEV_NULL,
763 if (command_result != 0)
764 throw std::runtime_error("spumux pipeline failed");
768 void generate_menu_dispatch(std::ostream &, int indent,
769 int first_menu, int last_menu);
771 void webdvd_window::generate_dvd()
773 temp_file temp("webdvd-dvdauthor-");
775 std::ofstream file(temp.get_name().c_str());
777 // We generate code that uses registers in the following way:
779 // g0: button destination (when jumping to menu 1), then scratch
780 // g1: current location
781 // g2-g11: location history (g2 = most recent)
782 // g12: location that last linked to a video
784 // All locations are divided into two bitfields: the least
785 // significant 10 bits are a page/menu number and the most
786 // significant 6 bits are a link/button number, and numbering
787 // starts at 1, not 0. This is done for compatibility with
788 // the encoding of the s8 (button) register.
790 static const int button_mult = dvd::reg_s8_button_mult;
791 static const int menu_mask = button_mult - 1;
792 static const int button_mask = (1 << dvd::reg_bits) - button_mult;
793 static const int location_bias = button_mult + 1;
800 for (std::size_t menu_num = 0;
801 menu_num != contents_.menus.size();
804 dvd_contents::menu & menu = contents_.menus[menu_num];
808 // This is the first (title) menu, which needs to include
809 // initialisation and dispatch code.
812 " <pgc entry='title'>\n"
814 // Has the location been set yet?
817 // Initialise the current location to first button on
819 " g1 = " << location_bias << ";\n"
823 // Has the user selected a link?
826 // First update the history.
827 // Does link go to the last page in the history?
828 " if (((g0 ^ g2) & " << menu_mask
830 // It does; we treat this as going back and pop the old
831 // location off the history stack into the current
832 // location. Clear the free stack slot.
834 " g1 = g2; g2 = g3; g3 = g4; g4 = g5;\n"
835 " g5 = g6; g6 = g7; g7 = g8; g8 = g9;\n"
836 " g9 = g10; g10 = g11; g11 = 0;\n"
839 // Link goes to some other page, so push current
840 // location onto the history stack and set the current
841 // location to be exactly the target location.
843 " g11 = g10; g10 = g9; g9 = g8; g8 = g7;\n"
844 " g7 = g6; g6 = g5; g5 = g4; g4 = g3;\n"
845 " g3 = g2; g2 = g1; g1 = g0;\n"
848 // Find the target page number.
849 " g0 = g1 & " << menu_mask << ";\n";
850 // There seems to be no way to perform a computed jump,
851 // so we generate all possible jumps and a binary search
852 // to select the correct one.
853 generate_menu_dispatch(file, 12,
854 0, contents_.menus.size() - 1);
858 else // menu_num != 0
866 // Clear link indicator and highlight the
867 // appropriate link/button.
868 " g0 = 0; s8 = g1 & " << button_mask << ";\n"
871 << menu.vob_temp->get_name() << "'/>\n";
873 for (std::size_t button_num = 0;
874 button_num != menu.entries.size();
878 // Update current location.
880 << location_bias + button_num * button_mult + menu_num
883 // Jump to appropriate resource.
884 if (menu.entries[button_num].first == dvd_contents::menu_pgc)
887 << location_bias + menu.entries[button_num].second
892 assert(menu.entries[button_num].first
893 == dvd_contents::title_pgc);
894 file << " jump title "
895 << 1 + menu.entries[button_num].second << ";";
898 file << " </button>\n";
908 // Generate a titleset for each title. This appears to make
909 // jumping to titles a whole lot simpler (but limits us to 99
911 for (std::size_t title_num = 0;
912 title_num != contents_.titles.size();
917 // Generate a dummy menu so that the menu button on the
918 // remote control will work.
920 " <pgc entry='root'>\n"
921 " <pre> jump vmgm menu; </pre>\n"
926 // Record calling page/menu.
927 " <pre> g12 = g1; </pre>\n"
928 << contents_.titles[title_num].vob_list <<
929 // If page/menu location has not been changed during the
930 // video, change the location to be the following
931 // link/button when returning to it. In any case,
932 // return to a page/menu.
933 " <post> if (g1 eq g12) g1 = g1 + " << button_mult
934 << "; call menu; </post>\n"
946 const char * argv[] = {
948 "-o", output_dir_.c_str(),
949 "-x", temp.get_name().c_str(),
953 Glib::spawn_sync(".",
954 Glib::ArrayHandle<std::string>(
955 argv, sizeof(argv)/sizeof(argv[0]),
956 Glib::OWNERSHIP_NONE),
957 Glib::SPAWN_SEARCH_PATH
958 | Glib::SPAWN_STDOUT_TO_DEV_NULL,
962 if (command_result != 0)
963 throw std::runtime_error("dvdauthor failed");
967 void generate_menu_dispatch(std::ostream & file, int indent,
968 int first_menu, int last_menu)
970 if (first_menu == last_menu)
974 // This dispatch code is generated *on* the first menu
975 // so don't create an infinite loop.
979 file << std::setw(indent) << ""
980 << "jump menu " << 1 + first_menu << ";\n";
983 else // first_menu != last_menu
985 if (first_menu == 0 && last_menu == 1)
987 // dvdauthor doesn't allow empty blocks or null
988 // statements so when selecting between the first 2
989 // menus we don't use an "else" part. We must use
990 // braces so that a following "else" will match the
992 file << std::setw(indent) << "" << "{\n"
993 << std::setw(indent) << "" << "if (g0 eq 2)\n"
994 << std::setw(indent + 2) << "" << "jump menu 2;\n"
995 << std::setw(indent) << "" << "}\n";
999 int middle = (first_menu + last_menu) / 2;
1000 file << std::setw(indent) << "" << "if (g0 le " << 1 + middle
1002 generate_menu_dispatch(file, indent + 2,
1003 first_menu, middle);
1004 file << std::setw(indent) << "" << "else\n";
1005 generate_menu_dispatch(file, indent + 2,
1006 middle + 1, last_menu);
1011 const video::frame_params & lookup_frame_params(const char * str)
1014 static const struct { const char * str; bool is_ntsc; }
1020 // For DVD purposes, SECAM can be treated identically to PAL.
1024 for (std::size_t i = 0;
1025 i != sizeof(known_strings)/sizeof(known_strings[0]);
1027 if (std::strcmp(str, known_strings[i].str) == 0)
1028 return known_strings[i].is_ntsc ?
1029 video::ntsc_params : video::pal_params;
1030 throw std::runtime_error(
1031 std::string("Invalid video standard: ").append(str));
1034 void print_usage(std::ostream & stream, const char * command_name)
1036 stream << "Usage: " << command_name
1037 << (" [gtk-options] [--video-std std-name]"
1038 " [--preview] menu-url [output-dir]\n");
1041 void set_browser_preferences()
1043 // Disable IE-compatibility kluge that causes backgrounds to
1044 // sometimes/usually be missing from snapshots. This is only
1045 // effective from Mozilla 1.8 onward.
1046 # if MOZ_VERSION_MAJOR > 1 \
1047 || (MOZ_VERSION_MAJOR == 1 && MOZ_VERSION_MINOR >= 8)
1048 nsCOMPtr<nsIPrefService> pref_service;
1049 static const nsCID pref_service_cid = NS_PREFSERVICE_CID;
1050 check(CallGetService<nsIPrefService>(pref_service_cid,
1051 getter_AddRefs(pref_service)));
1052 nsCOMPtr<nsIPrefBranch> pref_branch;
1053 check(pref_service->GetDefaultBranch("layout",
1054 getter_AddRefs(pref_branch)));
1055 check(pref_branch->SetBoolPref(
1056 "fire_onload_after_image_background_loads",
1060 // TODO: Set display resolution? Unfortunately Mozilla doesn't
1061 // support non-square pixels (and neither do fontconfig or Xft
1067 int main(int argc, char ** argv)
1071 video::frame_params frame_params = video::pal_params;
1072 bool preview_mode = false;
1073 std::string menu_url;
1074 std::string output_dir;
1076 // Do initial option parsing. We have to do this before
1077 // letting Gtk parse the arguments since we may need to spawn
1080 while (argi != argc)
1082 if (std::strcmp(argv[argi], "--") == 0)
1086 else if (std::strcmp(argv[argi], "--help") == 0)
1088 print_usage(std::cout, argv[0]);
1089 return EXIT_SUCCESS;
1091 else if (std::strcmp(argv[argi], "--preview") == 0)
1093 preview_mode = true;
1096 else if (std::strcmp(argv[argi], "--video-std") == 0)
1098 if (argi + 1 == argc)
1100 std::cerr << "Missing argument to --video-std\n";
1101 print_usage(std::cerr, argv[0]);
1102 return EXIT_FAILURE;
1104 frame_params = lookup_frame_params(argv[argi + 1]);
1113 std::auto_ptr<x_frame_buffer> fb;
1116 // Spawn Xvfb and set env variables so that Xlib will use it
1117 // Use 8 bits each for RGB components, which should translate into
1118 // "enough" bits for YUV components.
1119 fb.reset(new x_frame_buffer(frame_params.width,
1120 frame_params.height,
1122 setenv("XAUTHORITY", fb->get_authority().c_str(), true);
1123 setenv("DISPLAY", fb->get_display().c_str(), true);
1127 Gtk::Main kit(argc, argv);
1129 // Complete option parsing with Gtk's options out of the way.
1131 while (argi != argc)
1133 if (std::strcmp(argv[argi], "--") == 0)
1138 else if (std::strcmp(argv[argi], "--preview") == 0)
1142 else if (std::strcmp(argv[argi], "--video-std") == 0)
1146 else if (argv[argi][0] == '-')
1148 std::cerr << "Invalid option: " << argv[argi] << "\n";
1149 print_usage(std::cerr, argv[0]);
1150 return EXIT_FAILURE;
1158 // Look for a starting URL or filename and (except in preview
1159 // mode) an output directory after the options.
1160 if (argc - argi != (preview_mode ? 1 : 2))
1162 print_usage(std::cerr, argv[0]);
1163 return EXIT_FAILURE;
1165 if (std::strstr(argv[argi], "://"))
1167 // It appears to be an absolute URL, so use it as-is.
1168 menu_url = argv[argi];
1172 // Assume it's a filename. Resolve it to an absolute URL.
1173 std::string path(argv[argi]);
1174 if (!Glib::path_is_absolute(path))
1175 path = Glib::build_filename(Glib::get_current_dir(), path);
1176 menu_url = Glib::filename_to_uri(path);
1179 output_dir = argv[argi + 1];
1181 // Initialise Mozilla
1182 browser_widget::initialiser browser_init;
1183 set_browser_preferences();
1185 // Run the browser/converter
1186 webdvd_window window(frame_params, menu_url, output_dir);
1187 Gtk::Main::run(window);
1189 catch (std::exception & e)
1191 std::cerr << "Fatal error: " << e.what() << "\n";
1192 return EXIT_FAILURE;
1195 return EXIT_SUCCESS;