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