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