]> git.decadent.org.uk Git - videolink.git/blob - webdvd.cpp
Corrected length of background filename buffer.
[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 <string>
13
14 #include <stdlib.h>
15 #include <unistd.h>
16
17 #include <gdkmm/pixbuf.h>
18 #include <gtkmm/main.h>
19 #include <gtkmm/window.h>
20
21 #include <imglib2/ImageErrors.h>
22 #include <nsGUIEvent.h>
23 #include <nsIBoxObject.h>
24 #include <nsIContent.h>
25 #include <nsIDocShell.h>
26 #include <nsIDOMAbstractView.h>
27 #include <nsIDOMDocumentEvent.h>
28 #include <nsIDOMDocumentView.h>
29 #include <nsIDOMElement.h>
30 #include <nsIDOMEventTarget.h>
31 #include <nsIDOMHTMLDocument.h>
32 #include <nsIDOMMouseEvent.h>
33 #include <nsIDOMNSDocument.h>
34 #include <nsIDOMWindow.h>
35 #include <nsIEventStateManager.h>
36 #include <nsIInterfaceRequestorUtils.h>
37 #include <nsIURI.h> // required before nsILink.h
38 #include <nsILink.h>
39 #include <nsIPresContext.h>
40 #include <nsIPresShell.h>
41 #include <nsIWebBrowser.h>
42 #include <nsString.h>
43
44 #include "browserwidget.hpp"
45 #include "childiterator.hpp"
46 #include "dvd.hpp"
47 #include "framebuffer.hpp"
48 #include "linkiterator.hpp"
49 #include "pixbufs.hpp"
50 #include "stylesheets.hpp"
51 #include "video.hpp"
52 #include "xpcom_support.hpp"
53
54 using xpcom_support::check;
55
56 namespace
57 {
58     struct rectangle
59     {
60         int left, top;     // inclusive
61         int right, bottom; // exclusive
62
63         rectangle operator|=(const rectangle & other)
64             {
65                 if (other.empty())
66                 {
67                     // use current extents unchanged
68                 }
69                 else if (empty())
70                 {
71                     // use other extents
72                     *this = other;
73                 }
74                 else
75                 {
76                     // find rectangle enclosing both extents
77                     left = std::min(left, other.left);
78                     top = std::min(top, other.top);
79                     right = std::max(right, other.right);
80                     bottom = std::max(bottom, other.bottom);
81                 }
82
83                 return *this;
84             }
85
86         rectangle operator&=(const rectangle & other)
87             {
88                 // find rectangle enclosed in both extents
89                 left = std::max(left, other.left);
90                 top = std::max(top, other.top);
91                 right = std::max(left, std::min(right, other.right));
92                 bottom = std::max(top, std::min(bottom, other.bottom));
93                 return *this;
94             }
95
96         bool empty() const
97             {
98                 return left == right || bottom == top;
99             }
100     };
101
102     rectangle get_elem_rect(nsIDOMNSDocument * ns_doc,
103                             nsIDOMElement * elem)
104     {
105         rectangle result;
106
107         nsCOMPtr<nsIBoxObject> box;
108         check(ns_doc->GetBoxObjectFor(elem, getter_AddRefs(box)));
109         int width, height;
110         check(box->GetScreenX(&result.left));
111         check(box->GetScreenY(&result.top));
112         check(box->GetWidth(&width));
113         check(box->GetHeight(&height));
114         result.right = result.left + width;
115         result.bottom = result.top + height;
116
117         for (ChildIterator it = ChildIterator(elem), end; it != end; ++it)
118         {
119             nsCOMPtr<nsIDOMNode> child_node(*it);
120             PRUint16 child_type;
121             if (check(child_node->GetNodeType(&child_type)),
122                 child_type == nsIDOMNode::ELEMENT_NODE)
123             {
124                 nsCOMPtr<nsIDOMElement> child_elem(
125                     do_QueryInterface(child_node));
126                 result |= get_elem_rect(ns_doc, child_elem);
127             }
128         }
129
130         return result;
131     }
132
133     class WebDvdWindow : public Gtk::Window
134     {
135     public:
136         WebDvdWindow(int width, int height);
137         void add_page(const std::string & uri);
138
139     private:
140         void add_video(const std::string & uri);
141         void load_next_page();
142         void on_net_state_change(const char * uri, gint flags, guint status);
143         void save_screenshot();
144         void process_links(nsIPresShell * pres_shell,
145                            nsIPresContext * pres_context,
146                            nsIDOMWindow * dom_window);
147         void generate_dvdauthor_file();
148
149         enum ResourceType { page_resource, video_resource };
150         typedef std::pair<ResourceType, int> ResourceEntry;
151         int width_, height_;
152         BrowserWidget browser_widget_;
153         nsCOMPtr<nsIStyleSheet> stylesheet_;
154         std::queue<std::string> page_queue_;
155         std::map<std::string, ResourceEntry> resource_map_;
156         std::vector<std::vector<std::string> > page_links_;
157         std::vector<std::string> video_paths_;
158         bool loading_;
159         int pending_req_count_;
160         struct link_state;
161         std::auto_ptr<link_state> link_state_;
162     };
163
164     WebDvdWindow::WebDvdWindow(int width, int height)
165             : width_(width), height_(height),
166               stylesheet_(load_css("file://" WEBDVD_LIB_DIR "/webdvd.css")),
167               loading_(false),
168               pending_req_count_(0)
169     {
170         set_default_size(width, height);
171         add(browser_widget_);
172         browser_widget_.show();
173         browser_widget_.signal_net_state().connect(
174             SigC::slot(*this, &WebDvdWindow::on_net_state_change));
175     }
176
177     void WebDvdWindow::add_page(const std::string & uri)
178     {
179         if (resource_map_.insert(
180                 std::make_pair(uri, ResourceEntry(page_resource, 0)))
181             .second)
182         {
183             page_queue_.push(uri);
184             if (!loading_)
185                 load_next_page();
186         }
187     }
188
189     void WebDvdWindow::add_video(const std::string & uri)
190     {
191         if (resource_map_.insert(
192                 std::make_pair(uri, ResourceEntry(video_resource,
193                                                   video_paths_.size() + 1)))
194             .second)
195         {
196             // FIXME: Should accept some slightly different URI prefixes
197             // (e.g. file://localhost/) and decode any URI-escaped
198             // characters in the path.
199             assert(uri.compare(0, 8, "file:///") == 0);
200             video_paths_.push_back(uri.substr(7));
201         }
202     }
203
204     void WebDvdWindow::load_next_page()
205     {
206         loading_ = true;
207
208         assert(!page_queue_.empty());
209         const std::string & uri = page_queue_.front();
210         std::cout << "loading " << uri << std::endl;
211
212         std::size_t page_count = page_links_.size();
213         resource_map_[uri].second = ++page_count;
214         page_links_.resize(page_count);
215         browser_widget_.load_uri(uri);
216     }
217
218     void WebDvdWindow::on_net_state_change(const char * uri,
219                                            gint flags, guint status)
220     {
221         enum {
222             process_nothing,
223             process_new_page,
224             process_current_link
225         } action = process_nothing;
226
227         if (flags & GTK_MOZ_EMBED_FLAG_IS_REQUEST)
228         {
229             if (flags & GTK_MOZ_EMBED_FLAG_START)
230                 ++pending_req_count_;
231             if (flags & GTK_MOZ_EMBED_FLAG_STOP)
232             {
233                 assert(pending_req_count_ != 0);
234                 --pending_req_count_;
235             }
236             if (pending_req_count_ == 0 && link_state_.get())
237                 action = process_current_link;
238         }
239             
240         if (flags & GTK_MOZ_EMBED_FLAG_STOP
241             && flags & GTK_MOZ_EMBED_FLAG_IS_WINDOW)
242             action = process_new_page;
243
244         if (action != process_nothing)
245         {
246             assert(loading_ && !page_queue_.empty());
247             assert(pending_req_count_ == 0);
248
249             try
250             {
251                 // Check whether the load was successful, ignoring this
252                 // pseudo-error.
253                 if (status != NS_IMAGELIB_ERROR_LOAD_ABORTED)
254                     check(status);
255
256                 nsCOMPtr<nsIWebBrowser> browser(
257                     browser_widget_.get_browser());
258                 nsCOMPtr<nsIDocShell> doc_shell(do_GetInterface(browser));
259                 assert(doc_shell);
260                 nsCOMPtr<nsIPresShell> pres_shell;
261                 check(doc_shell->GetPresShell(getter_AddRefs(pres_shell)));
262                 nsCOMPtr<nsIPresContext> pres_context;
263                 check(doc_shell->GetPresContext(
264                           getter_AddRefs(pres_context)));
265                 nsCOMPtr<nsIDOMWindow> dom_window;
266                 check(browser->GetContentDOMWindow(
267                           getter_AddRefs(dom_window)));
268
269                 if (action == process_new_page)
270                 {
271                     apply_style_sheet(stylesheet_, pres_shell);
272                     save_screenshot();
273                 }
274                 process_links(pres_shell, pres_context, dom_window);
275                 if (!link_state_.get())
276                 {
277                     page_queue_.pop();
278                     if (page_queue_.empty())
279                     {
280                         generate_dvdauthor_file();
281                         Gtk::Main::quit();
282                     }
283                     else
284                         load_next_page();
285                 }
286             }
287             catch (std::exception & e)
288             {
289                 std::cerr << "Fatal error";
290                 if (!page_queue_.empty())
291                     std::cerr << " while processing <" << page_queue_.front()
292                               << ">";
293                 std::cerr << ": " << e.what() << "\n";
294                 Gtk::Main::quit();
295             }
296         }
297     }
298
299     void WebDvdWindow::save_screenshot()
300     {
301         char filename[25];
302         std::sprintf(filename, "page_%06d_back.png", page_links_.size());
303         Glib::RefPtr<Gdk::Window> window(get_window());
304         assert(window);
305         window->process_updates(true);
306         std::cout << "saving " << filename << std::endl;
307         Gdk::Pixbuf::create(Glib::RefPtr<Gdk::Drawable>(window),
308                             window->get_colormap(),
309                             0, 0, 0, 0, width_, height_)
310             ->save(filename, "png");
311     }
312
313     struct WebDvdWindow::link_state
314     {
315         Glib::RefPtr<Gdk::Pixbuf> diff_pixbuf;
316
317         std::ofstream spumux_file;
318
319         int link_num;
320         LinkIterator links_it, links_end;
321
322         rectangle link_rect;
323         bool link_changing;
324         Glib::RefPtr<Gdk::Pixbuf> norm_pixbuf;
325     };
326
327     void WebDvdWindow::process_links(nsIPresShell * pres_shell,
328                                      nsIPresContext * pres_context,
329                                      nsIDOMWindow * dom_window)
330     {
331         Glib::RefPtr<Gdk::Window> window(get_window());
332         assert(window);
333
334         nsCOMPtr<nsIDOMDocument> basic_doc;
335         check(dom_window->GetDocument(getter_AddRefs(basic_doc)));
336         nsCOMPtr<nsIDOMNSDocument> ns_doc(do_QueryInterface(basic_doc));
337         assert(ns_doc);
338         nsCOMPtr<nsIEventStateManager> event_state_man(
339             pres_context->EventStateManager()); // does not AddRef
340         assert(event_state_man);
341         nsCOMPtr<nsIDOMDocumentEvent> event_factory(
342             do_QueryInterface(basic_doc));
343         assert(event_factory);
344         nsCOMPtr<nsIDOMDocumentView> doc_view(do_QueryInterface(basic_doc));
345         assert(doc_view);
346         nsCOMPtr<nsIDOMAbstractView> view;
347         check(doc_view->GetDefaultView(getter_AddRefs(view)));
348
349         // Set up or recover our iteration state.
350         std::auto_ptr<link_state> state(link_state_);
351         if (!state.get())
352         {
353             state.reset(new link_state);
354
355             state->diff_pixbuf = Gdk::Pixbuf::create(Gdk::COLORSPACE_RGB,
356                                                      true, // has_alpha
357                                                      8, // bits_per_sample
358                                                      width_, height_);
359
360             char spumux_filename[20];
361             std::sprintf(spumux_filename,
362                          "page_%06d.spumux", page_links_.size());
363             state->spumux_file.open(spumux_filename);
364             state->spumux_file <<
365                 "<subpictures>\n"
366                 "  <stream>\n"
367                 "    <spu force='yes' start='00:00:00.00'\n"
368                 "        highlight='page_" << std::setfill('0')
369                                << std::setw(6) << page_links_.size()
370                                << "_links.png'\n"
371                 "        select='page_" << std::setfill('0')
372                                << std::setw(6) << page_links_.size()
373                                << "_links.png'>\n";
374
375             state->link_num = 0;
376             state->links_it = LinkIterator(basic_doc);
377             state->link_changing = false;
378         }
379             
380         rectangle window_rect = { 0, 0, width_, height_ };
381
382         for (/* no initialisation */;
383              state->links_it != state->links_end;
384              ++state->links_it)
385         {
386             nsCOMPtr<nsIDOMNode> node(*state->links_it);
387
388             // Find the link URI.
389             nsCOMPtr<nsILink> link(do_QueryInterface(node));
390             assert(link);
391             nsCOMPtr<nsIURI> uri;
392             check(link->GetHrefURI(getter_AddRefs(uri)));
393             std::string uri_string;
394             {
395                 nsCString uri_ns_string;
396                 check(uri->GetSpec(uri_ns_string));
397                 uri_string.assign(uri_ns_string.BeginReading(),
398                                   uri_ns_string.EndReading());
399             }
400             std::string uri_sans_fragment(uri_string, 0, uri_string.find('#'));
401
402             // Is this a new link?
403             if (!state->link_changing)
404             {
405                 // Find a rectangle enclosing the link and clip it to the
406                 // window.
407                 nsCOMPtr<nsIDOMElement> elem(do_QueryInterface(node));
408                 assert(elem);
409                 state->link_rect = get_elem_rect(ns_doc, elem);
410                 state->link_rect &= window_rect;
411
412                 if (state->link_rect.empty())
413                 {
414                     std::cerr << "Ignoring invisible link to "
415                               << uri_string << "\n";
416                     continue;
417                 }
418
419                 ++state->link_num;
420
421                 if (state->link_num >= dvd::menu_buttons_max)
422                 {
423                     if (state->link_num == dvd::menu_buttons_max)
424                         std::cerr << "No more than " << dvd::menu_buttons_max
425                                   << " buttons can be placed on a page\n";
426                     std::cerr << "Ignoring link to " << uri_string << "\n";
427                     continue;
428                 }
429
430                 // Check whether this is a link to a video or a page then
431                 // add it to the known resources if not already seen.
432                 nsCString path;
433                 check(uri->GetPath(path));
434                 // FIXME: This is a bit of a hack.  Perhaps we could decide
435                 // later based on the MIME type determined by Mozilla?
436                 if (path.Length() > 4
437                     && std::strcmp(path.EndReading() - 4, ".vob") == 0)
438                 {
439                     PRBool is_file;
440                     check(uri->SchemeIs("file", &is_file));
441                     if (!is_file)
442                     {
443                         std::cerr << "Links to video must use the file:"
444                                   << " scheme\n";
445                         continue;
446                     }
447                     add_video(uri_sans_fragment);
448                 }
449                 else
450                 {
451                     add_page(uri_sans_fragment);
452                 }
453
454                 nsCOMPtr<nsIContent> content(do_QueryInterface(node));
455                 assert(content);
456                 nsCOMPtr<nsIDOMEventTarget> event_target(
457                     do_QueryInterface(node));
458                 assert(event_target);
459
460                 state->norm_pixbuf = Gdk::Pixbuf::create(
461                     Glib::RefPtr<Gdk::Drawable>(window),
462                     window->get_colormap(),
463                     state->link_rect.left,
464                     state->link_rect.top,
465                     0,
466                     0,
467                     state->link_rect.right - state->link_rect.left,
468                     state->link_rect.bottom - state->link_rect.top);
469
470                 nsCOMPtr<nsIDOMEvent> event;
471                 check(event_factory->CreateEvent(
472                           NS_ConvertASCIItoUTF16("MouseEvents"),
473                           getter_AddRefs(event)));
474                 nsCOMPtr<nsIDOMMouseEvent> mouse_event(
475                     do_QueryInterface(event));
476                 assert(mouse_event);
477                 check(mouse_event->InitMouseEvent(
478                           NS_ConvertASCIItoUTF16("mouseover"),
479                           true,  // can bubble
480                           true,  // cancelable
481                           view,
482                           0,     // detail: mouse click count
483                           state->link_rect.left, // screenX
484                           state->link_rect.top,  // screenY
485                           state->link_rect.left, // clientX
486                           state->link_rect.top,  // clientY
487                           false, false, false, false, // qualifiers
488                           0,     // button: left (or primary)
489                           0));   // related target
490                 PRBool dummy;
491                 check(event_target->DispatchEvent(mouse_event,
492                                                   &dummy));
493                 check(event_state_man->SetContentState(content,
494                                                        NS_EVENT_STATE_HOVER));
495
496                 pres_shell->FlushPendingNotifications(true);
497
498                 // We may have to exit and wait for image loading
499                 // to complete, at which point we will be called
500                 // again.
501                 if (pending_req_count_ > 0)
502                 {
503                     state->link_changing = true;
504                     link_state_ = state;
505                     return;
506                 }
507             }
508
509             window->process_updates(true);
510
511             Glib::RefPtr<Gdk::Pixbuf> changed_pixbuf(
512                 Gdk::Pixbuf::create(
513                     Glib::RefPtr<Gdk::Drawable>(window),
514                     window->get_colormap(),
515                     state->link_rect.left,
516                     state->link_rect.top,
517                     0,
518                     0,
519                     state->link_rect.right - state->link_rect.left,
520                     state->link_rect.bottom - state->link_rect.top));
521             diff_rgb_pixbufs(
522                 state->norm_pixbuf,
523                 changed_pixbuf,
524                 state->diff_pixbuf,
525                 state->link_rect.left,
526                 state->link_rect.top,
527                 state->link_rect.right - state->link_rect.left,
528                 state->link_rect.bottom - state->link_rect.top);
529
530             state->spumux_file <<
531                 "      <button x0='" << state->link_rect.left << "'"
532                 " y0='" << state->link_rect.top << "'"
533                 " x1='" << state->link_rect.right - 1 << "'"
534                 " y1='" << state->link_rect.bottom - 1 << "'/>\n";
535
536             // Add to the page's links, ignoring any fragment (for now).
537             page_links_.back().push_back(uri_sans_fragment);
538         }
539
540         quantise_rgba_pixbuf(state->diff_pixbuf, dvd::button_n_colours);
541
542         char filename[25];
543         std::sprintf(filename, "page_%06d_links.png", page_links_.size());
544         std::cout << "saving " << filename << std::endl;
545         state->diff_pixbuf->save(filename, "png");
546
547         state->spumux_file <<
548             "    </spu>\n"
549             "  </stream>\n"
550             "</subpictures>\n";
551     }
552
553     void generate_page_dispatch(std::ostream &, int indent,
554                                 int first_page, int last_page);
555
556     void WebDvdWindow::generate_dvdauthor_file()
557     {
558         std::ofstream file("webdvd.dvdauthor");
559
560         // We generate code that uses registers in the following way:
561         //
562         // g0:     link destination (when jumping to menu 1), then scratch
563         // g1:     current location
564         // g2-g11: location history (g2 = most recent)
565         // g12:    location that last linked to a video
566         //
567         // All locations are divided into two bitfields: the least
568         // significant 10 bits are a page/menu number and the most
569         // significant 6 bits are a link/button number.  This is
570         // chosen for compatibility with the encoding of the s8
571         // (button) register.
572         //
573         static const int link_mult = dvd::reg_s8_button_mult;
574         static const int page_mask = link_mult - 1;
575         static const int link_mask = (1 << dvd::reg_bits) - link_mult;
576
577         file <<
578             "<dvdauthor>\n"
579             "  <vmgm>\n"
580             "    <menus>\n";
581             
582         for (std::size_t page_num = 1;
583              page_num <= page_links_.size();
584              ++page_num)
585         {
586             std::vector<std::string> & page_links =
587                 page_links_[page_num - 1];
588
589             if (page_num == 1)
590             {
591                 // This is the first page (root menu) which needs to
592                 // include initialisation and dispatch code.
593         
594                 file <<
595                     "      <pgc entry='title'>\n"
596                     "        <pre>\n"
597                     // Has the location been set yet?
598                     "          if (g1 eq 0)\n"
599                     "          {\n"
600                     // Initialise the current location to first link on
601                     // this page.
602                     "            g1 = " << 1 * link_mult + 1 << ";\n"
603                     "          }\n"
604                     "          else\n"
605                     "          {\n"
606                     // Has the user selected a link?
607                     "            if (g0 ne 0)\n"
608                     "            {\n"
609                     // First update the history.
610                     // Does link go to the last page in the history?
611                     "              if (((g0 ^ g2) &amp; " << page_mask
612                      << ") == 0)\n"
613                     // It does; we treat this as going back and pop the old
614                     // location off the history stack into the current
615                     // location.  Clear the free stack slot.
616                     "              {\n"
617                     "                g1 = g2; g2 = g3; g3 = g4; g4 = g5;\n"
618                     "                g5 = g6; g6 = g7; g7 = g8; g8 = g9;\n"
619                     "                g9 = g10; g10 = g11; g11 = 0;\n"
620                     "              }\n"
621                     "              else\n"
622                     // Link goes to some other page, so push current
623                     // location onto the history stack and set the current
624                     // location to be exactly the target location.
625                     "              {\n"
626                     "                g11 = g10; g10 = g9; g9 = g8; g8 = g7;\n"
627                     "                g7 = g6; g6 = g5; g5 = g4; g4 = g3;\n"
628                     "                g3 = g2; g2 = g1; g1 = g0;\n"
629                     "              }\n"
630                     "            }\n"
631                     // Find the target page number.
632                     "            g0 = g1 &amp; " << page_mask << ";\n";
633                 // There seems to be no way to perform a computed jump,
634                 // so we generate all possible jumps and a binary search
635                 // to select the correct one.
636                 generate_page_dispatch(file, 12, 1, page_links_.size());
637                 file <<
638                     "          }\n";
639             }
640             else // page_num != 1
641             {
642                 file <<
643                     "      <pgc>\n"
644                     "        <pre>\n";
645             }
646
647             file <<
648                 // Clear link indicator and highlight the
649                 // appropriate link/button.
650                 "          g0 = 0; s8 = g1 &amp; " << link_mask << ";\n"
651                 "        </pre>\n"
652                 "        <vob file='page_"
653                  << std::setfill('0') << std::setw(6) << page_num
654                  << ".vob'/>\n";
655
656             for (std::size_t link_num = 1;
657                  link_num <= page_links.size();
658                  ++link_num)
659             {
660                 file <<
661                     "        <button>"
662                     // Update current location.
663                     " g1 = " << link_num * link_mult + page_num << ";";
664
665                 // Jump to appropriate resource.
666                 const ResourceEntry & resource_loc =
667                     resource_map_[page_links[link_num - 1]];
668                 if (resource_loc.first == page_resource)
669                     file <<
670                         " g0 = " << 1 * link_mult + resource_loc.second << ";"
671                         " jump menu 1;";
672                 else if (resource_loc.first == video_resource)
673                     file << " jump title " << resource_loc.second << ";";
674
675                 file <<  " </button>\n";
676             }
677
678             file << "      </pgc>\n";
679         }
680
681         file <<
682             "    </menus>\n"
683             "  </vmgm>\n";
684
685         // Generate a titleset for each video.  This appears to make
686         // jumping to titles a whole lot simpler.
687         for (std::size_t video_num = 1;
688              video_num <= video_paths_.size();
689              ++video_num)
690         {
691             file <<
692                 "  <titleset>\n"
693                 // Generate a dummy menu so that the menu button on the
694                 // remote control will work.
695                 "    <menus>\n"
696                 "      <pgc entry='root'>\n"
697                 "        <pre> jump vmgm menu; </pre>\n"
698                 "      </pgc>\n"
699                 "    </menus>\n"
700                 "    <titles>\n"
701                 "      <pgc>\n"
702                 // Record calling page/menu.
703                 "        <pre> g12 = g1; </pre>\n"
704                 // FIXME: Should XML-escape the path
705                 "        <vob file='" << video_paths_[video_num - 1]
706                  << "'/>\n"
707                 // If page/menu location has not been changed during the
708                 // video, change the location to be the following
709                 // link/button when returning to it.  In any case,
710                 // return to a page/menu.
711                 "        <post> if (g1 eq g12) g1 = g1 + " << link_mult
712                  << "; call menu; </post>\n"
713                 "      </pgc>\n"
714                 "    </titles>\n"
715                 "  </titleset>\n";
716         }
717
718         file <<
719             "</dvdauthor>\n";
720     }
721
722     void generate_page_dispatch(std::ostream & file, int indent,
723                                 int first_page, int last_page)
724     {
725         if (first_page == 1 && last_page == 1)
726         {
727             // The dispatch code is *on* page 1 so we must not dispatch to
728             // page 1 since that would cause an infinite loop.  This case
729             // should be unreachable if there is more than one page due
730             // to the following case.
731         }
732         else if (first_page == 1 && last_page == 2)
733         {
734             // dvdauthor doesn't allow empty blocks or null statements so
735             // when selecting between pages 1 and 2 we don't use an "else"
736             // part.  We must use braces so that a following "else" will
737             // match the right "if".
738             file << std::setw(indent) << "" << "{\n"
739                  << std::setw(indent) << "" << "if (g0 eq 2)\n"
740                  << std::setw(indent + 2) << "" << "jump menu 2;\n"
741                  << std::setw(indent) << "" << "}\n";
742         }
743         else if (first_page == last_page)
744         {
745             file << std::setw(indent) << ""
746                  << "jump menu " << first_page << ";\n";
747         }
748         else
749         {
750             int middle = (first_page + last_page) / 2;
751             file << std::setw(indent) << "" << "if (g0 le " << middle << ")\n";
752             generate_page_dispatch(file, indent + 2, first_page, middle);
753             file << std::setw(indent) << "" << "else\n";
754             generate_page_dispatch(file, indent + 2, middle + 1, last_page);
755         }
756     }
757
758 } // namespace
759
760 int main(int argc, char ** argv)
761 {
762     // Get dimensions
763     int width = video::pal_oscan_width, height = video::pal_oscan_height;
764     for (int i = 1; i < argc - 1; ++i)
765         if (std::strcmp(argv[i], "-geometry") == 0)
766         {
767             std::sscanf(argv[i + 1], "%dx%d", &width, &height);
768             break;
769         }
770     // A depth of 24 results in 8 bits each for RGB components, which
771     // translates into "enough" bits for YUV components.
772     const int depth = 24;
773
774     try
775     {
776         // Spawn Xvfb and set env variables so that Xlib will use it
777         FrameBuffer fb(width, height, depth);
778         setenv("XAUTHORITY", fb.get_x_authority().c_str(), true);
779         setenv("DISPLAY", fb.get_x_display().c_str(), true);
780
781         // Initialise Gtk and Mozilla
782         Gtk::Main kit(argc, argv);
783         BrowserWidget::init();
784
785         WebDvdWindow window(width, height);
786         for (int argi = 1; argi < argc; ++argi)
787             window.add_page(argv[argi]);
788         if (argc < 2)
789             window.add_page("about:");
790         Gtk::Main::run(window);
791     }
792     catch (std::exception & e)
793     {
794         std::cerr << "Fatal error: " << e.what() << "\n";
795         return EXIT_FAILURE;
796     }
797
798     return EXIT_SUCCESS;
799 }