]> git.decadent.org.uk Git - videolink.git/blob - webdvd.cpp
Added -ansi to C{,XX}FLAGS to disable non-standard names.
[videolink.git] / webdvd.cpp
1 // Copyright 2005-6 Ben Hutchings <ben@decadentplace.org.uk>.
2 // See the file "COPYING" for licence details.
3
4 #include <cassert>
5 #include <cstring>
6 #include <exception>
7 #include <fstream>
8 #include <iomanip>
9 #include <iostream>
10 #include <memory>
11 #include <queue>
12 #include <set>
13 #include <sstream>
14 #include <string>
15
16 #include <stdlib.h>
17
18 #include <boost/shared_ptr.hpp>
19
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>
25
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
44 #include <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>
51 #include <nsString.h>
52
53 #include "browser_widget.hpp"
54 #include "child_iterator.hpp"
55 #include "dvd.hpp"
56 #include "generate_dvd.hpp"
57 #include "link_iterator.hpp"
58 #include "null_prompt_service.hpp"
59 #include "pixbufs.hpp"
60 #include "style_sheets.hpp"
61 #include "temp_file.hpp"
62 #include "video.hpp"
63 #include "x_frame_buffer.hpp"
64 #include "xml_utils.hpp"
65 #include "xpcom_support.hpp"
66
67 using xpcom_support::check;
68
69 namespace
70 {
71     struct rectangle
72     {
73         int left, top;     // inclusive
74         int right, bottom; // exclusive
75
76         rectangle operator|=(const rectangle & other)
77             {
78                 if (other.empty())
79                 {
80                     // use current extents unchanged
81                 }
82                 else if (empty())
83                 {
84                     // use other extents
85                     *this = other;
86                 }
87                 else
88                 {
89                     // find rectangle enclosing both extents
90                     left = std::min(left, other.left);
91                     top = std::min(top, other.top);
92                     right = std::max(right, other.right);
93                     bottom = std::max(bottom, other.bottom);
94                 }
95
96                 return *this;
97             }
98
99         rectangle operator&=(const rectangle & other)
100             {
101                 // find rectangle enclosed in both extents
102                 left = std::max(left, other.left);
103                 top = std::max(top, other.top);
104                 right = std::max(left, std::min(right, other.right));
105                 bottom = std::max(top, std::min(bottom, other.bottom));
106                 return *this;
107             }
108
109         bool empty() const
110             {
111                 return left == right || bottom == top;
112             }
113     };
114
115     rectangle get_elem_rect(nsIDOMNSDocument * ns_doc,
116                             nsIDOMElement * elem)
117     {
118         rectangle result;
119
120         // Start with this element's bounding box
121         nsCOMPtr<nsIBoxObject> box;
122         check(ns_doc->GetBoxObjectFor(elem, getter_AddRefs(box)));
123         int width, height;
124         check(box->GetScreenX(&result.left));
125         check(box->GetScreenY(&result.top));
126         check(box->GetWidth(&width));
127         check(box->GetHeight(&height));
128         result.right = result.left + width;
129         result.bottom = result.top + height;
130
131         // Merge bounding boxes of all child elements
132         for (child_iterator it = child_iterator(elem), end; it != end; ++it)
133         {
134             nsCOMPtr<nsIDOMNode> child_node(*it);
135             PRUint16 child_type;
136             if (check(child_node->GetNodeType(&child_type)),
137                 child_type == nsIDOMNode::ELEMENT_NODE)
138             {
139                 nsCOMPtr<nsIDOMElement> child_elem(
140                     do_QueryInterface(child_node));
141                 result |= get_elem_rect(ns_doc, child_elem);
142             }
143         }
144
145         return result;
146     }
147
148
149     class webdvd_window : public Gtk::Window
150     {
151     public:
152         webdvd_window(
153             const video::frame_params & frame_params,
154             const std::string & main_page_uri,
155             const std::string & output_dir);
156
157     private:
158         dvd_contents::pgc_ref add_menu(const std::string & uri);
159         dvd_contents::pgc_ref add_title(const std::string & uri);
160         void load_next_page();
161         void on_net_state_change(const char * uri, gint flags, guint status);
162         bool browser_is_busy() const
163             {
164                 return pending_window_update_ || pending_req_count_;
165             }
166         bool process_page();
167         void save_screenshot();
168         void process_links(nsIPresShell * pres_shell,
169                            nsIPresContext * pres_context,
170                            nsIDOMWindow * dom_window);
171
172         video::frame_params frame_params_;
173         std::string output_dir_;
174         browser_widget browser_widget_;
175         nsCOMPtr<nsIStyleSheet> stylesheet_;
176
177         dvd_contents contents_;
178         typedef std::map<std::string, dvd_contents::pgc_ref> resource_map_type;
179         resource_map_type resource_map_;
180
181         std::queue<std::string> page_queue_;
182         bool pending_window_update_;
183         int pending_req_count_;
184         bool have_tweaked_page_;
185         std::auto_ptr<temp_file> background_temp_;
186         struct page_state;
187         std::auto_ptr<page_state> page_state_;
188     };
189
190     webdvd_window::webdvd_window(
191         const video::frame_params & frame_params,
192         const std::string & main_page_uri,
193         const std::string & output_dir)
194             : frame_params_(frame_params),
195               output_dir_(output_dir),
196               stylesheet_(load_css("file://" WEBDVD_LIB_DIR "/webdvd.css")),
197               pending_window_update_(false),
198               pending_req_count_(0),
199               have_tweaked_page_(false)
200     {
201         set_size_request(frame_params_.width, frame_params_.height);
202         set_resizable(false);
203
204         add(browser_widget_);
205         browser_widget_.show();
206         browser_widget_.signal_net_state().connect(
207             SigC::slot(*this, &webdvd_window::on_net_state_change));
208
209         add_menu(main_page_uri);
210         load_next_page();
211     }
212
213     dvd_contents::pgc_ref webdvd_window::add_menu(const std::string & uri)
214     {
215         dvd_contents::pgc_ref next_menu(dvd_contents::menu_pgc,
216                                         contents_.menus.size());
217         std::pair<resource_map_type::iterator, bool> insert_result(
218             resource_map_.insert(std::make_pair(uri, next_menu)));
219
220         if (!insert_result.second)
221         {
222             return insert_result.first->second;
223         }
224         else
225         {
226             page_queue_.push(uri);
227             contents_.menus.resize(contents_.menus.size() + 1);
228             return next_menu;
229         }
230     }
231
232     dvd_contents::pgc_ref webdvd_window::add_title(const std::string & uri)
233     {
234         dvd_contents::pgc_ref next_title(dvd_contents::title_pgc,
235                                          contents_.titles.size());
236         std::pair<resource_map_type::iterator, bool> insert_result(
237             resource_map_.insert(std::make_pair(uri, next_title)));
238
239         if (!insert_result.second)
240         {
241             return insert_result.first->second;
242         }
243         else
244         {
245             Glib::ustring hostname;
246             std::string path(Glib::filename_from_uri(uri, hostname));
247             // FIXME: Should check the hostname
248
249             vob_list list;
250
251             // Store a reference to a linked VOB file, or the contents
252             // of a linked VOB list file.
253             if (path.compare(path.size() - 4, 4, ".vob") == 0)
254             {
255                 if (!Glib::file_test(path, Glib::FILE_TEST_IS_REGULAR))
256                     throw std::runtime_error(
257                         path + " is missing or not a regular file");
258                 vob_ref ref;
259                 ref.file = path;
260                 list.push_back(ref);
261             }
262             else
263             {
264                 assert(path.compare(path.size() - 8, 8, ".voblist") == 0);
265                 read_vob_list(path).swap(list);
266             }
267
268             contents_.titles.resize(contents_.titles.size() + 1);
269             contents_.titles.back().swap(list);
270             return next_title;
271         }
272     }
273
274     void webdvd_window::load_next_page()
275     {
276         assert(!page_queue_.empty());
277         const std::string & uri = page_queue_.front();
278         std::cout << "loading " << uri << std::endl;
279
280         browser_widget_.load_uri(uri);
281     }
282
283     void webdvd_window::on_net_state_change(const char * uri,
284                                            gint flags, guint status)
285     {
286 #       ifdef DEBUG_ON_NET_STATE_CHANGE
287         std::cout << "webdvd_window::on_net_state_change(";
288         if (uri)
289             std::cout << '"' << uri << '"';
290         else
291             std::cout << "NULL";
292         std::cout << ", ";
293         {
294             gint flags_left = flags;
295             static const struct {
296                 gint value;
297                 const char * name;
298             } flag_names[] = {
299                 { GTK_MOZ_EMBED_FLAG_START, "STATE_START" },
300                 { GTK_MOZ_EMBED_FLAG_REDIRECTING, "STATE_REDIRECTING" },
301                 { GTK_MOZ_EMBED_FLAG_TRANSFERRING, "STATE_TRANSFERRING" },
302                 { GTK_MOZ_EMBED_FLAG_NEGOTIATING, "STATE_NEGOTIATING" },
303                 { GTK_MOZ_EMBED_FLAG_STOP, "STATE_STOP" },
304                 { GTK_MOZ_EMBED_FLAG_IS_REQUEST, "STATE_IS_REQUEST" },
305                 { GTK_MOZ_EMBED_FLAG_IS_DOCUMENT, "STATE_IS_DOCUMENT" },
306                 { GTK_MOZ_EMBED_FLAG_IS_NETWORK, "STATE_IS_NETWORK" },
307                 { GTK_MOZ_EMBED_FLAG_IS_WINDOW, "STATE_IS_WINDOW" }
308             };
309             for (int i = 0; i != sizeof(flag_names)/sizeof(flag_names[0]); ++i)
310             {
311                 if (flags & flag_names[i].value)
312                 {
313                     std::cout << flag_names[i].name;
314                     flags_left -= flag_names[i].value;
315                     if (flags_left)
316                         std::cout << " | ";
317                 }
318             }
319             if (flags_left)
320                 std::cout << "0x" << std::setbase(16) << flags_left;
321         }
322         std::cout << ", " << "0x" << std::setbase(16) << status << ")\n";
323 #       endif // DEBUG_ON_NET_STATE_CHANGE
324
325         if (flags & GTK_MOZ_EMBED_FLAG_IS_REQUEST)
326         {
327             if (flags & GTK_MOZ_EMBED_FLAG_START)
328                 ++pending_req_count_;
329
330             if (flags & GTK_MOZ_EMBED_FLAG_STOP)
331             {
332                 assert(pending_req_count_ != 0);
333                 --pending_req_count_;
334             }
335         }
336             
337         if (flags & GTK_MOZ_EMBED_FLAG_IS_DOCUMENT
338             && flags & GTK_MOZ_EMBED_FLAG_START)
339         {
340             pending_window_update_ = true;
341             have_tweaked_page_ = false;
342         }
343
344         if (flags & GTK_MOZ_EMBED_FLAG_IS_WINDOW
345             && flags & GTK_MOZ_EMBED_FLAG_STOP)
346         {
347             // Check whether the load was successful, ignoring this
348             // pseudo-error.
349             if (status != NS_IMAGELIB_ERROR_LOAD_ABORTED)
350                 check(status);
351
352             pending_window_update_ = false;
353         }
354
355         if (!browser_is_busy())
356         {
357             try
358             {
359                 if (!process_page())
360                     Gtk::Main::quit();
361             }
362             catch (std::exception & e)
363             {
364                 std::cerr << "Fatal error";
365                 if (!page_queue_.empty())
366                     std::cerr << " while processing <" << page_queue_.front()
367                               << ">";
368                 std::cerr << ": " << e.what() << "\n";
369                 Gtk::Main::quit();
370             }
371             catch (Glib::Exception & e)
372             {
373                 std::cerr << "Fatal error";
374                 if (!page_queue_.empty())
375                     std::cerr << " while processing <" << page_queue_.front()
376                               << ">";
377                 std::cerr << ": " << e.what() << "\n";
378                 Gtk::Main::quit();
379             }
380         }
381     }
382
383     bool webdvd_window::process_page()
384     {
385         assert(!page_queue_.empty());
386
387         nsCOMPtr<nsIWebBrowser> browser(browser_widget_.get_browser());
388         nsCOMPtr<nsIDocShell> doc_shell(do_GetInterface(browser));
389         assert(doc_shell);
390         nsCOMPtr<nsIPresShell> pres_shell;
391         check(doc_shell->GetPresShell(getter_AddRefs(pres_shell)));
392         nsCOMPtr<nsIPresContext> pres_context;
393         check(doc_shell->GetPresContext(getter_AddRefs(pres_context)));
394         nsCOMPtr<nsIDOMWindow> dom_window;
395         check(browser->GetContentDOMWindow(getter_AddRefs(dom_window)));
396
397         // If we haven't done so already, apply the stylesheet and
398         // disable scrollbars.
399         if (!have_tweaked_page_)
400         {
401             apply_style_sheet(stylesheet_, pres_shell);
402
403             // This actually only needs to be done once.
404             nsCOMPtr<nsIDOMBarProp> dom_bar_prop;
405             check(dom_window->GetScrollbars(getter_AddRefs(dom_bar_prop)));
406             check(dom_bar_prop->SetVisible(false));
407
408             have_tweaked_page_ = true;
409
410             // Might need to wait a while for things to load or more
411             // likely for a re-layout.
412             if (browser_is_busy())
413                 return true;
414         }
415
416         // All further work should only be done if we're not in preview mode.
417         if (!output_dir_.empty())
418         {
419             // If we haven't already started work on this menu, save a
420             // screenshot of its normal appearance.
421             if (!page_state_.get())
422                 save_screenshot();
423
424             // Start or continue processing links.
425             process_links(pres_shell, pres_context, dom_window);
426
427             // If we've finished work on the links, move on to the
428             // next page, if any, or else generate the DVD filesystem.
429             if (!page_state_.get())
430             {
431                 page_queue_.pop();
432                 if (page_queue_.empty())
433                 {
434                     generate_dvd(contents_, output_dir_);
435                     return false;
436                 }
437                 else
438                 {
439                     load_next_page();
440                 }
441             }
442         }
443
444         return true;
445     }
446
447     void webdvd_window::save_screenshot()
448     {
449         Glib::RefPtr<Gdk::Window> window(get_window());
450         assert(window);
451         window->process_updates(true);
452
453         background_temp_.reset(new temp_file("webdvd-back-"));
454         background_temp_->close();
455         std::cout << "saving " << background_temp_->get_name() << std::endl;
456         Gdk::Pixbuf::create(Glib::RefPtr<Gdk::Drawable>(window),
457                             window->get_colormap(),
458                             0, 0, 0, 0,
459                             frame_params_.width, frame_params_.height)
460             ->save(background_temp_->get_name(), "png");
461     }
462
463     struct webdvd_window::page_state
464     {
465         page_state(nsIDOMDocument * doc, int width, int height)
466                 : diff_pixbuf(Gdk::Pixbuf::create(
467                                   Gdk::COLORSPACE_RGB,
468                                   true, 8, // has_alpha, bits_per_sample
469                                   width, height)),
470                   spumux_temp("webdvd-spumux-"),
471                   links_temp("webdvd-links-"),
472                   link_num(0),
473                   links_it(doc),
474                   link_changing(false)
475             {
476                 spumux_temp.close();
477                 links_temp.close();
478             }
479
480         Glib::RefPtr<Gdk::Pixbuf> diff_pixbuf;
481
482         temp_file spumux_temp;
483         std::ofstream spumux_file;
484
485         temp_file links_temp;
486
487         unsigned link_num;
488         link_iterator links_it, links_end;
489
490         rectangle link_rect;
491         bool link_changing;
492         Glib::RefPtr<Gdk::Pixbuf> norm_pixbuf;
493     };
494
495     void webdvd_window::process_links(nsIPresShell * pres_shell,
496                                      nsIPresContext * pres_context,
497                                      nsIDOMWindow * dom_window)
498     {
499         Glib::RefPtr<Gdk::Window> window(get_window());
500         assert(window);
501
502         nsCOMPtr<nsIDOMDocument> basic_doc;
503         check(dom_window->GetDocument(getter_AddRefs(basic_doc)));
504         nsCOMPtr<nsIDOMNSDocument> ns_doc(do_QueryInterface(basic_doc));
505         assert(ns_doc);
506         nsCOMPtr<nsIEventStateManager> event_state_man(
507             pres_context->EventStateManager()); // does not AddRef
508         assert(event_state_man);
509         nsCOMPtr<nsIDOMDocumentEvent> event_factory(
510             do_QueryInterface(basic_doc));
511         assert(event_factory);
512         nsCOMPtr<nsIDOMDocumentView> doc_view(do_QueryInterface(basic_doc));
513         assert(doc_view);
514         nsCOMPtr<nsIDOMAbstractView> view;
515         check(doc_view->GetDefaultView(getter_AddRefs(view)));
516
517         // Set up or recover our iteration state.
518         std::auto_ptr<page_state> state(page_state_);
519         if (!state.get())
520         {
521             state.reset(
522                 new page_state(
523                     basic_doc, frame_params_.width, frame_params_.height));
524             
525             state->spumux_file.open(state->spumux_temp.get_name().c_str());
526             state->spumux_file <<
527                 "<subpictures>\n"
528                 "  <stream>\n"
529                 "    <spu force='yes' start='00:00:00.00'\n"
530                 "        highlight='" << state->links_temp.get_name() << "'\n"
531                 "        select='" << state->links_temp.get_name() << "'>\n";
532         }
533
534         rectangle window_rect = {
535             0, 0, frame_params_.width, frame_params_.height
536         };
537
538         unsigned menu_num = resource_map_[page_queue_.front()].index;
539
540         for (/* no initialisation */;
541              state->links_it != state->links_end;
542              ++state->links_it)
543         {
544             nsCOMPtr<nsIDOMNode> node(*state->links_it);
545
546             // Find the link URI and separate any fragment from it.
547             nsCOMPtr<nsILink> link(do_QueryInterface(node));
548             assert(link);
549             nsCOMPtr<nsIURI> uri_iface;
550             check(link->GetHrefURI(getter_AddRefs(uri_iface)));
551             std::string uri_and_fragment, uri, fragment;
552             {
553                 nsCString uri_and_fragment_ns;
554                 check(uri_iface->GetSpec(uri_and_fragment_ns));
555                 uri_and_fragment.assign(uri_and_fragment_ns.BeginReading(),
556                                         uri_and_fragment_ns.EndReading());
557
558                 std::size_t hash_pos = uri_and_fragment.find('#');
559                 uri.assign(uri_and_fragment, 0, hash_pos);
560                 if (hash_pos != std::string::npos)
561                     fragment.assign(uri_and_fragment,
562                                     hash_pos + 1, std::string::npos);
563             }
564
565             // Is this a new link?
566             if (!state->link_changing)
567             {
568                 // Find a rectangle enclosing the link and clip it to the
569                 // window.
570                 nsCOMPtr<nsIDOMElement> elem(do_QueryInterface(node));
571                 assert(elem);
572                 state->link_rect = get_elem_rect(ns_doc, elem);
573                 state->link_rect &= window_rect;
574
575                 if (state->link_rect.empty())
576                 {
577                     std::cerr << "Ignoring invisible link to "
578                               << uri_and_fragment << "\n";
579                     continue;
580                 }
581
582                 ++state->link_num;
583
584                 if (state->link_num >= unsigned(dvd::menu_buttons_max))
585                 {
586                     if (state->link_num == unsigned(dvd::menu_buttons_max))
587                         std::cerr << "No more than " << dvd::menu_buttons_max
588                                   << " buttons can be placed on a menu\n";
589                     std::cerr << "Ignoring link to " << uri_and_fragment
590                               << "\n";
591                     continue;
592                 }
593
594                 state->spumux_file <<
595                     "      <button x0='" << state->link_rect.left << "'"
596                     " y0='" << state->link_rect.top << "'"
597                     " x1='" << state->link_rect.right - 1 << "'"
598                     " y1='" << state->link_rect.bottom - 1 << "'/>\n";
599
600                 // Check whether this is a link to a video or a page then
601                 // add it to the known resources if not already seen; then
602                 // add it to the menu entries.
603                 dvd_contents::pgc_ref target;
604                 // FIXME: This is a bit of a hack.  Perhaps we could decide
605                 // later based on the MIME type determined by Mozilla?
606                 if ((uri.size() > 4
607                      && uri.compare(uri.size() - 4, 4, ".vob") == 0)
608                     || (uri.size() > 8
609                         && uri.compare(uri.size() - 8, 8, ".voblist") == 0))
610                 {
611                     PRBool is_file;
612                     check(uri_iface->SchemeIs("file", &is_file));
613                     if (!is_file)
614                     {
615                         std::cerr << "Links to video must use the file:"
616                                   << " scheme\n";
617                         continue;
618                     }
619                     target = add_title(uri);
620                     target.sub_index =
621                         std::strtoul(fragment.c_str(), NULL, 10);
622                 }
623                 else
624                 {
625                     target = add_menu(uri);
626                     // TODO: If there's a fragment, work out which button
627                     // is closest and set target.sub_index.
628                 }
629                 contents_.menus[menu_num].entries.push_back(target);
630
631                 nsCOMPtr<nsIContent> content(do_QueryInterface(node));
632                 assert(content);
633                 nsCOMPtr<nsIDOMEventTarget> event_target(
634                     do_QueryInterface(node));
635                 assert(event_target);
636
637                 state->norm_pixbuf = Gdk::Pixbuf::create(
638                     Glib::RefPtr<Gdk::Drawable>(window),
639                     window->get_colormap(),
640                     state->link_rect.left,
641                     state->link_rect.top,
642                     0,
643                     0,
644                     state->link_rect.right - state->link_rect.left,
645                     state->link_rect.bottom - state->link_rect.top);
646
647                 nsCOMPtr<nsIDOMEvent> event;
648                 check(event_factory->CreateEvent(
649                           NS_ConvertASCIItoUTF16("MouseEvents"),
650                           getter_AddRefs(event)));
651                 nsCOMPtr<nsIDOMMouseEvent> mouse_event(
652                     do_QueryInterface(event));
653                 assert(mouse_event);
654                 check(mouse_event->InitMouseEvent(
655                           NS_ConvertASCIItoUTF16("mouseover"),
656                           true,  // can bubble
657                           true,  // cancelable
658                           view,
659                           0,     // detail: mouse click count
660                           state->link_rect.left, // screenX
661                           state->link_rect.top,  // screenY
662                           state->link_rect.left, // clientX
663                           state->link_rect.top,  // clientY
664                           false, false, false, false, // qualifiers
665                           0,     // button: left (or primary)
666                           0));   // related target
667                 PRBool dummy;
668                 check(event_target->DispatchEvent(mouse_event,
669                                                   &dummy));
670                 check(event_state_man->SetContentState(content,
671                                                        NS_EVENT_STATE_HOVER));
672
673                 pres_shell->FlushPendingNotifications(true);
674
675                 // We may have to exit and wait for image loading
676                 // to complete, at which point we will be called
677                 // again.
678                 if (browser_is_busy())
679                 {
680                     state->link_changing = true;
681                     page_state_ = state;
682                     return;
683                 }
684             }
685
686             window->process_updates(true);
687
688             Glib::RefPtr<Gdk::Pixbuf> changed_pixbuf(
689                 Gdk::Pixbuf::create(
690                     Glib::RefPtr<Gdk::Drawable>(window),
691                     window->get_colormap(),
692                     state->link_rect.left,
693                     state->link_rect.top,
694                     0,
695                     0,
696                     state->link_rect.right - state->link_rect.left,
697                     state->link_rect.bottom - state->link_rect.top));
698             diff_rgb_pixbufs(
699                 state->norm_pixbuf,
700                 changed_pixbuf,
701                 state->diff_pixbuf,
702                 state->link_rect.left,
703                 state->link_rect.top,
704                 state->link_rect.right - state->link_rect.left,
705                 state->link_rect.bottom - state->link_rect.top);
706         }
707
708         quantise_rgba_pixbuf(state->diff_pixbuf, dvd::button_n_colours);
709
710         std::cout << "saving " << state->links_temp.get_name()
711                   << std::endl;
712         state->diff_pixbuf->save(state->links_temp.get_name(), "png");
713
714         state->spumux_file <<
715             "    </spu>\n"
716             "  </stream>\n"
717             "</subpictures>\n";
718
719         state->spumux_file.close();
720
721         // TODO: if (!state->spumux_file) throw ...
722
723         {
724             std::ostringstream command_stream;
725             command_stream << "pngtopnm "
726                            << background_temp_->get_name()
727                            << " | ppmtoy4m -v0 -n1 -F"
728                            << frame_params_.rate_numer
729                            << ":" << frame_params_.rate_denom
730                            << " -A" << frame_params_.pixel_ratio_width
731                            << ":" << frame_params_.pixel_ratio_height
732                            << (" -Ip -S420_mpeg2"
733                                " | mpeg2enc -v0 -f8 -a2 -o/dev/stdout"
734                                " | mplex -v0 -f8 -o/dev/stdout /dev/stdin"
735                                " | spumux -v0 -mdvd ")
736                            << state->spumux_temp.get_name()
737                            << " > "
738                            << contents_.menus[menu_num].vob_temp->get_name();
739             std::string command(command_stream.str());
740             const char * argv[] = {
741                 "/bin/sh", "-c", command.c_str(), 0
742             };
743             std::cout << "running " << argv[2] << std::endl;
744             int command_result;
745             Glib::spawn_sync(".",
746                              Glib::ArrayHandle<std::string>(
747                                  argv, sizeof(argv)/sizeof(argv[0]),
748                                  Glib::OWNERSHIP_NONE),
749                              Glib::SPAWN_STDOUT_TO_DEV_NULL,
750                              SigC::Slot0<void>(),
751                              0, 0,
752                              &command_result);
753             if (command_result != 0)
754                 throw std::runtime_error("spumux pipeline failed");
755         }
756     }
757
758     const video::frame_params & lookup_frame_params(const char * str)
759     {
760         assert(str);
761         static const struct { const char * str; bool is_ntsc; }
762         known_strings[] = {
763             { "NTSC",  true },
764             { "ntsc",  true },
765             { "PAL",   false },
766             { "pal",   false },
767             // For DVD purposes, SECAM can be treated identically to PAL.
768             { "SECAM", false },
769             { "secam", false }
770         };
771         for (std::size_t i = 0;
772              i != sizeof(known_strings)/sizeof(known_strings[0]);
773              ++i)
774             if (std::strcmp(str, known_strings[i].str) == 0)
775                 return known_strings[i].is_ntsc ?
776                     video::ntsc_params : video::pal_params;
777         throw std::runtime_error(
778             std::string("Invalid video standard: ").append(str));
779     }
780
781     void print_usage(std::ostream & stream, const char * command_name)
782     {
783         stream << "Usage: " << command_name
784                << (" [gtk-options] [--video-std std-name]"
785                    " [--preview] menu-url [output-dir]\n");
786     }
787     
788     void set_browser_preferences()
789     {
790         nsCOMPtr<nsIPrefService> pref_service;
791         static const nsCID pref_service_cid = NS_PREFSERVICE_CID;
792         check(CallGetService<nsIPrefService>(pref_service_cid,
793                                              getter_AddRefs(pref_service)));
794         nsCOMPtr<nsIPrefBranch> pref_branch;
795
796         // Disable IE-compatibility kluge that causes backgrounds to
797         // sometimes/usually be missing from snapshots.  This is only
798         // effective from Mozilla 1.8 onward.
799 #       if MOZ_VERSION_MAJOR > 1                                 \
800            || (MOZ_VERSION_MAJOR == 1 && MOZ_VERSION_MINOR >= 8)
801         check(pref_service->GetDefaultBranch("layout",
802                                              getter_AddRefs(pref_branch)));
803         check(pref_branch->SetBoolPref(
804                   "fire_onload_after_image_background_loads",
805                   true));
806 #       endif
807
808         // Set display resolution.  With standard-definition video we
809         // will be fitting ~600 pixels across a screen typically
810         // ranging from 10 to 25 inches wide, for a resolution of
811         // 24-60 dpi.  I therefore declare the average horizontal
812         // resolution to be 40 dpi.  The vertical resolution will be
813         // slightly higher (PAL/SECAM) or lower (NTSC), but
814         // unfortunately Mozilla doesn't support non-square pixels
815         // (and neither do fontconfig or Xft anyway).
816         check(pref_service->GetDefaultBranch("browser.display",
817                                              getter_AddRefs(pref_branch)));
818         check(pref_branch->SetIntPref("screen_resolution", 40));
819     }
820
821 } // namespace
822
823 int main(int argc, char ** argv)
824 {
825     try
826     {
827         video::frame_params frame_params = video::pal_params;
828         bool preview_mode = false;
829         std::string menu_url;
830         std::string output_dir;
831
832         // Do initial option parsing.  We have to do this before
833         // letting Gtk parse the arguments since we may need to spawn
834         // Xvfb first.
835         int argi = 1;
836         while (argi != argc)
837         {
838             if (std::strcmp(argv[argi], "--") == 0)
839             {
840                 break;
841             }
842             else if (std::strcmp(argv[argi], "--help") == 0)
843             {
844                 print_usage(std::cout, argv[0]);
845                 return EXIT_SUCCESS;
846             }
847             else if (std::strcmp(argv[argi], "--preview") == 0)
848             {
849                 preview_mode = true;
850                 argi += 1;
851             }
852             else if (std::strcmp(argv[argi], "--video-std") == 0)
853             {
854                 if (argi + 1 == argc)
855                 {
856                     std::cerr << "Missing argument to --video-std\n";
857                     print_usage(std::cerr, argv[0]);
858                     return EXIT_FAILURE;
859                 }
860                 frame_params = lookup_frame_params(argv[argi + 1]);
861                 argi += 2;
862             }
863             else
864             {
865                 argi += 1;
866             }
867         }
868
869         std::auto_ptr<x_frame_buffer> fb;
870         if (!preview_mode)
871         {
872             // Spawn Xvfb and set env variables so that Xlib will use it
873             // Use 8 bits each for RGB components, which should translate into
874             // "enough" bits for YUV components.
875             fb.reset(new x_frame_buffer(frame_params.width,
876                                         frame_params.height,
877                                         3 * 8));
878             setenv("XAUTHORITY", fb->get_authority().c_str(), true);
879             setenv("DISPLAY", fb->get_display().c_str(), true);
880         }
881
882         // Initialise Gtk
883         Gtk::Main kit(argc, argv);
884
885         // Complete option parsing with Gtk's options out of the way.
886         argi = 1;
887         while (argi != argc)
888         {
889             if (std::strcmp(argv[argi], "--") == 0)
890             {
891                 argi += 1;
892                 break;
893             }
894             else if (std::strcmp(argv[argi], "--preview") == 0)
895             {
896                 argi += 1;
897             }
898             else if (std::strcmp(argv[argi], "--video-std") == 0)
899             {
900                 argi += 2;
901             }
902             else if (argv[argi][0] == '-')
903             {
904                 std::cerr << "Invalid option: " << argv[argi] << "\n";
905                 print_usage(std::cerr, argv[0]);
906                 return EXIT_FAILURE;
907             }
908             else
909             {
910                 break;
911             }
912         }
913
914         // Look for a starting URL or filename and (except in preview
915         // mode) an output directory after the options.
916         if (argc - argi != (preview_mode ? 1 : 2))
917         {
918             print_usage(std::cerr, argv[0]);
919             return EXIT_FAILURE;
920         }
921         if (std::strstr(argv[argi], "://"))
922         {
923             // It appears to be an absolute URL, so use it as-is.
924             menu_url = argv[argi];
925         }
926         else
927         {
928             // Assume it's a filename.  Resolve it to an absolute URL.
929             std::string path(argv[argi]);
930             if (!Glib::path_is_absolute(path))
931                 path = Glib::build_filename(Glib::get_current_dir(), path);
932             menu_url = Glib::filename_to_uri(path);             
933         }
934         if (!preview_mode)
935             output_dir = argv[argi + 1];
936
937         // Initialise Mozilla
938         browser_widget::initialiser browser_init;
939         set_browser_preferences();
940         if (!preview_mode)
941             null_prompt_service::install();
942
943         // Run the browser/converter
944         webdvd_window window(frame_params, menu_url, output_dir);
945         Gtk::Main::run(window);
946     }
947     catch (std::exception & e)
948     {
949         std::cerr << "Fatal error: " << e.what() << "\n";
950         return EXIT_FAILURE;
951     }
952
953     return EXIT_SUCCESS;
954 }