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