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