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