Fix player stress testing with expanded controls.
[dcpomatic.git] / src / tools / dcpomatic_player.cc
1 /*
2     Copyright (C) 2017-2020 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 #include "wx/wx_signal_manager.h"
22 #include "wx/wx_util.h"
23 #include "wx/about_dialog.h"
24 #include "wx/report_problem_dialog.h"
25 #include "wx/film_viewer.h"
26 #include "wx/player_information.h"
27 #include "wx/update_dialog.h"
28 #include "wx/player_config_dialog.h"
29 #include "wx/verify_dcp_dialog.h"
30 #include "wx/standard_controls.h"
31 #include "wx/playlist_controls.h"
32 #ifdef DCPOMATIC_VARIANT_SWAROOP
33 #include "wx/swaroop_controls.h"
34 #endif
35 #include "wx/timer_display.h"
36 #include "wx/system_information_dialog.h"
37 #include "lib/cross.h"
38 #include "lib/config.h"
39 #include "lib/util.h"
40 #include "lib/internet.h"
41 #include "lib/update_checker.h"
42 #include "lib/compose.hpp"
43 #include "lib/dcp_content.h"
44 #include "lib/job_manager.h"
45 #include "lib/job.h"
46 #include "lib/film.h"
47 #include "lib/null_log.h"
48 #include "lib/video_content.h"
49 #include "lib/text_content.h"
50 #include "lib/ratio.h"
51 #include "lib/verify_dcp_job.h"
52 #include "lib/dcp_examiner.h"
53 #include "lib/examine_content_job.h"
54 #include "lib/server.h"
55 #include "lib/dcpomatic_socket.h"
56 #include "lib/scoped_temporary.h"
57 #include "lib/monitor_checker.h"
58 #include "lib/lock_file_checker.h"
59 #include "lib/ffmpeg_content.h"
60 #include "lib/dcpomatic_log.h"
61 #include "lib/file_log.h"
62 #include <dcp/dcp.h>
63 #include <dcp/raw_convert.h>
64 #include <dcp/exceptions.h>
65 #include <wx/wx.h>
66 #include <wx/stdpaths.h>
67 #include <wx/splash.h>
68 #include <wx/cmdline.h>
69 #include <wx/preferences.h>
70 #include <wx/progdlg.h>
71 #include <wx/display.h>
72 #ifdef __WXGTK__
73 #include <X11/Xlib.h>
74 #endif
75 #ifdef __WXOSX__
76 #include <ApplicationServices/ApplicationServices.h>
77 #endif
78 #include <boost/bind.hpp>
79 #include <boost/algorithm/string.hpp>
80 #include <iostream>
81
82 #ifdef check
83 #undef check
84 #endif
85
86 #define MAX_CPLS 32
87
88 using std::string;
89 using std::cout;
90 using std::list;
91 using std::exception;
92 using std::vector;
93 using boost::shared_ptr;
94 using boost::weak_ptr;
95 using boost::scoped_array;
96 using boost::optional;
97 using boost::dynamic_pointer_cast;
98 using boost::thread;
99 using boost::bind;
100 using dcp::raw_convert;
101 using namespace dcpomatic;
102
103 #ifdef DCPOMATIC_PLAYER_STRESS_TEST
104 /* Interval to check what to do next with the stress checker, in milliseconds */
105 #define STRESS_TEST_CHECK_INTERVAL 20
106
107 class Command
108 {
109 public:
110         enum Type {
111                 NONE,
112                 OPEN,
113                 PLAY,
114                 WAIT,
115                 STOP,
116                 SEEK,
117         };
118
119         Command(string line)
120                 : type (NONE)
121                 , int_param (0)
122         {
123                 vector<string> bits;
124                 boost::split (bits, line, boost::is_any_of(" "));
125                 if (bits[0] == "O") {
126                         if (bits.size() != 2) {
127                                 return;
128                         }
129                         type = OPEN;
130                         string_param = bits[1];
131                 } else if (bits[0] == "P") {
132                         type = PLAY;
133                 } else if (bits[0] == "W") {
134                         if (bits.size() != 2) {
135                                 return;
136                         }
137                         type = WAIT;
138                         int_param = raw_convert<int>(bits[1]);
139                 } else if (bits[0] == "S") {
140                         type = STOP;
141                 } else if (bits[0] == "K") {
142                         if (bits.size() != 2) {
143                                 return;
144                         }
145                         type = SEEK;
146                         int_param = raw_convert<int>(bits[1]);
147                 }
148         }
149
150         Type type;
151         string string_param;
152         int int_param;
153 };
154 #endif
155
156 enum {
157         ID_file_open = 1,
158         ID_file_add_ov,
159         ID_file_add_kdm,
160         ID_file_history,
161         /* Allow spare IDs after _history for the recent files list */
162         ID_file_close = 100,
163         ID_view_cpl,
164         /* Allow spare IDs for CPLs */
165         ID_view_full_screen = 200,
166         ID_view_dual_screen,
167         ID_view_closed_captions,
168         ID_view_scale_appropriate,
169         ID_view_scale_full,
170         ID_view_scale_half,
171         ID_view_scale_quarter,
172         ID_help_report_a_problem,
173         ID_tools_verify,
174         ID_tools_check_for_updates,
175         ID_tools_timing,
176         ID_tools_system_information,
177         /* IDs for shortcuts (with no associated menu item) */
178         ID_start_stop,
179         ID_back_frame,
180         ID_forward_frame
181 };
182
183 class DOMFrame : public wxFrame
184 {
185 public:
186         DOMFrame ()
187                 : wxFrame (0, -1, _("DCP-o-matic Player"))
188                 , _dual_screen (0)
189                 , _update_news_requested (false)
190                 , _info (0)
191                 , _mode (Config::instance()->player_mode())
192                 , _config_dialog (0)
193                 , _file_menu (0)
194                 , _history_items (0)
195                 , _history_position (0)
196                 , _history_separator (0)
197                 , _system_information_dialog (0)
198                 , _view_full_screen (0)
199                 , _view_dual_screen (0)
200 #ifdef DCPOMATIC_PLAYER_STRESS_TEST
201                 , _timer (this)
202                 , _stress_suspended (false)
203 #endif
204 {
205                 dcpomatic_log.reset (new NullLog());
206
207 #if defined(DCPOMATIC_WINDOWS)
208                 maybe_open_console ();
209                 cout << "DCP-o-matic Player is starting." << "\n";
210 #endif
211
212                 wxMenuBar* bar = new wxMenuBar;
213                 setup_menu (bar);
214                 set_menu_sensitivity ();
215                 SetMenuBar (bar);
216
217 #ifdef DCPOMATIC_WINDOWS
218                 SetIcon (wxIcon (std_to_wx ("id")));
219 #endif
220
221                 _config_changed_connection = Config::instance()->Changed.connect (boost::bind (&DOMFrame::config_changed, this, _1));
222                 update_from_config (Config::PLAYER_DEBUG_LOG);
223
224                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_open, this), ID_file_open);
225                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_add_ov, this), ID_file_add_ov);
226                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_add_kdm, this), ID_file_add_kdm);
227                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_history, this, _1), ID_file_history, ID_file_history + HISTORY_SIZE);
228                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_close, this), ID_file_close);
229                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_exit, this), wxID_EXIT);
230                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::edit_preferences, this), wxID_PREFERENCES);
231                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::view_full_screen, this), ID_view_full_screen);
232                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::view_dual_screen, this), ID_view_dual_screen);
233                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::view_closed_captions, this), ID_view_closed_captions);
234                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::view_cpl, this, _1), ID_view_cpl, ID_view_cpl + MAX_CPLS);
235                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::set_decode_reduction, this, optional<int>(0)), ID_view_scale_full);
236                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::set_decode_reduction, this, optional<int>(1)), ID_view_scale_half);
237                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::set_decode_reduction, this, optional<int>(2)), ID_view_scale_quarter);
238                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::help_about, this), wxID_ABOUT);
239                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::help_report_a_problem, this), ID_help_report_a_problem);
240                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_verify, this), ID_tools_verify);
241                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_check_for_updates, this), ID_tools_check_for_updates);
242                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_timing, this), ID_tools_timing);
243                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_system_information, this), ID_tools_system_information);
244
245                 /* Use a panel as the only child of the Frame so that we avoid
246                    the dark-grey background on Windows.
247                 */
248                 _overall_panel = new wxPanel (this, wxID_ANY);
249
250                 _viewer.reset (new FilmViewer (_overall_panel));
251 #ifdef DCPOMATIC_VARIANT_SWAROOP
252                 SwaroopControls* sc = new SwaroopControls (_overall_panel, _viewer);
253                 _controls = sc;
254                 sc->ResetFilm.connect (bind(&DOMFrame::reset_film_weak, this, _1));
255 #else
256                 if (Config::instance()->player_mode() == Config::PLAYER_MODE_DUAL) {
257                         PlaylistControls* pc = new PlaylistControls (_overall_panel, _viewer);
258                         _controls = pc;
259                         pc->ResetFilm.connect (bind(&DOMFrame::reset_film_weak, this, _1));
260                 } else {
261                         _controls = new StandardControls (_overall_panel, _viewer, false);
262                 }
263 #endif
264                 _viewer->set_dcp_decode_reduction (Config::instance()->decode_reduction ());
265                 _viewer->PlaybackPermitted.connect (bind(&DOMFrame::playback_permitted, this));
266                 _viewer->Started.connect (bind(&DOMFrame::playback_started, this, _1));
267                 _viewer->Stopped.connect (bind(&DOMFrame::playback_stopped, this, _1));
268                 _info = new PlayerInformation (_overall_panel, _viewer);
269                 setup_main_sizer (Config::instance()->player_mode());
270 #ifdef __WXOSX__
271                 int accelerators = 4;
272 #else
273                 int accelerators = 3;
274 #endif
275
276                 wxAcceleratorEntry* accel = new wxAcceleratorEntry[accelerators];
277                 accel[0].Set(wxACCEL_NORMAL, WXK_SPACE, ID_start_stop);
278                 accel[1].Set(wxACCEL_NORMAL, WXK_LEFT, ID_back_frame);
279                 accel[2].Set(wxACCEL_NORMAL, WXK_RIGHT, ID_forward_frame);
280 #ifdef __WXOSX__
281                 accel[3].Set(wxACCEL_CTRL, static_cast<int>('W'), ID_file_close);
282 #endif
283                 wxAcceleratorTable accel_table (accelerators, accel);
284                 SetAcceleratorTable (accel_table);
285                 delete[] accel;
286
287                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::start_stop_pressed, this), ID_start_stop);
288                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::back_frame, this), ID_back_frame);
289                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::forward_frame, this), ID_forward_frame);
290
291                 reset_film ();
292
293                 UpdateChecker::instance()->StateChanged.connect (boost::bind (&DOMFrame::update_checker_state_changed, this));
294 #ifdef DCPOMATIC_VARIANT_SWAROOP
295                 MonitorChecker::instance()->StateChanged.connect(boost::bind(&DOMFrame::monitor_checker_state_changed, this));
296                 MonitorChecker::instance()->run ();
297                 LockFileChecker::instance()->StateChanged.connect(boost::bind(&DOMFrame::lock_checker_state_changed, this));
298                 LockFileChecker::instance()->run ();
299 #endif
300                 setup_screen ();
301
302 #ifdef DCPOMATIC_VARIANT_SWAROOP
303                 sc->check_restart ();
304 #endif
305         }
306
307 #ifdef DCPOMATIC_PLAYER_STRESS_TEST
308         void stress (boost::filesystem::path script_file)
309         {
310                 Bind (wxEVT_TIMER, boost::bind(&DOMFrame::check_commands, this));
311                 _timer.Start(STRESS_TEST_CHECK_INTERVAL);
312                 vector<string> lines;
313                 string const script = dcp::file_to_string(script_file);
314                 boost::split (lines, script, boost::is_any_of("\n"));
315                 BOOST_FOREACH (string i, lines) {
316                         _commands.push_back (Command(i));
317                 }
318                 _current_command = _commands.begin();
319         }
320
321         void check_commands ()
322         {
323                 if (_stress_suspended) {
324                         return;
325                 }
326
327                 if (_current_command == _commands.end()) {
328                         _timer.Stop ();
329                         cout << "ST: finished.\n";
330                         return;
331                 }
332
333                 switch (_current_command->type) {
334                         case Command::OPEN:
335                                 load_dcp (_current_command->string_param);
336                                 ++_current_command;
337                                 break;
338                         case Command::PLAY:
339                                 cout << "ST: play\n";
340                                 _controls->play ();
341                                 ++_current_command;
342                                 break;
343                         case Command::WAIT:
344                                 /* int_param here is the number of milliseconds to wait */
345                                 if (_wait_remaining) {
346                                         _wait_remaining = *_wait_remaining - STRESS_TEST_CHECK_INTERVAL;
347                                         if (_wait_remaining < 0) {
348                                                 cout << "ST: wait done.\n";
349                                                 _wait_remaining = optional<int>();
350                                                 ++_current_command;
351                                         }
352                                 } else {
353                                         _wait_remaining = _current_command->int_param;
354                                         cout << "ST: waiting for " << *_wait_remaining << ".\n";
355                                 }
356                                 break;
357                         case Command::STOP:
358                                 cout << "ST: stop\n";
359                                 _controls->stop ();
360                                 ++_current_command;
361                                 break;
362                         case Command::NONE:
363                                 ++_current_command;
364                                 break;
365                         case Command::SEEK:
366                                 /* int_param here is a number between 0 and 4095, corresponding to the possible slider positions */
367                                 cout << "ST: seek to " << _current_command->int_param << "\n";
368                                 _controls->seek (_current_command->int_param);
369                                 ++_current_command;
370                                 break;
371                 }
372         }
373 #endif
374
375 #ifdef DCPOMATIC_VARIANT_SWAROOP
376         void monitor_checker_state_changed ()
377         {
378                 if (!MonitorChecker::instance()->ok()) {
379                         _viewer->stop ();
380                         error_dialog (this, _("The required display devices are not connected correctly."));
381                 }
382         }
383
384         void lock_checker_state_changed ()
385         {
386                 if (!LockFileChecker::instance()->ok()) {
387                         _viewer->stop ();
388                         error_dialog (this, _("The lock file is not present."));
389                 }
390         }
391 #endif
392
393         void setup_main_sizer (Config::PlayerMode mode)
394         {
395                 wxSizer* main_sizer = new wxBoxSizer (wxVERTICAL);
396                 if (mode != Config::PLAYER_MODE_DUAL) {
397                         main_sizer->Add (_viewer->panel(), 1, wxEXPAND | wxALIGN_CENTER_VERTICAL);
398                 }
399                 main_sizer->Add (_controls, mode == Config::PLAYER_MODE_DUAL ? 1 : 0, wxEXPAND | wxALL, 6);
400                 main_sizer->Add (_info, 0, wxEXPAND | wxALL, 6);
401                 _overall_panel->SetSizer (main_sizer);
402                 _overall_panel->Layout ();
403         }
404
405         bool playback_permitted ()
406         {
407 #ifdef DCPOMATIC_VARIANT_SWAROOP
408                 if (!MonitorChecker::instance()->ok()) {
409                         error_dialog (this, _("The required display devices are not connected correctly."));
410                         return false;
411                 }
412                 if (!LockFileChecker::instance()->ok()) {
413                         error_dialog (this, _("The lock file is not present."));
414                         return false;
415                 }
416 #endif
417                 if (!_film || !Config::instance()->respect_kdm_validity_periods()) {
418                         return true;
419                 }
420
421                 bool ok = true;
422                 BOOST_FOREACH (shared_ptr<Content> i, _film->content()) {
423                         shared_ptr<DCPContent> d = dynamic_pointer_cast<DCPContent>(i);
424                         if (d && !d->kdm_timing_window_valid()) {
425                                 ok = false;
426                         }
427                 }
428
429 #ifdef DCPOMATIC_VARIANT_SWAROOP
430                 BOOST_FOREACH (shared_ptr<Content> i, _film->content()) {
431                         shared_ptr<FFmpegContent> c = dynamic_pointer_cast<FFmpegContent>(i);
432                         if (c && !c->kdm_timing_window_valid()) {
433                                 ok = false;
434                         }
435                 }
436 #endif
437
438                 if (!ok) {
439                         error_dialog (this, _("The KDM does not allow playback of this content at this time."));
440                 }
441
442                 return ok;
443         }
444
445         void playback_started (DCPTime time)
446         {
447                 /* XXX: this only logs the first piece of content; probably should be each piece? */
448                 if (_film->content().empty()) {
449                         return;
450                 }
451
452                 shared_ptr<DCPContent> dcp = dynamic_pointer_cast<DCPContent>(_film->content().front());
453                 if (dcp) {
454                         DCPExaminer ex (dcp, true);
455                         shared_ptr<dcp::CPL> playing_cpl;
456                         BOOST_FOREACH (shared_ptr<dcp::CPL> i, ex.cpls()) {
457                                 if (!dcp->cpl() || i->id() == *dcp->cpl()) {
458                                         playing_cpl = i;
459                                 }
460                         }
461                         DCPOMATIC_ASSERT (playing_cpl);
462
463                         _controls->log (
464                                 wxString::Format(
465                                         "playback-started %s %s %s",
466                                         time.timecode(_film->video_frame_rate()).c_str(),
467                                         dcp->directories().front().string().c_str(),
468                                         playing_cpl->annotation_text().c_str()
469                                         )
470                                 );
471                 }
472
473                 shared_ptr<FFmpegContent> ffmpeg = dynamic_pointer_cast<FFmpegContent>(_film->content().front());
474                 if (ffmpeg) {
475                         _controls->log (
476                                 wxString::Format(
477                                         "playback-started %s %s",
478                                         time.timecode(_film->video_frame_rate()).c_str(),
479                                         ffmpeg->path(0).string().c_str()
480                                         )
481                                 );
482                 }
483         }
484
485         void playback_stopped (DCPTime time)
486         {
487 #ifdef DCPOMATIC_VARIANT_SWAROOP
488                 try {
489                         boost::filesystem::remove (Config::path("position"));
490                 } catch (...) {
491                         /* Never mind */
492                 }
493 #endif
494
495                 _controls->log (wxString::Format("playback-stopped %s", time.timecode(_film->video_frame_rate()).c_str()));
496         }
497
498         void set_decode_reduction (optional<int> reduction)
499         {
500                 _viewer->set_dcp_decode_reduction (reduction);
501                 _info->triggered_update ();
502                 Config::instance()->set_decode_reduction (reduction);
503         }
504
505         void load_dcp (boost::filesystem::path dir)
506         {
507                 DCPOMATIC_ASSERT (_film);
508
509                 reset_film ();
510                 try {
511                         _stress_suspended = true;
512                         shared_ptr<DCPContent> dcp (new DCPContent(dir));
513                         shared_ptr<Job> job (new ExamineContentJob(_film, dcp));
514                         _examine_job_connection = job->Finished.connect(bind(&DOMFrame::add_dcp_to_film, this, weak_ptr<Job>(job), weak_ptr<Content>(dcp)));
515                         JobManager::instance()->add (job);
516                         bool const ok = display_progress (_("DCP-o-matic Player"), _("Loading content"));
517                         if (!ok || !report_errors_from_last_job(this)) {
518                                 return;
519                         }
520 #ifndef DCPOMATIC_VARIANT_SWAROOP
521                         Config::instance()->add_to_player_history (dir);
522 #endif
523                 } catch (dcp::DCPReadError& e) {
524                         error_dialog (this, wxString::Format(_("Could not load a DCP from %s"), std_to_wx(dir.string())), std_to_wx(e.what()));
525                 }
526         }
527
528         void add_dcp_to_film (weak_ptr<Job> weak_job, weak_ptr<Content> weak_content)
529         {
530                 shared_ptr<Job> job = weak_job.lock ();
531                 if (!job || !job->finished_ok()) {
532                         return;
533                 }
534
535                 shared_ptr<Content> content = weak_content.lock ();
536                 if (!content) {
537                         return;
538                 }
539
540                 _film->add_content (content);
541                 _stress_suspended = false;
542         }
543
544         void reset_film_weak (weak_ptr<Film> weak_film)
545         {
546                 shared_ptr<Film> film = weak_film.lock ();
547                 if (film) {
548                         reset_film (film);
549                 }
550         }
551
552         void reset_film (shared_ptr<Film> film = shared_ptr<Film>(new Film(optional<boost::filesystem::path>())))
553         {
554                 _film = film;
555                 _film->set_tolerant (true);
556                 _film->set_audio_channels (MAX_DCP_AUDIO_CHANNELS);
557                 _viewer->set_film (_film);
558                 _controls->set_film (_film);
559                 _film->Change.connect (bind(&DOMFrame::film_changed, this, _1, _2));
560                 _info->triggered_update ();
561         }
562
563         void film_changed (ChangeType type, Film::Property property)
564         {
565                 if (type != CHANGE_TYPE_DONE || property != Film::CONTENT) {
566                         return;
567                 }
568
569                 if (_viewer->playing ()) {
570                         _viewer->stop ();
571                 }
572
573                 /* Start off as Flat */
574                 _film->set_container (Ratio::from_id("185"));
575
576                 BOOST_FOREACH (shared_ptr<Content> i, _film->content()) {
577                         shared_ptr<DCPContent> dcp = dynamic_pointer_cast<DCPContent>(i);
578
579                         BOOST_FOREACH (shared_ptr<TextContent> j, i->text) {
580                                 j->set_use (true);
581                         }
582
583                         if (i->video) {
584                                 Ratio const * r = Ratio::nearest_from_ratio(i->video->size().ratio());
585                                 if (r->id() == "239") {
586                                         /* Any scope content means we use scope */
587                                         _film->set_container(r);
588                                 }
589                         }
590
591                         /* Any 3D content means we use 3D mode */
592                         if (i->video && i->video->frame_type() != VIDEO_FRAME_TYPE_2D) {
593                                 _film->set_three_d (true);
594                         }
595                 }
596
597                 _viewer->seek (DCPTime(), true);
598                 _info->triggered_update ();
599
600                 set_menu_sensitivity ();
601
602                 wxMenuItemList old = _cpl_menu->GetMenuItems();
603                 for (wxMenuItemList::iterator i = old.begin(); i != old.end(); ++i) {
604                         _cpl_menu->Remove (*i);
605                 }
606
607                 if (_film->content().size() == 1) {
608                         /* Offer a CPL menu */
609                         shared_ptr<DCPContent> first = dynamic_pointer_cast<DCPContent>(_film->content().front());
610                         if (first) {
611                                 DCPExaminer ex (first, true);
612                                 int id = ID_view_cpl;
613                                 BOOST_FOREACH (shared_ptr<dcp::CPL> i, ex.cpls()) {
614                                         wxMenuItem* j = _cpl_menu->AppendRadioItem(
615                                                 id,
616                                                 wxString::Format("%s (%s)", std_to_wx(i->annotation_text()).data(), std_to_wx(i->id()).data())
617                                                 );
618                                         j->Check(!first->cpl() || i->id() == *first->cpl());
619                                         ++id;
620                                 }
621                         }
622                 }
623         }
624
625 private:
626
627         bool report_errors_from_last_job (wxWindow* parent) const
628         {
629                 JobManager* jm = JobManager::instance ();
630
631                 DCPOMATIC_ASSERT (!jm->get().empty());
632
633                 shared_ptr<Job> last = jm->get().back();
634                 if (last->finished_in_error()) {
635                         error_dialog(parent, wxString::Format(_("Could not load DCP.\n\n%s."), std_to_wx(last->error_summary()).data()), std_to_wx(last->error_details()));
636                         return false;
637                 }
638
639                 return true;
640         }
641
642         void setup_menu (wxMenuBar* m)
643         {
644                 _file_menu = new wxMenu;
645                 _file_menu->Append (ID_file_open, _("&Open...\tCtrl-O"));
646                 _file_add_ov = _file_menu->Append (ID_file_add_ov, _("&Add OV..."));
647                 _file_add_kdm = _file_menu->Append (ID_file_add_kdm, _("Add &KDM..."));
648
649                 _history_position = _file_menu->GetMenuItems().GetCount();
650
651                 _file_menu->AppendSeparator ();
652                 _file_menu->Append (ID_file_close, _("&Close"));
653                 _file_menu->AppendSeparator ();
654
655 #ifdef __WXOSX__
656                 _file_menu->Append (wxID_EXIT, _("&Exit"));
657 #else
658                 _file_menu->Append (wxID_EXIT, _("&Quit"));
659 #endif
660
661 #ifdef __WXOSX__
662                 wxMenuItem* prefs = _file_menu->Append (wxID_PREFERENCES, _("&Preferences...\tCtrl-P"));
663 #else
664                 wxMenu* edit = new wxMenu;
665                 wxMenuItem* prefs = edit->Append (wxID_PREFERENCES, _("&Preferences...\tCtrl-P"));
666 #endif
667
668                 prefs->Enable (Config::instance()->have_write_permission());
669
670                 _cpl_menu = new wxMenu;
671
672                 wxMenu* view = new wxMenu;
673                 optional<int> c = Config::instance()->decode_reduction();
674                 _view_cpl = view->Append(ID_view_cpl, _("CPL"), _cpl_menu);
675                 view->AppendSeparator();
676 #ifndef DCPOMATIC_VARIANT_SWAROOP
677                 _view_full_screen = view->AppendCheckItem(ID_view_full_screen, _("Full screen\tF11"));
678                 _view_dual_screen = view->AppendCheckItem(ID_view_dual_screen, _("Dual screen\tShift+F11"));
679 #endif
680                 setup_menu ();
681                 view->AppendSeparator();
682                 view->Append(ID_view_closed_captions, _("Closed captions..."));
683                 view->AppendSeparator();
684                 view->AppendRadioItem(ID_view_scale_appropriate, _("Set decode resolution to match display"))->Check(!static_cast<bool>(c));
685                 view->AppendRadioItem(ID_view_scale_full, _("Decode at full resolution"))->Check(c && c.get() == 0);
686                 view->AppendRadioItem(ID_view_scale_half, _("Decode at half resolution"))->Check(c && c.get() == 1);
687                 view->AppendRadioItem(ID_view_scale_quarter, _("Decode at quarter resolution"))->Check(c && c.get() == 2);
688
689                 wxMenu* tools = new wxMenu;
690                 _tools_verify = tools->Append (ID_tools_verify, _("Verify DCP"));
691                 tools->AppendSeparator ();
692                 tools->Append (ID_tools_check_for_updates, _("Check for updates"));
693                 tools->Append (ID_tools_timing, _("Timing..."));
694                 tools->Append (ID_tools_system_information, _("System information..."));
695
696                 wxMenu* help = new wxMenu;
697 #ifdef __WXOSX__
698                 help->Append (wxID_ABOUT, _("About DCP-o-matic"));
699 #else
700                 help->Append (wxID_ABOUT, _("About"));
701 #endif
702                 help->Append (ID_help_report_a_problem, _("Report a problem..."));
703
704                 m->Append (_file_menu, _("&File"));
705 #ifndef __WXOSX__
706                 m->Append (edit, _("&Edit"));
707 #endif
708                 m->Append (view, _("&View"));
709                 m->Append (tools, _("&Tools"));
710                 m->Append (help, _("&Help"));
711         }
712
713         void file_open ()
714         {
715                 wxString d = wxStandardPaths::Get().GetDocumentsDir();
716                 if (Config::instance()->last_player_load_directory()) {
717                         d = std_to_wx (Config::instance()->last_player_load_directory()->string());
718                 }
719
720                 wxDirDialog* c = new wxDirDialog (this, _("Select DCP to open"), d, wxDEFAULT_DIALOG_STYLE | wxDD_DIR_MUST_EXIST);
721
722                 int r;
723                 while (true) {
724                         r = c->ShowModal ();
725                         if (r == wxID_OK && c->GetPath() == wxStandardPaths::Get().GetDocumentsDir()) {
726                                 error_dialog (this, _("You did not select a folder.  Make sure that you select a folder before clicking Open."));
727                         } else {
728                                 break;
729                         }
730                 }
731
732                 if (r == wxID_OK) {
733                         boost::filesystem::path const dcp (wx_to_std (c->GetPath ()));
734                         load_dcp (dcp);
735                         Config::instance()->set_last_player_load_directory (dcp.parent_path());
736                 }
737
738                 c->Destroy ();
739         }
740
741         void file_add_ov ()
742         {
743                 wxDirDialog* c = new wxDirDialog (
744                         this,
745                         _("Select DCP to open as OV"),
746                         wxStandardPaths::Get().GetDocumentsDir(),
747                         wxDEFAULT_DIALOG_STYLE | wxDD_DIR_MUST_EXIST
748                         );
749
750                 int r;
751                 while (true) {
752                         r = c->ShowModal ();
753                         if (r == wxID_OK && c->GetPath() == wxStandardPaths::Get().GetDocumentsDir()) {
754                                 error_dialog (this, _("You did not select a folder.  Make sure that you select a folder before clicking Open."));
755                         } else {
756                                 break;
757                         }
758                 }
759
760                 if (r == wxID_OK) {
761                         DCPOMATIC_ASSERT (_film);
762                         shared_ptr<DCPContent> dcp = boost::dynamic_pointer_cast<DCPContent>(_film->content().front());
763                         DCPOMATIC_ASSERT (dcp);
764                         dcp->add_ov (wx_to_std(c->GetPath()));
765                         JobManager::instance()->add(shared_ptr<Job>(new ExamineContentJob (_film, dcp)));
766                         bool const ok = display_progress (_("DCP-o-matic Player"), _("Loading content"));
767                         if (!ok || !report_errors_from_last_job(this)) {
768                                 return;
769                         }
770                         BOOST_FOREACH (shared_ptr<TextContent> i, dcp->text) {
771                                 i->set_use (true);
772                         }
773                         if (dcp->video) {
774                                 Ratio const * r = Ratio::nearest_from_ratio(dcp->video->size().ratio());
775                                 if (r) {
776                                         _film->set_container(r);
777                                 }
778                         }
779                 }
780
781                 c->Destroy ();
782                 _info->triggered_update ();
783         }
784
785         void file_add_kdm ()
786         {
787                 wxFileDialog* d = new wxFileDialog (this, _("Select KDM"));
788
789                 if (d->ShowModal() == wxID_OK) {
790                         DCPOMATIC_ASSERT (_film);
791 #ifdef DCPOMATIC_VARIANT_SWAROOP
792                         shared_ptr<FFmpegContent> ffmpeg = boost::dynamic_pointer_cast<FFmpegContent>(_film->content().front());
793                         if (ffmpeg) {
794                                 try {
795                                         ffmpeg->add_kdm (EncryptedECinemaKDM(dcp::file_to_string(wx_to_std(d->GetPath()), MAX_KDM_SIZE)));
796                                 } catch (exception& e) {
797                                         error_dialog (this, wxString::Format(_("Could not load KDM.")), std_to_wx(e.what()));
798                                         d->Destroy();
799                                         return;
800                                 }
801                         }
802 #endif
803                         shared_ptr<DCPContent> dcp = boost::dynamic_pointer_cast<DCPContent>(_film->content().front());
804 #ifndef DCPOMATIC_VARIANT_SWAROOP
805                         DCPOMATIC_ASSERT (dcp);
806 #endif
807                         try {
808                                 if (dcp) {
809                                         dcp->add_kdm (dcp::EncryptedKDM(dcp::file_to_string(wx_to_std(d->GetPath()), MAX_KDM_SIZE)));
810                                         dcp->examine (_film, shared_ptr<Job>());
811                                 }
812                         } catch (exception& e) {
813                                 error_dialog (this, wxString::Format (_("Could not load KDM.")), std_to_wx(e.what()));
814                                 d->Destroy ();
815                                 return;
816                         }
817                 }
818
819                 d->Destroy ();
820                 _info->triggered_update ();
821         }
822
823         void file_history (wxCommandEvent& event)
824         {
825                 vector<boost::filesystem::path> history = Config::instance()->player_history ();
826                 int n = event.GetId() - ID_file_history;
827                 if (n >= 0 && n < static_cast<int> (history.size ())) {
828                         try {
829                                 load_dcp (history[n]);
830                         } catch (exception& e) {
831                                 error_dialog (0, std_to_wx(String::compose(wx_to_std(_("Could not load DCP %1.")), history[n])), std_to_wx(e.what()));
832                         }
833                 }
834         }
835
836         void file_close ()
837         {
838                 reset_film ();
839                 _info->triggered_update ();
840                 set_menu_sensitivity ();
841         }
842
843         void file_exit ()
844         {
845                 Close ();
846         }
847
848         void edit_preferences ()
849         {
850                 if (!Config::instance()->have_write_permission()) {
851                         return;
852                 }
853
854                 if (!_config_dialog) {
855                         _config_dialog = create_player_config_dialog ();
856                 }
857                 _config_dialog->Show (this);
858         }
859
860         void view_cpl (wxCommandEvent& ev)
861         {
862                 shared_ptr<DCPContent> dcp = boost::dynamic_pointer_cast<DCPContent>(_film->content().front());
863                 DCPOMATIC_ASSERT (dcp);
864                 DCPExaminer ex (dcp, true);
865                 int id = ev.GetId() - ID_view_cpl;
866                 DCPOMATIC_ASSERT (id >= 0);
867                 DCPOMATIC_ASSERT (id < int(ex.cpls().size()));
868                 list<shared_ptr<dcp::CPL> > cpls = ex.cpls();
869                 list<shared_ptr<dcp::CPL> >::iterator i = cpls.begin();
870                 while (id > 0) {
871                         ++i;
872                         --id;
873                 }
874
875                 dcp->set_cpl ((*i)->id());
876                 dcp->examine (_film, shared_ptr<Job>());
877         }
878
879         void view_full_screen ()
880         {
881                 if (_mode == Config::PLAYER_MODE_FULL) {
882                         _mode = Config::PLAYER_MODE_WINDOW;
883                 } else {
884                         _mode = Config::PLAYER_MODE_FULL;
885                 }
886                 setup_screen ();
887                 setup_menu ();
888         }
889
890         void view_dual_screen ()
891         {
892                 if (_mode == Config::PLAYER_MODE_DUAL) {
893                         _mode = Config::PLAYER_MODE_WINDOW;
894                 } else {
895                         _mode = Config::PLAYER_MODE_DUAL;
896                 }
897                 setup_screen ();
898                 setup_menu ();
899         }
900
901         void setup_menu ()
902         {
903                 if (_view_full_screen) {
904                         _view_full_screen->Check (_mode == Config::PLAYER_MODE_FULL);
905                 }
906                 if (_view_dual_screen) {
907                         _view_dual_screen->Check (_mode == Config::PLAYER_MODE_DUAL);
908                 }
909         }
910
911         void setup_screen ()
912         {
913                 _controls->Show (_mode != Config::PLAYER_MODE_FULL);
914                 _info->Show (_mode != Config::PLAYER_MODE_FULL);
915                 _overall_panel->SetBackgroundColour (_mode == Config::PLAYER_MODE_FULL ? wxColour(0, 0, 0) : wxNullColour);
916                 ShowFullScreen (_mode == Config::PLAYER_MODE_FULL);
917                 _viewer->set_pad_black (_mode != Config::PLAYER_MODE_WINDOW);
918
919                 if (_mode == Config::PLAYER_MODE_DUAL) {
920                         _dual_screen = new wxFrame (this, wxID_ANY, wxT(""));
921                         _dual_screen->SetBackgroundColour (wxColour(0, 0, 0));
922                         _dual_screen->ShowFullScreen (true);
923                         _viewer->panel()->Reparent (_dual_screen);
924                         _dual_screen->Show ();
925                         if (wxDisplay::GetCount() > 1) {
926                                 switch (Config::instance()->image_display()) {
927                                 case 0:
928                                         _dual_screen->Move (0, 0);
929                                         Move (wxDisplay(0).GetClientArea().GetWidth(), 0);
930                                         break;
931                                 case 1:
932                                         _dual_screen->Move (wxDisplay(0).GetClientArea().GetWidth(), 0);
933                                         // (0, 0) doesn't seem to work for some strange reason
934                                         Move (8, 8);
935                                         break;
936                                 }
937                         }
938                 } else {
939                         if (_dual_screen) {
940                                 _viewer->panel()->Reparent (_overall_panel);
941                                 _dual_screen->Destroy ();
942                                 _dual_screen = 0;
943                         }
944                 }
945
946                 setup_main_sizer (_mode);
947         }
948
949         void view_closed_captions ()
950         {
951                 _viewer->show_closed_captions ();
952         }
953
954         void tools_verify ()
955         {
956                 shared_ptr<DCPContent> dcp = boost::dynamic_pointer_cast<DCPContent>(_film->content().front());
957                 DCPOMATIC_ASSERT (dcp);
958
959                 JobManager* jm = JobManager::instance ();
960                 jm->add (shared_ptr<Job> (new VerifyDCPJob (dcp->directories())));
961                 bool const ok = display_progress (_("DCP-o-matic Player"), _("Verifying DCP"));
962                 if (!ok) {
963                         return;
964                 }
965
966                 DCPOMATIC_ASSERT (!jm->get().empty());
967                 shared_ptr<VerifyDCPJob> last = dynamic_pointer_cast<VerifyDCPJob> (jm->get().back());
968                 DCPOMATIC_ASSERT (last);
969
970                 VerifyDCPDialog* d = new VerifyDCPDialog (this, last);
971                 d->ShowModal ();
972                 d->Destroy ();
973         }
974
975         void tools_check_for_updates ()
976         {
977                 UpdateChecker::instance()->run ();
978                 _update_news_requested = true;
979         }
980
981         void tools_timing ()
982         {
983                 TimerDisplay* d = new TimerDisplay (this, _viewer->state_timer(), _viewer->gets());
984                 d->ShowModal ();
985                 d->Destroy ();
986         }
987
988         void tools_system_information ()
989         {
990                 if (!_system_information_dialog) {
991                         _system_information_dialog = new SystemInformationDialog (this, _viewer);
992                 }
993
994                 _system_information_dialog->Show ();
995         }
996
997         void help_about ()
998         {
999                 AboutDialog* d = new AboutDialog (this);
1000                 d->ShowModal ();
1001                 d->Destroy ();
1002         }
1003
1004         void help_report_a_problem ()
1005         {
1006                 ReportProblemDialog* d = new ReportProblemDialog (this);
1007                 if (d->ShowModal () == wxID_OK) {
1008                         d->report ();
1009                 }
1010                 d->Destroy ();
1011         }
1012
1013         void update_checker_state_changed ()
1014         {
1015                 UpdateChecker* uc = UpdateChecker::instance ();
1016
1017                 bool const announce =
1018                         _update_news_requested ||
1019                         (uc->stable() && Config::instance()->check_for_updates()) ||
1020                         (uc->test() && Config::instance()->check_for_updates() && Config::instance()->check_for_test_updates());
1021
1022                 _update_news_requested = false;
1023
1024                 if (!announce) {
1025                         return;
1026                 }
1027
1028                 if (uc->state() == UpdateChecker::YES) {
1029                         UpdateDialog* dialog = new UpdateDialog (this, uc->stable (), uc->test ());
1030                         dialog->ShowModal ();
1031                         dialog->Destroy ();
1032                 } else if (uc->state() == UpdateChecker::FAILED) {
1033                         error_dialog (this, _("The DCP-o-matic download server could not be contacted."));
1034                 } else {
1035                         error_dialog (this, _("There are no new versions of DCP-o-matic available."));
1036                 }
1037
1038                 _update_news_requested = false;
1039         }
1040
1041         void config_changed (Config::Property prop)
1042         {
1043                 /* Instantly save any config changes when using the player GUI */
1044                 try {
1045                         Config::instance()->write_config();
1046                 } catch (FileError& e) {
1047                         if (prop != Config::HISTORY) {
1048                                 error_dialog (
1049                                         this,
1050                                         wxString::Format(
1051                                                 _("Could not write to config file at %s.  Your changes have not been saved."),
1052                                                 std_to_wx(e.file().string())
1053                                                 )
1054                                         );
1055                         }
1056                 } catch (exception& e) {
1057                         error_dialog (
1058                                 this,
1059                                 _("Could not write to config file.  Your changes have not been saved.")
1060                                 );
1061                 }
1062
1063                 update_from_config (prop);
1064         }
1065
1066         void update_from_config (Config::Property prop)
1067         {
1068                 for (int i = 0; i < _history_items; ++i) {
1069                         delete _file_menu->Remove (ID_file_history + i);
1070                 }
1071
1072                 if (_history_separator) {
1073                         _file_menu->Remove (_history_separator);
1074                 }
1075                 delete _history_separator;
1076                 _history_separator = 0;
1077
1078                 int pos = _history_position;
1079
1080                 /* Clear out non-existant history items before we re-build the menu */
1081                 Config::instance()->clean_player_history ();
1082                 vector<boost::filesystem::path> history = Config::instance()->player_history ();
1083
1084                 if (!history.empty ()) {
1085                         _history_separator = _file_menu->InsertSeparator (pos++);
1086                 }
1087
1088                 for (size_t i = 0; i < history.size(); ++i) {
1089                         string s;
1090                         if (i < 9) {
1091                                 s = String::compose ("&%1 %2", i + 1, history[i].string());
1092                         } else {
1093                                 s = history[i].string();
1094                         }
1095                         _file_menu->Insert (pos++, ID_file_history + i, std_to_wx (s));
1096                 }
1097
1098                 _history_items = history.size ();
1099
1100                 if (prop == Config::PLAYER_DEBUG_LOG) {
1101                         optional<boost::filesystem::path> p = Config::instance()->player_debug_log_file();
1102                         if (p) {
1103                                 dcpomatic_log.reset (new FileLog(*p));
1104                         } else {
1105                                 dcpomatic_log.reset (new NullLog());
1106                         }
1107                         dcpomatic_log->set_types (LogEntry::TYPE_GENERAL | LogEntry::TYPE_WARNING | LogEntry::TYPE_ERROR | LogEntry::TYPE_DEBUG_PLAYER);
1108                 }
1109         }
1110
1111         void set_menu_sensitivity ()
1112         {
1113                 _tools_verify->Enable (static_cast<bool>(_film));
1114                 _file_add_ov->Enable (static_cast<bool>(_film));
1115                 _file_add_kdm->Enable (static_cast<bool>(_film));
1116                 _view_cpl->Enable (static_cast<bool>(_film));
1117         }
1118
1119         void start_stop_pressed ()
1120         {
1121                 if (_viewer->playing()) {
1122                         _viewer->stop();
1123                 } else {
1124                         _viewer->start();
1125                 }
1126         }
1127
1128         void back_frame ()
1129         {
1130                 _viewer->seek_by (-_viewer->one_video_frame(), true);
1131         }
1132
1133         void forward_frame ()
1134         {
1135                 _viewer->seek_by (_viewer->one_video_frame(), true);
1136         }
1137
1138 private:
1139
1140         wxFrame* _dual_screen;
1141         bool _update_news_requested;
1142         PlayerInformation* _info;
1143         Config::PlayerMode _mode;
1144         wxPreferencesEditor* _config_dialog;
1145         wxPanel* _overall_panel;
1146         wxMenu* _file_menu;
1147         wxMenuItem* _view_cpl;
1148         wxMenu* _cpl_menu;
1149         int _history_items;
1150         int _history_position;
1151         wxMenuItem* _history_separator;
1152         shared_ptr<FilmViewer> _viewer;
1153         Controls* _controls;
1154         SystemInformationDialog* _system_information_dialog;
1155         boost::shared_ptr<Film> _film;
1156         boost::signals2::scoped_connection _config_changed_connection;
1157         boost::signals2::scoped_connection _examine_job_connection;
1158         wxMenuItem* _file_add_ov;
1159         wxMenuItem* _file_add_kdm;
1160         wxMenuItem* _tools_verify;
1161         wxMenuItem* _view_full_screen;
1162         wxMenuItem* _view_dual_screen;
1163 #ifdef DCPOMATIC_PLAYER_STRESS_TEST
1164         wxTimer _timer;
1165         list<Command> _commands;
1166         list<Command>::const_iterator _current_command;
1167         /** Remaining time that the script must wait, in milliseconds */
1168         optional<int> _wait_remaining;
1169         bool _stress_suspended;
1170 #endif
1171 };
1172
1173 static const wxCmdLineEntryDesc command_line_description[] = {
1174         { wxCMD_LINE_PARAM, 0, 0, "DCP to load or create", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
1175         { wxCMD_LINE_OPTION, "c", "config", "Directory containing config.xml", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
1176 #ifdef DCPOMATIC_PLAYER_STRESS_TEST
1177         { wxCMD_LINE_OPTION, "s", "stress", "File containing description of stress test", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
1178 #endif
1179         { wxCMD_LINE_NONE, "", "", "", wxCmdLineParamType (0), 0 }
1180 };
1181
1182 class PlayServer : public Server
1183 {
1184 public:
1185         explicit PlayServer (DOMFrame* frame)
1186                 : Server (PLAYER_PLAY_PORT)
1187                 , _frame (frame)
1188         {}
1189
1190         void handle (shared_ptr<Socket> socket)
1191         {
1192                 try {
1193                         int const length = socket->read_uint32 ();
1194                         scoped_array<char> buffer (new char[length]);
1195                         socket->read (reinterpret_cast<uint8_t*> (buffer.get()), length);
1196                         string s (buffer.get());
1197                         signal_manager->when_idle (bind (&DOMFrame::load_dcp, _frame, s));
1198                         socket->write (reinterpret_cast<uint8_t const *> ("OK"), 3);
1199                 } catch (...) {
1200
1201                 }
1202         }
1203
1204 private:
1205         DOMFrame* _frame;
1206 };
1207
1208 /** @class App
1209  *  @brief The magic App class for wxWidgets.
1210  */
1211 class App : public wxApp
1212 {
1213 public:
1214         App ()
1215                 : wxApp ()
1216                 , _frame (0)
1217         {
1218 #ifdef DCPOMATIC_LINUX
1219                 XInitThreads ();
1220 #endif
1221         }
1222
1223 private:
1224
1225         bool OnInit ()
1226         {
1227                 wxSplashScreen* splash = 0;
1228                 try {
1229                         wxInitAllImageHandlers ();
1230
1231                         Config::FailedToLoad.connect (boost::bind (&App::config_failed_to_load, this));
1232                         Config::Warning.connect (boost::bind (&App::config_warning, this, _1));
1233
1234                         splash = maybe_show_splash ();
1235
1236                         SetAppName (_("DCP-o-matic Player"));
1237
1238                         if (!wxApp::OnInit()) {
1239                                 return false;
1240                         }
1241
1242 #ifdef DCPOMATIC_LINUX
1243                         unsetenv ("UBUNTU_MENUPROXY");
1244 #endif
1245
1246 #ifdef __WXOSX__
1247                         ProcessSerialNumber serial;
1248                         GetCurrentProcess (&serial);
1249                         TransformProcessType (&serial, kProcessTransformToForegroundApplication);
1250 #endif
1251
1252                         dcpomatic_setup_path_encoding ();
1253
1254                         /* Enable i18n; this will create a Config object
1255                            to look for a force-configured language.  This Config
1256                            object will be wrong, however, because dcpomatic_setup
1257                            hasn't yet been called and there aren't any filters etc.
1258                            set up yet.
1259                         */
1260                         dcpomatic_setup_i18n ();
1261
1262                         /* Set things up, including filters etc.
1263                            which will now be internationalised correctly.
1264                         */
1265                         dcpomatic_setup ();
1266
1267                         /* Force the configuration to be re-loaded correctly next
1268                            time it is needed.
1269                         */
1270                         Config::drop ();
1271
1272                         signal_manager = new wxSignalManager (this);
1273
1274                         _frame = new DOMFrame ();
1275                         SetTopWindow (_frame);
1276                         _frame->Maximize ();
1277                         if (splash) {
1278                                 splash->Destroy ();
1279                                 splash = 0;
1280                         }
1281                         _frame->Show ();
1282
1283                         PlayServer* server = new PlayServer (_frame);
1284                         new thread (boost::bind (&PlayServer::run, server));
1285
1286                         if (!_dcp_to_load.empty() && boost::filesystem::is_directory (_dcp_to_load)) {
1287                                 try {
1288                                         _frame->load_dcp (_dcp_to_load);
1289                                 } catch (exception& e) {
1290                                         error_dialog (0, std_to_wx (String::compose (wx_to_std (_("Could not load DCP %1.")), _dcp_to_load)), std_to_wx(e.what()));
1291                                 }
1292                         }
1293
1294 #ifdef DCPOMATIC_PLAYER_STRESS_TEST
1295                         if (_stress) {
1296                                 try {
1297                                         _frame->stress (_stress.get());
1298                                 } catch (exception& e) {
1299                                         error_dialog (0, wxString::Format("Could not load stress test file %s", std_to_wx(*_stress)));
1300                                 }
1301                         }
1302 #endif
1303
1304                         Bind (wxEVT_IDLE, boost::bind (&App::idle, this));
1305
1306                         if (Config::instance()->check_for_updates ()) {
1307                                 UpdateChecker::instance()->run ();
1308                         }
1309                 }
1310                 catch (exception& e)
1311                 {
1312                         if (splash) {
1313                                 splash->Destroy ();
1314                         }
1315                         error_dialog (0, _("DCP-o-matic Player could not start."), std_to_wx(e.what()));
1316                 }
1317
1318                 return true;
1319         }
1320
1321         void OnInitCmdLine (wxCmdLineParser& parser)
1322         {
1323                 parser.SetDesc (command_line_description);
1324                 parser.SetSwitchChars (wxT ("-"));
1325         }
1326
1327         bool OnCmdLineParsed (wxCmdLineParser& parser)
1328         {
1329                 if (parser.GetParamCount() > 0) {
1330                         _dcp_to_load = wx_to_std (parser.GetParam (0));
1331                 }
1332
1333                 wxString config;
1334                 if (parser.Found("c", &config)) {
1335                         Config::override_path = wx_to_std (config);
1336                 }
1337 #ifdef DCPOMATIC_PLAYER_STRESS_TEST
1338                 wxString stress;
1339                 if (parser.Found("s", &stress)) {
1340                         _stress = wx_to_std (stress);
1341                 }
1342 #endif
1343
1344                 return true;
1345         }
1346
1347         void report_exception ()
1348         {
1349                 try {
1350                         throw;
1351                 } catch (FileError& e) {
1352                         error_dialog (
1353                                 0,
1354                                 wxString::Format (
1355                                         _("An exception occurred: %s (%s)\n\n") + REPORT_PROBLEM,
1356                                         std_to_wx (e.what()),
1357                                         std_to_wx (e.file().string().c_str ())
1358                                         )
1359                                 );
1360                 } catch (exception& e) {
1361                         error_dialog (
1362                                 0,
1363                                 wxString::Format (
1364                                         _("An exception occurred: %s.\n\n") + REPORT_PROBLEM,
1365                                         std_to_wx (e.what ())
1366                                         )
1367                                 );
1368                 } catch (...) {
1369                         error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
1370                 }
1371         }
1372
1373         /* An unhandled exception has occurred inside the main event loop */
1374         bool OnExceptionInMainLoop ()
1375         {
1376                 report_exception ();
1377                 /* This will terminate the program */
1378                 return false;
1379         }
1380
1381         void OnUnhandledException ()
1382         {
1383                 report_exception ();
1384         }
1385
1386         void idle ()
1387         {
1388                 signal_manager->ui_idle ();
1389         }
1390
1391         void config_failed_to_load ()
1392         {
1393                 message_dialog (_frame, _("The existing configuration failed to load.  Default values will be used instead.  These may take a short time to create."));
1394         }
1395
1396         void config_warning (string m)
1397         {
1398                 message_dialog (_frame, std_to_wx (m));
1399         }
1400
1401         DOMFrame* _frame;
1402         string _dcp_to_load;
1403 #ifdef DCPOMATIC_PLAYER_STRESS_TEST
1404         boost::optional<string> _stress;
1405 #endif
1406 };
1407
1408 IMPLEMENT_APP (App)