]> git.decadent.org.uk Git - videolink.git/blob - videolink.cpp
9ed174675f2a85d45f58737ded4d62a1d802677c
[videolink.git] / videolink.cpp
1 // Copyright 2005-8 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 <gdk/gdkkeysyms.h>
19 #include <gdkmm/pixbuf.h>
20 #include <glibmm/convert.h>
21 #include <glibmm/spawn.h>
22 #include <gtkmm/main.h>
23 #include <gtkmm/window.h>
24
25 #include "wchar_t_short.h"
26 #include <ImageErrors.h>
27 #if MOZ_VERSION_MAJOR == 1 && MOZ_VERSION_MINOR == 9
28 #include <nsWeakPtr.h>
29 /* For some reason <nsWeakPtr.h> no longer defines this */
30 typedef nsCOMPtr<nsIWeakReference> nsWeakPtr;
31 #endif
32 #include <nsGUIEvent.h>
33 #include <nsIBoxObject.h>
34 #include <nsIContent.h>
35 #include <nsIDocShell.h>
36 #include <nsIDOMAbstractView.h>
37 #include <nsIDOMBarProp.h>
38 #include <nsIDOMDocumentEvent.h>
39 #include <nsIDOMDocumentView.h>
40 #include <nsIDOMElement.h>
41 #include <nsIDOMEventTarget.h>
42 #include <nsIDOMHTMLDocument.h>
43 #include <nsIDOMMouseEvent.h>
44 #include <nsIDOMNSDocument.h>
45 #include <nsIDOMWindow.h>
46 #include <nsIEventStateManager.h>
47 #include <nsIInterfaceRequestorUtils.h>
48 #include <nsIURI.h> // required before nsILink.h
49 #include <nsILink.h>
50 #include <nsIPrefBranch.h>
51 #include <nsIPrefService.h>
52 #include <nsIPresShell.h>
53 #include <nsServiceManagerUtils.h>
54 #include <nsIWebBrowser.h>
55 #ifdef MOZILLA_INTERNAL_API
56 #include <nsString.h>
57 #else
58 #include <nsStringAPI.h>
59 #endif
60 #include "wchar_t_default.h"
61
62 #include "browser_widget.hpp"
63 #include "child_iterator.hpp"
64 #include "dvd.hpp"
65 #include "event_state_manager.hpp"
66 #include "generate_dvd.hpp"
67 #include "geometry.hpp"
68 #include "link_iterator.hpp"
69 #include "null_prompt_service.hpp"
70 #include "pixbufs.hpp"
71 #include "style_sheets.hpp"
72 #include "temp_file.hpp"
73 #include "video.hpp"
74 #include "warp_pointer.hpp"
75 #include "x_frame_buffer.hpp"
76 #include "xml_utils.hpp"
77 #include "xpcom_support.hpp"
78
79 using xpcom_support::check;
80
81 namespace
82 {
83     rectangle get_elem_rect(nsIDOMNSDocument * ns_doc,
84                             nsIDOMElement * elem)
85     {
86         rectangle result;
87
88         // Start with this element's bounding box
89         nsCOMPtr<nsIBoxObject> box;
90         check(ns_doc->GetBoxObjectFor(elem, getter_AddRefs(box)));
91         int width, height;
92         check(box->GetScreenX(&result.left));
93         check(box->GetScreenY(&result.top));
94         check(box->GetWidth(&width));
95         check(box->GetHeight(&height));
96         result.right = result.left + width;
97         result.bottom = result.top + height;
98
99         // Merge bounding boxes of all child elements
100         for (child_iterator it = child_iterator(elem), end; it != end; ++it)
101         {
102             nsCOMPtr<nsIDOMNode> child_node(*it);
103             PRUint16 child_type;
104             if (check(child_node->GetNodeType(&child_type)),
105                 child_type == nsIDOMNode::ELEMENT_NODE)
106             {
107                 nsCOMPtr<nsIDOMElement> child_elem(
108                     do_QueryInterface(child_node));
109                 result |= get_elem_rect(ns_doc, child_elem);
110             }
111         }
112
113         return result;
114     }
115
116
117     enum video_format
118     {
119         video_format_none,
120         video_format_mpeg2_ps,
121         video_format_vob_list
122     };
123
124     video_format video_format_from_uri(const std::string & uri)
125     {
126         // FIXME: This is a bit of a hack.  Perhaps we could decide
127         // later based on the MIME type determined by Mozilla?
128         static struct {
129             const char * extension;
130             video_format format;
131         } const mapping[] = {
132             {".vob",     video_format_mpeg2_ps},
133             {".mpeg",    video_format_mpeg2_ps},
134             {".mpeg2",   video_format_mpeg2_ps},
135             {".mpg",     video_format_mpeg2_ps},
136             {".voblist", video_format_vob_list}
137         };
138         for (std::size_t i = 0;
139              i != sizeof(mapping) / sizeof(mapping[0]);
140              ++i)
141         {
142             std::size_t ext_len = std::strlen(mapping[i].extension);
143             if (uri.size() > ext_len
144                 && uri.compare(uri.size() - ext_len, ext_len,
145                                mapping[i].extension) == 0)
146                 return mapping[i].format;
147         }
148         return video_format_none;
149     }
150
151
152     class base_window : public Gtk::Window
153     {
154     public:
155         base_window(const video::frame_params & frame_params);
156
157     protected:
158         video::frame_params frame_params_;
159         browser_widget browser_widget_;
160     };
161
162     base_window::base_window(const video::frame_params & frame_params)
163         : frame_params_(frame_params)
164     {
165         set_size_request(frame_params_.width, frame_params_.height);
166         set_resizable(false);
167
168         add(browser_widget_);
169         browser_widget_.show();
170     }
171
172     class preview_window : public base_window
173     {
174     public:
175         preview_window(const video::frame_params & frame_params,
176                        const std::string & main_page_uri);
177
178     private:
179         bool on_idle();
180         bool on_key_press(GdkEventKey *);
181
182         std::string main_page_uri_;
183     };
184
185     preview_window::preview_window(const video::frame_params & frame_params,
186                                    const std::string & main_page_uri)
187         : base_window(frame_params),
188           main_page_uri_(main_page_uri)
189     {
190         Glib::signal_idle().connect(
191             sigc::mem_fun(this, &preview_window::on_idle));
192         signal_key_press_event().connect(
193             sigc::mem_fun(this, &preview_window::on_key_press));
194     }
195
196     bool preview_window::on_idle()
197     {
198         browser_widget_.load_uri(main_page_uri_);
199         return false; // don't call again
200     }
201
202     bool preview_window::on_key_press(GdkEventKey * event)
203     {
204         switch (event->keyval)
205         {
206         case GDK_t: // = top menu
207             browser_widget_.load_uri(main_page_uri_);
208             return true;
209         case GDK_q: // = quit
210             Gtk::Main::quit();
211             return true;
212         default:
213             return false;
214         }
215     }
216
217     class conversion_window : public base_window
218     {
219     public:
220         conversion_window(const video::frame_params & frame_params,
221                           const std::string & main_page_uri,
222                           const std::string & output_dir,
223                           dvd_generator::mpeg_encoder encoder);
224
225         bool is_finished() const;
226
227     private:
228         struct page_state;
229
230         dvd_generator::pgc_ref add_menu(const std::string & uri);
231         dvd_generator::pgc_ref add_title(const std::string & uri,
232                                          video_format format);
233         void load_next_page();
234         bool on_idle();
235         void on_net_state_change(const char * uri, gint flags, guint status);
236         bool browser_is_busy() const
237             {
238                 return pending_window_update_ || pending_req_count_;
239             }
240         // Do as much processing as possible.  Return a flag indicating
241         // whether to call again once the browser is idle.
242         bool process();
243         // Return a Pixbuf containing a copy of the window contents.
244         Glib::RefPtr<Gdk::Pixbuf> get_screenshot();
245         // Do as much processing as possible on the page links.  Return
246         // a flag indicating whether to call again once the browser is
247         // idle.
248         bool process_links(
249             page_state * state,
250             nsIDOMDocument * basic_doc,
251             nsIDocShell * doc_shell,
252             nsIDOMWindow * dom_window);
253
254         std::string output_dir_;
255
256         enum {
257             state_initial,
258             state_processing,
259             state_finished
260         } state_;
261
262         dvd_generator generator_;
263         typedef std::map<std::string, dvd_generator::pgc_ref>
264             resource_map_type;
265         resource_map_type resource_map_;
266
267         std::queue<std::string> page_queue_;
268         bool pending_window_update_;
269         int pending_req_count_;
270         std::auto_ptr<page_state> page_state_;
271     };
272
273     conversion_window::conversion_window(
274         const video::frame_params & frame_params,
275         const std::string & main_page_uri,
276         const std::string & output_dir,
277         dvd_generator::mpeg_encoder encoder)
278         : base_window(frame_params),
279           output_dir_(output_dir),
280           state_(state_initial),
281           generator_(frame_params, encoder),
282           pending_window_update_(false),
283           pending_req_count_(0)
284     {
285         Glib::signal_idle().connect(
286             sigc::mem_fun(this, &conversion_window::on_idle));
287         browser_widget_.signal_net_state().connect(
288             sigc::mem_fun(this, &conversion_window::on_net_state_change));
289
290         add_menu(main_page_uri);
291     }
292
293     bool conversion_window::is_finished() const
294     {
295         return state_ == state_finished;
296     }
297
298     dvd_generator::pgc_ref conversion_window::add_menu(const std::string & uri)
299     {
300         dvd_generator::pgc_ref & pgc_ref = resource_map_[uri];
301         if (pgc_ref.type == dvd_generator::unknown_pgc)
302         {
303             pgc_ref = generator_.add_menu();
304             page_queue_.push(uri);
305         }
306         return pgc_ref;
307     }
308
309     dvd_generator::pgc_ref conversion_window::add_title(const std::string & uri,
310                                                       video_format format)
311     {
312         dvd_generator::pgc_ref & pgc_ref = resource_map_[uri];
313
314         if (pgc_ref.type == dvd_generator::unknown_pgc)
315         {
316             Glib::ustring hostname;
317             std::string path(Glib::filename_from_uri(uri, hostname));
318             // FIXME: Should check the hostname
319
320             vob_list list;
321
322             // Store a reference to a linked VOB file, or the contents
323             // of a linked VOB list file.
324             if (format == video_format_mpeg2_ps)
325             {
326                 if (!Glib::file_test(path, Glib::FILE_TEST_IS_REGULAR))
327                     throw std::runtime_error(
328                         path + " is missing or not a regular file");
329                 vob_ref ref;
330                 ref.file = path;
331                 list.push_back(ref);
332             }
333             else if (format == video_format_vob_list)
334             {
335                 read_vob_list(path).swap(list);
336             }
337             else
338             {
339                 assert(!"unrecognised format in add_title");
340             }
341
342             pgc_ref = generator_.add_title(list);
343         }
344
345         return pgc_ref;
346     }
347
348     void conversion_window::load_next_page()
349     {
350         assert(!page_queue_.empty());
351         const std::string & uri = page_queue_.front();
352         std::cout << "INFO: Loading <" << uri << ">" << std::endl;
353
354         browser_widget_.load_uri(uri);
355     }
356
357     void conversion_window::on_net_state_change(const char * uri,
358                                                 gint flags, guint status)
359     {
360 #       ifdef DEBUG_ON_NET_STATE_CHANGE
361         std::cout << "conversion_window::on_net_state_change(";
362         if (uri)
363             std::cout << '"' << uri << '"';
364         else
365             std::cout << "NULL";
366         std::cout << ", ";
367         {
368             gint flags_left = flags;
369             static const struct {
370                 gint value;
371                 const char * name;
372             } flag_names[] = {
373                 { GTK_MOZ_EMBED_FLAG_START, "STATE_START" },
374                 { GTK_MOZ_EMBED_FLAG_REDIRECTING, "STATE_REDIRECTING" },
375                 { GTK_MOZ_EMBED_FLAG_TRANSFERRING, "STATE_TRANSFERRING" },
376                 { GTK_MOZ_EMBED_FLAG_NEGOTIATING, "STATE_NEGOTIATING" },
377                 { GTK_MOZ_EMBED_FLAG_STOP, "STATE_STOP" },
378                 { GTK_MOZ_EMBED_FLAG_IS_REQUEST, "STATE_IS_REQUEST" },
379                 { GTK_MOZ_EMBED_FLAG_IS_DOCUMENT, "STATE_IS_DOCUMENT" },
380                 { GTK_MOZ_EMBED_FLAG_IS_NETWORK, "STATE_IS_NETWORK" },
381                 { GTK_MOZ_EMBED_FLAG_IS_WINDOW, "STATE_IS_WINDOW" }
382             };
383             for (int i = 0; i != sizeof(flag_names)/sizeof(flag_names[0]); ++i)
384             {
385                 if (flags & flag_names[i].value)
386                 {
387                     std::cout << flag_names[i].name;
388                     flags_left -= flag_names[i].value;
389                     if (flags_left)
390                         std::cout << " | ";
391                 }
392             }
393             if (flags_left)
394                 std::cout << "0x" << std::setbase(16) << flags_left;
395         }
396         std::cout << ", " << "0x" << std::setbase(16) << status << ")\n";
397 #       endif // DEBUG_ON_NET_STATE_CHANGE
398
399         if (flags & GTK_MOZ_EMBED_FLAG_IS_REQUEST)
400         {
401             if (flags & GTK_MOZ_EMBED_FLAG_START)
402                 ++pending_req_count_;
403
404             if (flags & GTK_MOZ_EMBED_FLAG_STOP)
405             {
406                 assert(pending_req_count_ != 0);
407                 --pending_req_count_;
408             }
409         }
410             
411         if (flags & GTK_MOZ_EMBED_FLAG_IS_DOCUMENT
412             && flags & GTK_MOZ_EMBED_FLAG_START)
413         {
414             pending_window_update_ = true;
415         }
416
417         if (flags & GTK_MOZ_EMBED_FLAG_IS_WINDOW
418             && flags & GTK_MOZ_EMBED_FLAG_STOP)
419         {
420             // Check whether the load was successful, ignoring this
421             // pseudo-error.
422             if (status != NS_IMAGELIB_ERROR_LOAD_ABORTED)
423                 check(status);
424
425             pending_window_update_ = false;
426         }
427     }
428
429     struct conversion_window::page_state
430     {
431         page_state(Glib::RefPtr<Gdk::Pixbuf> norm_pixbuf,
432                    nsIDOMDocument * doc, int width, int height)
433                 : norm_pixbuf(norm_pixbuf),
434                   diff_pixbuf(Gdk::Pixbuf::create(
435                                   Gdk::COLORSPACE_RGB,
436                                   true, 8, // has_alpha, bits_per_sample
437                                   width, height)),
438                   links_it(doc),
439                   link_changing(false)
440             {
441             }
442
443         Glib::RefPtr<Gdk::Pixbuf> norm_pixbuf;
444         Glib::RefPtr<Gdk::Pixbuf> diff_pixbuf;
445
446         link_iterator links_it, links_end;
447
448         rectangle link_rect;
449         std::string link_target;
450         bool link_changing;
451     };
452
453     bool conversion_window::on_idle()
454     {
455         if (state_ == state_initial)
456         {
457             // Put pointer in the top-left so that no links appear in
458             // the hover state when we take a screenshot.
459             warp_pointer(get_window(),
460                          -frame_params_.width, -frame_params_.height);
461
462             load_next_page();
463
464             state_ = state_processing;
465         }
466         else if (state_ == state_processing && !browser_is_busy())
467         {
468             try
469             {
470                 if (!process())
471                 {
472                     state_ = state_finished;
473                     Gtk::Main::quit();
474                 }
475             }
476             catch (...)
477             {
478                 // Print context of exception.
479                 if (!page_queue_.empty())
480                 {
481                     std::cerr << "ERROR: While processing page <"
482                               << page_queue_.front() << ">:\n";
483                     if (page_state_.get() && !page_state_->link_target.empty())
484                         std::cerr << "ERROR: While processing link to <"
485                                   << page_state_->link_target << ">:\n";
486                 }
487
488                 // Print exception message.
489                 try
490                 {
491                     throw;
492                 }
493                 catch (std::exception & e)
494                 {
495                     std::cerr << "ERROR: " << e.what() << "\n";
496                 }
497                 catch (Glib::Exception & e)
498                 {
499                     std::cerr << "ERROR: " << e.what() << "\n";
500                 }
501                 catch (...)
502                 {
503                     std::cerr << "ERROR: Unknown exception\n";
504                 }
505
506                 Gtk::Main::quit();
507             }
508         }
509
510         // Call again if we're not done.
511         return state_ != state_finished;
512     }
513
514     bool conversion_window::process()
515     {
516         assert(!page_queue_.empty());
517
518         nsCOMPtr<nsIWebBrowser> browser(browser_widget_.get_browser());
519         nsCOMPtr<nsIDocShell> doc_shell(do_GetInterface(browser));
520         assert(doc_shell);
521         nsCOMPtr<nsIDOMWindow> dom_window;
522         check(browser->GetContentDOMWindow(getter_AddRefs(dom_window)));
523
524         nsCOMPtr<nsIDOMDocument> basic_doc;
525         check(dom_window->GetDocument(getter_AddRefs(basic_doc)));
526
527         // Start or continue processing links.
528         if (!page_state_.get())
529             page_state_.reset(
530                 new page_state(
531                     get_screenshot(),
532                     basic_doc, frame_params_.width, frame_params_.height));
533         if (!process_links(page_state_.get(), basic_doc, doc_shell, dom_window))
534         {
535             // We've finished work on the links so generate the
536             // menu VOB.
537             quantise_rgba_pixbuf(page_state_->diff_pixbuf,
538                                  dvd::button_n_colours);
539             generator_.generate_menu_vob(
540                 resource_map_[page_queue_.front()].index,
541                 page_state_->norm_pixbuf, page_state_->diff_pixbuf);
542
543             // Move on to the next page, if any, or else generate
544             // the DVD filesystem.
545             page_state_.reset();
546             page_queue_.pop();
547             if (!page_queue_.empty())
548             {
549                 load_next_page();
550             }
551             else
552             {
553                 generator_.generate(output_dir_);
554                 return false;
555             }
556         }
557
558         return true;
559     }
560
561     Glib::RefPtr<Gdk::Pixbuf> conversion_window::get_screenshot()
562     {
563         Glib::RefPtr<Gdk::Window> window(get_window());
564         assert(window);
565         window->process_updates(true);
566
567         return Gdk::Pixbuf::create(Glib::RefPtr<Gdk::Drawable>(window),
568                                    window->get_colormap(),
569                                    0, 0, 0, 0,
570                                    frame_params_.width, frame_params_.height);
571     }
572
573     bool conversion_window::process_links(
574         page_state * state,
575         nsIDOMDocument * basic_doc,
576         nsIDocShell * doc_shell,
577         nsIDOMWindow * dom_window)
578     {
579         Glib::RefPtr<Gdk::Window> window(get_window());
580         assert(window);
581
582         nsCOMPtr<nsIDOMNSDocument> ns_doc(do_QueryInterface(basic_doc));
583         assert(ns_doc);
584         nsCOMPtr<nsIPresShell> pres_shell;
585         check(doc_shell->GetPresShell(getter_AddRefs(pres_shell)));
586         nsCOMPtr<nsIEventStateManager> event_state_man(
587             get_event_state_manager(doc_shell));
588         assert(event_state_man);
589         nsCOMPtr<nsIDOMDocumentEvent> event_factory(
590             do_QueryInterface(basic_doc));
591         assert(event_factory);
592         nsCOMPtr<nsIDOMDocumentView> doc_view(do_QueryInterface(basic_doc));
593         assert(doc_view);
594         nsCOMPtr<nsIDOMAbstractView> view;
595         check(doc_view->GetDefaultView(getter_AddRefs(view)));
596
597         rectangle window_rect = {
598             0, 0, frame_params_.width, frame_params_.height
599         };
600
601         unsigned menu_index = resource_map_[page_queue_.front()].index;
602
603         for (/* no initialisation */;
604              state->links_it != state->links_end;
605              ++state->links_it)
606         {
607             nsCOMPtr<nsIDOMNode> node(*state->links_it);
608
609             // Find the link URI and separate any fragment from it.
610             nsCOMPtr<nsILink> link(do_QueryInterface(node));
611             assert(link);
612             nsCOMPtr<nsIURI> uri_iface;
613             check(link->GetHrefURI(getter_AddRefs(uri_iface)));
614             std::string uri, fragment;
615             {
616                 nsCString link_target_ns;
617                 check(uri_iface->GetSpec(link_target_ns));
618                 const char * str;
619                 PRUint32 len = NS_CStringGetData(link_target_ns, &str);
620                 state->link_target.assign(str, len);
621
622                 std::size_t hash_pos = state->link_target.find('#');
623                 uri.assign(state->link_target, 0, hash_pos);
624                 if (hash_pos != std::string::npos)
625                     fragment.assign(state->link_target,
626                                     hash_pos + 1, std::string::npos);
627             }
628
629             // Is this a new link?
630             if (!state->link_changing)
631             {
632                 // Find a rectangle enclosing the link and clip it to the
633                 // window.
634                 nsCOMPtr<nsIDOMElement> elem(do_QueryInterface(node));
635                 assert(elem);
636                 state->link_rect = get_elem_rect(ns_doc, elem);
637                 state->link_rect &= window_rect;
638
639                 if (state->link_rect.empty())
640                 {
641                     std::cerr << "WARN: Ignoring invisible link to <"
642                               << state->link_target << ">\n";
643                     continue;
644                 }
645
646                 // Check whether this is a link to a video or a page then
647                 // add it to the known resources if not already seen; then
648                 // add it to the menu entries.
649                 dvd_generator::pgc_ref target;
650                 video_format format = video_format_from_uri(uri);
651                 if (format != video_format_none)
652                 {
653                     PRBool is_file;
654                     check(uri_iface->SchemeIs("file", &is_file));
655                     if (!is_file)
656                         throw std::runtime_error(
657                             "Link to video does not use file: scheme");
658                     target = add_title(uri, format);
659                     target.sub_index =
660                         std::strtoul(fragment.c_str(), NULL, 10);
661                 }
662                 else // video_format == video_format_none
663                 {
664                     target = add_menu(uri);
665                     // TODO: If there's a fragment, work out which button
666                     // is closest and set target.sub_index.
667                 }
668
669                 generator_.add_menu_entry(menu_index,
670                                           state->link_rect, target);
671
672                 nsCOMPtr<nsIContent> content(do_QueryInterface(node));
673                 assert(content);
674                 nsCOMPtr<nsIDOMEventTarget> event_target(
675                     do_QueryInterface(node));
676                 assert(event_target);
677
678                 nsCOMPtr<nsIDOMEvent> event;
679                 check(event_factory->CreateEvent(
680                           NS_ConvertASCIItoUTF16("MouseEvents"),
681                           getter_AddRefs(event)));
682                 nsCOMPtr<nsIDOMMouseEvent> mouse_event(
683                     do_QueryInterface(event));
684                 assert(mouse_event);
685                 check(mouse_event->InitMouseEvent(
686                           NS_ConvertASCIItoUTF16("mouseover"),
687                           true,  // can bubble
688                           true,  // cancelable
689                           view,
690                           0,     // detail: mouse click count
691                           state->link_rect.left, // screenX
692                           state->link_rect.top,  // screenY
693                           state->link_rect.left, // clientX
694                           state->link_rect.top,  // clientY
695                           false, false, false, false, // qualifiers
696                           0,     // button: left (or primary)
697                           0));   // related target
698                 PRBool dummy;
699                 check(event_target->DispatchEvent(mouse_event,
700                                                   &dummy));
701                 check(event_state_man->SetContentState(content,
702                                                        NS_EVENT_STATE_HOVER));
703
704                 pres_shell->FlushPendingNotifications(Flush_Display);
705
706                 // We may have to exit and wait for image loading
707                 // to complete, at which point we will be called
708                 // again.
709                 if (browser_is_busy())
710                 {
711                     state->link_changing = true;
712                     return true;
713                 }
714             }
715
716             window->process_updates(true);
717
718             Glib::RefPtr<Gdk::Pixbuf> changed_pixbuf(
719                 Gdk::Pixbuf::create(
720                     Glib::RefPtr<Gdk::Drawable>(window),
721                     window->get_colormap(),
722                     state->link_rect.left,
723                     state->link_rect.top,
724                     0,
725                     0,
726                     state->link_rect.right - state->link_rect.left,
727                     state->link_rect.bottom - state->link_rect.top));
728             diff_rgb_pixbufs(
729                 state->norm_pixbuf,
730                 changed_pixbuf,
731                 state->diff_pixbuf,
732                 state->link_rect.left,
733                 state->link_rect.top,
734                 state->link_rect.right - state->link_rect.left,
735                 state->link_rect.bottom - state->link_rect.top);
736         }
737
738         return false;
739     }
740
741     const video::frame_params & lookup_frame_params(const char * str)
742     {
743         assert(str);
744         static const char * const known_strings[] = {
745             "525",    "625",
746             "525/60", "625/50",
747             "NTSC",   "PAL",
748             "ntsc",   "pal"
749         };
750         for (std::size_t i = 0;
751              i != sizeof(known_strings)/sizeof(known_strings[0]);
752              ++i)
753             if (std::strcmp(str, known_strings[i]) == 0)
754                 return (i & 1)
755                     ? video::frame_params_625
756                     : video::frame_params_525;
757         throw std::runtime_error(
758             std::string("Invalid video standard: ").append(str));
759     }
760
761     void print_usage(std::ostream & stream, const char * command_name)
762     {
763         stream <<
764             "Usage: " << command_name << " [gtk-options] [--preview]\n"
765             "           [--video-std {525|525/60|NTSC|ntsc"
766             " | 625|625/50|PAL|pal}]\n"
767             "           [--encoder {ffmpeg|mjpegtools}]\n"
768             "           menu-url [output-dir]\n";
769     }
770     
771     void set_browser_preferences()
772     {
773         nsCOMPtr<nsIPrefService> pref_service;
774         static const nsCID pref_service_cid = NS_PREFSERVICE_CID;
775         check(CallGetService<nsIPrefService>(pref_service_cid,
776                                              getter_AddRefs(pref_service)));
777         nsCOMPtr<nsIPrefBranch> pref_branch;
778         check(pref_service->GetBranch("", getter_AddRefs(pref_branch)));
779
780         // Disable IE-compatibility kluge that causes backgrounds to
781         // sometimes/usually be missing from snapshots.  This is only
782         // effective from Mozilla 1.8 onward.
783         check(pref_branch->SetBoolPref(
784                   "layout.fire_onload_after_image_background_loads",
785                   true));
786
787         // Set display resolution.  With standard-definition video we
788         // will be fitting ~600 pixels across a screen typically
789         // ranging from 10 to 25 inches wide, for a resolution of
790         // 24-60 dpi.  I therefore declare the average horizontal
791         // resolution to be 40 dpi.  The vertical resolution will be
792         // slightly different but unfortunately Mozilla doesn't
793         // support non-square pixels (and neither do fontconfig or Xft
794         // anyway).
795
796         // The browser.display.screen_resolution preference sets the
797         // the nominal resolution for dimensions expressed in pixels.
798         // (They may be scaled!)  In Mozilla 1.7 it also sets the
799         // assumed resolution of the display - hence pixel sizes are
800         // respected on-screen - but this is no longer the case in
801         // 1.8.  Therefore it was renamed to layout.css.dpi in 1.8.1.
802         // In 1.8 we need to set the assumed screen resolution
803         // separately, but don't know how yet.  Setting one to 40
804         // but not the other is *bad*, so currently we set neither.
805
806 #       if 0
807             check(pref_branch->SetIntPref("browser.display.screen_resolution",
808                                           40));
809 #       endif
810     }
811
812 } // namespace
813
814 void fatal_error(const std::string & message)
815 {
816     std::cerr << "ERROR: " << message << "\n";
817     Gtk::Main::quit();
818 }
819
820 int main(int argc, char ** argv)
821 {
822     try
823     {
824         video::frame_params frame_params = video::frame_params_625;
825         bool preview_mode = false;
826         std::string menu_url;
827         std::string output_dir;
828         dvd_generator::mpeg_encoder encoder =
829             dvd_generator::mpeg_encoder_ffmpeg;
830
831         // Do initial option parsing.  We have to do this before
832         // letting Gtk parse the arguments since we may need to spawn
833         // Xvfb first.
834         int argi = 1;
835         while (argi != argc)
836         {
837             if (std::strcmp(argv[argi], "--") == 0)
838             {
839                 break;
840             }
841             else if (std::strcmp(argv[argi], "--help") == 0)
842             {
843                 print_usage(std::cout, argv[0]);
844                 return EXIT_SUCCESS;
845             }
846             else if (std::strcmp(argv[argi], "--preview") == 0)
847             {
848                 preview_mode = true;
849                 argi += 1;
850             }
851             else if (std::strcmp(argv[argi], "--video-std") == 0)
852             {
853                 if (argi + 1 == argc)
854                 {
855                     std::cerr << "Missing argument to --video-std\n";
856                     print_usage(std::cerr, argv[0]);
857                     return EXIT_FAILURE;
858                 }
859                 frame_params = lookup_frame_params(argv[argi + 1]);
860                 argi += 2;
861             }
862             else
863             {
864                 argi += 1;
865             }
866         }
867
868         std::auto_ptr<x_frame_buffer> fb;
869         if (!preview_mode)
870         {
871             // Spawn Xvfb and set env variables so that Xlib will use it
872             // Use 8 bits each for RGB components, which should translate into
873             // "enough" bits for YUV components.
874             fb.reset(new x_frame_buffer(frame_params.width,
875                                         frame_params.height,
876                                         3 * 8));
877             setenv("XAUTHORITY", fb->get_authority().c_str(), true);
878             setenv("DISPLAY", fb->get_display().c_str(), true);
879         }
880
881         // Initialise Gtk
882         Gtk::Main kit(argc, argv);
883
884         // Complete option parsing with Gtk's options out of the way.
885         argi = 1;
886         while (argi != argc)
887         {
888             if (std::strcmp(argv[argi], "--") == 0)
889             {
890                 argi += 1;
891                 break;
892             }
893             else if (std::strcmp(argv[argi], "--preview") == 0)
894             {
895                 argi += 1;
896             }
897             else if (std::strcmp(argv[argi], "--video-std") == 0)
898             {
899                 argi += 2;
900             }
901             else if (std::strcmp(argv[argi], "--save-temps") == 0)
902             {
903                 temp_file::keep_all(true);
904                 argi += 1;
905             }
906             else if (std::strcmp(argv[argi], "--encoder") == 0)
907             {
908                 if (argi + 1 == argc)
909                 {
910                     std::cerr << "Missing argument to --encoder\n";
911                     print_usage(std::cerr, argv[0]);
912                     return EXIT_FAILURE;
913                 }
914                 if (std::strcmp(argv[argi + 1], "ffmpeg") == 0)
915                 {
916                     encoder = dvd_generator::mpeg_encoder_ffmpeg;
917                 }
918                 else if (std::strcmp(argv[argi + 1], "mjpegtools") == 0)
919                 {
920                     encoder = dvd_generator::mpeg_encoder_mjpegtools;
921                 }
922                 else
923                 {
924                     std::cerr << "Invalid argument to --encoder\n";
925                     print_usage(std::cerr, argv[0]);
926                     return EXIT_FAILURE;
927                 }
928                 argi += 2;
929             }
930             else if (argv[argi][0] == '-')
931             {
932                 std::cerr << "Invalid option: " << argv[argi] << "\n";
933                 print_usage(std::cerr, argv[0]);
934                 return EXIT_FAILURE;
935             }
936             else
937             {
938                 break;
939             }
940         }
941
942         // Look for a starting URL or filename and (except in preview
943         // mode) an output directory after the options.
944         if (argc - argi != (preview_mode ? 1 : 2))
945         {
946             print_usage(std::cerr, argv[0]);
947             return EXIT_FAILURE;
948         }
949         if (std::strstr(argv[argi], "://"))
950         {
951             // It appears to be an absolute URL, so use it as-is.
952             menu_url = argv[argi];
953         }
954         else
955         {
956             // Assume it's a filename.  Resolve it to an absolute URL.
957             std::string path(argv[argi]);
958             if (!Glib::path_is_absolute(path))
959                 path = Glib::build_filename(Glib::get_current_dir(), path);
960             menu_url = Glib::filename_to_uri(path);             
961         }
962         if (!preview_mode)
963             output_dir = argv[argi + 1];
964
965         // Initialise Mozilla
966         browser_widget::initialiser browser_init;
967         set_browser_preferences();
968         init_agent_style_sheet("file://" VIDEOLINK_SHARE_DIR "/videolink.css");
969         init_agent_style_sheet(std::string("file://" VIDEOLINK_SHARE_DIR "/")
970                                .append(frame_params.common_name).append(".css")
971                                .c_str());
972         if (!preview_mode)
973             null_prompt_service::install();
974
975         // Run the browser/converter
976         if (preview_mode)
977         {
978             preview_window window(frame_params, menu_url);
979             window.show();
980             window.signal_hide().connect(sigc::ptr_fun(Gtk::Main::quit));
981             Gtk::Main::run();
982             return EXIT_SUCCESS;
983         }
984         else
985         {
986             conversion_window window(frame_params, menu_url, output_dir, encoder);
987             window.show();
988             window.signal_hide().connect(sigc::ptr_fun(Gtk::Main::quit));
989             Gtk::Main::run();
990             return window.is_finished() ? EXIT_SUCCESS  : EXIT_FAILURE;
991         }
992     }
993     catch (std::exception & e)
994     {
995         std::cerr << "ERROR: " << e.what() << "\n";
996         return EXIT_FAILURE;
997     }
998 }