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