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