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 webdvd_window::generate_dvd()
770 temp_file temp("webdvd-dvdauthor-");
772 std::ofstream file(temp.get_name().c_str());
774 // We generate code that uses registers in the following way:
777 // g1: current location
778 // g12: location that last jumped to a video
780 // All locations are divided into two bitfields: the least
781 // significant 10 bits are a page/menu number and the most
782 // significant 6 bits are a link/button number, and numbering
783 // starts at 1, not 0. This is done for compatibility with
784 // the encoding of the s8 (button) register.
786 static const int button_mult = dvd::reg_s8_button_mult;
787 static const int menu_mask = button_mult - 1;
788 static const int button_mask = (1 << dvd::reg_bits) - button_mult;
795 for (std::size_t menu_num = 0;
796 menu_num != contents_.menus.size();
799 dvd_contents::menu & menu = contents_.menus[menu_num];
803 // This is the first (title) menu, displayed when the
804 // disc is first played.
806 " <pgc entry='title'>\n"
808 // Initialise the current location if it is not set
809 // (all general registers are initially 0).
811 " g1 = " << 1 + button_mult << ";\n";
820 // When a title finishes or the user presses the menu
821 // button, this always jumps to the titleset's root menu.
822 // We want to return the user to the last menu they used.
823 // So we arrange for each titleset's root menu to return
824 // to the vmgm title menu and then dispatch from there to
825 // whatever the correct menu is. We determine the correct
826 // menu by looking at the menu part of g1.
828 file << " g0 = g1 & " << menu_mask << ";\n";
830 // There is a limit of 128 VM instructions in each PGC.
831 // Therefore in each menu's <pre> section we generate
832 // jumps to menus with numbers greater by 512, 256, 128,
833 // ..., 1 where (a) such a menu exists, (b) this menu
834 // number is divisible by twice that increment and (c) the
835 // correct menu is that or a later menu. Thus each menu
836 // has at most 10 such conditional jumps and is reachable
837 // by at most 10 jumps from the title menu. This chain of
838 // jumps might take too long on some players; this has yet
839 // to be investigated.
841 for (std::size_t menu_incr = (menu_mask + 1) / 2;
845 if (menu_num + menu_incr < contents_.menus.size()
846 && (menu_num & (menu_incr * 2 - 1)) == 0)
849 " if (g0 ge " << 1 + menu_num + menu_incr
851 " jump menu " << 1 + menu_num + menu_incr
857 // Highlight the appropriate button.
858 " s8 = g1 & " << button_mask << ";\n"
860 " <vob file='" << menu.vob_temp->get_name() << "'/>\n";
862 for (std::size_t button_num = 0;
863 button_num != menu.entries.size();
866 file << " <button> ";
868 if (menu.entries[button_num].first == dvd_contents::menu_pgc)
870 int dest_menu_num = menu.entries[button_num].second;
872 // Look for a button on the new menu that links
873 // back to this one. If there is one, set that to
874 // be the highlighted button; otherwise, use the
876 const std::vector<dvd_contents::pgc_ref> &
878 contents_.menus[dest_menu_num].entries;
879 dvd_contents::pgc_ref this_pgc(
880 dvd_contents::menu_pgc, menu_num);
881 std::size_t dest_button_num = dest_menu_entries.size();
882 while (dest_button_num != 0
883 && dest_menu_entries[--dest_button_num] != this_pgc)
887 << (1 + dest_menu_num
888 + (1 + dest_button_num) * button_mult)
889 << "; jump menu " << 1 + dest_menu_num << ";";
893 assert(menu.entries[button_num].first
894 == dvd_contents::title_pgc);
897 << 1 + menu_num + (1 + button_num) * button_mult
899 << 1 + menu.entries[button_num].second << ";";
902 file << " </button>\n";
912 // Generate a titleset for each title. This appears to make
913 // jumping to titles a whole lot simpler (but limits us to 99
915 for (std::size_t title_num = 0;
916 title_num != contents_.titles.size();
921 // Generate a dummy menu so that the menu button on the
922 // remote control will work.
924 " <pgc entry='root'>\n"
925 " <pre> jump vmgm menu; </pre>\n"
930 // Record calling location.
931 " <pre> g12 = g1; </pre>\n"
932 << contents_.titles[title_num].vob_list <<
933 // If the menu location has not been changed during
934 // the title, set the location to be the following
935 // button in the menu. In any case, return to some
937 " <post> if (g1 eq g12) g1 = g1 + " << button_mult
938 << "; call menu; </post>\n"
950 const char * argv[] = {
952 "-o", output_dir_.c_str(),
953 "-x", temp.get_name().c_str(),
957 Glib::spawn_sync(".",
958 Glib::ArrayHandle<std::string>(
959 argv, sizeof(argv)/sizeof(argv[0]),
960 Glib::OWNERSHIP_NONE),
961 Glib::SPAWN_SEARCH_PATH
962 | Glib::SPAWN_STDOUT_TO_DEV_NULL,
966 if (command_result != 0)
967 throw std::runtime_error("dvdauthor failed");
971 const video::frame_params & lookup_frame_params(const char * str)
974 static const struct { const char * str; bool is_ntsc; }
980 // For DVD purposes, SECAM can be treated identically to PAL.
984 for (std::size_t i = 0;
985 i != sizeof(known_strings)/sizeof(known_strings[0]);
987 if (std::strcmp(str, known_strings[i].str) == 0)
988 return known_strings[i].is_ntsc ?
989 video::ntsc_params : video::pal_params;
990 throw std::runtime_error(
991 std::string("Invalid video standard: ").append(str));
994 void print_usage(std::ostream & stream, const char * command_name)
996 stream << "Usage: " << command_name
997 << (" [gtk-options] [--video-std std-name]"
998 " [--preview] menu-url [output-dir]\n");
1001 void set_browser_preferences()
1003 // Disable IE-compatibility kluge that causes backgrounds to
1004 // sometimes/usually be missing from snapshots. This is only
1005 // effective from Mozilla 1.8 onward.
1006 # if MOZ_VERSION_MAJOR > 1 \
1007 || (MOZ_VERSION_MAJOR == 1 && MOZ_VERSION_MINOR >= 8)
1008 nsCOMPtr<nsIPrefService> pref_service;
1009 static const nsCID pref_service_cid = NS_PREFSERVICE_CID;
1010 check(CallGetService<nsIPrefService>(pref_service_cid,
1011 getter_AddRefs(pref_service)));
1012 nsCOMPtr<nsIPrefBranch> pref_branch;
1013 check(pref_service->GetDefaultBranch("layout",
1014 getter_AddRefs(pref_branch)));
1015 check(pref_branch->SetBoolPref(
1016 "fire_onload_after_image_background_loads",
1020 // TODO: Set display resolution? Unfortunately Mozilla doesn't
1021 // support non-square pixels (and neither do fontconfig or Xft
1027 int main(int argc, char ** argv)
1031 video::frame_params frame_params = video::pal_params;
1032 bool preview_mode = false;
1033 std::string menu_url;
1034 std::string output_dir;
1036 // Do initial option parsing. We have to do this before
1037 // letting Gtk parse the arguments since we may need to spawn
1040 while (argi != argc)
1042 if (std::strcmp(argv[argi], "--") == 0)
1046 else if (std::strcmp(argv[argi], "--help") == 0)
1048 print_usage(std::cout, argv[0]);
1049 return EXIT_SUCCESS;
1051 else if (std::strcmp(argv[argi], "--preview") == 0)
1053 preview_mode = true;
1056 else if (std::strcmp(argv[argi], "--video-std") == 0)
1058 if (argi + 1 == argc)
1060 std::cerr << "Missing argument to --video-std\n";
1061 print_usage(std::cerr, argv[0]);
1062 return EXIT_FAILURE;
1064 frame_params = lookup_frame_params(argv[argi + 1]);
1073 std::auto_ptr<x_frame_buffer> fb;
1076 // Spawn Xvfb and set env variables so that Xlib will use it
1077 // Use 8 bits each for RGB components, which should translate into
1078 // "enough" bits for YUV components.
1079 fb.reset(new x_frame_buffer(frame_params.width,
1080 frame_params.height,
1082 setenv("XAUTHORITY", fb->get_authority().c_str(), true);
1083 setenv("DISPLAY", fb->get_display().c_str(), true);
1087 Gtk::Main kit(argc, argv);
1089 // Complete option parsing with Gtk's options out of the way.
1091 while (argi != argc)
1093 if (std::strcmp(argv[argi], "--") == 0)
1098 else if (std::strcmp(argv[argi], "--preview") == 0)
1102 else if (std::strcmp(argv[argi], "--video-std") == 0)
1106 else if (argv[argi][0] == '-')
1108 std::cerr << "Invalid option: " << argv[argi] << "\n";
1109 print_usage(std::cerr, argv[0]);
1110 return EXIT_FAILURE;
1118 // Look for a starting URL or filename and (except in preview
1119 // mode) an output directory after the options.
1120 if (argc - argi != (preview_mode ? 1 : 2))
1122 print_usage(std::cerr, argv[0]);
1123 return EXIT_FAILURE;
1125 if (std::strstr(argv[argi], "://"))
1127 // It appears to be an absolute URL, so use it as-is.
1128 menu_url = argv[argi];
1132 // Assume it's a filename. Resolve it to an absolute URL.
1133 std::string path(argv[argi]);
1134 if (!Glib::path_is_absolute(path))
1135 path = Glib::build_filename(Glib::get_current_dir(), path);
1136 menu_url = Glib::filename_to_uri(path);
1139 output_dir = argv[argi + 1];
1141 // Initialise Mozilla
1142 browser_widget::initialiser browser_init;
1143 set_browser_preferences();
1145 // Run the browser/converter
1146 webdvd_window window(frame_params, menu_url, output_dir);
1147 Gtk::Main::run(window);
1149 catch (std::exception & e)
1151 std::cerr << "Fatal error: " << e.what() << "\n";
1152 return EXIT_FAILURE;
1155 return EXIT_SUCCESS;