]> git.decadent.org.uk Git - videolink.git/blob - webdvd.cpp
Replaced multiple is-browser-busy tests with a member function.
[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 <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 "link_iterator.hpp"
57 #include "pixbufs.hpp"
58 #include "style_sheets.hpp"
59 #include "temp_file.hpp"
60 #include "video.hpp"
61 #include "x_frame_buffer.hpp"
62 #include "xpcom_support.hpp"
63
64 using xpcom_support::check;
65
66 namespace
67 {
68     struct rectangle
69     {
70         int left, top;     // inclusive
71         int right, bottom; // exclusive
72
73         rectangle operator|=(const rectangle & other)
74             {
75                 if (other.empty())
76                 {
77                     // use current extents unchanged
78                 }
79                 else if (empty())
80                 {
81                     // use other extents
82                     *this = other;
83                 }
84                 else
85                 {
86                     // find rectangle enclosing both extents
87                     left = std::min(left, other.left);
88                     top = std::min(top, other.top);
89                     right = std::max(right, other.right);
90                     bottom = std::max(bottom, other.bottom);
91                 }
92
93                 return *this;
94             }
95
96         rectangle operator&=(const rectangle & other)
97             {
98                 // find rectangle enclosed in both extents
99                 left = std::max(left, other.left);
100                 top = std::max(top, other.top);
101                 right = std::max(left, std::min(right, other.right));
102                 bottom = std::max(top, std::min(bottom, other.bottom));
103                 return *this;
104             }
105
106         bool empty() const
107             {
108                 return left == right || bottom == top;
109             }
110     };
111
112     rectangle get_elem_rect(nsIDOMNSDocument * ns_doc,
113                             nsIDOMElement * elem)
114     {
115         rectangle result;
116
117         // Start with this element's bounding box
118         nsCOMPtr<nsIBoxObject> box;
119         check(ns_doc->GetBoxObjectFor(elem, getter_AddRefs(box)));
120         int width, height;
121         check(box->GetScreenX(&result.left));
122         check(box->GetScreenY(&result.top));
123         check(box->GetWidth(&width));
124         check(box->GetHeight(&height));
125         result.right = result.left + width;
126         result.bottom = result.top + height;
127
128         // Merge bounding boxes of all child elements
129         for (child_iterator it = child_iterator(elem), end; it != end; ++it)
130         {
131             nsCOMPtr<nsIDOMNode> child_node(*it);
132             PRUint16 child_type;
133             if (check(child_node->GetNodeType(&child_type)),
134                 child_type == nsIDOMNode::ELEMENT_NODE)
135             {
136                 nsCOMPtr<nsIDOMElement> child_elem(
137                     do_QueryInterface(child_node));
138                 result |= get_elem_rect(ns_doc, child_elem);
139             }
140         }
141
142         return result;
143     }
144
145
146     std::string xml_escape(const std::string & str)
147     {
148         std::string result;
149         std::size_t begin = 0;
150
151         for (;;)
152         {
153             std::size_t end = str.find_first_of("\"&'<>", begin);
154             result.append(str, begin, end - begin);
155             if (end == std::string::npos)
156                 return result;
157
158             const char * entity = NULL;
159             switch (str[end])
160             {
161             case '"':  entity = "&quot;"; break;
162             case '&':  entity = "&amp;";  break;
163             case '\'': entity = "&apos;"; break;
164             case '<':  entity = "&lt;";   break;
165             case '>':  entity = "&gt;";   break;
166             }
167             assert(entity);
168             result.append(entity);
169
170             begin = end + 1;
171         }
172     }
173
174     
175     struct dvd_contents
176     {
177         enum pgc_type { menu_pgc, title_pgc };
178         typedef std::pair<pgc_type, int> pgc_ref;
179
180         struct menu
181         {
182             menu()
183                     : vob_temp(new temp_file("webdvd-vob-"))
184                 {
185                     vob_temp->close();
186                 }
187
188             boost::shared_ptr<temp_file> vob_temp;
189             std::vector<pgc_ref> entries;
190         };
191
192         struct title
193         {
194             explicit title(const std::string & vob_list)
195                     : vob_list(vob_list)
196                 {}
197
198             std::string vob_list;
199         };
200
201         std::vector<menu> menus;
202         std::vector<title> titles;
203     };
204
205     class webdvd_window : public Gtk::Window
206     {
207     public:
208         webdvd_window(
209             const video::frame_params & frame_params,
210             const std::string & main_page_uri,
211             const std::string & output_dir);
212
213     private:
214         dvd_contents::pgc_ref add_menu(const std::string & uri);
215         dvd_contents::pgc_ref add_title(const std::string & uri);
216         void load_next_page();
217         void on_net_state_change(const char * uri, gint flags, guint status);
218         bool browser_is_busy() const
219             {
220                 return pending_window_update_ || pending_req_count_;
221             }
222         bool process_page();
223         void save_screenshot();
224         void process_links(nsIPresShell * pres_shell,
225                            nsIPresContext * pres_context,
226                            nsIDOMWindow * dom_window);
227         void generate_dvd();
228
229         video::frame_params frame_params_;
230         std::string output_dir_;
231         browser_widget browser_widget_;
232         nsCOMPtr<nsIStyleSheet> stylesheet_;
233
234         dvd_contents contents_;
235         typedef std::map<std::string, dvd_contents::pgc_ref> resource_map_type;
236         resource_map_type resource_map_;
237
238         std::queue<std::string> page_queue_;
239         bool pending_window_update_;
240         int pending_req_count_;
241         bool have_tweaked_page_;
242         std::auto_ptr<temp_file> background_temp_;
243         struct page_state;
244         std::auto_ptr<page_state> page_state_;
245     };
246
247     webdvd_window::webdvd_window(
248         const video::frame_params & frame_params,
249         const std::string & main_page_uri,
250         const std::string & output_dir)
251             : frame_params_(frame_params),
252               output_dir_(output_dir),
253               stylesheet_(load_css("file://" WEBDVD_LIB_DIR "/webdvd.css")),
254               pending_window_update_(false),
255               pending_req_count_(0),
256               have_tweaked_page_(false)
257     {
258         set_size_request(frame_params_.width, frame_params_.height);
259         set_resizable(false);
260
261         add(browser_widget_);
262         browser_widget_.show();
263         browser_widget_.signal_net_state().connect(
264             SigC::slot(*this, &webdvd_window::on_net_state_change));
265
266         add_menu(main_page_uri);
267         load_next_page();
268     }
269
270     dvd_contents::pgc_ref webdvd_window::add_menu(const std::string & uri)
271     {
272         dvd_contents::pgc_ref next_menu(dvd_contents::menu_pgc,
273                                         contents_.menus.size());
274         std::pair<resource_map_type::iterator, bool> insert_result(
275             resource_map_.insert(std::make_pair(uri, next_menu)));
276
277         if (!insert_result.second)
278         {
279             return insert_result.first->second;
280         }
281         else
282         {
283             page_queue_.push(uri);
284             contents_.menus.resize(contents_.menus.size() + 1);
285             return next_menu;
286         }
287     }
288
289     dvd_contents::pgc_ref webdvd_window::add_title(const std::string & uri)
290     {
291         dvd_contents::pgc_ref next_title(dvd_contents::title_pgc,
292                                          contents_.titles.size());
293         std::pair<resource_map_type::iterator, bool> insert_result(
294             resource_map_.insert(std::make_pair(uri, next_title)));
295
296         if (!insert_result.second)
297         {
298             return insert_result.first->second;
299         }
300         else
301         {
302             Glib::ustring hostname;
303             std::string filename(Glib::filename_from_uri(uri, hostname));
304             // FIXME: Should check the hostname
305
306             std::string vob_list;
307
308             // Store a reference to a linked VOB file, or the contents
309             // of a linked VOB list file.
310             if (filename.compare(filename.size() - 4, 4, ".vob") == 0)
311             {
312                 if (!Glib::file_test(filename, Glib::FILE_TEST_IS_REGULAR))
313                     throw std::runtime_error(
314                         filename + " is missing or not a regular file");
315                 vob_list
316                     .append("<vob file='")
317                     .append(xml_escape(filename))
318                     .append("'/>\n");
319             }
320             else
321             {
322                 assert(filename.compare(filename.size() - 8, 8, ".voblist")
323                        == 0);
324                 // TODO: Validate the file contents
325                 vob_list.assign(Glib::file_get_contents(filename));
326             }
327
328             contents_.titles.push_back(dvd_contents::title(vob_list));
329             return next_title;
330         }
331     }
332
333     void webdvd_window::load_next_page()
334     {
335         assert(!page_queue_.empty());
336         const std::string & uri = page_queue_.front();
337         std::cout << "loading " << uri << std::endl;
338
339         browser_widget_.load_uri(uri);
340     }
341
342     void webdvd_window::on_net_state_change(const char * uri,
343                                            gint flags, guint status)
344     {
345 #       ifdef DEBUG_ON_NET_STATE_CHANGE
346         std::cout << "webdvd_window::on_net_state_change(";
347         if (uri)
348             std::cout << '"' << uri << '"';
349         else
350             std::cout << "NULL";
351         std::cout << ", ";
352         {
353             gint flags_left = flags;
354             static const struct {
355                 gint value;
356                 const char * name;
357             } flag_names[] = {
358                 { GTK_MOZ_EMBED_FLAG_START, "STATE_START" },
359                 { GTK_MOZ_EMBED_FLAG_REDIRECTING, "STATE_REDIRECTING" },
360                 { GTK_MOZ_EMBED_FLAG_TRANSFERRING, "STATE_TRANSFERRING" },
361                 { GTK_MOZ_EMBED_FLAG_NEGOTIATING, "STATE_NEGOTIATING" },
362                 { GTK_MOZ_EMBED_FLAG_STOP, "STATE_STOP" },
363                 { GTK_MOZ_EMBED_FLAG_IS_REQUEST, "STATE_IS_REQUEST" },
364                 { GTK_MOZ_EMBED_FLAG_IS_DOCUMENT, "STATE_IS_DOCUMENT" },
365                 { GTK_MOZ_EMBED_FLAG_IS_NETWORK, "STATE_IS_NETWORK" },
366                 { GTK_MOZ_EMBED_FLAG_IS_WINDOW, "STATE_IS_WINDOW" }
367             };
368             for (int i = 0; i != sizeof(flag_names)/sizeof(flag_names[0]); ++i)
369             {
370                 if (flags & flag_names[i].value)
371                 {
372                     std::cout << flag_names[i].name;
373                     flags_left -= flag_names[i].value;
374                     if (flags_left)
375                         std::cout << " | ";
376                 }
377             }
378             if (flags_left)
379                 std::cout << "0x" << std::setbase(16) << flags_left;
380         }
381         std::cout << ", " << "0x" << std::setbase(16) << status << ")\n";
382 #       endif // DEBUG_ON_NET_STATE_CHANGE
383
384         if (flags & GTK_MOZ_EMBED_FLAG_IS_REQUEST)
385         {
386             if (flags & GTK_MOZ_EMBED_FLAG_START)
387                 ++pending_req_count_;
388
389             if (flags & GTK_MOZ_EMBED_FLAG_STOP)
390             {
391                 assert(pending_req_count_ != 0);
392                 --pending_req_count_;
393             }
394         }
395             
396         if (flags & GTK_MOZ_EMBED_FLAG_IS_DOCUMENT
397             && flags & GTK_MOZ_EMBED_FLAG_START)
398         {
399             pending_window_update_ = true;
400             have_tweaked_page_ = false;
401         }
402
403         if (flags & GTK_MOZ_EMBED_FLAG_IS_WINDOW
404             && flags & GTK_MOZ_EMBED_FLAG_STOP)
405         {
406             // Check whether the load was successful, ignoring this
407             // pseudo-error.
408             if (status != NS_IMAGELIB_ERROR_LOAD_ABORTED)
409                 check(status);
410
411             pending_window_update_ = false;
412         }
413
414         if (!browser_is_busy())
415         {
416             try
417             {
418                 if (!process_page())
419                     Gtk::Main::quit();
420             }
421             catch (std::exception & e)
422             {
423                 std::cerr << "Fatal error";
424                 if (!page_queue_.empty())
425                     std::cerr << " while processing <" << page_queue_.front()
426                               << ">";
427                 std::cerr << ": " << e.what() << "\n";
428                 Gtk::Main::quit();
429             }
430         }
431     }
432
433     bool webdvd_window::process_page()
434     {
435         assert(!page_queue_.empty());
436
437         nsCOMPtr<nsIWebBrowser> browser(browser_widget_.get_browser());
438         nsCOMPtr<nsIDocShell> doc_shell(do_GetInterface(browser));
439         assert(doc_shell);
440         nsCOMPtr<nsIPresShell> pres_shell;
441         check(doc_shell->GetPresShell(getter_AddRefs(pres_shell)));
442         nsCOMPtr<nsIPresContext> pres_context;
443         check(doc_shell->GetPresContext(getter_AddRefs(pres_context)));
444         nsCOMPtr<nsIDOMWindow> dom_window;
445         check(browser->GetContentDOMWindow(getter_AddRefs(dom_window)));
446
447         // If we haven't done so already, apply the stylesheet and
448         // disable scrollbars.
449         if (!have_tweaked_page_)
450         {
451             apply_style_sheet(stylesheet_, pres_shell);
452
453             // This actually only needs to be done once.
454             nsCOMPtr<nsIDOMBarProp> dom_bar_prop;
455             check(dom_window->GetScrollbars(getter_AddRefs(dom_bar_prop)));
456             check(dom_bar_prop->SetVisible(false));
457
458             have_tweaked_page_ = true;
459
460             // Might need to wait a while for things to load or more
461             // likely for a re-layout.
462             if (browser_is_busy())
463                 return true;
464         }
465
466         // All further work should only be done if we're not in preview mode.
467         if (!output_dir_.empty())
468         {
469             // If we haven't already started work on this menu, save a
470             // screenshot of its normal appearance.
471             if (!page_state_.get())
472                 save_screenshot();
473
474             // Start or continue processing links.
475             process_links(pres_shell, pres_context, dom_window);
476
477             // If we've finished work on the links, move on to the
478             // next page, if any, or else generate the DVD filesystem.
479             if (!page_state_.get())
480             {
481                 page_queue_.pop();
482                 if (page_queue_.empty())
483                 {
484                     generate_dvd();
485                     return false;
486                 }
487                 else
488                 {
489                     load_next_page();
490                 }
491             }
492         }
493
494         return true;
495     }
496
497     void webdvd_window::save_screenshot()
498     {
499         Glib::RefPtr<Gdk::Window> window(get_window());
500         assert(window);
501         window->process_updates(true);
502
503         background_temp_.reset(new temp_file("webdvd-back-"));
504         background_temp_->close();
505         std::cout << "saving " << background_temp_->get_name() << std::endl;
506         Gdk::Pixbuf::create(Glib::RefPtr<Gdk::Drawable>(window),
507                             window->get_colormap(),
508                             0, 0, 0, 0,
509                             frame_params_.width, frame_params_.height)
510             ->save(background_temp_->get_name(), "png");
511     }
512
513     struct webdvd_window::page_state
514     {
515         page_state(nsIDOMDocument * doc, int width, int height)
516                 : diff_pixbuf(Gdk::Pixbuf::create(
517                                   Gdk::COLORSPACE_RGB,
518                                   true, 8, // has_alpha, bits_per_sample
519                                   width, height)),
520                   spumux_temp("webdvd-spumux-"),
521                   links_temp("webdvd-links-"),
522                   link_num(0),
523                   links_it(doc),
524                   link_changing(false)
525             {
526                 spumux_temp.close();
527                 links_temp.close();
528             }
529
530         Glib::RefPtr<Gdk::Pixbuf> diff_pixbuf;
531
532         temp_file spumux_temp;
533         std::ofstream spumux_file;
534
535         temp_file links_temp;
536
537         int link_num;
538         link_iterator links_it, links_end;
539
540         rectangle link_rect;
541         bool link_changing;
542         Glib::RefPtr<Gdk::Pixbuf> norm_pixbuf;
543     };
544
545     void webdvd_window::process_links(nsIPresShell * pres_shell,
546                                      nsIPresContext * pres_context,
547                                      nsIDOMWindow * dom_window)
548     {
549         Glib::RefPtr<Gdk::Window> window(get_window());
550         assert(window);
551
552         nsCOMPtr<nsIDOMDocument> basic_doc;
553         check(dom_window->GetDocument(getter_AddRefs(basic_doc)));
554         nsCOMPtr<nsIDOMNSDocument> ns_doc(do_QueryInterface(basic_doc));
555         assert(ns_doc);
556         nsCOMPtr<nsIEventStateManager> event_state_man(
557             pres_context->EventStateManager()); // does not AddRef
558         assert(event_state_man);
559         nsCOMPtr<nsIDOMDocumentEvent> event_factory(
560             do_QueryInterface(basic_doc));
561         assert(event_factory);
562         nsCOMPtr<nsIDOMDocumentView> doc_view(do_QueryInterface(basic_doc));
563         assert(doc_view);
564         nsCOMPtr<nsIDOMAbstractView> view;
565         check(doc_view->GetDefaultView(getter_AddRefs(view)));
566
567         // Set up or recover our iteration state.
568         std::auto_ptr<page_state> state(page_state_);
569         if (!state.get())
570         {
571             state.reset(
572                 new page_state(
573                     basic_doc, frame_params_.width, frame_params_.height));
574             
575             state->spumux_file.open(state->spumux_temp.get_name().c_str());
576             state->spumux_file <<
577                 "<subpictures>\n"
578                 "  <stream>\n"
579                 "    <spu force='yes' start='00:00:00.00'\n"
580                 "        highlight='" << state->links_temp.get_name() << "'\n"
581                 "        select='" << state->links_temp.get_name() << "'>\n";
582         }
583
584         rectangle window_rect = {
585             0, 0, frame_params_.width, frame_params_.height
586         };
587
588         int menu_num = resource_map_[page_queue_.front()].second;
589
590         for (/* no initialisation */;
591              state->links_it != state->links_end;
592              ++state->links_it)
593         {
594             nsCOMPtr<nsIDOMNode> node(*state->links_it);
595
596             // Find the link URI.
597             nsCOMPtr<nsILink> link(do_QueryInterface(node));
598             assert(link);
599             nsCOMPtr<nsIURI> uri;
600             check(link->GetHrefURI(getter_AddRefs(uri)));
601             std::string uri_string;
602             {
603                 nsCString uri_ns_string;
604                 check(uri->GetSpec(uri_ns_string));
605                 uri_string.assign(uri_ns_string.BeginReading(),
606                                   uri_ns_string.EndReading());
607             }
608             std::string uri_sans_fragment(uri_string, 0, uri_string.find('#'));
609
610             // Is this a new link?
611             if (!state->link_changing)
612             {
613                 // Find a rectangle enclosing the link and clip it to the
614                 // window.
615                 nsCOMPtr<nsIDOMElement> elem(do_QueryInterface(node));
616                 assert(elem);
617                 state->link_rect = get_elem_rect(ns_doc, elem);
618                 state->link_rect &= window_rect;
619
620                 if (state->link_rect.empty())
621                 {
622                     std::cerr << "Ignoring invisible link to "
623                               << uri_string << "\n";
624                     continue;
625                 }
626
627                 ++state->link_num;
628
629                 if (state->link_num >= dvd::menu_buttons_max)
630                 {
631                     if (state->link_num == dvd::menu_buttons_max)
632                         std::cerr << "No more than " << dvd::menu_buttons_max
633                                   << " buttons can be placed on a menu\n";
634                     std::cerr << "Ignoring link to " << uri_string << "\n";
635                     continue;
636                 }
637
638                 state->spumux_file <<
639                     "      <button x0='" << state->link_rect.left << "'"
640                     " y0='" << state->link_rect.top << "'"
641                     " x1='" << state->link_rect.right - 1 << "'"
642                     " y1='" << state->link_rect.bottom - 1 << "'/>\n";
643
644                 // Check whether this is a link to a video or a page then
645                 // add it to the known resources if not already seen; then
646                 // add it to the menu entries.
647                 nsCString path;
648                 check(uri->GetPath(path));
649                 dvd_contents::pgc_ref dest_pgc;
650                 // FIXME: This is a bit of a hack.  Perhaps we could decide
651                 // later based on the MIME type determined by Mozilla?
652                 if ((path.Length() > 4
653                      && std::strcmp(path.EndReading() - 4, ".vob") == 0)
654                     || (path.Length() > 8
655                         && std::strcmp(path.EndReading() - 8, ".voblist")
656                            == 0))
657                 {
658                     PRBool is_file;
659                     check(uri->SchemeIs("file", &is_file));
660                     if (!is_file)
661                     {
662                         std::cerr << "Links to video must use the file:"
663                                   << " scheme\n";
664                         continue;
665                     }
666                     dest_pgc = add_title(uri_sans_fragment);
667                 }
668                 else
669                 {
670                     dest_pgc = add_menu(uri_sans_fragment);
671                 }
672                 contents_.menus[menu_num].entries.push_back(dest_pgc);
673
674                 nsCOMPtr<nsIContent> content(do_QueryInterface(node));
675                 assert(content);
676                 nsCOMPtr<nsIDOMEventTarget> event_target(
677                     do_QueryInterface(node));
678                 assert(event_target);
679
680                 state->norm_pixbuf = Gdk::Pixbuf::create(
681                     Glib::RefPtr<Gdk::Drawable>(window),
682                     window->get_colormap(),
683                     state->link_rect.left,
684                     state->link_rect.top,
685                     0,
686                     0,
687                     state->link_rect.right - state->link_rect.left,
688                     state->link_rect.bottom - state->link_rect.top);
689
690                 nsCOMPtr<nsIDOMEvent> event;
691                 check(event_factory->CreateEvent(
692                           NS_ConvertASCIItoUTF16("MouseEvents"),
693                           getter_AddRefs(event)));
694                 nsCOMPtr<nsIDOMMouseEvent> mouse_event(
695                     do_QueryInterface(event));
696                 assert(mouse_event);
697                 check(mouse_event->InitMouseEvent(
698                           NS_ConvertASCIItoUTF16("mouseover"),
699                           true,  // can bubble
700                           true,  // cancelable
701                           view,
702                           0,     // detail: mouse click count
703                           state->link_rect.left, // screenX
704                           state->link_rect.top,  // screenY
705                           state->link_rect.left, // clientX
706                           state->link_rect.top,  // clientY
707                           false, false, false, false, // qualifiers
708                           0,     // button: left (or primary)
709                           0));   // related target
710                 PRBool dummy;
711                 check(event_target->DispatchEvent(mouse_event,
712                                                   &dummy));
713                 check(event_state_man->SetContentState(content,
714                                                        NS_EVENT_STATE_HOVER));
715
716                 pres_shell->FlushPendingNotifications(true);
717
718                 // We may have to exit and wait for image loading
719                 // to complete, at which point we will be called
720                 // again.
721                 if (browser_is_busy())
722                 {
723                     state->link_changing = true;
724                     page_state_ = state;
725                     return;
726                 }
727             }
728
729             window->process_updates(true);
730
731             Glib::RefPtr<Gdk::Pixbuf> changed_pixbuf(
732                 Gdk::Pixbuf::create(
733                     Glib::RefPtr<Gdk::Drawable>(window),
734                     window->get_colormap(),
735                     state->link_rect.left,
736                     state->link_rect.top,
737                     0,
738                     0,
739                     state->link_rect.right - state->link_rect.left,
740                     state->link_rect.bottom - state->link_rect.top));
741             diff_rgb_pixbufs(
742                 state->norm_pixbuf,
743                 changed_pixbuf,
744                 state->diff_pixbuf,
745                 state->link_rect.left,
746                 state->link_rect.top,
747                 state->link_rect.right - state->link_rect.left,
748                 state->link_rect.bottom - state->link_rect.top);
749         }
750
751         quantise_rgba_pixbuf(state->diff_pixbuf, dvd::button_n_colours);
752
753         std::cout << "saving " << state->links_temp.get_name()
754                   << std::endl;
755         state->diff_pixbuf->save(state->links_temp.get_name(), "png");
756
757         state->spumux_file <<
758             "    </spu>\n"
759             "  </stream>\n"
760             "</subpictures>\n";
761
762         state->spumux_file.close();
763
764         // TODO: if (!state->spumux_file) throw ...
765
766         {
767             std::ostringstream command_stream;
768             command_stream << "pngtopnm "
769                            << background_temp_->get_name()
770                            << " | ppmtoy4m -v0 -n1 -F"
771                            << frame_params_.rate_numer
772                            << ":" << frame_params_.rate_denom
773                            << " -A" << frame_params_.pixel_ratio_width
774                            << ":" << frame_params_.pixel_ratio_height
775                            << (" -Ip -S420_mpeg2"
776                                " | mpeg2enc -v0 -f8 -a2 -o/dev/stdout"
777                                " | mplex -v0 -f8 -o/dev/stdout /dev/stdin"
778                                " | spumux -v0 -mdvd ")
779                            << state->spumux_temp.get_name()
780                            << " > "
781                            << contents_.menus[menu_num].vob_temp->get_name();
782             std::string command(command_stream.str());
783             const char * argv[] = {
784                 "/bin/sh", "-c", command.c_str(), 0
785             };
786             std::cout << "running " << argv[2] << std::endl;
787             int command_result;
788             Glib::spawn_sync(".",
789                              Glib::ArrayHandle<std::string>(
790                                  argv, sizeof(argv)/sizeof(argv[0]),
791                                  Glib::OWNERSHIP_NONE),
792                              Glib::SPAWN_STDOUT_TO_DEV_NULL,
793                              SigC::Slot0<void>(),
794                              0, 0,
795                              &command_result);
796             if (command_result != 0)
797                 throw std::runtime_error("spumux pipeline failed");
798         }
799     }
800
801     void webdvd_window::generate_dvd()
802     {
803         temp_file temp("webdvd-dvdauthor-");
804         temp.close();
805         std::ofstream file(temp.get_name().c_str());
806
807         // We generate code that uses registers in the following way:
808         //
809         // g0:     scratch
810         // g1:     current location
811         // g12:    location that last jumped to a video
812         //
813         // All locations are divided into two bitfields: the least
814         // significant 10 bits are a page/menu number and the most
815         // significant 6 bits are a link/button number, and numbering
816         // starts at 1, not 0.  This is done for compatibility with
817         // the encoding of the s8 (button) register.
818         //
819         static const int button_mult = dvd::reg_s8_button_mult;
820         static const int menu_mask = button_mult - 1;
821         static const int button_mask = (1 << dvd::reg_bits) - button_mult;
822
823         file <<
824             "<dvdauthor>\n"
825             "  <vmgm>\n"
826             "    <menus>\n";
827             
828         for (std::size_t menu_num = 0;
829              menu_num != contents_.menus.size();
830              ++menu_num)
831         {
832             dvd_contents::menu & menu = contents_.menus[menu_num];
833
834             if (menu_num == 0)
835             {
836                 // This is the first (title) menu, displayed when the
837                 // disc is first played.
838                 file <<
839                     "      <pgc entry='title'>\n"
840                     "        <pre>\n"
841                     // Initialise the current location if it is not set
842                     // (all general registers are initially 0).
843                     "          if (g1 eq 0)\n"
844                     "            g1 = " << 1 + button_mult << ";\n";
845             }
846             else
847             {
848                 file <<
849                     "      <pgc>\n"
850                     "        <pre>\n";
851             }
852
853             // When a title finishes or the user presses the menu
854             // button, this always jumps to the titleset's root menu.
855             // We want to return the user to the last menu they used.
856             // So we arrange for each titleset's root menu to return
857             // to the vmgm title menu and then dispatch from there to
858             // whatever the correct menu is.  We determine the correct
859             // menu by looking at the menu part of g1.
860
861             file << "          g0 = g1 &amp; " << menu_mask << ";\n";
862
863             // There is a limit of 128 VM instructions in each PGC.
864             // Therefore in each menu's <pre> section we generate
865             // jumps to menus with numbers greater by 512, 256, 128,
866             // ..., 1 where (a) such a menu exists, (b) this menu
867             // number is divisible by twice that increment and (c) the
868             // correct menu is that or a later menu.  Thus each menu
869             // has at most 10 such conditional jumps and is reachable
870             // by at most 10 jumps from the title menu.  This chain of
871             // jumps might take too long on some players; this has yet
872             // to be investigated.
873             
874             for (std::size_t menu_incr = (menu_mask + 1) / 2;
875                  menu_incr != 0;
876                  menu_incr /= 2)
877             {
878                 if (menu_num + menu_incr < contents_.menus.size()
879                     && (menu_num & (menu_incr * 2 - 1)) == 0)
880                 {
881                     file <<
882                         "          if (g0 ge " << 1 + menu_num + menu_incr
883                                                << ")\n"
884                         "            jump menu " << 1 + menu_num + menu_incr
885                                                << ";\n";
886                 }
887             }
888
889             file <<
890                 // Highlight the appropriate button.
891                 "          s8 = g1 &amp; " << button_mask << ";\n"
892                 "        </pre>\n"
893                 "        <vob file='" << menu.vob_temp->get_name() << "'/>\n";
894
895             for (std::size_t button_num = 0;
896                  button_num != menu.entries.size();
897                  ++button_num)
898             {
899                 file << "        <button> ";
900
901                 if (menu.entries[button_num].first == dvd_contents::menu_pgc)
902                 {
903                     int dest_menu_num = menu.entries[button_num].second;
904
905                     // Look for a button on the new menu that links
906                     // back to this one.  If there is one, set that to
907                     // be the highlighted button; otherwise, use the
908                     // first button.
909                     const std::vector<dvd_contents::pgc_ref> &
910                         dest_menu_entries =
911                         contents_.menus[dest_menu_num].entries;
912                     dvd_contents::pgc_ref this_pgc(
913                         dvd_contents::menu_pgc, menu_num);
914                     std::size_t dest_button_num = dest_menu_entries.size();
915                     while (dest_button_num != 0
916                            && dest_menu_entries[--dest_button_num] != this_pgc)
917                         ;
918                          
919                     file << "g1 = "
920                          << (1 + dest_menu_num
921                              + (1 + dest_button_num) * button_mult)
922                          << "; jump menu " << 1 + dest_menu_num << ";";
923                 }
924                 else
925                 {
926                     assert(menu.entries[button_num].first
927                            == dvd_contents::title_pgc);
928
929                     file << "g1 = "
930                          << 1 + menu_num + (1 + button_num) * button_mult
931                          << "; jump title "
932                          << 1 + menu.entries[button_num].second << ";";
933                 }
934
935                 file <<  " </button>\n";
936             }
937
938             file << "      </pgc>\n";
939         }
940
941         file <<
942             "    </menus>\n"
943             "  </vmgm>\n";
944
945         // Generate a titleset for each title.  This appears to make
946         // jumping to titles a whole lot simpler (but limits us to 99
947         // titles).
948         for (std::size_t title_num = 0;
949              title_num != contents_.titles.size();
950              ++title_num)
951         {
952             file <<
953                 "  <titleset>\n"
954                 // Generate a dummy menu so that the menu button on the
955                 // remote control will work.
956                 "    <menus>\n"
957                 "      <pgc entry='root'>\n"
958                 "        <pre> jump vmgm menu; </pre>\n"
959                 "      </pgc>\n"
960                 "    </menus>\n"
961                 "    <titles>\n"
962                 "      <pgc>\n"
963                 // Record calling location.
964                 "        <pre> g12 = g1; </pre>\n"
965                  << contents_.titles[title_num].vob_list <<
966                 // If the menu location has not been changed during
967                 // the title, set the location to be the following
968                 // button in the menu.  In any case, return to some
969                 // menu.
970                 "        <post> if (g1 eq g12) g1 = g1 + " << button_mult
971                  << "; call menu; </post>\n"
972                 "      </pgc>\n"
973                 "    </titles>\n"
974                 "  </titleset>\n";
975         }
976
977         file <<
978             "</dvdauthor>\n";
979
980         file.close();
981
982         {
983             const char * argv[] = {
984                 "dvdauthor",
985                 "-o", output_dir_.c_str(),
986                 "-x", temp.get_name().c_str(),
987                 0
988             };
989             int command_result;
990             Glib::spawn_sync(".",
991                              Glib::ArrayHandle<std::string>(
992                                  argv, sizeof(argv)/sizeof(argv[0]),
993                                  Glib::OWNERSHIP_NONE),
994                              Glib::SPAWN_SEARCH_PATH
995                              | Glib::SPAWN_STDOUT_TO_DEV_NULL,
996                              SigC::Slot0<void>(),
997                              0, 0,
998                              &command_result);
999             if (command_result != 0)
1000                 throw std::runtime_error("dvdauthor failed");
1001         }
1002     }
1003
1004     const video::frame_params & lookup_frame_params(const char * str)
1005     {
1006         assert(str);
1007         static const struct { const char * str; bool is_ntsc; }
1008         known_strings[] = {
1009             { "NTSC",  true },
1010             { "ntsc",  true },
1011             { "PAL",   false },
1012             { "pal",   false },
1013             // For DVD purposes, SECAM can be treated identically to PAL.
1014             { "SECAM", false },
1015             { "secam", false }
1016         };
1017         for (std::size_t i = 0;
1018              i != sizeof(known_strings)/sizeof(known_strings[0]);
1019              ++i)
1020             if (std::strcmp(str, known_strings[i].str) == 0)
1021                 return known_strings[i].is_ntsc ?
1022                     video::ntsc_params : video::pal_params;
1023         throw std::runtime_error(
1024             std::string("Invalid video standard: ").append(str));
1025     }
1026
1027     void print_usage(std::ostream & stream, const char * command_name)
1028     {
1029         stream << "Usage: " << command_name
1030                << (" [gtk-options] [--video-std std-name]"
1031                    " [--preview] menu-url [output-dir]\n");
1032     }
1033     
1034     void set_browser_preferences()
1035     {
1036         nsCOMPtr<nsIPrefService> pref_service;
1037         static const nsCID pref_service_cid = NS_PREFSERVICE_CID;
1038         check(CallGetService<nsIPrefService>(pref_service_cid,
1039                                              getter_AddRefs(pref_service)));
1040         nsCOMPtr<nsIPrefBranch> pref_branch;
1041
1042         // Disable IE-compatibility kluge that causes backgrounds to
1043         // sometimes/usually be missing from snapshots.  This is only
1044         // effective from Mozilla 1.8 onward.
1045 #       if MOZ_VERSION_MAJOR > 1                                 \
1046            || (MOZ_VERSION_MAJOR == 1 && MOZ_VERSION_MINOR >= 8)
1047         check(pref_service->GetDefaultBranch("layout",
1048                                              getter_AddRefs(pref_branch)));
1049         check(pref_branch->SetBoolPref(
1050                   "fire_onload_after_image_background_loads",
1051                   true));
1052 #       endif
1053
1054         // Set display resolution.  With standard-definition video we
1055         // will be fitting ~600 pixels across a screen typically
1056         // ranging from 10 to 25 inches wide, for a resolution of
1057         // 24-60 dpi.  I therefore declare the average horizontal
1058         // resolution to be 40 dpi.  The vertical resolution will be
1059         // slightly higher (PAL/SECAM) or lower (NTSC), but
1060         // unfortunately Mozilla doesn't support non-square pixels
1061         // (and neither do fontconfig or Xft anyway).
1062         check(pref_service->GetDefaultBranch("browser.display",
1063                                              getter_AddRefs(pref_branch)));
1064         check(pref_branch->SetIntPref("screen_resolution", 40));
1065     }
1066
1067 } // namespace
1068
1069 int main(int argc, char ** argv)
1070 {
1071     try
1072     {
1073         video::frame_params frame_params = video::pal_params;
1074         bool preview_mode = false;
1075         std::string menu_url;
1076         std::string output_dir;
1077
1078         // Do initial option parsing.  We have to do this before
1079         // letting Gtk parse the arguments since we may need to spawn
1080         // Xvfb first.
1081         int argi = 1;
1082         while (argi != argc)
1083         {
1084             if (std::strcmp(argv[argi], "--") == 0)
1085             {
1086                 break;
1087             }
1088             else if (std::strcmp(argv[argi], "--help") == 0)
1089             {
1090                 print_usage(std::cout, argv[0]);
1091                 return EXIT_SUCCESS;
1092             }
1093             else if (std::strcmp(argv[argi], "--preview") == 0)
1094             {
1095                 preview_mode = true;
1096                 argi += 1;
1097             }
1098             else if (std::strcmp(argv[argi], "--video-std") == 0)
1099             {
1100                 if (argi + 1 == argc)
1101                 {
1102                     std::cerr << "Missing argument to --video-std\n";
1103                     print_usage(std::cerr, argv[0]);
1104                     return EXIT_FAILURE;
1105                 }
1106                 frame_params = lookup_frame_params(argv[argi + 1]);
1107                 argi += 2;
1108             }
1109             else
1110             {
1111                 argi += 1;
1112             }
1113         }
1114
1115         std::auto_ptr<x_frame_buffer> fb;
1116         if (!preview_mode)
1117         {
1118             // Spawn Xvfb and set env variables so that Xlib will use it
1119             // Use 8 bits each for RGB components, which should translate into
1120             // "enough" bits for YUV components.
1121             fb.reset(new x_frame_buffer(frame_params.width,
1122                                         frame_params.height,
1123                                         3 * 8));
1124             setenv("XAUTHORITY", fb->get_authority().c_str(), true);
1125             setenv("DISPLAY", fb->get_display().c_str(), true);
1126         }
1127
1128         // Initialise Gtk
1129         Gtk::Main kit(argc, argv);
1130
1131         // Complete option parsing with Gtk's options out of the way.
1132         argi = 1;
1133         while (argi != argc)
1134         {
1135             if (std::strcmp(argv[argi], "--") == 0)
1136             {
1137                 argi += 1;
1138                 break;
1139             }
1140             else if (std::strcmp(argv[argi], "--preview") == 0)
1141             {
1142                 argi += 1;
1143             }
1144             else if (std::strcmp(argv[argi], "--video-std") == 0)
1145             {
1146                 argi += 2;
1147             }
1148             else if (argv[argi][0] == '-')
1149             {
1150                 std::cerr << "Invalid option: " << argv[argi] << "\n";
1151                 print_usage(std::cerr, argv[0]);
1152                 return EXIT_FAILURE;
1153             }
1154             else
1155             {
1156                 break;
1157             }
1158         }
1159
1160         // Look for a starting URL or filename and (except in preview
1161         // mode) an output directory after the options.
1162         if (argc - argi != (preview_mode ? 1 : 2))
1163         {
1164             print_usage(std::cerr, argv[0]);
1165             return EXIT_FAILURE;
1166         }
1167         if (std::strstr(argv[argi], "://"))
1168         {
1169             // It appears to be an absolute URL, so use it as-is.
1170             menu_url = argv[argi];
1171         }
1172         else
1173         {
1174             // Assume it's a filename.  Resolve it to an absolute URL.
1175             std::string path(argv[argi]);
1176             if (!Glib::path_is_absolute(path))
1177                 path = Glib::build_filename(Glib::get_current_dir(), path);
1178             menu_url = Glib::filename_to_uri(path);             
1179         }
1180         if (!preview_mode)
1181             output_dir = argv[argi + 1];
1182
1183         // Initialise Mozilla
1184         browser_widget::initialiser browser_init;
1185         set_browser_preferences();
1186
1187         // Run the browser/converter
1188         webdvd_window window(frame_params, menu_url, output_dir);
1189         Gtk::Main::run(window);
1190     }
1191     catch (std::exception & e)
1192     {
1193         std::cerr << "Fatal error: " << e.what() << "\n";
1194         return EXIT_FAILURE;
1195     }
1196
1197     return EXIT_SUCCESS;
1198 }