]> git.decadent.org.uk Git - videolink.git/blob - webdvd.cpp
Changed WebDvdWindow to resist resizing in preview mode.
[videolink.git] / webdvd.cpp
1 // Copyright 2005 Ben Hutchings <ben@decadentplace.org.uk>.
2 // See the file "COPYING" for licence details.
3
4 #include <cassert>
5 #include <exception>
6 #include <fstream>
7 #include <iomanip>
8 #include <iostream>
9 #include <memory>
10 #include <queue>
11 #include <set>
12 #include <sstream>
13 #include <string>
14
15 #include <stdlib.h>
16 #include <unistd.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 <nsIDOMDocumentEvent.h>
33 #include <nsIDOMDocumentView.h>
34 #include <nsIDOMElement.h>
35 #include <nsIDOMEventTarget.h>
36 #include <nsIDOMHTMLDocument.h>
37 #include <nsIDOMMouseEvent.h>
38 #include <nsIDOMNSDocument.h>
39 #include <nsIDOMWindow.h>
40 #include <nsIEventStateManager.h>
41 #include <nsIInterfaceRequestorUtils.h>
42 #include <nsIURI.h> // required before nsILink.h
43 #include <nsILink.h>
44 #include <nsIPresContext.h>
45 #include <nsIPresShell.h>
46 #include <nsIWebBrowser.h>
47 #include <nsString.h>
48
49 #include "browserwidget.hpp"
50 #include "childiterator.hpp"
51 #include "dvd.hpp"
52 #include "framebuffer.hpp"
53 #include "linkiterator.hpp"
54 #include "pixbufs.hpp"
55 #include "stylesheets.hpp"
56 #include "temp_file.hpp"
57 #include "video.hpp"
58 #include "xpcom_support.hpp"
59
60 using xpcom_support::check;
61
62 namespace
63 {
64     struct rectangle
65     {
66         int left, top;     // inclusive
67         int right, bottom; // exclusive
68
69         rectangle operator|=(const rectangle & other)
70             {
71                 if (other.empty())
72                 {
73                     // use current extents unchanged
74                 }
75                 else if (empty())
76                 {
77                     // use other extents
78                     *this = other;
79                 }
80                 else
81                 {
82                     // find rectangle enclosing both extents
83                     left = std::min(left, other.left);
84                     top = std::min(top, other.top);
85                     right = std::max(right, other.right);
86                     bottom = std::max(bottom, other.bottom);
87                 }
88
89                 return *this;
90             }
91
92         rectangle operator&=(const rectangle & other)
93             {
94                 // find rectangle enclosed in both extents
95                 left = std::max(left, other.left);
96                 top = std::max(top, other.top);
97                 right = std::max(left, std::min(right, other.right));
98                 bottom = std::max(top, std::min(bottom, other.bottom));
99                 return *this;
100             }
101
102         bool empty() const
103             {
104                 return left == right || bottom == top;
105             }
106     };
107
108     rectangle get_elem_rect(nsIDOMNSDocument * ns_doc,
109                             nsIDOMElement * elem)
110     {
111         rectangle result;
112
113         // Start with this element's bounding box
114         nsCOMPtr<nsIBoxObject> box;
115         check(ns_doc->GetBoxObjectFor(elem, getter_AddRefs(box)));
116         int width, height;
117         check(box->GetScreenX(&result.left));
118         check(box->GetScreenY(&result.top));
119         check(box->GetWidth(&width));
120         check(box->GetHeight(&height));
121         result.right = result.left + width;
122         result.bottom = result.top + height;
123
124         // Merge bounding boxes of all child elements
125         for (ChildIterator it = ChildIterator(elem), end; it != end; ++it)
126         {
127             nsCOMPtr<nsIDOMNode> child_node(*it);
128             PRUint16 child_type;
129             if (check(child_node->GetNodeType(&child_type)),
130                 child_type == nsIDOMNode::ELEMENT_NODE)
131             {
132                 nsCOMPtr<nsIDOMElement> child_elem(
133                     do_QueryInterface(child_node));
134                 result |= get_elem_rect(ns_doc, child_elem);
135             }
136         }
137
138         return result;
139     }
140
141     class WebDvdWindow : public Gtk::Window
142     {
143     public:
144         WebDvdWindow(
145             const video::frame_params & frame_params,
146             const std::string & main_page_uri,
147             const std::string & output_dir);
148
149     private:
150         void add_page(const std::string & uri);
151         void add_video(const std::string & uri);
152         void load_next_page();
153         void on_net_state_change(const char * uri, gint flags, guint status);
154         bool process_page();
155         void save_screenshot();
156         void process_links(nsIPresShell * pres_shell,
157                            nsIPresContext * pres_context,
158                            nsIDOMWindow * dom_window);
159         void generate_dvd();
160
161         enum ResourceType { page_resource, video_resource };
162         typedef std::pair<ResourceType, int> ResourceEntry;
163         video::frame_params frame_params_;
164         std::string output_dir_;
165         BrowserWidget browser_widget_;
166         nsCOMPtr<nsIStyleSheet> stylesheet_;
167         std::queue<std::string> page_queue_;
168         std::map<std::string, ResourceEntry> resource_map_;
169         std::vector<std::vector<std::string> > page_links_;
170         std::vector<std::string> video_paths_;
171         bool pending_window_update_;
172         int pending_req_count_;
173         std::auto_ptr<temp_file> background_temp_;
174         struct page_state;
175         std::auto_ptr<page_state> page_state_;
176         std::vector<boost::shared_ptr<temp_file> > page_temp_files_;
177     };
178
179     WebDvdWindow::WebDvdWindow(
180         const video::frame_params & frame_params,
181         const std::string & main_page_uri,
182         const std::string & output_dir)
183             : frame_params_(frame_params),
184               output_dir_(output_dir),
185               stylesheet_(load_css("file://" WEBDVD_LIB_DIR "/webdvd.css")),
186               pending_window_update_(false),
187               pending_req_count_(0)
188     {
189         set_size_request(frame_params_.width, frame_params_.height);
190         set_resizable(false);
191
192         add(browser_widget_);
193         browser_widget_.show();
194         browser_widget_.signal_net_state().connect(
195             SigC::slot(*this, &WebDvdWindow::on_net_state_change));
196
197         add_page(main_page_uri);
198         load_next_page();
199     }
200
201     void WebDvdWindow::add_page(const std::string & uri)
202     {
203         if (resource_map_.insert(
204                 std::make_pair(uri, ResourceEntry(page_resource, 0)))
205             .second)
206         {
207             page_queue_.push(uri);
208         }
209     }
210
211     void WebDvdWindow::add_video(const std::string & uri)
212     {
213         if (resource_map_.insert(
214                 std::make_pair(uri, ResourceEntry(video_resource,
215                                                   video_paths_.size() + 1)))
216             .second)
217         {
218             // FIXME: Should accept some slightly different URI prefixes
219             // (e.g. file://localhost/) and decode any URI-escaped
220             // characters in the path.
221             assert(uri.compare(0, 8, "file:///") == 0);
222             video_paths_.push_back(uri.substr(7));
223         }
224     }
225
226     void WebDvdWindow::load_next_page()
227     {
228         assert(!page_queue_.empty());
229         const std::string & uri = page_queue_.front();
230         std::cout << "loading " << uri << std::endl;
231
232         std::size_t page_count = page_links_.size();
233         resource_map_[uri].second = ++page_count;
234         page_links_.resize(page_count);
235
236         pending_window_update_ = true;
237         browser_widget_.load_uri(uri);
238     }
239
240     void WebDvdWindow::on_net_state_change(const char * uri,
241                                            gint flags, guint status)
242     {
243         if (flags & GTK_MOZ_EMBED_FLAG_IS_REQUEST)
244         {
245             if (flags & GTK_MOZ_EMBED_FLAG_START)
246                 ++pending_req_count_;
247
248             if (flags & GTK_MOZ_EMBED_FLAG_STOP)
249             {
250                 assert(pending_req_count_ != 0);
251                 --pending_req_count_;
252             }
253         }
254             
255         if (flags & GTK_MOZ_EMBED_FLAG_STOP
256             && flags & GTK_MOZ_EMBED_FLAG_IS_WINDOW)
257         {
258             // Check whether the load was successful, ignoring this
259             // pseudo-error.
260             if (status != NS_IMAGELIB_ERROR_LOAD_ABORTED)
261                 check(status);
262
263             pending_window_update_ = false;
264         }
265
266         if (pending_req_count_ == 0 && !pending_window_update_)
267         {
268             try
269             {
270                 if (!process_page())
271                     Gtk::Main::quit();
272             }
273             catch (std::exception & e)
274             {
275                 std::cerr << "Fatal error";
276                 if (!page_queue_.empty())
277                     std::cerr << " while processing <" << page_queue_.front()
278                               << ">";
279                 std::cerr << ": " << e.what() << "\n";
280                 Gtk::Main::quit();
281             }
282         }
283     }
284
285     bool WebDvdWindow::process_page()
286     {
287         assert(!page_queue_.empty());
288
289         nsCOMPtr<nsIWebBrowser> browser(browser_widget_.get_browser());
290         nsCOMPtr<nsIDocShell> doc_shell(do_GetInterface(browser));
291         assert(doc_shell);
292         nsCOMPtr<nsIPresShell> pres_shell;
293         check(doc_shell->GetPresShell(getter_AddRefs(pres_shell)));
294         nsCOMPtr<nsIPresContext> pres_context;
295         check(doc_shell->GetPresContext(getter_AddRefs(pres_context)));
296         nsCOMPtr<nsIDOMWindow> dom_window;
297         check(browser->GetContentDOMWindow(getter_AddRefs(dom_window)));
298
299         if (output_dir_.empty())
300         {
301             // In preview mode, just apply the stylesheet and let the
302             // user select links.
303             apply_style_sheet(stylesheet_, pres_shell);
304         }
305         else
306         {
307             // If we haven't already started work on this page, apply
308             // the stylesheet and save a screenshot of its normal
309             // appearance.
310             if (!page_state_.get())
311             {
312                 apply_style_sheet(stylesheet_, pres_shell);
313                 save_screenshot();
314             }
315
316             // Start or continue processing links.
317             process_links(pres_shell, pres_context, dom_window);
318
319             // If we've finished work on the links, move on to the
320             // next page, if any, or else generate the DVD filesystem.
321             if (!page_state_.get())
322             {
323                 page_queue_.pop();
324                 if (page_queue_.empty())
325                 {
326                     generate_dvd();
327                     return false;
328                 }
329                 else
330                 {
331                     load_next_page();
332                 }
333             }
334         }
335
336         return true;
337     }
338
339     void WebDvdWindow::save_screenshot()
340     {
341         Glib::RefPtr<Gdk::Window> window(get_window());
342         assert(window);
343         window->process_updates(true);
344
345         background_temp_.reset(new temp_file("webdvd-back-"));
346         background_temp_->close();
347         std::cout << "saving " << background_temp_->get_name() << std::endl;
348         Gdk::Pixbuf::create(Glib::RefPtr<Gdk::Drawable>(window),
349                             window->get_colormap(),
350                             0, 0, 0, 0,
351                             frame_params_.width, frame_params_.height)
352             ->save(background_temp_->get_name(), "png");
353     }
354
355     struct WebDvdWindow::page_state
356     {
357         page_state(nsIDOMDocument * doc, int width, int height)
358                 : diff_pixbuf(Gdk::Pixbuf::create(
359                                   Gdk::COLORSPACE_RGB,
360                                   true, 8, // has_alpha, bits_per_sample
361                                   width, height)),
362                   spumux_temp("webdvd-spumux-"),
363                   links_temp("webdvd-links-"),
364                   link_num(0),
365                   links_it(doc),
366                   link_changing(false)
367             {
368                 spumux_temp.close();
369                 links_temp.close();
370             }
371
372         Glib::RefPtr<Gdk::Pixbuf> diff_pixbuf;
373
374         temp_file spumux_temp;
375         std::ofstream spumux_file;
376
377         temp_file links_temp;
378
379         int link_num;
380         LinkIterator links_it, links_end;
381
382         rectangle link_rect;
383         bool link_changing;
384         Glib::RefPtr<Gdk::Pixbuf> norm_pixbuf;
385     };
386
387     void WebDvdWindow::process_links(nsIPresShell * pres_shell,
388                                      nsIPresContext * pres_context,
389                                      nsIDOMWindow * dom_window)
390     {
391         Glib::RefPtr<Gdk::Window> window(get_window());
392         assert(window);
393
394         nsCOMPtr<nsIDOMDocument> basic_doc;
395         check(dom_window->GetDocument(getter_AddRefs(basic_doc)));
396         nsCOMPtr<nsIDOMNSDocument> ns_doc(do_QueryInterface(basic_doc));
397         assert(ns_doc);
398         nsCOMPtr<nsIEventStateManager> event_state_man(
399             pres_context->EventStateManager()); // does not AddRef
400         assert(event_state_man);
401         nsCOMPtr<nsIDOMDocumentEvent> event_factory(
402             do_QueryInterface(basic_doc));
403         assert(event_factory);
404         nsCOMPtr<nsIDOMDocumentView> doc_view(do_QueryInterface(basic_doc));
405         assert(doc_view);
406         nsCOMPtr<nsIDOMAbstractView> view;
407         check(doc_view->GetDefaultView(getter_AddRefs(view)));
408
409         // Set up or recover our iteration state.
410         std::auto_ptr<page_state> state(page_state_);
411         if (!state.get())
412         {
413             state.reset(
414                 new page_state(
415                     basic_doc, frame_params_.width, frame_params_.height));
416             
417             state->spumux_file.open(state->spumux_temp.get_name().c_str());
418             state->spumux_file <<
419                 "<subpictures>\n"
420                 "  <stream>\n"
421                 "    <spu force='yes' start='00:00:00.00'\n"
422                 "        highlight='" << state->links_temp.get_name() << "'\n"
423                 "        select='" << state->links_temp.get_name() << "'>\n";
424         }
425
426         rectangle window_rect = {
427             0, 0, frame_params_.width, frame_params_.height
428         };
429
430         for (/* no initialisation */;
431              state->links_it != state->links_end;
432              ++state->links_it)
433         {
434             nsCOMPtr<nsIDOMNode> node(*state->links_it);
435
436             // Find the link URI.
437             nsCOMPtr<nsILink> link(do_QueryInterface(node));
438             assert(link);
439             nsCOMPtr<nsIURI> uri;
440             check(link->GetHrefURI(getter_AddRefs(uri)));
441             std::string uri_string;
442             {
443                 nsCString uri_ns_string;
444                 check(uri->GetSpec(uri_ns_string));
445                 uri_string.assign(uri_ns_string.BeginReading(),
446                                   uri_ns_string.EndReading());
447             }
448             std::string uri_sans_fragment(uri_string, 0, uri_string.find('#'));
449
450             // Is this a new link?
451             if (!state->link_changing)
452             {
453                 // Find a rectangle enclosing the link and clip it to the
454                 // window.
455                 nsCOMPtr<nsIDOMElement> elem(do_QueryInterface(node));
456                 assert(elem);
457                 state->link_rect = get_elem_rect(ns_doc, elem);
458                 state->link_rect &= window_rect;
459
460                 if (state->link_rect.empty())
461                 {
462                     std::cerr << "Ignoring invisible link to "
463                               << uri_string << "\n";
464                     continue;
465                 }
466
467                 ++state->link_num;
468
469                 if (state->link_num >= dvd::menu_buttons_max)
470                 {
471                     if (state->link_num == dvd::menu_buttons_max)
472                         std::cerr << "No more than " << dvd::menu_buttons_max
473                                   << " buttons can be placed on a page\n";
474                     std::cerr << "Ignoring link to " << uri_string << "\n";
475                     continue;
476                 }
477
478                 // Check whether this is a link to a video or a page then
479                 // add it to the known resources if not already seen.
480                 nsCString path;
481                 check(uri->GetPath(path));
482                 // FIXME: This is a bit of a hack.  Perhaps we could decide
483                 // later based on the MIME type determined by Mozilla?
484                 if (path.Length() > 4
485                     && std::strcmp(path.EndReading() - 4, ".vob") == 0)
486                 {
487                     PRBool is_file;
488                     check(uri->SchemeIs("file", &is_file));
489                     if (!is_file)
490                     {
491                         std::cerr << "Links to video must use the file:"
492                                   << " scheme\n";
493                         continue;
494                     }
495                     add_video(uri_sans_fragment);
496                 }
497                 else
498                 {
499                     add_page(uri_sans_fragment);
500                 }
501
502                 nsCOMPtr<nsIContent> content(do_QueryInterface(node));
503                 assert(content);
504                 nsCOMPtr<nsIDOMEventTarget> event_target(
505                     do_QueryInterface(node));
506                 assert(event_target);
507
508                 state->norm_pixbuf = Gdk::Pixbuf::create(
509                     Glib::RefPtr<Gdk::Drawable>(window),
510                     window->get_colormap(),
511                     state->link_rect.left,
512                     state->link_rect.top,
513                     0,
514                     0,
515                     state->link_rect.right - state->link_rect.left,
516                     state->link_rect.bottom - state->link_rect.top);
517
518                 nsCOMPtr<nsIDOMEvent> event;
519                 check(event_factory->CreateEvent(
520                           NS_ConvertASCIItoUTF16("MouseEvents"),
521                           getter_AddRefs(event)));
522                 nsCOMPtr<nsIDOMMouseEvent> mouse_event(
523                     do_QueryInterface(event));
524                 assert(mouse_event);
525                 check(mouse_event->InitMouseEvent(
526                           NS_ConvertASCIItoUTF16("mouseover"),
527                           true,  // can bubble
528                           true,  // cancelable
529                           view,
530                           0,     // detail: mouse click count
531                           state->link_rect.left, // screenX
532                           state->link_rect.top,  // screenY
533                           state->link_rect.left, // clientX
534                           state->link_rect.top,  // clientY
535                           false, false, false, false, // qualifiers
536                           0,     // button: left (or primary)
537                           0));   // related target
538                 PRBool dummy;
539                 check(event_target->DispatchEvent(mouse_event,
540                                                   &dummy));
541                 check(event_state_man->SetContentState(content,
542                                                        NS_EVENT_STATE_HOVER));
543
544                 pres_shell->FlushPendingNotifications(true);
545
546                 // We may have to exit and wait for image loading
547                 // to complete, at which point we will be called
548                 // again.
549                 if (pending_req_count_ > 0)
550                 {
551                     state->link_changing = true;
552                     page_state_ = state;
553                     return;
554                 }
555             }
556
557             window->process_updates(true);
558
559             Glib::RefPtr<Gdk::Pixbuf> changed_pixbuf(
560                 Gdk::Pixbuf::create(
561                     Glib::RefPtr<Gdk::Drawable>(window),
562                     window->get_colormap(),
563                     state->link_rect.left,
564                     state->link_rect.top,
565                     0,
566                     0,
567                     state->link_rect.right - state->link_rect.left,
568                     state->link_rect.bottom - state->link_rect.top));
569             diff_rgb_pixbufs(
570                 state->norm_pixbuf,
571                 changed_pixbuf,
572                 state->diff_pixbuf,
573                 state->link_rect.left,
574                 state->link_rect.top,
575                 state->link_rect.right - state->link_rect.left,
576                 state->link_rect.bottom - state->link_rect.top);
577
578             state->spumux_file <<
579                 "      <button x0='" << state->link_rect.left << "'"
580                 " y0='" << state->link_rect.top << "'"
581                 " x1='" << state->link_rect.right - 1 << "'"
582                 " y1='" << state->link_rect.bottom - 1 << "'/>\n";
583
584             // Add to the page's links, ignoring any fragment (for now).
585             page_links_.back().push_back(uri_sans_fragment);
586         }
587
588         quantise_rgba_pixbuf(state->diff_pixbuf, dvd::button_n_colours);
589
590         std::cout << "saving " << state->links_temp.get_name()
591                   << std::endl;
592         state->diff_pixbuf->save(state->links_temp.get_name(), "png");
593
594         state->spumux_file <<
595             "    </spu>\n"
596             "  </stream>\n"
597             "</subpictures>\n";
598
599         state->spumux_file.close();
600
601         // TODO: if (!state->spumux_file) throw ...
602
603         {
604             boost::shared_ptr<temp_file> vob_temp(
605                 new temp_file("webdvd-vob-"));
606             std::ostringstream command_stream;
607             command_stream << "pngtopnm "
608                            << background_temp_->get_name()
609                            << " | ppmtoy4m -v0 -n1 -F"
610                            << frame_params_.rate_numer
611                            << ":" << frame_params_.rate_denom
612                            << " -A" << frame_params_.pixel_ratio_width
613                            << ":" << frame_params_.pixel_ratio_height
614                            << (" -Ip -S420_mpeg2"
615                                " | mpeg2enc -v0 -f8 -a2 -o/dev/stdout"
616                                " | mplex -v0 -f8 -o/dev/stdout /dev/stdin"
617                                " | spumux -v0 -mdvd ")
618                            << state->spumux_temp.get_name()
619                            << " > " << vob_temp->get_name();
620             std::string command(command_stream.str());
621             const char * argv[] = {
622                 "/bin/sh", "-c", command.c_str(), 0
623             };
624             std::cout << "running " << argv[2] << std::endl;
625             int command_result;
626             Glib::spawn_sync(".",
627                              Glib::ArrayHandle<std::string>(
628                                  argv, sizeof(argv)/sizeof(argv[0]),
629                                  Glib::OWNERSHIP_NONE),
630                              Glib::SPAWN_STDOUT_TO_DEV_NULL,
631                              SigC::Slot0<void>(),
632                              0, 0,
633                              &command_result);
634             if (command_result != 0)
635                 throw std::runtime_error("spumux pipeline failed");
636
637             page_temp_files_.push_back(vob_temp);
638         }
639     }
640
641     void generate_page_dispatch(std::ostream &, int indent,
642                                 int first_page, int last_page);
643
644     void WebDvdWindow::generate_dvd()
645     {
646         temp_file temp("webdvd-dvdauthor-");
647         temp.close();
648         std::ofstream file(temp.get_name().c_str());
649
650         // We generate code that uses registers in the following way:
651         //
652         // g0:     link destination (when jumping to menu 1), then scratch
653         // g1:     current location
654         // g2-g11: location history (g2 = most recent)
655         // g12:    location that last linked to a video
656         //
657         // All locations are divided into two bitfields: the least
658         // significant 10 bits are a page/menu number and the most
659         // significant 6 bits are a link/button number.  This is
660         // chosen for compatibility with the encoding of the s8
661         // (button) register.
662         //
663         static const int link_mult = dvd::reg_s8_button_mult;
664         static const int page_mask = link_mult - 1;
665         static const int link_mask = (1 << dvd::reg_bits) - link_mult;
666
667         file <<
668             "<dvdauthor>\n"
669             "  <vmgm>\n"
670             "    <menus>\n";
671             
672         for (std::size_t page_num = 1;
673              page_num <= page_links_.size();
674              ++page_num)
675         {
676             std::vector<std::string> & page_links =
677                 page_links_[page_num - 1];
678
679             if (page_num == 1)
680             {
681                 // This is the first page (root menu) which needs to
682                 // include initialisation and dispatch code.
683         
684                 file <<
685                     "      <pgc entry='title'>\n"
686                     "        <pre>\n"
687                     // Has the location been set yet?
688                     "          if (g1 eq 0)\n"
689                     "          {\n"
690                     // Initialise the current location to first link on
691                     // this page.
692                     "            g1 = " << 1 * link_mult + 1 << ";\n"
693                     "          }\n"
694                     "          else\n"
695                     "          {\n"
696                     // Has the user selected a link?
697                     "            if (g0 ne 0)\n"
698                     "            {\n"
699                     // First update the history.
700                     // Does link go to the last page in the history?
701                     "              if (((g0 ^ g2) &amp; " << page_mask
702                      << ") == 0)\n"
703                     // It does; we treat this as going back and pop the old
704                     // location off the history stack into the current
705                     // location.  Clear the free stack slot.
706                     "              {\n"
707                     "                g1 = g2; g2 = g3; g3 = g4; g4 = g5;\n"
708                     "                g5 = g6; g6 = g7; g7 = g8; g8 = g9;\n"
709                     "                g9 = g10; g10 = g11; g11 = 0;\n"
710                     "              }\n"
711                     "              else\n"
712                     // Link goes to some other page, so push current
713                     // location onto the history stack and set the current
714                     // location to be exactly the target location.
715                     "              {\n"
716                     "                g11 = g10; g10 = g9; g9 = g8; g8 = g7;\n"
717                     "                g7 = g6; g6 = g5; g5 = g4; g4 = g3;\n"
718                     "                g3 = g2; g2 = g1; g1 = g0;\n"
719                     "              }\n"
720                     "            }\n"
721                     // Find the target page number.
722                     "            g0 = g1 &amp; " << page_mask << ";\n";
723                 // There seems to be no way to perform a computed jump,
724                 // so we generate all possible jumps and a binary search
725                 // to select the correct one.
726                 generate_page_dispatch(file, 12, 1, page_links_.size());
727                 file <<
728                     "          }\n";
729             }
730             else // page_num != 1
731             {
732                 file <<
733                     "      <pgc>\n"
734                     "        <pre>\n";
735             }
736
737             file <<
738                 // Clear link indicator and highlight the
739                 // appropriate link/button.
740                 "          g0 = 0; s8 = g1 &amp; " << link_mask << ";\n"
741                 "        </pre>\n"
742                 "        <vob file='"
743                  << page_temp_files_[page_num - 1]->get_name() << "'/>\n";
744
745             for (std::size_t link_num = 1;
746                  link_num <= page_links.size();
747                  ++link_num)
748             {
749                 file <<
750                     "        <button>"
751                     // Update current location.
752                     " g1 = " << link_num * link_mult + page_num << ";";
753
754                 // Jump to appropriate resource.
755                 const ResourceEntry & resource_loc =
756                     resource_map_[page_links[link_num - 1]];
757                 if (resource_loc.first == page_resource)
758                     file <<
759                         " g0 = " << 1 * link_mult + resource_loc.second << ";"
760                         " jump menu 1;";
761                 else if (resource_loc.first == video_resource)
762                     file << " jump title " << resource_loc.second << ";";
763
764                 file <<  " </button>\n";
765             }
766
767             file << "      </pgc>\n";
768         }
769
770         file <<
771             "    </menus>\n"
772             "  </vmgm>\n";
773
774         // Generate a titleset for each video.  This appears to make
775         // jumping to titles a whole lot simpler.
776         for (std::size_t video_num = 1;
777              video_num <= video_paths_.size();
778              ++video_num)
779         {
780             file <<
781                 "  <titleset>\n"
782                 // Generate a dummy menu so that the menu button on the
783                 // remote control will work.
784                 "    <menus>\n"
785                 "      <pgc entry='root'>\n"
786                 "        <pre> jump vmgm menu; </pre>\n"
787                 "      </pgc>\n"
788                 "    </menus>\n"
789                 "    <titles>\n"
790                 "      <pgc>\n"
791                 // Record calling page/menu.
792                 "        <pre> g12 = g1; </pre>\n"
793                 // FIXME: Should XML-escape the path
794                 "        <vob file='" << video_paths_[video_num - 1]
795                  << "'/>\n"
796                 // If page/menu location has not been changed during the
797                 // video, change the location to be the following
798                 // link/button when returning to it.  In any case,
799                 // return to a page/menu.
800                 "        <post> if (g1 eq g12) g1 = g1 + " << link_mult
801                  << "; call menu; </post>\n"
802                 "      </pgc>\n"
803                 "    </titles>\n"
804                 "  </titleset>\n";
805         }
806
807         file <<
808             "</dvdauthor>\n";
809
810         file.close();
811
812         {
813             const char * argv[] = {
814                 "dvdauthor",
815                 "-o", output_dir_.c_str(),
816                 "-x", temp.get_name().c_str(),
817                 0
818             };
819             int command_result;
820             Glib::spawn_sync(".",
821                              Glib::ArrayHandle<std::string>(
822                                  argv, sizeof(argv)/sizeof(argv[0]),
823                                  Glib::OWNERSHIP_NONE),
824                              Glib::SPAWN_SEARCH_PATH
825                              | Glib::SPAWN_STDOUT_TO_DEV_NULL,
826                              SigC::Slot0<void>(),
827                              0, 0,
828                              &command_result);
829             if (command_result != 0)
830                 throw std::runtime_error("dvdauthor failed");
831         }
832     }
833
834     void generate_page_dispatch(std::ostream & file, int indent,
835                                 int first_page, int last_page)
836     {
837         if (first_page == 1 && last_page == 1)
838         {
839             // The dispatch code is *on* page 1 so we must not dispatch to
840             // page 1 since that would cause an infinite loop.  This case
841             // should be unreachable if there is more than one page due
842             // to the following case.
843         }
844         else if (first_page == 1 && last_page == 2)
845         {
846             // dvdauthor doesn't allow empty blocks or null statements so
847             // when selecting between pages 1 and 2 we don't use an "else"
848             // part.  We must use braces so that a following "else" will
849             // match the right "if".
850             file << std::setw(indent) << "" << "{\n"
851                  << std::setw(indent) << "" << "if (g0 eq 2)\n"
852                  << std::setw(indent + 2) << "" << "jump menu 2;\n"
853                  << std::setw(indent) << "" << "}\n";
854         }
855         else if (first_page == last_page)
856         {
857             file << std::setw(indent) << ""
858                  << "jump menu " << first_page << ";\n";
859         }
860         else
861         {
862             int middle = (first_page + last_page) / 2;
863             file << std::setw(indent) << "" << "if (g0 le " << middle << ")\n";
864             generate_page_dispatch(file, indent + 2, first_page, middle);
865             file << std::setw(indent) << "" << "else\n";
866             generate_page_dispatch(file, indent + 2, middle + 1, last_page);
867         }
868     }
869
870     const video::frame_params & lookup_frame_params(const char * str)
871     {
872         assert(str);
873         static const struct { const char * str; bool is_ntsc; }
874         known_strings[] = {
875             { "NTSC",  true },
876             { "ntsc",  true },
877             { "PAL",   false },
878             { "pal",   false },
879             // For DVD purposes, SECAM can be treated identically to PAL.
880             { "SECAM", false },
881             { "secam", false }
882         };
883         for (std::size_t i = 0;
884              i != sizeof(known_strings)/sizeof(known_strings[0]);
885              ++i)
886             if (std::strcmp(str, known_strings[i].str) == 0)
887                 return known_strings[i].is_ntsc ?
888                     video::ntsc_params : video::pal_params;
889         throw std::runtime_error(
890             std::string("Invalid video standard: ").append(str));
891     }
892
893     void print_usage(std::ostream & stream, const char * command_name)
894     {
895         stream << "Usage: " << command_name
896                << (" [gtk-options] [--video-std std-name]"
897                    " [--preview] menu-url [output-dir]\n");
898     }
899     
900 } // namespace
901
902 int main(int argc, char ** argv)
903 {
904     try
905     {
906         video::frame_params frame_params = video::pal_params;
907         bool preview_mode = false;
908
909         // Do initial argument parsing.  We have to do this before
910         // letting Gtk parse the arguments since we may need to spawn
911         // Xvfb first.
912         int argi = 1;
913         while (argi != argc)
914         {
915             if (std::strcmp(argv[argi], "--") == 0)
916             {
917                 break;
918             }
919             else if (std::strcmp(argv[argi], "--help") == 0)
920             {
921                 print_usage(std::cout, argv[0]);
922                 return EXIT_SUCCESS;
923             }
924             else if (std::strcmp(argv[argi], "--preview") == 0)
925             {
926                 preview_mode = true;
927                 argi += 1;
928             }
929             else if (std::strcmp(argv[argi], "--video-std") == 0)
930             {
931                 if (argi + 1 == argc)
932                 {
933                     std::cerr << "Missing argument to --video-std\n";
934                     print_usage(std::cerr, argv[0]);
935                     return EXIT_FAILURE;
936                 }
937                 frame_params = lookup_frame_params(argv[argi + 1]);
938                 argi += 2;
939             }
940             else
941             {
942                 argi += 1;
943             }
944         }
945
946         std::auto_ptr<FrameBuffer> fb;
947         if (!preview_mode)
948         {
949             // Spawn Xvfb and set env variables so that Xlib will use it
950             // Use 8 bits each for RGB components, which should translate into
951             // "enough" bits for YUV components.
952             fb.reset(new FrameBuffer(frame_params.width, frame_params.height,
953                                      3 * 8));
954             setenv("XAUTHORITY", fb->get_x_authority().c_str(), true);
955             setenv("DISPLAY", fb->get_x_display().c_str(), true);
956         }
957
958         // Initialise Gtk
959         Gtk::Main kit(argc, argv);
960
961         // Complete argument parsing with Gtk's options out of the way.
962         argi = 1;
963         while (argi != argc)
964         {
965             if (std::strcmp(argv[argi], "--") == 0)
966             {
967                 argi += 1;
968                 break;
969             }
970             else if (std::strcmp(argv[argi], "--preview") == 0)
971             {
972                 argi += 1;
973             }
974             else if (std::strcmp(argv[argi], "--video-std") == 0)
975             {
976                 argi += 2;
977             }
978             else if (argv[argi][0] == '-')
979             {
980                 std::cerr << "Invalid option: " << argv[argi] << "\n";
981                 print_usage(std::cerr, argv[0]);
982                 return EXIT_FAILURE;
983             }
984             else
985             {
986                 break;
987             }
988         }
989         if (argc - argi != (preview_mode ? 1 : 2))
990         {
991             print_usage(std::cerr, argv[0]);
992             return EXIT_FAILURE;
993         }
994
995         // Initialise Mozilla
996         BrowserWidget::init();
997
998         WebDvdWindow window(frame_params,
999                             argv[argi],
1000                             preview_mode ? "" : argv[argi + 1]);
1001         Gtk::Main::run(window);
1002     }
1003     catch (std::exception & e)
1004     {
1005         std::cerr << "Fatal error: " << e.what() << "\n";
1006         return EXIT_FAILURE;
1007     }
1008
1009     return EXIT_SUCCESS;
1010 }