only call IPlayerCallback::OnPlayBackSpeedChanged if the speed has actually changed
[vuplus_xbmc] / xbmc / Application.cpp
1 /*
2  *      Copyright (C) 2005-2008 Team XBMC
3  *      http://xbmc.org
4  *
5  *  This Program is free software; you can redistribute it and/or modify
6  *  it under the terms of the GNU General Public License as published by
7  *  the Free Software Foundation; either version 2, or (at your option)
8  *  any later version.
9  *
10  *  This Program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  *  GNU General Public License for more details.
14  *
15  *  You should have received a copy of the GNU General Public License
16  *  along with XBMC; see the file COPYING.  If not, write to
17  *  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
18  *  http://www.gnu.org/copyleft/gpl.html
19  *
20  */
21
22 #include "threads/SystemClock.h"
23 #include "system.h"
24 #include "Application.h"
25 #include "interfaces/Builtins.h"
26 #include "utils/Variant.h"
27 #include "utils/Splash.h"
28 #include "input/KeyboardLayoutConfiguration.h"
29 #include "LangInfo.h"
30 #include "Util.h"
31 #include "pictures/Picture.h"
32 #include "guilib/TextureManager.h"
33 #include "cores/dvdplayer/DVDFileInfo.h"
34 #include "PlayListPlayer.h"
35 #include "Autorun.h"
36 #ifdef HAS_LCD
37 #include "utils/LCDFactory.h"
38 #endif
39 #include "guilib/GUIControlProfiler.h"
40 #include "utils/LangCodeExpander.h"
41 #include "GUIInfoManager.h"
42 #include "playlists/PlayListFactory.h"
43 #include "guilib/GUIFontManager.h"
44 #include "guilib/GUIColorManager.h"
45 #include "guilib/GUITextLayout.h"
46 #include "addons/Skin.h"
47 #ifdef HAS_PYTHON
48 #include "interfaces/python/XBPython.h"
49 #endif
50 #include "input/ButtonTranslator.h"
51 #include "guilib/GUIAudioManager.h"
52 #include "network/libscrobbler/lastfmscrobbler.h"
53 #include "network/libscrobbler/librefmscrobbler.h"
54 #include "GUIPassword.h"
55 #include "input/InertialScrollingHandler.h"
56 #include "ApplicationMessenger.h"
57 #include "SectionLoader.h"
58 #include "cores/DllLoader/DllLoaderContainer.h"
59 #include "GUIUserMessages.h"
60 #include "filesystem/DirectoryCache.h"
61 #include "filesystem/StackDirectory.h"
62 #include "filesystem/SpecialProtocol.h"
63 #include "filesystem/DllLibCurl.h"
64 #include "filesystem/MythSession.h"
65 #include "filesystem/PluginDirectory.h"
66 #ifdef HAS_FILESYSTEM_SAP
67 #include "filesystem/SAPDirectory.h"
68 #endif
69 #ifdef HAS_FILESYSTEM_HTSP
70 #include "filesystem/HTSPDirectory.h"
71 #endif
72 #include "utils/TuxBoxUtil.h"
73 #include "utils/SystemInfo.h"
74 #include "utils/TimeUtils.h"
75 #include "GUILargeTextureManager.h"
76 #include "TextureCache.h"
77 #include "music/LastFmManager.h"
78 #include "playlists/SmartPlayList.h"
79 #ifdef HAS_FILESYSTEM_RAR
80 #include "filesystem/RarManager.h"
81 #endif
82 #include "playlists/PlayList.h"
83 #include "windowing/WindowingFactory.h"
84 #include "powermanagement/PowerManager.h"
85 #include "powermanagement/DPMSSupport.h"
86 #include "settings/Settings.h"
87 #include "settings/AdvancedSettings.h"
88 #include "guilib/LocalizeStrings.h"
89 #include "utils/CPUInfo.h"
90
91 #include "input/KeyboardStat.h"
92 #include "input/XBMC_vkeys.h"
93 #include "input/MouseStat.h"
94
95 #if defined(FILESYSTEM) && !defined(_LINUX)
96 #include "filesystem/FileDAAP.h"
97 #endif
98 #ifdef HAS_UPNP
99 #include "network/UPnP.h"
100 #include "filesystem/UPnPDirectory.h"
101 #endif
102 #if defined(_LINUX) && defined(HAS_FILESYSTEM_SMB)
103 #include "filesystem/SMBDirectory.h"
104 #endif
105 #ifdef HAS_FILESYSTEM_NFS
106 #include "filesystem/FileNFS.h"
107 #endif
108 #ifdef HAS_FILESYSTEM_SFTP
109 #include "filesystem/FileSFTP.h"
110 #endif
111 #include "PartyModeManager.h"
112 #ifdef HAS_VIDEO_PLAYBACK
113 #include "cores/VideoRenderers/RenderManager.h"
114 #endif
115 #ifdef HAS_KARAOKE
116 #include "music/karaoke/karaokelyricsmanager.h"
117 #include "music/karaoke/GUIDialogKaraokeSongSelector.h"
118 #include "music/karaoke/GUIWindowKaraokeLyrics.h"
119 #endif
120 #include "guilib/AudioContext.h"
121 #include "guilib/GUIFontTTF.h"
122 #include "network/Network.h"
123 #include "storage/IoSupport.h"
124 #include "network/Zeroconf.h"
125 #include "network/ZeroconfBrowser.h"
126 #ifndef _LINUX
127 #include "utils/Win32Exception.h"
128 #endif
129 #ifdef HAS_EVENT_SERVER
130 #include "network/EventServer.h"
131 #endif
132 #ifdef HAS_DBUS_SERVER
133 #include "interfaces/DbusServer.h"
134 #endif
135 #ifdef HAS_HTTPAPI
136 #include "interfaces/http-api/XBMChttp.h"
137 #endif
138 #ifdef HAS_JSONRPC
139 #include "interfaces/json-rpc/JSONRPC.h"
140 #include "network/TCPServer.h"
141 #endif
142 #ifdef HAS_AIRPLAY
143 #include "network/AirPlayServer.h"
144 #endif
145 #ifdef HAS_AIRTUNES
146 #include "network/AirTunesServer.h"
147 #endif
148 #if defined(HAVE_LIBCRYSTALHD)
149 #include "cores/dvdplayer/DVDCodecs/Video/CrystalHD.h"
150 #endif
151 #include "interfaces/AnnouncementManager.h"
152 #include "peripherals/Peripherals.h"
153 #ifdef HAVE_LIBCEC
154 #include "peripherals/devices/PeripheralCecAdapter.h"
155 #endif
156 #include "peripherals/dialogs/GUIDialogPeripheralManager.h"
157 #include "peripherals/dialogs/GUIDialogPeripheralSettings.h"
158
159 // Windows includes
160 #include "guilib/GUIWindowManager.h"
161 #include "windows/GUIWindowHome.h"
162 #include "guilib/GUIStandardWindow.h"
163 #include "settings/GUIWindowSettings.h"
164 #include "windows/GUIWindowFileManager.h"
165 #include "settings/GUIWindowSettingsCategory.h"
166 #include "music/windows/GUIWindowMusicPlaylist.h"
167 #include "music/windows/GUIWindowMusicSongs.h"
168 #include "music/windows/GUIWindowMusicNav.h"
169 #include "music/windows/GUIWindowMusicPlaylistEditor.h"
170 #include "video/windows/GUIWindowVideoPlaylist.h"
171 #include "music/dialogs/GUIDialogMusicInfo.h"
172 #include "video/dialogs/GUIDialogVideoInfo.h"
173 #include "video/windows/GUIWindowVideoNav.h"
174 #include "settings/GUIWindowSettingsProfile.h"
175 #ifdef HAS_GL
176 #include "rendering/gl/GUIWindowTestPatternGL.h"
177 #endif
178 #ifdef HAS_DX
179 #include "rendering/dx/GUIWindowTestPatternDX.h"
180 #endif
181 #include "settings/GUIWindowSettingsScreenCalibration.h"
182 #include "programs/GUIWindowPrograms.h"
183 #include "pictures/GUIWindowPictures.h"
184 #include "windows/GUIWindowWeather.h"
185 #include "windows/GUIWindowLoginScreen.h"
186 #include "addons/GUIWindowAddonBrowser.h"
187 #include "music/windows/GUIWindowVisualisation.h"
188 #include "windows/GUIWindowDebugInfo.h"
189 #include "windows/GUIWindowPointer.h"
190 #include "windows/GUIWindowSystemInfo.h"
191 #include "windows/GUIWindowScreensaver.h"
192 #include "windows/GUIWindowScreensaverDim.h"
193 #include "pictures/GUIWindowSlideShow.h"
194 #include "windows/GUIWindowStartup.h"
195 #include "video/windows/GUIWindowFullScreen.h"
196 #include "video/dialogs/GUIDialogVideoOSD.h"
197 #include "music/dialogs/GUIDialogMusicOverlay.h"
198 #include "video/dialogs/GUIDialogVideoOverlay.h"
199
200 // Dialog includes
201 #include "music/dialogs/GUIDialogMusicOSD.h"
202 #include "music/dialogs/GUIDialogVisualisationPresetList.h"
203 #include "dialogs/GUIDialogTextViewer.h"
204 #include "network/GUIDialogNetworkSetup.h"
205 #include "dialogs/GUIDialogMediaSource.h"
206 #include "video/dialogs/GUIDialogVideoSettings.h"
207 #include "video/dialogs/GUIDialogAudioSubtitleSettings.h"
208 #include "video/dialogs/GUIDialogVideoBookmarks.h"
209 #include "settings/GUIDialogProfileSettings.h"
210 #include "settings/GUIDialogLockSettings.h"
211 #include "settings/GUIDialogContentSettings.h"
212 #include "video/dialogs/GUIDialogVideoScan.h"
213 #include "dialogs/GUIDialogBusy.h"
214 #include "dialogs/GUIDialogKeyboard.h"
215 #include "dialogs/GUIDialogYesNo.h"
216 #include "dialogs/GUIDialogOK.h"
217 #include "dialogs/GUIDialogProgress.h"
218 #include "dialogs/GUIDialogSelect.h"
219 #include "dialogs/GUIDialogSeekBar.h"
220 #include "dialogs/GUIDialogKaiToast.h"
221 #include "dialogs/GUIDialogVolumeBar.h"
222 #include "dialogs/GUIDialogMuteBug.h"
223 #include "video/dialogs/GUIDialogFileStacking.h"
224 #include "dialogs/GUIDialogNumeric.h"
225 #include "dialogs/GUIDialogGamepad.h"
226 #include "dialogs/GUIDialogSubMenu.h"
227 #include "dialogs/GUIDialogFavourites.h"
228 #include "dialogs/GUIDialogButtonMenu.h"
229 #include "dialogs/GUIDialogContextMenu.h"
230 #include "music/dialogs/GUIDialogMusicScan.h"
231 #include "dialogs/GUIDialogPlayerControls.h"
232 #include "music/dialogs/GUIDialogSongInfo.h"
233 #include "dialogs/GUIDialogSmartPlaylistEditor.h"
234 #include "dialogs/GUIDialogSmartPlaylistRule.h"
235 #include "pictures/GUIDialogPictureInfo.h"
236 #include "addons/GUIDialogAddonSettings.h"
237 #include "addons/GUIDialogAddonInfo.h"
238 #ifdef HAS_LINUX_NETWORK
239 #include "network/GUIDialogAccessPoints.h"
240 #endif
241 #include "video/dialogs/GUIDialogFullScreenInfo.h"
242 #include "video/dialogs/GUIDialogTeletext.h"
243 #include "dialogs/GUIDialogSlider.h"
244 #include "guilib/GUIControlFactory.h"
245 #include "dialogs/GUIDialogCache.h"
246 #include "dialogs/GUIDialogPlayEject.h"
247 #include "utils/XMLUtils.h"
248 #include "addons/AddonInstaller.h"
249
250 #ifdef HAS_PERFORMANCE_SAMPLE
251 #include "utils/PerformanceSample.h"
252 #else
253 #define MEASURE_FUNCTION
254 #endif
255
256 #ifdef HAS_SDL_AUDIO
257 #include <SDL/SDL_mixer.h>
258 #endif
259 #ifdef _WIN32
260 #include <shlobj.h>
261 #include "win32util.h"
262 #endif
263 #ifdef HAS_XRANDR
264 #include "windowing/X11/XRandR.h"
265 #endif
266
267 #ifdef TARGET_DARWIN_OSX
268 #include "CocoaInterface.h"
269 #include "XBMCHelper.h"
270 #endif
271 #ifdef TARGET_DARWIN
272 #include "DarwinUtils.h"
273 #endif
274
275 #ifdef HAS_DVD_DRIVE
276 #include <cdio/logging.h>
277 #endif
278
279 #ifdef HAS_HAL
280 #include "linux/HALManager.h"
281 #endif
282
283 #include "storage/MediaManager.h"
284 #include "utils/JobManager.h"
285 #include "utils/SaveFileStateJob.h"
286 #include "utils/AlarmClock.h"
287
288 #ifdef _LINUX
289 #include "XHandle.h"
290 #endif
291
292 #ifdef HAS_LIRC
293 #include "input/linux/LIRC.h"
294 #endif
295 #ifdef HAS_IRSERVERSUITE
296   #include "input/windows/IRServerSuite.h"
297 #endif
298
299 using namespace std;
300 using namespace ADDON;
301 using namespace XFILE;
302 #ifdef HAS_DVD_DRIVE
303 using namespace MEDIA_DETECT;
304 #endif
305 using namespace PLAYLIST;
306 using namespace VIDEO;
307 using namespace MUSIC_INFO;
308 #ifdef HAS_EVENT_SERVER
309 using namespace EVENTSERVER;
310 #endif
311 #ifdef HAS_DBUS_SERVER
312 using namespace DBUSSERVER;
313 #endif
314 #ifdef HAS_JSONRPC
315 using namespace JSONRPC;
316 #endif
317 using namespace ANNOUNCEMENT;
318 using namespace PERIPHERALS;
319
320 using namespace XbmcThreads;
321
322 // uncomment this if you want to use release libs in the debug build.
323 // Atm this saves you 7 mb of memory
324 #define USE_RELEASE_LIBS
325
326 #define MAX_FFWD_SPEED 5
327
328 //extern IDirectSoundRenderer* m_pAudioDecoder;
329 CApplication::CApplication(void) : m_itemCurrentFile(new CFileItem), m_progressTrackingItem(new CFileItem)
330 {
331   m_iPlaySpeed = 1;
332   m_pPlayer = NULL;
333   m_bScreenSave = false;
334   m_dpms = NULL;
335   m_dpmsIsActive = false;
336   m_dpmsIsManual = false;
337   m_iScreenSaveLock = 0;
338   m_bInitializing = true;
339   m_eForcedNextPlayer = EPC_NONE;
340   m_strPlayListFile = "";
341   m_nextPlaylistItem = -1;
342   m_bPlaybackStarting = false;
343   m_skinReloading = false;
344
345 #ifdef HAS_GLX
346   XInitThreads();
347 #endif
348
349   //true while we in IsPaused mode! Workaround for OnPaused, which must be add. after v2.0
350   m_bIsPaused = false;
351
352   /* for now always keep this around */
353 #ifdef HAS_KARAOKE
354   m_pKaraokeMgr = new CKaraokeLyricsManager();
355 #endif
356   m_currentStack = new CFileItemList;
357
358   m_frameCount = 0;
359
360   m_bPresentFrame = false;
361   m_bPlatformDirectories = true;
362
363   m_bStandalone = false;
364   m_bEnableLegacyRes = false;
365   m_bSystemScreenSaverEnable = false;
366   m_pInertialScrollingHandler = new CInertialScrollingHandler();
367 }
368
369 CApplication::~CApplication(void)
370 {
371   delete m_currentStack;
372
373 #ifdef HAS_KARAOKE
374   delete m_pKaraokeMgr;
375 #endif
376
377   delete m_dpms;
378   delete m_pInertialScrollingHandler;
379 }
380
381 bool CApplication::OnEvent(XBMC_Event& newEvent)
382 {
383   switch(newEvent.type)
384   {
385     case XBMC_QUIT:
386       if (!g_application.m_bStop)
387         g_application.getApplicationMessenger().Quit();
388       break;
389     case XBMC_KEYDOWN:
390       g_application.OnKey(g_Keyboard.ProcessKeyDown(newEvent.key.keysym));
391       break;
392     case XBMC_KEYUP:
393       g_Keyboard.ProcessKeyUp();
394       break;
395     case XBMC_MOUSEBUTTONDOWN:
396     case XBMC_MOUSEBUTTONUP:
397     case XBMC_MOUSEMOTION:
398       g_Mouse.HandleEvent(newEvent);
399       g_application.ProcessMouse();
400       break;
401     case XBMC_VIDEORESIZE:
402       if (!g_application.m_bInitializing &&
403           !g_advancedSettings.m_fullScreen)
404       {
405         g_Windowing.SetWindowResolution(newEvent.resize.w, newEvent.resize.h);
406         g_graphicsContext.SetVideoResolution(RES_WINDOW, true);
407         g_guiSettings.SetInt("window.width", newEvent.resize.w);
408         g_guiSettings.SetInt("window.height", newEvent.resize.h);
409         g_settings.Save();
410       }
411       break;
412     case XBMC_USEREVENT:
413       g_application.getApplicationMessenger().UserEvent(newEvent.user.code);
414       break;
415     case XBMC_APPCOMMAND:
416       return g_application.OnAppCommand(newEvent.appcommand.action);
417   }
418   return true;
419 }
420
421 // This function does not return!
422 void CApplication::FatalErrorHandler(bool WindowSystemInitialized, bool MapDrives, bool InitNetwork)
423 {
424   fprintf(stderr, "Fatal error encountered, aborting\n");
425   fprintf(stderr, "Error log at %sxbmc.log\n", g_settings.m_logFolder.c_str());
426   abort();
427 }
428
429 extern "C" void __stdcall init_emu_environ();
430 extern "C" void __stdcall update_emu_environ();
431
432 //
433 // Utility function used to copy files from the application bundle
434 // over to the user data directory in Application Support/XBMC.
435 //
436 static void CopyUserDataIfNeeded(const CStdString &strPath, const CStdString &file)
437 {
438   CStdString destPath = URIUtils::AddFileToFolder(strPath, file);
439   if (!CFile::Exists(destPath))
440   {
441     // need to copy it across
442     CStdString srcPath = URIUtils::AddFileToFolder("special://xbmc/userdata/", file);
443     CFile::Cache(srcPath, destPath);
444   }
445 }
446
447 void CApplication::Preflight()
448 {
449 #ifdef HAS_DBUS
450   // call 'dbus_threads_init_default' before any other dbus calls in order to
451   // avoid race conditions with other threads using dbus connections
452   dbus_threads_init_default();
453 #endif
454
455   // run any platform preflight scripts.
456 #if defined(__APPLE__) && !defined(__arm__)
457   CStdString install_path;
458
459   CUtil::GetHomePath(install_path);
460   setenv("XBMC_HOME", install_path.c_str(), 0);
461   install_path += "/tools/darwin/runtime/preflight";
462   system(install_path.c_str());
463 #endif
464 }
465
466 bool CApplication::Create()
467 {
468   g_settings.Initialize(); //Initialize default AdvancedSettings
469
470   m_bSystemScreenSaverEnable = g_Windowing.IsSystemScreenSaverEnabled();
471   g_Windowing.EnableSystemScreenSaver(false);
472
473 #ifdef _LINUX
474   tzset();   // Initialize timezone information variables
475 #endif
476
477   // Grab a handle to our thread to be used later in identifying the render thread.
478   m_threadID = CThread::GetCurrentThreadId();
479
480 #ifndef _LINUX
481   //floating point precision to 24 bits (faster performance)
482   _controlfp(_PC_24, _MCW_PC);
483
484   /* install win32 exception translator, win32 exceptions
485    * can now be caught using c++ try catch */
486   win32_exception::install_handler();
487
488 #endif
489
490   // only the InitDirectories* for the current platform should return true
491   // putting this before the first log entries saves another ifdef for g_settings.m_logFolder
492   bool inited = InitDirectoriesLinux();
493   if (!inited)
494     inited = InitDirectoriesOSX();
495   if (!inited)
496     inited = InitDirectoriesWin32();
497
498   // copy required files
499   CopyUserDataIfNeeded("special://masterprofile/", "RssFeeds.xml");
500   CopyUserDataIfNeeded("special://masterprofile/", "favourites.xml");
501   CopyUserDataIfNeeded("special://masterprofile/", "Lircmap.xml");
502   CopyUserDataIfNeeded("special://masterprofile/", "LCD.xml");
503
504   if (!CLog::Init(_P(g_settings.m_logFolder).c_str()))
505   {
506     fprintf(stderr,"Could not init logging classes. Permission errors on ~/.xbmc?\n");
507     return false;
508   }
509
510   g_settings.LoadProfiles(PROFILES_FILE);
511
512   CLog::Log(LOGNOTICE, "-----------------------------------------------------------------------");
513 #if defined(__APPLE__)
514   CLog::Log(LOGNOTICE, "Starting XBMC, Platform: Mac OS X (%s). Built on %s (Git:%s)", g_sysinfo.GetUnameVersion().c_str(), __DATE__, GIT_REV);
515 #elif defined(__FreeBSD__)
516   CLog::Log(LOGNOTICE, "Starting XBMC, Platform: FreeBSD (%s). Built on %s (Git:%s)", g_sysinfo.GetUnameVersion().c_str(), __DATE__, GIT_REV);
517 #elif defined(_LINUX)
518   CLog::Log(LOGNOTICE, "Starting XBMC, Platform: Linux (%s, %s). Built on %s (Git:%s)", g_sysinfo.GetLinuxDistro().c_str(), g_sysinfo.GetUnameVersion().c_str(), __DATE__, GIT_REV);
519 #elif defined(_WIN32)
520   CLog::Log(LOGNOTICE, "Starting XBMC, Platform: %s. Built on %s (Git:%s, compiler %i)",g_sysinfo.GetKernelVersion().c_str(), __DATE__, GIT_REV, _MSC_VER);
521   CLog::Log(LOGNOTICE, g_cpuInfo.getCPUModel().c_str());
522   CLog::Log(LOGNOTICE, CWIN32Util::GetResInfoString());
523   CLog::Log(LOGNOTICE, "Running with %s rights", (CWIN32Util::IsCurrentUserLocalAdministrator() == TRUE) ? "administrator" : "restricted");
524   CLog::Log(LOGNOTICE, "Aero is %s", (g_sysinfo.IsAeroDisabled() == true) ? "disabled" : "enabled");
525 #endif
526   CSpecialProtocol::LogPaths();
527
528   CStdString executable = CUtil::ResolveExecutablePath();
529   CLog::Log(LOGNOTICE, "The executable running is: %s", executable.c_str());
530   CLog::Log(LOGNOTICE, "Log File is located: %sxbmc.log", g_settings.m_logFolder.c_str());
531   CLog::Log(LOGNOTICE, "-----------------------------------------------------------------------");
532
533   CStdString strExecutablePath;
534   CUtil::GetHomePath(strExecutablePath);
535
536   // if we are running from DVD our UserData location will be TDATA
537   if (URIUtils::IsDVD(strExecutablePath))
538   {
539     // TODO: Should we copy over any UserData folder from the DVD?
540     if (!CFile::Exists("special://masterprofile/guisettings.xml")) // first run - cache userdata folder
541     {
542       CFileItemList items;
543       CUtil::GetRecursiveListing("special://xbmc/userdata",items,"");
544       for (int i=0;i<items.Size();++i)
545           CFile::Cache(items[i]->GetPath(),"special://masterprofile/"+URIUtils::GetFileName(items[i]->GetPath()));
546     }
547     g_settings.m_logFolder = "special://masterprofile/";
548   }
549
550 #ifdef HAS_XRANDR
551   g_xrandr.LoadCustomModeLinesToAllOutputs();
552 #endif
553
554   // Init our DllLoaders emu env
555   init_emu_environ();
556
557
558 #ifdef HAS_SDL
559   CLog::Log(LOGNOTICE, "Setup SDL");
560
561   /* Clean up on exit, exit on window close and interrupt */
562   atexit(SDL_Quit);
563
564   uint32_t sdlFlags = 0;
565
566 #if defined(HAS_SDL_OPENGL) || (HAS_GLES == 2)
567   sdlFlags |= SDL_INIT_VIDEO;
568 #endif
569
570 #ifdef HAS_SDL_AUDIO
571   sdlFlags |= SDL_INIT_AUDIO;
572 #endif
573
574 #ifdef HAS_SDL_JOYSTICK
575   sdlFlags |= SDL_INIT_JOYSTICK;
576 #endif
577
578   //depending on how it's compiled, SDL periodically calls XResetScreenSaver when it's fullscreen
579   //this might bring the monitor out of standby, so we have to disable it explicitly
580   //by passing 0 for overwrite to setsenv, the user can still override this by setting the environment variable
581 #if defined(_LINUX) && !defined(__APPLE__)
582   setenv("SDL_VIDEO_ALLOW_SCREENSAVER", "1", 0);
583 #endif
584
585 #endif // HAS_SDL
586
587 #ifdef _LINUX
588   // for nvidia cards - vsync currently ALWAYS enabled.
589   // the reason is that after screen has been setup changing this env var will make no difference.
590   setenv("__GL_SYNC_TO_VBLANK", "1", 0);
591   setenv("__GL_YIELD", "USLEEP", 0);
592 #endif
593
594 #ifdef HAS_SDL
595   if (SDL_Init(sdlFlags) != 0)
596   {
597     CLog::Log(LOGFATAL, "XBAppEx: Unable to initialize SDL: %s", SDL_GetError());
598     return false;
599   }
600 #endif
601
602   // for python scripts that check the OS
603 #ifdef __APPLE__
604   setenv("OS","OS X",true);
605 #elif defined(_LINUX)
606   setenv("OS","Linux",true);
607 #elif defined(_WIN32)
608   SetEnvironmentVariable("OS","win32");
609 #endif
610
611   // Initialize core peripheral port support. Note: If these parameters
612   // are 0 and NULL, respectively, then the default number and types of
613   // controllers will be initialized.
614   if (!g_Windowing.InitWindowSystem())
615   {
616     CLog::Log(LOGFATAL, "CApplication::Create: Unable to init windowing system");
617     return false;
618   }
619
620   g_powerManager.Initialize();
621
622   CLog::Log(LOGNOTICE, "load settings...");
623
624   g_guiSettings.Initialize();  // Initialize default Settings - don't move
625   g_powerManager.SetDefaults();
626   if (!g_settings.Load())
627     FatalErrorHandler(true, true, true);
628
629   CLog::Log(LOGINFO, "creating subdirectories");
630   CLog::Log(LOGINFO, "userdata folder: %s", g_settings.GetProfileUserDataFolder().c_str());
631   CLog::Log(LOGINFO, "recording folder:%s", g_guiSettings.GetString("audiocds.recordingpath",false).c_str());
632   CLog::Log(LOGINFO, "screenshots folder:%s", g_guiSettings.GetString("debug.screenshotpath",false).c_str());
633   CDirectory::Create(g_settings.GetUserDataFolder());
634   CDirectory::Create(g_settings.GetProfileUserDataFolder());
635   g_settings.CreateProfileFolders();
636
637   update_emu_environ();//apply the GUI settings
638
639   // initialize our charset converter
640   g_charsetConverter.reset();
641
642   // Load the langinfo to have user charset <-> utf-8 conversion
643   CStdString strLanguage = g_guiSettings.GetString("locale.language");
644   strLanguage[0] = toupper(strLanguage[0]);
645
646   CStdString strLangInfoPath;
647   strLangInfoPath.Format("special://xbmc/language/%s/langinfo.xml", strLanguage.c_str());
648
649   CLog::Log(LOGINFO, "load language info file: %s", strLangInfoPath.c_str());
650   g_langInfo.Load(strLangInfoPath);
651
652   CStdString strLanguagePath;
653   strLanguagePath.Format("special://xbmc/language/%s/strings.xml", strLanguage.c_str());
654
655   CLog::Log(LOGINFO, "load language file:%s", strLanguagePath.c_str());
656   if (!g_localizeStrings.Load(strLanguagePath))
657     FatalErrorHandler(false, false, true);
658
659   // start-up Addons Framework
660   // currently bails out if either cpluff Dll is unavailable or system dir can not be scanned
661   if (!CAddonMgr::Get().Init())
662   {
663     CLog::Log(LOGFATAL, "CApplication::Create: Unable to start CAddonMgr");
664     FatalErrorHandler(true, true, true);
665   }
666
667   g_peripherals.Initialise();
668
669   // Create the Mouse, Keyboard, Remote, and Joystick devices
670   // Initialize after loading settings to get joystick deadzone setting
671   g_Mouse.Initialize();
672   g_Mouse.SetEnabled(g_guiSettings.GetBool("input.enablemouse"));
673
674   g_Keyboard.Initialize();
675 #if defined(HAS_LIRC) || defined(HAS_IRSERVERSUITE)
676   g_RemoteControl.Initialize();
677 #endif
678 #ifdef HAS_SDL_JOYSTICK
679   g_Joystick.Initialize();
680 #endif
681
682 #if defined(__APPLE__) && !defined(__arm__)
683   // Configure and possible manually start the helper.
684   XBMCHelper::GetInstance().Configure();
685 #endif
686
687   // update the window resolution
688   g_Windowing.SetWindowResolution(g_guiSettings.GetInt("window.width"), g_guiSettings.GetInt("window.height"));
689
690   if (g_advancedSettings.m_startFullScreen && g_guiSettings.m_LookAndFeelResolution == RES_WINDOW)
691     g_guiSettings.m_LookAndFeelResolution = RES_DESKTOP;
692
693   if (!g_graphicsContext.IsValidResolution(g_guiSettings.m_LookAndFeelResolution))
694   {
695     // Oh uh - doesn't look good for starting in their wanted screenmode
696     CLog::Log(LOGERROR, "The screen resolution requested is not valid, resetting to a valid mode");
697     g_guiSettings.m_LookAndFeelResolution = RES_DESKTOP;
698   }
699
700 #ifdef __APPLE__
701   // force initial window creation to be windowed, if fullscreen, it will switch to it below
702   // fixes the white screen of death if starting fullscreen and switching to windowed.
703   bool bFullScreen = false;
704   if (!g_Windowing.CreateNewWindow("XBMC", bFullScreen, g_settings.m_ResInfo[RES_WINDOW], OnEvent))
705   {
706     CLog::Log(LOGFATAL, "CApplication::Create: Unable to create window");
707     return false;
708   }
709 #else
710   bool bFullScreen = g_guiSettings.m_LookAndFeelResolution != RES_WINDOW;
711   if (!g_Windowing.CreateNewWindow("XBMC", bFullScreen, g_settings.m_ResInfo[g_guiSettings.m_LookAndFeelResolution], OnEvent))
712   {
713     CLog::Log(LOGFATAL, "CApplication::Create: Unable to create window");
714     return false;
715   }
716 #endif
717
718   if (!g_Windowing.InitRenderSystem())
719   {
720     CLog::Log(LOGFATAL, "CApplication::Create: Unable to init rendering system");
721     return false;
722   }
723
724   // set GUI res and force the clear of the screen
725   g_graphicsContext.SetVideoResolution(g_guiSettings.m_LookAndFeelResolution);
726
727   if (g_advancedSettings.m_splashImage)
728   {
729     CStdString strUserSplash = "special://home/media/Splash.png";
730     if (CFile::Exists(strUserSplash))
731     {
732       CLog::Log(LOGINFO, "load user splash image: %s", CSpecialProtocol::TranslatePath(strUserSplash).c_str());
733       m_splash = new CSplash(strUserSplash);
734     }
735     else
736     {
737       CLog::Log(LOGINFO, "load default splash image: %s", CSpecialProtocol::TranslatePath("special://xbmc/media/Splash.png").c_str());
738       m_splash = new CSplash("special://xbmc/media/Splash.png");
739     }
740     m_splash->Show();
741   }
742
743   CLog::Log(LOGINFO, "load keymapping");
744   if (!CButtonTranslator::GetInstance().Load())
745     FatalErrorHandler(false, false, true);
746
747   int iResolution = g_graphicsContext.GetVideoResolution();
748   CLog::Log(LOGINFO, "GUI format %ix%i %s",
749             g_settings.m_ResInfo[iResolution].iWidth,
750             g_settings.m_ResInfo[iResolution].iHeight,
751             g_settings.m_ResInfo[iResolution].strMode.c_str());
752   g_windowManager.Initialize();
753
754   CUtil::InitRandomSeed();
755
756   g_mediaManager.Initialize();
757
758   m_lastFrameTime = XbmcThreads::SystemClockMillis();
759   m_lastRenderTime = m_lastFrameTime;
760
761   return Initialize();
762 }
763
764 bool CApplication::InitDirectoriesLinux()
765 {
766 /*
767    The following is the directory mapping for Platform Specific Mode:
768
769    special://xbmc/          => [read-only] system directory (/usr/share/xbmc)
770    special://home/          => [read-write] user's directory that will override special://xbmc/ system-wide
771                                installations like skins, screensavers, etc.
772                                ($HOME/.xbmc)
773                                NOTE: XBMC will look in both special://xbmc/addons and special://home/addons for addons.
774    special://masterprofile/ => [read-write] userdata of master profile. It will by default be
775                                mapped to special://home/userdata ($HOME/.xbmc/userdata)
776    special://profile/       => [read-write] current profile's userdata directory.
777                                Generally special://masterprofile for the master profile or
778                                special://masterprofile/profiles/<profile_name> for other profiles.
779
780    NOTE: All these root directories are lowercase. Some of the sub-directories
781          might be mixed case.
782 */
783
784 #if defined(_LINUX) && !defined(__APPLE__)
785   CStdString userName;
786   if (getenv("USER"))
787     userName = getenv("USER");
788   else
789     userName = "root";
790
791   CStdString userHome;
792   if (getenv("HOME"))
793     userHome = getenv("HOME");
794   else
795     userHome = "/root";
796
797   CStdString xbmcBinPath, xbmcPath;
798   CUtil::GetHomePath(xbmcBinPath, "XBMC_BIN_HOME");
799   xbmcPath = getenv("XBMC_HOME");
800
801   if (xbmcPath.IsEmpty())
802   {
803     xbmcPath = xbmcBinPath;
804     /* Check if xbmc binaries and arch independent data files are being kept in
805      * separate locations. */
806     if (!CFile::Exists(URIUtils::AddFileToFolder(xbmcPath, "language")))
807     {
808       /* Attempt to locate arch independent data files. */
809       CUtil::GetHomePath(xbmcPath);
810       if (!CFile::Exists(URIUtils::AddFileToFolder(xbmcPath, "language")))
811       {
812         fprintf(stderr, "Unable to find path to XBMC data files!\n");
813         exit(1);
814       }
815     }
816   }
817
818   /* Set some environment variables */
819   setenv("XBMC_BIN_HOME", xbmcBinPath.c_str(), 0);
820   setenv("XBMC_HOME", xbmcPath.c_str(), 0);
821
822   if (m_bPlatformDirectories)
823   {
824     // map our special drives
825     CSpecialProtocol::SetXBMCBinPath(xbmcBinPath);
826     CSpecialProtocol::SetXBMCPath(xbmcPath);
827     CSpecialProtocol::SetHomePath(userHome + "/.xbmc");
828     CSpecialProtocol::SetMasterProfilePath(userHome + "/.xbmc/userdata");
829
830     CStdString strTempPath = URIUtils::AddFileToFolder(userHome, ".xbmc/temp");
831     CSpecialProtocol::SetTempPath(strTempPath);
832
833     URIUtils::AddSlashAtEnd(strTempPath);
834     g_settings.m_logFolder = strTempPath;
835
836     CreateUserDirs();
837
838   }
839   else
840   {
841     URIUtils::AddSlashAtEnd(xbmcPath);
842     g_settings.m_logFolder = xbmcPath;
843
844     CSpecialProtocol::SetXBMCBinPath(xbmcBinPath);
845     CSpecialProtocol::SetXBMCPath(xbmcPath);
846     CSpecialProtocol::SetHomePath(URIUtils::AddFileToFolder(xbmcPath, "portable_data"));
847     CSpecialProtocol::SetMasterProfilePath(URIUtils::AddFileToFolder(xbmcPath, "portable_data/userdata"));
848
849     CStdString strTempPath = URIUtils::AddFileToFolder(xbmcPath, "portable_data/temp");
850     CSpecialProtocol::SetTempPath(strTempPath);
851     CreateUserDirs();
852
853     URIUtils::AddSlashAtEnd(strTempPath);
854     g_settings.m_logFolder = strTempPath;
855   }
856
857   return true;
858 #else
859   return false;
860 #endif
861 }
862
863 bool CApplication::InitDirectoriesOSX()
864 {
865 #ifdef __APPLE__
866   CStdString userName;
867   if (getenv("USER"))
868     userName = getenv("USER");
869   else
870     userName = "root";
871
872   CStdString userHome;
873   if (getenv("HOME"))
874     userHome = getenv("HOME");
875   else
876     userHome = "/root";
877
878   CStdString xbmcPath;
879   CUtil::GetHomePath(xbmcPath);
880   setenv("XBMC_HOME", xbmcPath.c_str(), 0);
881
882 #if defined(__arm__)
883   CStdString fontconfigPath;
884   fontconfigPath = xbmcPath + "/system/players/dvdplayer/etc/fonts/fonts.conf";
885   setenv("FONTCONFIG_FILE", fontconfigPath.c_str(), 0);
886 #endif
887   
888   // setup path to our internal dylibs so loader can find them
889   CStdString frameworksPath = CUtil::GetFrameworksPath();
890   CSpecialProtocol::SetXBMCFrameworksPath(frameworksPath);
891
892   // OSX always runs with m_bPlatformDirectories == true
893   if (m_bPlatformDirectories)
894   {
895     // map our special drives
896     CSpecialProtocol::SetXBMCBinPath(xbmcPath);
897     CSpecialProtocol::SetXBMCPath(xbmcPath);
898     #if defined(__arm__)
899       CSpecialProtocol::SetHomePath(userHome + "/Library/Preferences/XBMC");
900       CSpecialProtocol::SetMasterProfilePath(userHome + "/Library/Preferences/XBMC/userdata");
901     #else
902       CSpecialProtocol::SetHomePath(userHome + "/Library/Application Support/XBMC");
903       CSpecialProtocol::SetMasterProfilePath(userHome + "/Library/Application Support/XBMC/userdata");
904     #endif
905
906     // location for temp files
907     #if defined(__arm__)
908       CStdString strTempPath = URIUtils::AddFileToFolder(userHome,  "Library/Preferences/XBMC/temp");
909     #else
910       CStdString strTempPath = URIUtils::AddFileToFolder(userHome, ".xbmc/");
911       CDirectory::Create(strTempPath);
912       strTempPath = URIUtils::AddFileToFolder(userHome, ".xbmc/temp");
913     #endif
914     CSpecialProtocol::SetTempPath(strTempPath);
915
916     // xbmc.log file location
917     #if defined(__arm__)
918       strTempPath = userHome + "/Library/Preferences";
919     #else
920       strTempPath = userHome + "/Library/Logs";
921     #endif
922     URIUtils::AddSlashAtEnd(strTempPath);
923     g_settings.m_logFolder = strTempPath;
924
925     CreateUserDirs();
926   }
927   else
928   {
929     URIUtils::AddSlashAtEnd(xbmcPath);
930     g_settings.m_logFolder = xbmcPath;
931
932     CSpecialProtocol::SetXBMCBinPath(xbmcPath);
933     CSpecialProtocol::SetXBMCPath(xbmcPath);
934     CSpecialProtocol::SetHomePath(URIUtils::AddFileToFolder(xbmcPath, "portable_data"));
935     CSpecialProtocol::SetMasterProfilePath(URIUtils::AddFileToFolder(xbmcPath, "portable_data/userdata"));
936
937     CStdString strTempPath = URIUtils::AddFileToFolder(xbmcPath, "portable_data/temp");
938     CSpecialProtocol::SetTempPath(strTempPath);
939
940     URIUtils::AddSlashAtEnd(strTempPath);
941     g_settings.m_logFolder = strTempPath;
942   }
943
944   return true;
945 #else
946   return false;
947 #endif
948 }
949
950 bool CApplication::InitDirectoriesWin32()
951 {
952 #ifdef _WIN32
953   CStdString xbmcPath;
954
955   CUtil::GetHomePath(xbmcPath);
956   SetEnvironmentVariable("XBMC_HOME", xbmcPath.c_str());
957   CSpecialProtocol::SetXBMCBinPath(xbmcPath);
958   CSpecialProtocol::SetXBMCPath(xbmcPath);
959
960   if (m_bPlatformDirectories)
961   {
962
963     CStdString strWin32UserFolder = CWIN32Util::GetProfilePath();
964
965     // create user/app data/XBMC
966     CStdString homePath = URIUtils::AddFileToFolder(strWin32UserFolder, "XBMC");
967
968     // move log to platform dirs
969     g_settings.m_logFolder = homePath;
970     URIUtils::AddSlashAtEnd(g_settings.m_logFolder);
971
972     // map our special drives
973     CSpecialProtocol::SetXBMCBinPath(xbmcPath);
974     CSpecialProtocol::SetXBMCPath(xbmcPath);
975     CSpecialProtocol::SetHomePath(homePath);
976     CSpecialProtocol::SetMasterProfilePath(URIUtils::AddFileToFolder(homePath, "userdata"));
977     SetEnvironmentVariable("XBMC_PROFILE_USERDATA",_P("special://masterprofile").c_str());
978
979     CSpecialProtocol::SetTempPath(URIUtils::AddFileToFolder(homePath,"cache"));
980
981     CreateUserDirs();
982
983   }
984   else
985   {
986     URIUtils::AddSlashAtEnd(xbmcPath);
987     g_settings.m_logFolder = xbmcPath;
988
989     CSpecialProtocol::SetHomePath(URIUtils::AddFileToFolder(xbmcPath, "portable_data"));
990     CSpecialProtocol::SetMasterProfilePath(URIUtils::AddFileToFolder(xbmcPath, "portable_data/userdata"));
991
992     CStdString strTempPath = URIUtils::AddFileToFolder(xbmcPath, "portable_data/temp");
993     CSpecialProtocol::SetTempPath(strTempPath);
994
995     CreateUserDirs();
996
997     SetEnvironmentVariable("XBMC_PROFILE_USERDATA",_P("special://masterprofile/").c_str());
998   }
999
1000   // Expand the DLL search path with our directories
1001   CWIN32Util::ExtendDllPath();
1002
1003   // check for a DVD drive
1004   VECSOURCES vShare;
1005   CWIN32Util::GetDrivesByType(vShare, DVD_DRIVES);
1006   if(!vShare.empty())
1007     g_mediaManager.SetHasOpticalDrive(true);
1008
1009   // Can be removed once the StorageHandler supports optical media
1010   VECSOURCES::const_iterator it;
1011   for(it=vShare.begin();it!=vShare.end();++it)
1012     if(g_mediaManager.GetDriveStatus(it->strPath) == DRIVE_CLOSED_MEDIA_PRESENT)
1013       g_application.getApplicationMessenger().OpticalMount(it->strPath);
1014   // remove end
1015
1016   return true;
1017 #else
1018   return false;
1019 #endif
1020 }
1021
1022 void CApplication::CreateUserDirs()
1023 {
1024   CDirectory::Create("special://home/");
1025   CDirectory::Create("special://home/addons");
1026   CDirectory::Create("special://home/addons/packages");
1027   CDirectory::Create("special://home/media");
1028   CDirectory::Create("special://home/sounds");
1029   CDirectory::Create("special://home/system");
1030   CDirectory::Create("special://masterprofile/");
1031   CDirectory::Create("special://temp/");
1032   CDirectory::Create("special://temp/temp"); // temp directory for python and dllGetTempPathA
1033 }
1034
1035 bool CApplication::Initialize()
1036 {
1037 #if defined(HAS_DVD_DRIVE) && !defined(_WIN32) // somehow this throws an "unresolved external symbol" on win32
1038   // turn off cdio logging
1039   cdio_loglevel_default = CDIO_LOG_ERROR;
1040 #endif
1041
1042 #ifdef _LINUX // TODO: Win32 has no special://home/ mapping by default, so we
1043               //       must create these here. Ideally this should be using special://home/ and
1044               //       be platform agnostic (i.e. unify the InitDirectories*() functions)
1045   if (!m_bPlatformDirectories)
1046 #endif
1047   {
1048     CDirectory::Create("special://xbmc/language");
1049     CDirectory::Create("special://xbmc/addons");
1050     CDirectory::Create("special://xbmc/sounds");
1051   }
1052
1053   StartServices();
1054
1055   // Init DPMS, before creating the corresponding setting control.
1056   m_dpms = new DPMSSupport();
1057   g_guiSettings.GetSetting("powermanagement.displaysoff")->SetVisible(m_dpms->IsSupported());
1058
1059   g_windowManager.Add(new CGUIWindowHome);                     // window id = 0
1060   g_windowManager.Add(new CGUIWindowPrograms);                 // window id = 1
1061   g_windowManager.Add(new CGUIWindowPictures);                 // window id = 2
1062   g_windowManager.Add(new CGUIWindowFileManager);      // window id = 3
1063   g_windowManager.Add(new CGUIWindowSettings);                 // window id = 4
1064   g_windowManager.Add(new CGUIWindowSystemInfo);               // window id = 7
1065 #ifdef HAS_GL
1066   g_windowManager.Add(new CGUIWindowTestPatternGL);      // window id = 8
1067 #endif
1068 #ifdef HAS_DX
1069   g_windowManager.Add(new CGUIWindowTestPatternDX);      // window id = 8
1070 #endif
1071   g_windowManager.Add(new CGUIDialogTeletext);               // window id =
1072   g_windowManager.Add(new CGUIWindowSettingsScreenCalibration); // window id = 11
1073   g_windowManager.Add(new CGUIWindowSettingsCategory);         // window id = 12 slideshow:window id 2007
1074   g_windowManager.Add(new CGUIWindowVideoNav);                 // window id = 36
1075   g_windowManager.Add(new CGUIWindowVideoPlaylist);            // window id = 28
1076   g_windowManager.Add(new CGUIWindowLoginScreen);            // window id = 29
1077   g_windowManager.Add(new CGUIWindowSettingsProfile);          // window id = 34
1078   g_windowManager.Add(new CGUIWindowAddonBrowser);          // window id = 40
1079   g_windowManager.Add(new CGUIWindowScreensaverDim);            // window id = 97  
1080   g_windowManager.Add(new CGUIWindowDebugInfo);            // window id = 98
1081   g_windowManager.Add(new CGUIWindowPointer);            // window id = 99
1082   g_windowManager.Add(new CGUIDialogYesNo);              // window id = 100
1083   g_windowManager.Add(new CGUIDialogProgress);           // window id = 101
1084   g_windowManager.Add(new CGUIDialogKeyboard);           // window id = 103
1085   g_windowManager.Add(new CGUIDialogVolumeBar);          // window id = 104
1086   g_windowManager.Add(new CGUIDialogSeekBar);            // window id = 115
1087   g_windowManager.Add(new CGUIDialogSubMenu);            // window id = 105
1088   g_windowManager.Add(new CGUIDialogContextMenu);        // window id = 106
1089   g_windowManager.Add(new CGUIDialogKaiToast);           // window id = 107
1090   g_windowManager.Add(new CGUIDialogNumeric);            // window id = 109
1091   g_windowManager.Add(new CGUIDialogGamepad);            // window id = 110
1092   g_windowManager.Add(new CGUIDialogButtonMenu);         // window id = 111
1093   g_windowManager.Add(new CGUIDialogMusicScan);          // window id = 112
1094   g_windowManager.Add(new CGUIDialogMuteBug);            // window id = 113
1095   g_windowManager.Add(new CGUIDialogPlayerControls);     // window id = 114
1096 #ifdef HAS_KARAOKE
1097   g_windowManager.Add(new CGUIDialogKaraokeSongSelectorSmall); // window id 143
1098   g_windowManager.Add(new CGUIDialogKaraokeSongSelectorLarge); // window id 144
1099 #endif
1100   g_windowManager.Add(new CGUIDialogSlider);             // window id = 145
1101   g_windowManager.Add(new CGUIDialogMusicOSD);           // window id = 120
1102   g_windowManager.Add(new CGUIDialogVisualisationPresetList);   // window id = 122
1103   g_windowManager.Add(new CGUIDialogVideoSettings);             // window id = 123
1104   g_windowManager.Add(new CGUIDialogAudioSubtitleSettings);     // window id = 124
1105   g_windowManager.Add(new CGUIDialogVideoBookmarks);      // window id = 125
1106   // Don't add the filebrowser dialog - it's created and added when it's needed
1107   g_windowManager.Add(new CGUIDialogNetworkSetup);  // window id = 128
1108   g_windowManager.Add(new CGUIDialogMediaSource);   // window id = 129
1109   g_windowManager.Add(new CGUIDialogProfileSettings); // window id = 130
1110   g_windowManager.Add(new CGUIDialogVideoScan);      // window id = 133
1111   g_windowManager.Add(new CGUIDialogFavourites);     // window id = 134
1112   g_windowManager.Add(new CGUIDialogSongInfo);       // window id = 135
1113   g_windowManager.Add(new CGUIDialogSmartPlaylistEditor);       // window id = 136
1114   g_windowManager.Add(new CGUIDialogSmartPlaylistRule);       // window id = 137
1115   g_windowManager.Add(new CGUIDialogBusy);      // window id = 138
1116   g_windowManager.Add(new CGUIDialogPictureInfo);      // window id = 139
1117   g_windowManager.Add(new CGUIDialogAddonInfo);
1118   g_windowManager.Add(new CGUIDialogAddonSettings);      // window id = 140
1119 #ifdef HAS_LINUX_NETWORK
1120   g_windowManager.Add(new CGUIDialogAccessPoints);      // window id = 141
1121 #endif
1122
1123   g_windowManager.Add(new CGUIDialogLockSettings); // window id = 131
1124
1125   g_windowManager.Add(new CGUIDialogContentSettings);        // window id = 132
1126
1127   g_windowManager.Add(new CGUIDialogPlayEject);
1128
1129   g_windowManager.Add(new CGUIDialogPeripheralManager);
1130   g_windowManager.Add(new CGUIDialogPeripheralSettings);
1131
1132   g_windowManager.Add(new CGUIWindowMusicPlayList);          // window id = 500
1133   g_windowManager.Add(new CGUIWindowMusicSongs);             // window id = 501
1134   g_windowManager.Add(new CGUIWindowMusicNav);               // window id = 502
1135   g_windowManager.Add(new CGUIWindowMusicPlaylistEditor);    // window id = 503
1136
1137   g_windowManager.Add(new CGUIDialogSelect);             // window id = 2000
1138   g_windowManager.Add(new CGUIDialogMusicInfo);          // window id = 2001
1139   g_windowManager.Add(new CGUIDialogOK);                 // window id = 2002
1140   g_windowManager.Add(new CGUIDialogVideoInfo);          // window id = 2003
1141   g_windowManager.Add(new CGUIDialogTextViewer);
1142   g_windowManager.Add(new CGUIWindowFullScreen);         // window id = 2005
1143   g_windowManager.Add(new CGUIWindowVisualisation);      // window id = 2006
1144   g_windowManager.Add(new CGUIWindowSlideShow);          // window id = 2007
1145   g_windowManager.Add(new CGUIDialogFileStacking);       // window id = 2008
1146 #ifdef HAS_KARAOKE
1147   g_windowManager.Add(new CGUIWindowKaraokeLyrics);      // window id = 2009
1148 #endif
1149
1150   g_windowManager.Add(new CGUIDialogVideoOSD);           // window id = 2901
1151   g_windowManager.Add(new CGUIDialogMusicOverlay);       // window id = 2903
1152   g_windowManager.Add(new CGUIDialogVideoOverlay);       // window id = 2904
1153   g_windowManager.Add(new CGUIWindowScreensaver);        // window id = 2900 Screensaver
1154   g_windowManager.Add(new CGUIWindowWeather);            // window id = 2600 WEATHER
1155   g_windowManager.Add(new CGUIWindowStartup);            // startup window (id 2999)
1156
1157   /* window id's 3000 - 3100 are reserved for python */
1158
1159   // Make sure we have at least the default skin
1160   if (!LoadSkin(g_guiSettings.GetString("lookandfeel.skin")) && !LoadSkin(DEFAULT_SKIN))
1161   {
1162       CLog::Log(LOGERROR, "Default skin '%s' not found! Terminating..", DEFAULT_SKIN);
1163       FatalErrorHandler(true, true, true);
1164   }
1165
1166   if (g_advancedSettings.m_splashImage)
1167     SAFE_DELETE(m_splash);
1168
1169   if (g_guiSettings.GetBool("masterlock.startuplock") &&
1170       g_settings.GetMasterProfile().getLockMode() != LOCK_MODE_EVERYONE &&
1171      !g_settings.GetMasterProfile().getLockCode().IsEmpty())
1172   {
1173      g_passwordManager.CheckStartUpLock();
1174   }
1175
1176   // check if we should use the login screen
1177   if (g_settings.UsingLoginScreen())
1178     g_windowManager.ActivateWindow(WINDOW_LOGIN_SCREEN);
1179   else
1180     g_windowManager.ActivateWindow(g_SkinInfo->GetFirstWindow());
1181
1182   g_sysinfo.Refresh();
1183
1184   CLog::Log(LOGINFO, "removing tempfiles");
1185   CUtil::RemoveTempFiles();
1186
1187   //  Show mute symbol
1188   if (g_settings.m_bMute)
1189     Mute();
1190
1191   // if the user shutoff the xbox during music scan
1192   // restore the settings
1193   if (g_settings.m_bMyMusicIsScanning)
1194   {
1195     CLog::Log(LOGWARNING,"System rebooted during music scan! ... restoring UseTags and FindRemoteThumbs");
1196     RestoreMusicScanSettings();
1197   }
1198
1199   if (!g_settings.UsingLoginScreen())
1200   {
1201     UpdateLibraries();
1202 #ifdef HAS_PYTHON
1203   g_pythonParser.m_bLogin = true;
1204 #endif
1205   }
1206
1207   m_slowTimer.StartZero();
1208
1209 #if defined(__APPLE__) && !defined(__arm__)
1210   XBMCHelper::GetInstance().CaptureAllInput();
1211 #endif
1212 #if defined(HAVE_LIBCRYSTALHD)
1213   CCrystalHD::GetInstance();
1214 #endif
1215
1216   CAddonMgr::Get().StartServices(false);
1217
1218   CLog::Log(LOGNOTICE, "initialize done");
1219
1220   m_bInitializing = false;
1221
1222   // reset our screensaver (starts timers etc.)
1223   ResetScreenSaver();
1224   return true;
1225 }
1226
1227 bool CApplication::StartWebServer()
1228 {
1229 #ifdef HAS_WEB_SERVER
1230   if (g_guiSettings.GetBool("services.webserver") && m_network.IsAvailable())
1231   {
1232     int webPort = atoi(g_guiSettings.GetString("services.webserverport"));
1233     CLog::Log(LOGNOTICE, "Webserver: Starting...");
1234 #ifdef _LINUX
1235     if (webPort < 1024 && geteuid() != 0)
1236     {
1237         CLog::Log(LOGERROR, "Cannot start Web Server as port is smaller than 1024 and user is not root");
1238         return false;
1239     }
1240 #endif
1241
1242     bool started = false;
1243     if (m_WebServer.Start(webPort, g_guiSettings.GetString("services.webserverusername"), g_guiSettings.GetString("services.webserverpassword")))
1244     {
1245       std::map<std::string, std::string> txt; 
1246       started = true;
1247       // publish web frontend and API services
1248 #ifdef HAS_WEB_INTERFACE
1249       CZeroconf::GetInstance()->PublishService("servers.webserver", "_http._tcp", "XBMC Web Server", webPort, txt);
1250 #endif
1251 #ifdef HAS_HTTPAPI
1252       CZeroconf::GetInstance()->PublishService("servers.webapi", "_xbmc-web._tcp", "XBMC HTTP API", webPort, txt);
1253 #endif
1254 #ifdef HAS_JSONRPC
1255       CZeroconf::GetInstance()->PublishService("servers.webjsonrpc", "_xbmc-jsonrpc._tcp", "XBMC JSONRPC", webPort, txt);
1256 #endif
1257     }
1258 #ifdef HAS_HTTPAPI
1259     if (g_settings.m_HttpApiBroadcastLevel >= 1)
1260       getApplicationMessenger().HttpApi("broadcastlevel; StartUp;1");
1261 #endif
1262
1263     return started;
1264   }
1265 #endif
1266
1267   return true;
1268 }
1269
1270 void CApplication::StopWebServer()
1271 {
1272 #ifdef HAS_WEB_SERVER
1273   if (m_WebServer.IsStarted())
1274   {
1275     CLog::Log(LOGNOTICE, "Webserver: Stopping...");
1276     m_WebServer.Stop();
1277     if(! m_WebServer.IsStarted() )
1278     {
1279       CLog::Log(LOGNOTICE, "Webserver: Stopped...");
1280       CZeroconf::GetInstance()->RemoveService("servers.webserver");
1281       CZeroconf::GetInstance()->RemoveService("servers.webjsonrpc");
1282       CZeroconf::GetInstance()->RemoveService("servers.webapi");
1283     } else
1284       CLog::Log(LOGWARNING, "Webserver: Failed to stop.");
1285   }
1286 #endif
1287 }
1288
1289 void CApplication::StartAirplayServer()
1290 {
1291 #ifdef HAS_AIRPLAY
1292   if (g_guiSettings.GetBool("services.airplay") && m_network.IsAvailable())
1293   {
1294     CStdString password = g_guiSettings.GetString("services.airplaypassword");
1295     bool usePassword = g_guiSettings.GetBool("services.useairplaypassword");
1296     
1297     if (CAirPlayServer::StartServer(9091, true))
1298     {
1299       CAirPlayServer::SetCredentials(usePassword, password);
1300       std::map<std::string, std::string> txt;
1301       txt["deviceid"] = m_network.GetFirstConnectedInterface()->GetMacAddress();
1302       txt["features"] = "0x77";
1303       txt["model"] = "AppleTV2,1";
1304       txt["srcvers"] = "101.28";
1305       CZeroconf::GetInstance()->PublishService("servers.airplay", "_airplay._tcp", "XBMC", 9091, txt);
1306     }
1307   }
1308 #endif
1309 #ifdef HAS_AIRTUNES
1310   if (g_guiSettings.GetBool("services.airplay") && m_network.IsAvailable())
1311   {   
1312     CStdString password = g_guiSettings.GetString("services.airplaypassword");
1313     bool usePassword = g_guiSettings.GetBool("services.useairplaypassword");
1314       
1315     if (!CAirTunesServer::StartServer(5000, true, usePassword, password))
1316     {
1317       CLog::Log(LOGERROR, "Failed to start AirTunes Server");
1318     }
1319   }
1320 #endif
1321 }
1322
1323 void CApplication::StopAirplayServer(bool bWait)
1324 {
1325 #ifdef HAS_AIRPLAY
1326   CAirPlayServer::StopServer(bWait);
1327   CZeroconf::GetInstance()->RemoveService("servers.airplay");
1328 #endif
1329 #ifdef HAS_AIRTUNES
1330   CAirTunesServer::StopServer(bWait);
1331 #endif
1332 }
1333
1334 bool CApplication::StartJSONRPCServer()
1335 {
1336 #ifdef HAS_JSONRPC
1337   if (g_guiSettings.GetBool("services.esenabled"))
1338   {
1339     CJSONRPC::Initialize();
1340
1341     if (CTCPServer::StartServer(g_advancedSettings.m_jsonTcpPort, g_guiSettings.GetBool("services.esallinterfaces")))
1342     {
1343       std::map<std::string, std::string> txt;  
1344       CZeroconf::GetInstance()->PublishService("servers.jsonrpc", "_xbmc-jsonrpc._tcp", "XBMC JSONRPC", g_advancedSettings.m_jsonTcpPort, txt);
1345       return true;
1346     }
1347     else
1348       return false;
1349   }
1350 #endif
1351
1352   return true;
1353 }
1354
1355 void CApplication::StopJSONRPCServer(bool bWait)
1356 {
1357 #ifdef HAS_JSONRPC
1358   CTCPServer::StopServer(bWait);
1359   CZeroconf::GetInstance()->RemoveService("servers.jsonrpc");
1360 #endif
1361 }
1362
1363 void CApplication::StartUPnP()
1364 {
1365 #ifdef HAS_UPNP
1366   StartUPnPServer();
1367   StartUPnPRenderer();
1368 #endif
1369 }
1370
1371 void CApplication::StopUPnP(bool bWait)
1372 {
1373 #ifdef HAS_UPNP
1374   if (CUPnP::IsInstantiated())
1375   {
1376     CLog::Log(LOGNOTICE, "stopping upnp");
1377     CUPnP::ReleaseInstance(bWait);
1378   }
1379 #endif
1380 }
1381
1382 bool CApplication::StartEventServer()
1383 {
1384 #ifdef HAS_EVENT_SERVER
1385   CEventServer* server = CEventServer::GetInstance();
1386   if (!server)
1387   {
1388     CLog::Log(LOGERROR, "ES: Out of memory");
1389     return false;
1390   }
1391   if (g_guiSettings.GetBool("services.esenabled"))
1392   {
1393     CLog::Log(LOGNOTICE, "ES: Starting event server");
1394     server->StartServer();
1395     return true;
1396   }
1397 #endif
1398   return true;
1399 }
1400
1401 bool CApplication::StopEventServer(bool bWait, bool promptuser)
1402 {
1403 #ifdef HAS_EVENT_SERVER
1404   CEventServer* server = CEventServer::GetInstance();
1405   if (!server)
1406   {
1407     CLog::Log(LOGERROR, "ES: Out of memory");
1408     return false;
1409   }
1410   if (promptuser)
1411   {
1412     if (server->GetNumberOfClients() > 0)
1413     {
1414       bool cancelled = false;
1415       if (!CGUIDialogYesNo::ShowAndGetInput(13140, 13141, 13142, 20022,
1416                                             -1, -1, cancelled, 10000)
1417           || cancelled)
1418       {
1419         CLog::Log(LOGNOTICE, "ES: Not stopping event server");
1420         return false;
1421       }
1422     }
1423     CLog::Log(LOGNOTICE, "ES: Stopping event server with confirmation");
1424
1425     CEventServer::GetInstance()->StopServer(true);
1426   }
1427   else
1428   {
1429     if (!bWait)
1430       CLog::Log(LOGNOTICE, "ES: Stopping event server");
1431
1432     CEventServer::GetInstance()->StopServer(bWait);
1433   }
1434
1435   return true;
1436 #endif
1437 }
1438
1439 void CApplication::RefreshEventServer()
1440 {
1441 #ifdef HAS_EVENT_SERVER
1442   if (g_guiSettings.GetBool("services.esenabled"))
1443   {
1444     CEventServer::GetInstance()->RefreshSettings();
1445   }
1446 #endif
1447 }
1448
1449 void CApplication::StartDbusServer()
1450 {
1451 #ifdef HAS_DBUS_SERVER
1452   CDbusServer* serverDbus = CDbusServer::GetInstance();
1453   if (!serverDbus)
1454   {
1455     CLog::Log(LOGERROR, "DS: Out of memory");
1456     return;
1457   }
1458   CLog::Log(LOGNOTICE, "DS: Starting dbus server");
1459   serverDbus->StartServer( this );
1460 #endif
1461 }
1462
1463 bool CApplication::StopDbusServer(bool bWait)
1464 {
1465 #ifdef HAS_DBUS_SERVER
1466   CDbusServer* serverDbus = CDbusServer::GetInstance();
1467   if (!serverDbus)
1468   {
1469     CLog::Log(LOGERROR, "DS: Out of memory");
1470     return false;
1471   }
1472   CDbusServer::GetInstance()->StopServer(bWait);
1473 #endif
1474   return true;
1475 }
1476
1477 void CApplication::StartUPnPRenderer()
1478 {
1479 #ifdef HAS_UPNP
1480   if (g_guiSettings.GetBool("services.upnprenderer"))
1481   {
1482     CLog::Log(LOGNOTICE, "starting upnp renderer");
1483     CUPnP::GetInstance()->StartRenderer();
1484   }
1485 #endif
1486 }
1487
1488 void CApplication::StopUPnPRenderer()
1489 {
1490 #ifdef HAS_UPNP
1491   if (CUPnP::IsInstantiated())
1492   {
1493     CLog::Log(LOGNOTICE, "stopping upnp renderer");
1494     CUPnP::GetInstance()->StopRenderer();
1495   }
1496 #endif
1497 }
1498
1499 void CApplication::StartUPnPServer()
1500 {
1501 #ifdef HAS_UPNP
1502   if (g_guiSettings.GetBool("services.upnpserver"))
1503   {
1504     CLog::Log(LOGNOTICE, "starting upnp server");
1505     CUPnP::GetInstance()->StartServer();
1506   }
1507 #endif
1508 }
1509
1510 void CApplication::StopUPnPServer()
1511 {
1512 #ifdef HAS_UPNP
1513   if (CUPnP::IsInstantiated())
1514   {
1515     CLog::Log(LOGNOTICE, "stopping upnp server");
1516     CUPnP::GetInstance()->StopServer();
1517   }
1518 #endif
1519 }
1520
1521 void CApplication::StartZeroconf()
1522 {
1523 #ifdef HAS_ZEROCONF
1524   //entry in guisetting only present if HAS_ZEROCONF is set
1525   if(g_guiSettings.GetBool("services.zeroconf"))
1526   {
1527     CLog::Log(LOGNOTICE, "starting zeroconf publishing");
1528     CZeroconf::GetInstance()->Start();
1529   }
1530 #endif
1531 }
1532
1533 void CApplication::StopZeroconf()
1534 {
1535 #ifdef HAS_ZEROCONF
1536   if(CZeroconf::IsInstantiated())
1537   {
1538     CLog::Log(LOGNOTICE, "stopping zeroconf publishing");
1539     CZeroconf::GetInstance()->Stop();
1540   }
1541 #endif
1542 }
1543
1544 void CApplication::DimLCDOnPlayback(bool dim)
1545 {
1546 #ifdef HAS_LCD
1547   if (g_lcd)
1548   {
1549     if (dim)
1550       g_lcd->DisableOnPlayback(IsPlayingVideo(), IsPlayingAudio());
1551     else
1552       g_lcd->SetBackLight(1);
1553   }
1554 #endif
1555 }
1556
1557 void CApplication::StartServices()
1558 {
1559 #if !defined(_WIN32) && defined(HAS_DVD_DRIVE)
1560   // Start Thread for DVD Mediatype detection
1561   CLog::Log(LOGNOTICE, "start dvd mediatype detection");
1562   m_DetectDVDType.Create(false, THREAD_MINSTACKSIZE);
1563 #endif
1564
1565   CLog::Log(LOGNOTICE, "initializing playlistplayer");
1566   g_playlistPlayer.SetRepeat(PLAYLIST_MUSIC, g_settings.m_bMyMusicPlaylistRepeat ? PLAYLIST::REPEAT_ALL : PLAYLIST::REPEAT_NONE);
1567   g_playlistPlayer.SetShuffle(PLAYLIST_MUSIC, g_settings.m_bMyMusicPlaylistShuffle);
1568   g_playlistPlayer.SetRepeat(PLAYLIST_VIDEO, g_settings.m_bMyVideoPlaylistRepeat ? PLAYLIST::REPEAT_ALL : PLAYLIST::REPEAT_NONE);
1569   g_playlistPlayer.SetShuffle(PLAYLIST_VIDEO, g_settings.m_bMyVideoPlaylistShuffle);
1570   CLog::Log(LOGNOTICE, "DONE initializing playlistplayer");
1571
1572 #ifdef HAS_LCD
1573   CLCDFactory factory;
1574   g_lcd = factory.Create();
1575   if (g_lcd)
1576   {
1577     g_lcd->Initialize();
1578   }
1579 #endif
1580 }
1581
1582 void CApplication::StopServices()
1583 {
1584   m_network.NetworkMessage(CNetwork::SERVICES_DOWN, 0);
1585
1586 #if !defined(_WIN32) && defined(HAS_DVD_DRIVE)
1587   CLog::Log(LOGNOTICE, "stop dvd detect media");
1588   m_DetectDVDType.StopThread();
1589 #endif
1590
1591   g_peripherals.Clear();
1592 }
1593
1594 void CApplication::ReloadSkin()
1595 {
1596   m_skinReloading = false;
1597   CGUIMessage msg(GUI_MSG_LOAD_SKIN, -1, g_windowManager.GetActiveWindow());
1598   g_windowManager.SendMessage(msg);
1599   // Reload the skin, restoring the previously focused control.  We need this as
1600   // the window unload will reset all control states.
1601   CGUIWindow* pWindow = g_windowManager.GetWindow(g_windowManager.GetActiveWindow());
1602   int iCtrlID = pWindow->GetFocusedControlID();
1603   g_application.LoadSkin(g_guiSettings.GetString("lookandfeel.skin"));
1604   pWindow = g_windowManager.GetWindow(g_windowManager.GetActiveWindow());
1605   if (pWindow && pWindow->HasSaveLastControl())
1606   {
1607     CGUIMessage msg3(GUI_MSG_SETFOCUS, g_windowManager.GetActiveWindow(), iCtrlID, 0);
1608     pWindow->OnMessage(msg3);
1609   }
1610 }
1611
1612 bool CApplication::LoadSkin(const CStdString& skinID)
1613 {
1614   if (m_skinReloading)
1615     return false;
1616
1617   AddonPtr addon;
1618   if (CAddonMgr::Get().GetAddon(skinID, addon, ADDON_SKIN))
1619   {
1620     LoadSkin(boost::dynamic_pointer_cast<ADDON::CSkinInfo>(addon));
1621     return true;
1622   }
1623   return false;
1624 }
1625
1626 void CApplication::LoadSkin(const SkinPtr& skin)
1627 {
1628   if (!skin)
1629   {
1630     CLog::Log(LOGERROR, "failed to load requested skin, fallback to \"%s\" skin", DEFAULT_SKIN);
1631     g_guiSettings.SetString("lookandfeel.skin", DEFAULT_SKIN);
1632     LoadSkin(DEFAULT_SKIN);
1633     return ;
1634   }
1635
1636   bool bPreviousPlayingState=false;
1637   bool bPreviousRenderingState=false;
1638   if (g_application.m_pPlayer && g_application.IsPlayingVideo())
1639   {
1640     bPreviousPlayingState = !g_application.m_pPlayer->IsPaused();
1641     if (bPreviousPlayingState)
1642       g_application.m_pPlayer->Pause();
1643 #ifdef HAS_VIDEO_PLAYBACK
1644     if (!g_renderManager.Paused())
1645     {
1646       if (g_windowManager.GetActiveWindow() == WINDOW_FULLSCREEN_VIDEO)
1647      {
1648         g_windowManager.ActivateWindow(WINDOW_HOME);
1649         bPreviousRenderingState = true;
1650       }
1651     }
1652 #endif
1653   }
1654   // close the music and video overlays (they're re-opened automatically later)
1655   CSingleLock lock(g_graphicsContext);
1656
1657   // save the current window details
1658   int currentWindow = g_windowManager.GetActiveWindow();
1659   vector<int> currentModelessWindows;
1660   g_windowManager.GetActiveModelessWindows(currentModelessWindows);
1661
1662   UnloadSkin();
1663
1664   CLog::Log(LOGINFO, "  load skin from:%s", skin->Path().c_str());
1665   g_SkinInfo = skin;
1666   g_SkinInfo->Start();
1667
1668   CLog::Log(LOGINFO, "  load fonts for skin...");
1669   g_graphicsContext.SetMediaDir(skin->Path());
1670   g_directoryCache.ClearSubPaths(skin->Path());
1671   if (g_langInfo.ForceUnicodeFont() && !g_fontManager.IsFontSetUnicode(g_guiSettings.GetString("lookandfeel.font")))
1672   {
1673     CLog::Log(LOGINFO, "    language needs a ttf font, loading first ttf font available");
1674     CStdString strFontSet;
1675     if (g_fontManager.GetFirstFontSetUnicode(strFontSet))
1676     {
1677       CLog::Log(LOGINFO, "    new font is '%s'", strFontSet.c_str());
1678       g_guiSettings.SetString("lookandfeel.font", strFontSet);
1679       g_settings.Save();
1680     }
1681     else
1682       CLog::Log(LOGERROR, "    no ttf font found, but needed for the language %s.", g_guiSettings.GetString("locale.language").c_str());
1683   }
1684   g_colorManager.Load(g_guiSettings.GetString("lookandfeel.skincolors"));
1685
1686   g_fontManager.LoadFonts(g_guiSettings.GetString("lookandfeel.font"));
1687
1688   // load in the skin strings
1689   CStdString langPath, skinEnglishPath;
1690   URIUtils::AddFileToFolder(skin->Path(), "language", langPath);
1691   URIUtils::AddFileToFolder(langPath, g_guiSettings.GetString("locale.language"), langPath);
1692   URIUtils::AddFileToFolder(langPath, "strings.xml", langPath);
1693
1694   URIUtils::AddFileToFolder(skin->Path(), "language", skinEnglishPath);
1695   URIUtils::AddFileToFolder(skinEnglishPath, "English", skinEnglishPath);
1696   URIUtils::AddFileToFolder(skinEnglishPath, "strings.xml", skinEnglishPath);
1697
1698   g_localizeStrings.LoadSkinStrings(langPath, skinEnglishPath);
1699
1700   g_SkinInfo->LoadIncludes();
1701
1702   int64_t start;
1703   start = CurrentHostCounter();
1704
1705   CLog::Log(LOGINFO, "  load new skin...");
1706   CGUIWindowHome *pHome = (CGUIWindowHome *)g_windowManager.GetWindow(WINDOW_HOME);
1707   if (!pHome || !pHome->Load("Home.xml"))
1708   {
1709     // failed to load home.xml
1710     // fallback to default skin
1711     if ( strcmpi(skin->ID().c_str(), DEFAULT_SKIN) != 0)
1712     {
1713       CLog::Log(LOGERROR, "failed to load home.xml for skin:%s, fallback to \"%s\" skin", skin->ID().c_str(), DEFAULT_SKIN);
1714       g_guiSettings.SetString("lookandfeel.skin", DEFAULT_SKIN);
1715       LoadSkin(DEFAULT_SKIN);
1716       return ;
1717     }
1718   }
1719
1720   // Load the user windows
1721   LoadUserWindows();
1722
1723   int64_t end, freq;
1724   end = CurrentHostCounter();
1725   freq = CurrentHostFrequency();
1726   CLog::Log(LOGDEBUG,"Load Skin XML: %.2fms", 1000.f * (end - start) / freq);
1727
1728   CLog::Log(LOGINFO, "  initialize new skin...");
1729   g_windowManager.AddMsgTarget(this);
1730   g_windowManager.AddMsgTarget(&g_playlistPlayer);
1731   g_windowManager.AddMsgTarget(&g_infoManager);
1732   g_windowManager.AddMsgTarget(&g_fontManager);
1733   g_windowManager.SetCallback(*this);
1734   g_windowManager.Initialize();
1735   CTextureCache::Get().Initialize();
1736   g_audioManager.Enable(true);
1737   g_audioManager.Load();
1738
1739   if (g_SkinInfo->HasSkinFile("DialogFullScreenInfo.xml"))
1740     g_windowManager.Add(new CGUIDialogFullScreenInfo);
1741
1742   { // we can't register visible condition in dialog's ctor because infomanager is cleared when unloading skin
1743     CGUIDialog *overlay = (CGUIDialog *)g_windowManager.GetWindow(WINDOW_DIALOG_VIDEO_OVERLAY);
1744     if (overlay) overlay->SetVisibleCondition("skin.hasvideooverlay");
1745     overlay = (CGUIDialog *)g_windowManager.GetWindow(WINDOW_DIALOG_MUSIC_OVERLAY);
1746     if (overlay) overlay->SetVisibleCondition("skin.hasmusicoverlay");
1747   }
1748
1749   CLog::Log(LOGINFO, "  skin loaded...");
1750
1751   // leave the graphics lock
1752   lock.Leave();
1753
1754   // restore windows
1755   if (currentWindow != WINDOW_INVALID)
1756   {
1757     g_windowManager.ActivateWindow(currentWindow);
1758     for (unsigned int i = 0; i < currentModelessWindows.size(); i++)
1759     {
1760       CGUIDialog *dialog = (CGUIDialog *)g_windowManager.GetWindow(currentModelessWindows[i]);
1761       if (dialog) dialog->Show();
1762     }
1763   }
1764
1765   if (g_application.m_pPlayer && g_application.IsPlayingVideo())
1766   {
1767     if (bPreviousPlayingState)
1768       g_application.m_pPlayer->Pause();
1769     if (bPreviousRenderingState)
1770       g_windowManager.ActivateWindow(WINDOW_FULLSCREEN_VIDEO);
1771   }
1772 }
1773
1774 void CApplication::UnloadSkin(bool forReload /* = false */)
1775 {
1776   m_skinReloading = forReload;
1777
1778   CLog::Log(LOGINFO, "Unloading old skin %s...", forReload ? "for reload " : "");
1779
1780   g_audioManager.Enable(false);
1781
1782   g_windowManager.DeInitialize();
1783   CTextureCache::Get().Deinitialize();
1784
1785   // remove the skin-dependent window
1786   g_windowManager.Delete(WINDOW_DIALOG_FULLSCREEN_INFO);
1787
1788   g_TextureManager.Cleanup();
1789   g_largeTextureManager.CleanupUnusedImages(true);
1790
1791   g_fontManager.Clear();
1792
1793   g_colorManager.Clear();
1794
1795   g_charsetConverter.reset();
1796
1797   g_infoManager.Clear();
1798 }
1799
1800 bool CApplication::LoadUserWindows()
1801 {
1802   // Start from wherever home.xml is
1803   std::vector<CStdString> vecSkinPath;
1804   g_SkinInfo->GetSkinPaths(vecSkinPath);
1805   for (unsigned int i = 0;i < vecSkinPath.size();++i)
1806   {
1807     CLog::Log(LOGINFO, "Loading user windows, path %s", vecSkinPath[i].c_str());
1808     CFileItemList items;
1809     if (CDirectory::GetDirectory(vecSkinPath[i], items, ".xml", false))
1810     {
1811       for (int i = 0; i < items.Size(); ++i)
1812       {
1813         if (items[i]->m_bIsFolder)
1814           continue;
1815         CStdString skinFile = URIUtils::GetFileName(items[i]->GetPath());
1816         if (skinFile.Left(6).CompareNoCase("custom") == 0)
1817         {
1818           TiXmlDocument xmlDoc;
1819           if (!xmlDoc.LoadFile(items[i]->GetPath()))
1820           {
1821             CLog::Log(LOGERROR, "unable to load:%s, Line %d\n%s", items[i]->GetPath().c_str(), xmlDoc.ErrorRow(), xmlDoc.ErrorDesc());
1822             continue;
1823           }
1824
1825           // Root element should be <window>
1826           TiXmlElement* pRootElement = xmlDoc.RootElement();
1827           CStdString strValue = pRootElement->Value();
1828           if (!strValue.Equals("window"))
1829           {
1830             CLog::Log(LOGERROR, "file :%s doesnt contain <window>", skinFile.c_str());
1831             continue;
1832           }
1833
1834           // Read the <type> element to get the window type to create
1835           // If no type is specified, create a CGUIWindow as default
1836           CGUIWindow* pWindow = NULL;
1837           CStdString strType;
1838           if (pRootElement->Attribute("type"))
1839             strType = pRootElement->Attribute("type");
1840           else
1841           {
1842             const TiXmlNode *pType = pRootElement->FirstChild("type");
1843             if (pType && pType->FirstChild())
1844               strType = pType->FirstChild()->Value();
1845           }
1846           int id = WINDOW_INVALID;
1847           if (!pRootElement->Attribute("id", &id))
1848           {
1849             const TiXmlNode *pType = pRootElement->FirstChild("id");
1850             if (pType && pType->FirstChild())
1851               id = atol(pType->FirstChild()->Value());
1852           }
1853           CStdString visibleCondition;
1854           CGUIControlFactory::GetConditionalVisibility(pRootElement, visibleCondition);
1855
1856           if (strType.Equals("dialog"))
1857             pWindow = new CGUIDialog(id + WINDOW_HOME, skinFile);
1858           else if (strType.Equals("submenu"))
1859             pWindow = new CGUIDialogSubMenu(id + WINDOW_HOME, skinFile);
1860           else if (strType.Equals("buttonmenu"))
1861             pWindow = new CGUIDialogButtonMenu(id + WINDOW_HOME, skinFile);
1862           else
1863             pWindow = new CGUIStandardWindow(id + WINDOW_HOME, skinFile);
1864
1865           // Check to make sure the pointer isn't still null
1866           if (pWindow == NULL)
1867           {
1868             CLog::Log(LOGERROR, "Out of memory / Failed to create new object in LoadUserWindows");
1869             return false;
1870           }
1871           if (id == WINDOW_INVALID || g_windowManager.GetWindow(WINDOW_HOME + id))
1872           {
1873             delete pWindow;
1874             continue;
1875           }
1876           pWindow->SetVisibleCondition(visibleCondition);
1877           g_windowManager.AddCustomWindow(pWindow);
1878         }
1879       }
1880     }
1881   }
1882   return true;
1883 }
1884
1885 bool CApplication::RenderNoPresent()
1886 {
1887   MEASURE_FUNCTION;
1888
1889 // DXMERGE: This may have been important?
1890 //  g_graphicsContext.AcquireCurrentContext();
1891
1892   g_graphicsContext.Lock();
1893
1894   // dont show GUI when playing full screen video
1895   if (g_graphicsContext.IsFullScreenVideo())
1896   {
1897     if (m_bPresentFrame && IsPlaying() && !IsPaused())
1898     {
1899       ResetScreenSaver();
1900       g_renderManager.Present();
1901     }
1902     else
1903       g_renderManager.RenderUpdate(true);
1904
1905     // close window overlays
1906     CGUIDialog *overlay = (CGUIDialog *)g_windowManager.GetWindow(WINDOW_DIALOG_VIDEO_OVERLAY);
1907     if (overlay) overlay->Close(true);
1908     overlay = (CGUIDialog *)g_windowManager.GetWindow(WINDOW_DIALOG_MUSIC_OVERLAY);
1909     if (overlay) overlay->Close(true);
1910
1911   }
1912
1913   bool hasRendered = g_windowManager.Render();
1914
1915   // if we're recording an audio stream then show blinking REC
1916   if (!g_graphicsContext.IsFullScreenVideo())
1917   {
1918     if (m_pPlayer && m_pPlayer->IsRecording() )
1919     {
1920       static int iBlinkRecord = 0;
1921       iBlinkRecord++;
1922       if (iBlinkRecord > 25)
1923       {
1924         CGUIFont* pFont = g_fontManager.GetFont("font13");
1925         CGUITextLayout::DrawText(pFont, 60, 50, 0xffff0000, 0, "REC", 0);
1926       }
1927
1928       if (iBlinkRecord > 50)
1929         iBlinkRecord = 0;
1930     }
1931   }
1932
1933   g_graphicsContext.Unlock();
1934
1935   return hasRendered;
1936 }
1937
1938 float CApplication::GetDimScreenSaverLevel() const
1939 {
1940   if (!m_bScreenSave || !m_screenSaver ||
1941       (m_screenSaver->ID() != "screensaver.xbmc.builtin.dim" &&
1942        m_screenSaver->ID() != "screensaver.xbmc.builtin.black" &&
1943        m_screenSaver->ID() != "screensaver.xbmc.builtin.slideshow"))
1944     return 0;
1945
1946   if (!m_screenSaver->GetSetting("level").IsEmpty())
1947     return 100.0f - (float)atof(m_screenSaver->GetSetting("level"));
1948   return 100.0f;
1949 }
1950
1951 bool CApplication::WaitFrame(unsigned int timeout)
1952 {
1953   bool done = false;
1954
1955   // Wait for all other frames to be presented
1956   CSingleLock lock(m_frameMutex);
1957   //wait until event is set, but modify remaining time
1958
1959   TightConditionVariable<InversePredicate<int&> > cv(m_frameCond, InversePredicate<int&>(m_frameCount));
1960   cv.wait(lock,timeout);
1961   done = m_frameCount == 0;
1962
1963   return done;
1964 }
1965
1966 void CApplication::NewFrame()
1967 {
1968   // We just posted another frame. Keep track and notify.
1969   {
1970     CSingleLock lock(m_frameMutex);
1971     m_frameCount++;
1972   }
1973
1974   m_frameCond.notifyAll();
1975 }
1976
1977 void CApplication::Render()
1978 {
1979   // do not render if we are stopped
1980   if (m_bStop)
1981     return;
1982
1983   if (!m_AppActive && !m_bStop && (!IsPlayingVideo() || IsPaused()))
1984   {
1985     Sleep(1);
1986     ResetScreenSaver();
1987     return;
1988   }
1989
1990   MEASURE_FUNCTION;
1991
1992   int vsync_mode = g_guiSettings.GetInt("videoscreen.vsync");
1993
1994   bool decrement = false;
1995   bool hasRendered = false;
1996   bool limitFrames = false;
1997   unsigned int singleFrameTime = 10; // default limit 100 fps
1998
1999   {
2000     // Less fps in DPMS
2001     bool lowfps = m_dpmsIsActive;
2002     // Whether externalplayer is playing and we're unfocused
2003     bool extPlayerActive = m_eCurrentPlayer >= EPC_EXTPLAYER && IsPlaying() && !m_AppFocused;
2004
2005     m_bPresentFrame = false;
2006     if (!extPlayerActive && g_graphicsContext.IsFullScreenVideo() && !IsPaused())
2007     {
2008       CSingleLock lock(m_frameMutex);
2009
2010       TightConditionVariable<int&> cv(m_frameCond,m_frameCount);
2011       cv.wait(lock,100);
2012
2013       m_bPresentFrame = m_frameCount > 0;
2014       decrement = m_bPresentFrame;
2015       hasRendered = true;
2016     }
2017     else
2018     {
2019       // engage the frame limiter as needed
2020       limitFrames = lowfps || extPlayerActive;
2021       // DXMERGE - we checked for g_videoConfig.GetVSyncMode() before this
2022       //           perhaps allowing it to be set differently than the UI option??
2023       if (vsync_mode == VSYNC_DISABLED || vsync_mode == VSYNC_VIDEO)
2024         limitFrames = true; // not using vsync.
2025       else if ((g_infoManager.GetFPS() > g_graphicsContext.GetFPS() + 10) && g_infoManager.GetFPS() > 1000 / singleFrameTime)
2026         limitFrames = true; // using vsync, but it isn't working.
2027
2028       if (limitFrames)
2029       {
2030         if (extPlayerActive)
2031         {
2032           ResetScreenSaver();  // Prevent screensaver dimming the screen
2033           singleFrameTime = 1000;  // 1 fps, high wakeup latency but v.low CPU usage
2034         }
2035         else if (lowfps)
2036           singleFrameTime = 200;  // 5 fps, <=200 ms latency to wake up
2037       }
2038
2039       decrement = true;
2040     }
2041   }
2042
2043   CSingleLock lock(g_graphicsContext);
2044   g_infoManager.UpdateFPS();
2045
2046   if (g_graphicsContext.IsFullScreenVideo() && IsPlaying() && vsync_mode == VSYNC_VIDEO)
2047     g_Windowing.SetVSync(true);
2048   else if (vsync_mode == VSYNC_ALWAYS)
2049     g_Windowing.SetVSync(true);
2050   else if (vsync_mode != VSYNC_DRIVER)
2051     g_Windowing.SetVSync(false);
2052
2053   if(!g_Windowing.BeginRender())
2054     return;
2055
2056   if (RenderNoPresent())
2057     hasRendered = true;
2058
2059   g_Windowing.EndRender();
2060
2061   g_TextureManager.FreeUnusedTextures();
2062
2063   // reset our info cache - we do this at the end of Render so that it is
2064   // fresh for the next process(), or after a windowclose animation (where process()
2065   // isn't called)
2066   g_infoManager.ResetCache();
2067
2068   lock.Leave();
2069
2070   unsigned int now = XbmcThreads::SystemClockMillis();
2071   if (hasRendered)
2072     m_lastRenderTime = now;
2073
2074   //when nothing has been rendered for m_guiDirtyRegionNoFlipTimeout milliseconds,
2075   //we don't call g_graphicsContext.Flip() anymore, this saves gpu and cpu usage
2076   bool flip;
2077   if (g_advancedSettings.m_guiDirtyRegionNoFlipTimeout >= 0)
2078     flip = hasRendered || (now - m_lastRenderTime) < (unsigned int)g_advancedSettings.m_guiDirtyRegionNoFlipTimeout;
2079   else
2080     flip = true;
2081
2082   //fps limiter, make sure each frame lasts at least singleFrameTime milliseconds
2083   if (limitFrames || !flip)
2084   {
2085     if (!limitFrames)
2086       singleFrameTime = 40; //if not flipping, loop at 25 fps
2087
2088     unsigned int frameTime = now - m_lastFrameTime;
2089     if (frameTime < singleFrameTime)
2090       Sleep(singleFrameTime - frameTime);
2091   }
2092   m_lastFrameTime = XbmcThreads::SystemClockMillis();
2093
2094   if (flip)
2095     g_graphicsContext.Flip(g_windowManager.GetDirty());
2096   CTimeUtils::UpdateFrameTime(flip);
2097
2098   g_renderManager.UpdateResolution();
2099   g_renderManager.ManageCaptures();
2100
2101   {
2102     CSingleLock lock(m_frameMutex);
2103     if(m_frameCount > 0 && decrement)
2104       m_frameCount--;
2105   }
2106   m_frameCond.notifyAll();
2107 }
2108
2109 void CApplication::SetStandAlone(bool value)
2110 {
2111   g_advancedSettings.m_handleMounting = m_bStandalone = value;
2112 }
2113
2114 // OnKey() translates the key into a CAction which is sent on to our Window Manager.
2115 // The window manager will return true if the event is processed, false otherwise.
2116 // If not already processed, this routine handles global keypresses.  It returns
2117 // true if the key has been processed, false otherwise.
2118
2119 bool CApplication::OnKey(const CKey& key)
2120 {
2121
2122   // Turn the mouse off, as we've just got a keypress from controller or remote
2123   g_Mouse.SetActive(false);
2124
2125   // get the current active window
2126   int iWin = g_windowManager.GetActiveWindow() & WINDOW_ID_MASK;
2127
2128   // this will be checked for certain keycodes that need
2129   // special handling if the screensaver is active
2130   CAction action = CButtonTranslator::GetInstance().GetAction(iWin, key);
2131
2132   // a key has been pressed.
2133   // reset Idle Timer
2134   m_idleTimer.StartZero();
2135   bool processKey = AlwaysProcess(action);
2136
2137   ResetScreenSaver();
2138
2139   // allow some keys to be processed while the screensaver is active
2140   if (WakeUpScreenSaverAndDPMS() && !processKey)
2141   {
2142     CLog::Log(LOGDEBUG, "%s: %s pressed, screen saver/dpms woken up", __FUNCTION__, g_Keyboard.GetKeyName((int) key.GetButtonCode()).c_str());
2143     return true;
2144   }
2145
2146   // change this if we have a dialog up
2147   if (g_windowManager.HasModalDialog())
2148   {
2149     iWin = g_windowManager.GetTopMostModalDialogID() & WINDOW_ID_MASK;
2150   }
2151   if (iWin == WINDOW_DIALOG_FULLSCREEN_INFO)
2152   { // fullscreen info dialog - special case
2153     action = CButtonTranslator::GetInstance().GetAction(iWin, key);
2154
2155     if (!key.IsAnalogButton())
2156       CLog::Log(LOGDEBUG, "%s: %s pressed, trying fullscreen info action %s", __FUNCTION__, g_Keyboard.GetKeyName((int) key.GetButtonCode()).c_str(), action.GetName().c_str());
2157
2158     if (OnAction(action))
2159       return true;
2160
2161     // fallthrough to the main window
2162     iWin = WINDOW_FULLSCREEN_VIDEO;
2163   }
2164   if (iWin == WINDOW_FULLSCREEN_VIDEO)
2165   {
2166     // current active window is full screen video.
2167     if (g_application.m_pPlayer && g_application.m_pPlayer->IsInMenu())
2168     {
2169       // if player is in some sort of menu, (ie DVDMENU) map buttons differently
2170       action = CButtonTranslator::GetInstance().GetAction(WINDOW_VIDEO_MENU, key);
2171     }
2172     else
2173     {
2174       // no then use the fullscreen window section of keymap.xml to map key->action
2175       action = CButtonTranslator::GetInstance().GetAction(iWin, key);
2176     }
2177   }
2178   else
2179   {
2180     // current active window isnt the fullscreen window
2181     // just use corresponding section from keymap.xml
2182     // to map key->action
2183
2184     // first determine if we should use keyboard input directly
2185     bool useKeyboard = key.FromKeyboard() && (iWin == WINDOW_DIALOG_KEYBOARD || iWin == WINDOW_DIALOG_NUMERIC);
2186     CGUIWindow *window = g_windowManager.GetWindow(iWin);
2187     if (window)
2188     {
2189       CGUIControl *control = window->GetFocusedControl();
2190       if (control)
2191       {
2192         // If this is an edit control set usekeyboard to true. This causes the
2193         // keypress to be processed directly not through the key mappings.
2194         if (control->GetControlType() == CGUIControl::GUICONTROL_EDIT)
2195           useKeyboard = true;
2196
2197         // If the key pressed is shift-A to shift-Z set usekeyboard to true.
2198         // This causes the keypress to be used for list navigation.
2199         if (control->IsContainer() && key.GetModifiers() == CKey::MODIFIER_SHIFT && key.GetVKey() >= XBMCVK_A && key.GetVKey() <= XBMCVK_Z)
2200           useKeyboard = true;
2201       }
2202     }
2203     if (useKeyboard)
2204     {
2205       action = CAction(0); // reset our action
2206       if (g_guiSettings.GetBool("input.remoteaskeyboard"))
2207       {
2208         // users remote is executing keyboard commands, so use the virtualkeyboard section of keymap.xml
2209         // and send those rather than actual keyboard presses.  Only for navigation-type commands though
2210         action = CButtonTranslator::GetInstance().GetAction(WINDOW_DIALOG_KEYBOARD, key);
2211         if (!(action.GetID() == ACTION_MOVE_LEFT ||
2212               action.GetID() == ACTION_MOVE_RIGHT ||
2213               action.GetID() == ACTION_MOVE_UP ||
2214               action.GetID() == ACTION_MOVE_DOWN ||
2215               action.GetID() == ACTION_SELECT_ITEM ||
2216               action.GetID() == ACTION_ENTER ||
2217               action.GetID() == ACTION_PREVIOUS_MENU ||
2218               action.GetID() == ACTION_NAV_BACK))
2219         {
2220           // the action isn't plain navigation - check for a keyboard-specific keymap
2221           action = CButtonTranslator::GetInstance().GetAction(WINDOW_DIALOG_KEYBOARD, key, false);
2222           if (!(action.GetID() >= REMOTE_0 && action.GetID() <= REMOTE_9) ||
2223                 action.GetID() == ACTION_BACKSPACE ||
2224                 action.GetID() == ACTION_SHIFT ||
2225                 action.GetID() == ACTION_SYMBOLS ||
2226                 action.GetID() == ACTION_CURSOR_LEFT ||
2227                 action.GetID() == ACTION_CURSOR_RIGHT)
2228             action = CAction(0); // don't bother with this action
2229         }
2230       }
2231       if (!action.GetID())
2232       {
2233         // keyboard entry - pass the keys through directly
2234         if (key.GetFromHttpApi())
2235           action = CAction(key.GetButtonCode() != KEY_INVALID ? key.GetButtonCode() : 0, key.GetUnicode());
2236         else
2237         { // see if we've got an ascii key
2238           if (key.GetUnicode())
2239             action = CAction(key.GetAscii() | KEY_ASCII, key.GetUnicode());
2240           else
2241             action = CAction(key.GetVKey() | KEY_VKEY);
2242         }
2243       }
2244
2245       CLog::Log(LOGDEBUG, "%s: %s pressed, trying keyboard action %i", __FUNCTION__, g_Keyboard.GetKeyName((int) key.GetButtonCode()).c_str(), action.GetID());
2246
2247       if (OnAction(action))
2248         return true;
2249       // failed to handle the keyboard action, drop down through to standard action
2250     }
2251     if (key.GetFromHttpApi())
2252     {
2253       if (key.GetButtonCode() != KEY_INVALID)
2254         action = CButtonTranslator::GetInstance().GetAction(iWin, key);
2255     }
2256     else
2257       action = CButtonTranslator::GetInstance().GetAction(iWin, key);
2258   }
2259   if (!key.IsAnalogButton())
2260     CLog::Log(LOGDEBUG, "%s: %s pressed, action is %s", __FUNCTION__, g_Keyboard.GetKeyName((int) key.GetButtonCode()).c_str(), action.GetName().c_str());
2261
2262   //  Play a sound based on the action
2263   g_audioManager.PlayActionSound(action);
2264
2265   return OnAction(action);
2266 }
2267
2268 // OnAppCommand is called in response to a XBMC_APPCOMMAND event.
2269 // This needs to return true if it processed the appcommand or false if it didn't
2270 bool CApplication::OnAppCommand(const CAction &action)
2271 {
2272   // Reset the screen saver
2273   ResetScreenSaver();
2274
2275   // If we were currently in the screen saver wake up and don't process the appcommand
2276   if (WakeUpScreenSaverAndDPMS())
2277     return true;
2278
2279   // The action ID is the APPCOMMAND code. We need to retrieve the action
2280   // associated with this appcommand from the mapping table.
2281   uint32_t appcmd = action.GetID();
2282   CKey key(appcmd | KEY_APPCOMMAND, (unsigned int) 0);
2283   int iWin = g_windowManager.GetActiveWindow() & WINDOW_ID_MASK;
2284   CAction appcmdaction = CButtonTranslator::GetInstance().GetAction(iWin, key);
2285
2286   // If we couldn't find an action return false to indicate we have not
2287   // handled this appcommand
2288   if (!appcmdaction.GetID())
2289   {
2290     CLog::Log(LOGDEBUG, "%s: unknown appcommand %d", __FUNCTION__, appcmd);
2291     return false;
2292   }
2293
2294   // Process the appcommand
2295   CLog::Log(LOGDEBUG, "%s: appcommand %d, trying action %s", __FUNCTION__, appcmd, appcmdaction.GetName().c_str());
2296   OnAction(appcmdaction);
2297
2298   // Always return true regardless of whether the action succeeded or not.
2299   // This stops Windows handling the appcommand itself.
2300   return true;
2301 }
2302
2303 bool CApplication::OnAction(const CAction &action)
2304 {
2305 #ifdef HAS_HTTPAPI
2306   // Let's tell the outside world about this action, ignoring mouse moves
2307   if (g_settings.m_HttpApiBroadcastLevel>=2 && action.GetID() != ACTION_MOUSE_MOVE)
2308   {
2309     CStdString tmp;
2310     tmp.Format("%i",action.GetID());
2311     getApplicationMessenger().HttpApi("broadcastlevel; OnAction:"+tmp+";2");
2312   }
2313 #endif
2314
2315   // special case for switching between GUI & fullscreen mode.
2316   if (action.GetID() == ACTION_SHOW_GUI)
2317   { // Switch to fullscreen mode if we can
2318     if (SwitchToFullScreen())
2319     {
2320       m_navigationTimer.StartZero();
2321       return true;
2322     }
2323   }
2324
2325   if (action.GetID() == ACTION_TOGGLE_FULLSCREEN)
2326   {
2327     g_graphicsContext.ToggleFullScreenRoot();
2328     return true;
2329   }
2330
2331   if (action.IsMouse())
2332     g_Mouse.SetActive(true);
2333
2334   // The action PLAYPAUSE behaves as ACTION_PAUSE if we are currently
2335   // playing or ACTION_PLAYER_PLAY if we are not playing.
2336   if (action.GetID() == ACTION_PLAYER_PLAYPAUSE)
2337   {
2338     if (IsPlaying())
2339       return OnAction(CAction(ACTION_PAUSE));
2340     else
2341       return OnAction(CAction(ACTION_PLAYER_PLAY));
2342   }
2343
2344   //if the action would start or stop inertial scrolling
2345   //by gesture - bypass the normal OnAction handler of current window
2346   if( !m_pInertialScrollingHandler->CheckForInertialScrolling(&action) )
2347   {
2348     // in normal case
2349     // just pass the action to the current window and let it handle it
2350     if (g_windowManager.OnAction(action))
2351     {
2352       m_navigationTimer.StartZero();
2353       return true;
2354     }
2355   } 
2356
2357   // handle extra global presses
2358
2359   // screenshot : take a screenshot :)
2360   if (action.GetID() == ACTION_TAKE_SCREENSHOT)
2361   {
2362     CUtil::TakeScreenshot();
2363     return true;
2364   }
2365   // built in functions : execute the built-in
2366   if (action.GetID() == ACTION_BUILT_IN_FUNCTION)
2367   {
2368     CBuiltins::Execute(action.GetName());
2369     m_navigationTimer.StartZero();
2370     return true;
2371   }
2372
2373   // reload keymaps
2374   if (action.GetID() == ACTION_RELOAD_KEYMAPS)
2375   {
2376     CButtonTranslator::GetInstance().Clear();
2377     CButtonTranslator::GetInstance().Load();
2378   }
2379
2380   // show info : Shows the current video or song information
2381   if (action.GetID() == ACTION_SHOW_INFO)
2382   {
2383     g_infoManager.ToggleShowInfo();
2384     return true;
2385   }
2386
2387   // codec info : Shows the current song, video or picture codec information
2388   if (action.GetID() == ACTION_SHOW_CODEC)
2389   {
2390     g_infoManager.ToggleShowCodec();
2391     return true;
2392   }
2393
2394   if ((action.GetID() == ACTION_INCREASE_RATING || action.GetID() == ACTION_DECREASE_RATING) && IsPlayingAudio())
2395   {
2396     const CMusicInfoTag *tag = g_infoManager.GetCurrentSongTag();
2397     if (tag)
2398     {
2399       *m_itemCurrentFile->GetMusicInfoTag() = *tag;
2400       char rating = tag->GetRating();
2401       bool needsUpdate(false);
2402       if (rating > '0' && action.GetID() == ACTION_DECREASE_RATING)
2403       {
2404         m_itemCurrentFile->GetMusicInfoTag()->SetRating(rating - 1);
2405         needsUpdate = true;
2406       }
2407       else if (rating < '5' && action.GetID() == ACTION_INCREASE_RATING)
2408       {
2409         m_itemCurrentFile->GetMusicInfoTag()->SetRating(rating + 1);
2410         needsUpdate = true;
2411       }
2412       if (needsUpdate)
2413       {
2414         CMusicDatabase db;
2415         if (db.Open())      // OpenForWrite() ?
2416         {
2417           db.SetSongRating(m_itemCurrentFile->GetPath(), m_itemCurrentFile->GetMusicInfoTag()->GetRating());
2418           db.Close();
2419         }
2420         // send a message to all windows to tell them to update the fileitem (eg playlistplayer, media windows)
2421         CGUIMessage msg(GUI_MSG_NOTIFY_ALL, 0, 0, GUI_MSG_UPDATE_ITEM, 0, m_itemCurrentFile);
2422         g_windowManager.SendMessage(msg);
2423       }
2424     }
2425     return true;
2426   }
2427
2428   // stop : stops playing current audio song
2429   if (action.GetID() == ACTION_STOP)
2430   {
2431     StopPlaying();
2432     return true;
2433   }
2434
2435   // previous : play previous song from playlist
2436   if (action.GetID() == ACTION_PREV_ITEM)
2437   {
2438     // first check whether we're within 3 seconds of the start of the track
2439     // if not, we just revert to the start of the track
2440     if (m_pPlayer && m_pPlayer->CanSeek() && GetTime() > 3)
2441     {
2442       SeekTime(0);
2443       SetPlaySpeed(1);
2444     }
2445     else
2446     {
2447       g_playlistPlayer.PlayPrevious();
2448     }
2449     return true;
2450   }
2451
2452   // next : play next song from playlist
2453   if (action.GetID() == ACTION_NEXT_ITEM)
2454   {
2455     if (IsPlaying() && m_pPlayer->SkipNext())
2456       return true;
2457
2458     g_playlistPlayer.PlayNext();
2459
2460     return true;
2461   }
2462
2463   if ( IsPlaying())
2464   {
2465     // pause : pauses current audio song
2466     if (action.GetID() == ACTION_PAUSE && m_iPlaySpeed == 1)
2467     {
2468       m_pPlayer->Pause();
2469 #ifdef HAS_KARAOKE
2470       m_pKaraokeMgr->SetPaused( m_pPlayer->IsPaused() );
2471 #endif
2472       if (!m_pPlayer->IsPaused())
2473       { // unpaused - set the playspeed back to normal
2474         SetPlaySpeed(1);
2475       }
2476       g_audioManager.Enable(m_pPlayer->IsPaused() && !g_audioContext.IsPassthroughActive());
2477       return true;
2478     }
2479     if (!m_pPlayer->IsPaused())
2480     {
2481       // if we do a FF/RW in my music then map PLAY action togo back to normal speed
2482       // if we are playing at normal speed, then allow play to pause
2483       if (action.GetID() == ACTION_PLAYER_PLAY || action.GetID() == ACTION_PAUSE)
2484       {
2485         if (m_iPlaySpeed != 1)
2486         {
2487           SetPlaySpeed(1);
2488         }
2489         else
2490         {
2491           m_pPlayer->Pause();
2492         }
2493         return true;
2494       }
2495       if (action.GetID() == ACTION_PLAYER_FORWARD || action.GetID() == ACTION_PLAYER_REWIND)
2496       {
2497         int iPlaySpeed = m_iPlaySpeed;
2498         if (action.GetID() == ACTION_PLAYER_REWIND && iPlaySpeed == 1) // Enables Rewinding
2499           iPlaySpeed *= -2;
2500         else if (action.GetID() == ACTION_PLAYER_REWIND && iPlaySpeed > 1) //goes down a notch if you're FFing
2501           iPlaySpeed /= 2;
2502         else if (action.GetID() == ACTION_PLAYER_FORWARD && iPlaySpeed < 1) //goes up a notch if you're RWing
2503           iPlaySpeed /= 2;
2504         else
2505           iPlaySpeed *= 2;
2506
2507         if (action.GetID() == ACTION_PLAYER_FORWARD && iPlaySpeed == -1) //sets iSpeed back to 1 if -1 (didn't plan for a -1)
2508           iPlaySpeed = 1;
2509         if (iPlaySpeed > 32 || iPlaySpeed < -32)
2510           iPlaySpeed = 1;
2511
2512         SetPlaySpeed(iPlaySpeed);
2513         return true;
2514       }
2515       else if ((action.GetAmount() || GetPlaySpeed() != 1) && (action.GetID() == ACTION_ANALOG_REWIND || action.GetID() == ACTION_ANALOG_FORWARD))
2516       {
2517         // calculate the speed based on the amount the button is held down
2518         int iPower = (int)(action.GetAmount() * MAX_FFWD_SPEED + 0.5f);
2519         // returns 0 -> MAX_FFWD_SPEED
2520         int iSpeed = 1 << iPower;
2521         if (iSpeed != 1 && action.GetID() == ACTION_ANALOG_REWIND)
2522           iSpeed = -iSpeed;
2523         g_application.SetPlaySpeed(iSpeed);
2524         if (iSpeed == 1)
2525           CLog::Log(LOGDEBUG,"Resetting playspeed");
2526         return true;
2527       }
2528     }
2529     // allow play to unpause
2530     else
2531     {
2532       if (action.GetID() == ACTION_PLAYER_PLAY)
2533       {
2534         // unpause, and set the playspeed back to normal
2535         m_pPlayer->Pause();
2536         g_audioManager.Enable(m_pPlayer->IsPaused() && !g_audioContext.IsPassthroughActive());
2537
2538         g_application.SetPlaySpeed(1);
2539         return true;
2540       }
2541     }
2542   }
2543   if (action.GetID() == ACTION_MUTE)
2544   {
2545     ToggleMute();
2546     return true;
2547   }
2548
2549   if (action.GetID() == ACTION_TOGGLE_DIGITAL_ANALOG)
2550   {
2551     switch(g_guiSettings.GetInt("audiooutput.mode"))
2552     {
2553       case AUDIO_ANALOG: g_guiSettings.SetInt("audiooutput.mode", AUDIO_IEC958); break;
2554       case AUDIO_IEC958: g_guiSettings.SetInt("audiooutput.mode", AUDIO_HDMI  ); break;
2555       case AUDIO_HDMI  : g_guiSettings.SetInt("audiooutput.mode", AUDIO_ANALOG); break;
2556     }
2557
2558     g_application.Restart();
2559     if (g_windowManager.GetActiveWindow() == WINDOW_SETTINGS_SYSTEM)
2560     {
2561       CGUIMessage msg(GUI_MSG_WINDOW_INIT, 0,0,WINDOW_INVALID,g_windowManager.GetActiveWindow());
2562       g_windowManager.SendMessage(msg);
2563     }
2564     return true;
2565   }
2566
2567   // Check for global volume control
2568   if (action.GetAmount() && (action.GetID() == ACTION_VOLUME_UP || action.GetID() == ACTION_VOLUME_DOWN))
2569   {
2570     if (!m_pPlayer || !m_pPlayer->IsPassthrough())
2571     {
2572       // increase or decrease the volume
2573       int volume;
2574       if (g_settings.m_bMute)
2575       {
2576         volume = (int)((float)g_settings.m_iPreMuteVolumeLevel * 0.01f * (VOLUME_MAXIMUM - VOLUME_MINIMUM) + VOLUME_MINIMUM);
2577         UnMute();
2578       }
2579       else
2580         volume = g_settings.m_nVolumeLevel + g_settings.m_dynamicRangeCompressionLevel;
2581
2582       // calculate speed so that a full press will equal 1 second from min to max
2583       float speed = float(VOLUME_MAXIMUM - VOLUME_MINIMUM);
2584       if (action.GetRepeat())
2585         speed *= action.GetRepeat();
2586       else
2587         speed /= 50; //50 fps
2588
2589       if (action.GetID() == ACTION_VOLUME_UP)
2590         volume += (int)((float)fabs(action.GetAmount()) * action.GetAmount() * speed);
2591       else
2592         volume -= (int)((float)fabs(action.GetAmount()) * action.GetAmount() * speed);
2593
2594       SetVolume(volume, false);
2595     }
2596     // show visual feedback of volume change...
2597     ShowVolumeBar(&action);
2598     return true;
2599   }
2600   // Check for global seek control
2601   if (IsPlaying() && action.GetAmount() && (action.GetID() == ACTION_ANALOG_SEEK_FORWARD || action.GetID() == ACTION_ANALOG_SEEK_BACK))
2602   {
2603     if (!m_pPlayer->CanSeek()) return false;
2604     CGUIWindow *seekBar = g_windowManager.GetWindow(WINDOW_DIALOG_SEEK_BAR);
2605     if (seekBar)
2606       seekBar->OnAction(action);
2607     return true;
2608   }
2609   if (action.GetID() == ACTION_GUIPROFILE_BEGIN)
2610   {
2611     CGUIControlProfiler::Instance().SetOutputFile(_P("special://home/guiprofiler.xml"));
2612     CGUIControlProfiler::Instance().Start();
2613     return true;
2614   }
2615   if (action.GetID() == ACTION_SHOW_PLAYLIST)
2616   {
2617     int iPlaylist = g_playlistPlayer.GetCurrentPlaylist();
2618     if (iPlaylist == PLAYLIST_VIDEO)
2619       g_windowManager.ActivateWindow(WINDOW_VIDEO_PLAYLIST);
2620     else if (iPlaylist == PLAYLIST_MUSIC)
2621       g_windowManager.ActivateWindow(WINDOW_MUSIC_PLAYLIST);
2622     return true;
2623   }
2624   return false;
2625 }
2626
2627 void CApplication::UpdateLCD()
2628 {
2629 #ifdef HAS_LCD
2630   static unsigned int lTickCount = 0;
2631
2632   if (!g_lcd || !g_guiSettings.GetBool("videoscreen.haslcd"))
2633     return ;
2634   unsigned int lTimeOut = 1000;
2635   if ( m_iPlaySpeed != 1)
2636     lTimeOut = 0;
2637   if ( (XbmcThreads::SystemClockMillis() - lTickCount) >= lTimeOut)
2638   {
2639     if (g_application.NavigationIdleTime() < 5)
2640       g_lcd->Render(ILCD::LCD_MODE_NAVIGATION);
2641     else if (IsPlayingVideo())
2642       g_lcd->Render(ILCD::LCD_MODE_VIDEO);
2643     else if (IsPlayingAudio())
2644       g_lcd->Render(ILCD::LCD_MODE_MUSIC);
2645     else if (IsInScreenSaver())
2646       g_lcd->Render(ILCD::LCD_MODE_SCREENSAVER);
2647     else
2648       g_lcd->Render(ILCD::LCD_MODE_GENERAL);
2649
2650     // reset tick count
2651     lTickCount = XbmcThreads::SystemClockMillis();
2652   }
2653 #endif
2654 }
2655
2656 void CApplication::FrameMove(bool processEvents)
2657 {
2658   MEASURE_FUNCTION;
2659
2660   if (processEvents)
2661   {
2662     // currently we calculate the repeat time (ie time from last similar keypress) just global as fps
2663     float frameTime = m_frameTime.GetElapsedSeconds();
2664     m_frameTime.StartZero();
2665     // never set a frametime less than 2 fps to avoid problems when debuggin and on breaks
2666     if( frameTime > 0.5 ) frameTime = 0.5;
2667
2668     g_graphicsContext.Lock();
2669     // check if there are notifications to display
2670     CGUIDialogKaiToast *toast = (CGUIDialogKaiToast *)g_windowManager.GetWindow(WINDOW_DIALOG_KAI_TOAST);
2671     if (toast && toast->DoWork())
2672     {
2673       if (!toast->IsDialogRunning())
2674       {
2675         toast->Show();
2676       }
2677     }
2678     g_graphicsContext.Unlock();
2679
2680     UpdateLCD();
2681
2682 #if defined(HAS_LIRC) || defined(HAS_IRSERVERSUITE)
2683     // Read the input from a remote
2684     g_RemoteControl.Update();
2685 #endif
2686
2687     // process input actions
2688     CWinEvents::MessagePump();
2689     ProcessHTTPApiButtons();
2690     ProcessRemote(frameTime);
2691     ProcessGamepad(frameTime);
2692     ProcessEventServer(frameTime);
2693     ProcessPeripherals(frameTime);
2694     m_pInertialScrollingHandler->ProcessInertialScroll(frameTime);
2695   }
2696   if (!m_bStop)
2697     g_windowManager.Process(CTimeUtils::GetFrameTime());
2698   g_windowManager.FrameMove();
2699 }
2700
2701 bool CApplication::ProcessGamepad(float frameTime)
2702 {
2703 #ifdef HAS_SDL_JOYSTICK
2704   if (!m_AppFocused)
2705     return false;
2706   int iWin = g_windowManager.GetActiveWindow() & WINDOW_ID_MASK;
2707   if (g_windowManager.HasModalDialog())
2708   {
2709     iWin = g_windowManager.GetTopMostModalDialogID() & WINDOW_ID_MASK;
2710   }
2711   int bid;
2712   g_Joystick.Update();
2713   if (g_Joystick.GetButton(bid))
2714   {
2715     // reset Idle Timer
2716     m_idleTimer.StartZero();
2717
2718     ResetScreenSaver();
2719     if (WakeUpScreenSaverAndDPMS())
2720     {
2721       g_Joystick.Reset(true);
2722       return true;
2723     }
2724
2725     int actionID;
2726     CStdString actionName;
2727     bool fullrange;
2728     if (CButtonTranslator::GetInstance().TranslateJoystickString(iWin, g_Joystick.GetJoystick().c_str(), bid, JACTIVE_BUTTON, actionID, actionName, fullrange))
2729     {
2730       CAction action(actionID, 1.0f, 0.0f, actionName);
2731       g_audioManager.PlayActionSound(action);
2732       g_Joystick.Reset();
2733       g_Mouse.SetActive(false);
2734       return OnAction(action);
2735     }
2736     else
2737     {
2738       g_Joystick.Reset();
2739     }
2740   }
2741   if (g_Joystick.GetAxis(bid))
2742   {
2743     if (g_Joystick.GetAmount() < 0)
2744     {
2745       bid = -bid;
2746     }
2747
2748     int actionID;
2749     CStdString actionName;
2750     bool fullrange;
2751     if (CButtonTranslator::GetInstance().TranslateJoystickString(iWin, g_Joystick.GetJoystick().c_str(), bid, JACTIVE_AXIS, actionID, actionName, fullrange))
2752     {
2753       ResetScreenSaver();
2754       if (WakeUpScreenSaverAndDPMS())
2755       {
2756         return true;
2757       }
2758
2759       CAction action(actionID, fullrange ? (g_Joystick.GetAmount() + 1.0f)/2.0f : fabs(g_Joystick.GetAmount()), 0.0f, actionName);
2760       g_audioManager.PlayActionSound(action);
2761       g_Joystick.Reset();
2762       g_Mouse.SetActive(false);
2763       return OnAction(action);
2764     }
2765     else
2766     {
2767       g_Joystick.ResetAxis(abs(bid));
2768     }
2769   }
2770   int position;
2771   if (g_Joystick.GetHat(bid, position))
2772   {
2773     // reset Idle Timer
2774     m_idleTimer.StartZero();
2775
2776     ResetScreenSaver();
2777     if (WakeUpScreenSaverAndDPMS())
2778     {
2779       g_Joystick.Reset();
2780       return true;
2781     }
2782
2783     int actionID;
2784     CStdString actionName;
2785     bool fullrange;
2786
2787     bid = position<<16|bid;
2788
2789     if (CButtonTranslator::GetInstance().TranslateJoystickString(iWin, g_Joystick.GetJoystick().c_str(), bid, JACTIVE_HAT, actionID, actionName, fullrange))
2790     {
2791       CAction action(actionID, 1.0f, 0.0f, actionName);
2792       g_audioManager.PlayActionSound(action);
2793       g_Joystick.Reset();
2794       g_Mouse.SetActive(false);
2795       return OnAction(action);
2796     }
2797   }
2798 #endif
2799   return false;
2800 }
2801
2802 bool CApplication::ProcessRemote(float frameTime)
2803 {
2804 #if defined(HAS_LIRC) || defined(HAS_IRSERVERSUITE)
2805   if (g_RemoteControl.GetButton())
2806   {
2807     CKey key(g_RemoteControl.GetButton(), g_RemoteControl.GetHoldTime());
2808     g_RemoteControl.Reset();
2809     return OnKey(key);
2810   }
2811 #endif
2812   return false;
2813 }
2814
2815 bool CApplication::ProcessPeripherals(float frameTime)
2816 {
2817 #ifdef HAVE_LIBCEC
2818   vector<CPeripheral *> peripherals;
2819   if (g_peripherals.GetPeripheralsWithFeature(peripherals, FEATURE_CEC))
2820   {
2821     for (unsigned int iPeripheralPtr = 0; iPeripheralPtr < peripherals.size(); iPeripheralPtr++)
2822     {
2823       CPeripheralCecAdapter *cecDevice = (CPeripheralCecAdapter *) peripherals.at(iPeripheralPtr);
2824       if (cecDevice && cecDevice->GetButton())
2825       {
2826         CKey key(cecDevice->GetButton(), cecDevice->GetHoldTime());
2827         cecDevice->ResetButton();
2828         return OnKey(key);
2829       }
2830     }
2831   }
2832 #endif
2833
2834   return false;
2835 }
2836
2837 bool CApplication::ProcessMouse()
2838 {
2839   MEASURE_FUNCTION;
2840
2841   if (!g_Mouse.IsActive() || !m_AppFocused)
2842     return false;
2843
2844   // Get the mouse command ID
2845   uint32_t mousecommand = g_Mouse.GetAction();
2846   if (mousecommand == ACTION_NOOP)
2847     return true;
2848
2849   // Reset the screensaver and idle timers
2850   m_idleTimer.StartZero();
2851   ResetScreenSaver();
2852   if (WakeUpScreenSaverAndDPMS())
2853     return true;
2854
2855   // Retrieve the corresponding action
2856   int iWin;
2857   CKey key(mousecommand | KEY_MOUSE, (unsigned int) 0);
2858   if (g_windowManager.HasModalDialog())
2859     iWin = g_windowManager.GetTopMostModalDialogID() & WINDOW_ID_MASK;
2860   else
2861     iWin = g_windowManager.GetActiveWindow() & WINDOW_ID_MASK;
2862   CAction mouseaction = CButtonTranslator::GetInstance().GetAction(iWin, key);
2863
2864   // If we couldn't find an action return false to indicate we have not
2865   // handled this mouse action
2866   if (!mouseaction.GetID())
2867   {
2868     CLog::Log(LOGDEBUG, "%s: unknown mouse command %d", __FUNCTION__, mousecommand);
2869     return false;
2870   }
2871
2872   // Log mouse actions except for move and noop
2873   if (mouseaction.GetID() != ACTION_MOUSE_MOVE && mouseaction.GetID() != ACTION_NOOP)
2874     CLog::Log(LOGDEBUG, "%s: trying mouse action %s", __FUNCTION__, mouseaction.GetName().c_str());
2875
2876   // The action might not be a mouse action. For example wheel moves might
2877   // be mapped to volume up/down in mouse.xml. In this case we do not want
2878   // the mouse position saved in the action.
2879   if (!mouseaction.IsMouse())
2880     return OnAction(mouseaction);
2881
2882   // This is a mouse action so we need to record the mouse position
2883   return OnAction(CAction(mouseaction.GetID(), 
2884                           g_Mouse.GetHold(MOUSE_LEFT_BUTTON), 
2885                           (float)g_Mouse.GetX(), 
2886                           (float)g_Mouse.GetY(), 
2887                           (float)g_Mouse.GetDX(), 
2888                           (float)g_Mouse.GetDY(),
2889                           mouseaction.GetName()));
2890 }
2891
2892 void  CApplication::CheckForTitleChange()
2893 {
2894 #ifdef HAS_HTTPAPI
2895   if (g_settings.m_HttpApiBroadcastLevel>=1)
2896   {
2897     if (IsPlayingVideo())
2898     {
2899       const CVideoInfoTag* tagVal = g_infoManager.GetCurrentMovieTag();
2900       if (m_pXbmcHttp && tagVal && !(tagVal->m_strTitle.IsEmpty()))
2901       {
2902         CStdString msg=m_pXbmcHttp->GetOpenTag()+"MovieTitle:"+tagVal->m_strTitle+m_pXbmcHttp->GetCloseTag();
2903         if (m_prevMedia!=msg && g_settings.m_HttpApiBroadcastLevel>=1)
2904         {
2905           getApplicationMessenger().HttpApi("broadcastlevel; MediaChanged:"+msg+";1");
2906           m_prevMedia=msg;
2907         }
2908       }
2909     }
2910     else if (IsPlayingAudio())
2911     {
2912       const CMusicInfoTag* tagVal=g_infoManager.GetCurrentSongTag();
2913       if (m_pXbmcHttp && tagVal)
2914       {
2915         CStdString msg="";
2916         if (!tagVal->GetTitle().IsEmpty())
2917           msg=m_pXbmcHttp->GetOpenTag()+"AudioTitle:"+tagVal->GetTitle()+m_pXbmcHttp->GetCloseTag();
2918         if (!tagVal->GetArtist().IsEmpty())
2919           msg+=m_pXbmcHttp->GetOpenTag()+"AudioArtist:"+tagVal->GetArtist()+m_pXbmcHttp->GetCloseTag();
2920         if (m_prevMedia!=msg)
2921         {
2922           getApplicationMessenger().HttpApi("broadcastlevel; MediaChanged:"+msg+";1");
2923           m_prevMedia=msg;
2924         }
2925       }
2926     }
2927   }
2928 #endif
2929 }
2930
2931 bool CApplication::ProcessHTTPApiButtons()
2932 {
2933 #ifdef HAS_HTTPAPI
2934   if (m_pXbmcHttp)
2935   {
2936     // copy key from webserver, and reset it in case we're called again before
2937     // whatever happens in OnKey()
2938     CKey keyHttp(m_pXbmcHttp->GetKey());
2939     m_pXbmcHttp->ResetKey();
2940     if (keyHttp.GetButtonCode() != KEY_INVALID)
2941     {
2942       if (keyHttp.GetButtonCode() == KEY_VMOUSE) //virtual mouse
2943       {
2944         int actionID = ACTION_MOUSE_MOVE;
2945         if (keyHttp.GetLeftTrigger() == 1)
2946           actionID = ACTION_MOUSE_LEFT_CLICK;
2947         else if (keyHttp.GetLeftTrigger() == 2)
2948           actionID = ACTION_MOUSE_RIGHT_CLICK;
2949         else if (keyHttp.GetLeftTrigger() == 3)
2950           actionID = ACTION_MOUSE_MIDDLE_CLICK;
2951         else if (keyHttp.GetRightTrigger() == 1)
2952           actionID = ACTION_MOUSE_DOUBLE_CLICK;
2953         CAction action(actionID, keyHttp.GetLeftThumbX(), keyHttp.GetLeftThumbY());
2954         OnAction(action);
2955       }
2956       else
2957         OnKey(keyHttp);
2958       return true;
2959     }
2960   }
2961   return false;
2962 #endif
2963 }
2964
2965 bool CApplication::ProcessEventServer(float frameTime)
2966 {
2967 #ifdef HAS_EVENT_SERVER
2968   CEventServer* es = CEventServer::GetInstance();
2969   if (!es || !es->Running() || es->GetNumberOfClients()==0)
2970     return false;
2971
2972   // process any queued up actions
2973   if (es->ExecuteNextAction())
2974   {
2975     // reset idle timers
2976     m_idleTimer.StartZero();
2977     ResetScreenSaver();
2978     WakeUpScreenSaverAndDPMS();
2979   }
2980
2981   // now handle any buttons or axis
2982   std::string joystickName;
2983   bool isAxis = false;
2984   float fAmount = 0.0;
2985
2986   WORD wKeyID = es->GetButtonCode(joystickName, isAxis, fAmount);
2987
2988   if (wKeyID)
2989   {
2990     if (joystickName.length() > 0)
2991     {
2992       if (isAxis == true)
2993       {
2994         if (fabs(fAmount) >= 0.08)
2995           m_lastAxisMap[joystickName][wKeyID] = fAmount;
2996         else
2997           m_lastAxisMap[joystickName].erase(wKeyID);
2998       }
2999
3000       return ProcessJoystickEvent(joystickName, wKeyID, isAxis, fAmount);
3001     }
3002     else
3003     {
3004       CKey key;
3005       if(wKeyID == KEY_BUTTON_LEFT_ANALOG_TRIGGER)
3006         key = CKey(wKeyID, (BYTE)(255*fAmount), 0, 0.0, 0.0, 0.0, 0.0, frameTime);
3007       else if(wKeyID == KEY_BUTTON_RIGHT_ANALOG_TRIGGER)
3008         key = CKey(wKeyID, 0, (BYTE)(255*fAmount), 0.0, 0.0, 0.0, 0.0, frameTime);
3009       else if(wKeyID == KEY_BUTTON_LEFT_THUMB_STICK_LEFT)
3010         key = CKey(wKeyID, 0, 0, -fAmount, 0.0, 0.0, 0.0, frameTime);
3011       else if(wKeyID == KEY_BUTTON_LEFT_THUMB_STICK_RIGHT)
3012         key = CKey(wKeyID, 0, 0,  fAmount, 0.0, 0.0, 0.0, frameTime);
3013       else if(wKeyID == KEY_BUTTON_LEFT_THUMB_STICK_UP)
3014         key = CKey(wKeyID, 0, 0, 0.0,  fAmount, 0.0, 0.0, frameTime);
3015       else if(wKeyID == KEY_BUTTON_LEFT_THUMB_STICK_DOWN)
3016         key = CKey(wKeyID, 0, 0, 0.0, -fAmount, 0.0, 0.0, frameTime);
3017       else if(wKeyID == KEY_BUTTON_RIGHT_THUMB_STICK_LEFT)
3018         key = CKey(wKeyID, 0, 0, 0.0, 0.0, -fAmount, 0.0, frameTime);
3019       else if(wKeyID == KEY_BUTTON_RIGHT_THUMB_STICK_RIGHT)
3020         key = CKey(wKeyID, 0, 0, 0.0, 0.0,  fAmount, 0.0, frameTime);
3021       else if(wKeyID == KEY_BUTTON_RIGHT_THUMB_STICK_UP)
3022         key = CKey(wKeyID, 0, 0, 0.0, 0.0, 0.0,  fAmount, frameTime);
3023       else if(wKeyID == KEY_BUTTON_RIGHT_THUMB_STICK_DOWN)
3024         key = CKey(wKeyID, 0, 0, 0.0, 0.0, 0.0, -fAmount, frameTime);
3025       else
3026         key = CKey(wKeyID);
3027       return OnKey(key);
3028     }
3029   }
3030
3031   if (m_lastAxisMap.size() > 0)
3032   {
3033     // Process all the stored axis.
3034     for (map<std::string, map<int, float> >::iterator iter = m_lastAxisMap.begin(); iter != m_lastAxisMap.end(); ++iter)
3035     {
3036       for (map<int, float>::iterator iterAxis = (*iter).second.begin(); iterAxis != (*iter).second.end(); ++iterAxis)
3037         ProcessJoystickEvent((*iter).first, (*iterAxis).first, true, (*iterAxis).second);
3038     }
3039   }
3040
3041   {
3042     CPoint pos;
3043     if (es->GetMousePos(pos.x, pos.y) && g_Mouse.IsEnabled())
3044       return OnAction(CAction(ACTION_MOUSE_MOVE, pos.x, pos.y));
3045   }
3046 #endif
3047   return false;
3048 }
3049
3050 bool CApplication::ProcessJoystickEvent(const std::string& joystickName, int wKeyID, bool isAxis, float fAmount)
3051 {
3052 #if defined(HAS_EVENT_SERVER)
3053   m_idleTimer.StartZero();
3054
3055    // Make sure to reset screen saver, mouse.
3056    ResetScreenSaver();
3057    if (WakeUpScreenSaverAndDPMS())
3058      return true;
3059
3060 #ifdef HAS_SDL_JOYSTICK
3061    g_Joystick.Reset();
3062 #endif
3063    g_Mouse.SetActive(false);
3064
3065    // Figure out what window we're taking the event for.
3066    int iWin = g_windowManager.GetActiveWindow() & WINDOW_ID_MASK;
3067    if (g_windowManager.HasModalDialog())
3068        iWin = g_windowManager.GetTopMostModalDialogID() & WINDOW_ID_MASK;
3069
3070    // This code is copied from the OnKey handler, it should be factored out.
3071    if (iWin == WINDOW_FULLSCREEN_VIDEO &&
3072        g_application.m_pPlayer &&
3073        g_application.m_pPlayer->IsInMenu())
3074    {
3075      // If player is in some sort of menu, (ie DVDMENU) map buttons differently.
3076      iWin = WINDOW_VIDEO_MENU;
3077    }
3078
3079    int actionID;
3080    CStdString actionName;
3081    bool fullRange = false;
3082
3083    // Translate using regular joystick translator.
3084    if (CButtonTranslator::GetInstance().TranslateJoystickString(iWin, joystickName.c_str(), wKeyID, isAxis ? JACTIVE_AXIS : JACTIVE_BUTTON, actionID, actionName, fullRange))
3085    {
3086      CAction action(actionID, fAmount, 0.0f, actionName);
3087      g_audioManager.PlayActionSound(action);
3088      return OnAction(action);
3089    }
3090    else
3091    {
3092      CLog::Log(LOGDEBUG, "ERROR mapping joystick action. Joystick: %s %i",joystickName.c_str(), wKeyID);
3093    }
3094 #endif
3095
3096    return false;
3097 }
3098
3099 bool CApplication::Cleanup()
3100 {
3101   try
3102   {
3103     g_windowManager.Delete(WINDOW_MUSIC_PLAYLIST);
3104     g_windowManager.Delete(WINDOW_MUSIC_PLAYLIST_EDITOR);
3105     g_windowManager.Delete(WINDOW_MUSIC_FILES);
3106     g_windowManager.Delete(WINDOW_MUSIC_NAV);
3107     g_windowManager.Delete(WINDOW_DIALOG_MUSIC_INFO);
3108     g_windowManager.Delete(WINDOW_DIALOG_VIDEO_INFO);
3109     g_windowManager.Delete(WINDOW_VIDEO_FILES);
3110     g_windowManager.Delete(WINDOW_VIDEO_PLAYLIST);
3111     g_windowManager.Delete(WINDOW_VIDEO_NAV);
3112     g_windowManager.Delete(WINDOW_FILES);
3113     g_windowManager.Delete(WINDOW_DIALOG_YES_NO);
3114     g_windowManager.Delete(WINDOW_DIALOG_PROGRESS);
3115     g_windowManager.Delete(WINDOW_DIALOG_NUMERIC);
3116     g_windowManager.Delete(WINDOW_DIALOG_GAMEPAD);
3117     g_windowManager.Delete(WINDOW_DIALOG_SUB_MENU);
3118     g_windowManager.Delete(WINDOW_DIALOG_BUTTON_MENU);
3119     g_windowManager.Delete(WINDOW_DIALOG_CONTEXT_MENU);
3120     g_windowManager.Delete(WINDOW_DIALOG_MUSIC_SCAN);
3121     g_windowManager.Delete(WINDOW_DIALOG_PLAYER_CONTROLS);
3122     g_windowManager.Delete(WINDOW_DIALOG_KARAOKE_SONGSELECT);
3123     g_windowManager.Delete(WINDOW_DIALOG_KARAOKE_SELECTOR);
3124     g_windowManager.Delete(WINDOW_DIALOG_MUSIC_OSD);
3125     g_windowManager.Delete(WINDOW_DIALOG_VIS_PRESET_LIST);
3126     g_windowManager.Delete(WINDOW_DIALOG_SELECT);
3127     g_windowManager.Delete(WINDOW_DIALOG_OK);
3128     g_windowManager.Delete(WINDOW_DIALOG_FILESTACKING);
3129     g_windowManager.Delete(WINDOW_DIALOG_KEYBOARD);
3130     g_windowManager.Delete(WINDOW_FULLSCREEN_VIDEO);
3131     g_windowManager.Delete(WINDOW_DIALOG_PROFILE_SETTINGS);
3132     g_windowManager.Delete(WINDOW_DIALOG_LOCK_SETTINGS);
3133     g_windowManager.Delete(WINDOW_DIALOG_NETWORK_SETUP);
3134     g_windowManager.Delete(WINDOW_DIALOG_MEDIA_SOURCE);
3135     g_windowManager.Delete(WINDOW_DIALOG_VIDEO_OSD_SETTINGS);
3136     g_windowManager.Delete(WINDOW_DIALOG_AUDIO_OSD_SETTINGS);
3137     g_windowManager.Delete(WINDOW_DIALOG_VIDEO_BOOKMARKS);
3138     g_windowManager.Delete(WINDOW_DIALOG_VIDEO_SCAN);
3139     g_windowManager.Delete(WINDOW_DIALOG_CONTENT_SETTINGS);
3140     g_windowManager.Delete(WINDOW_DIALOG_FAVOURITES);
3141     g_windowManager.Delete(WINDOW_DIALOG_SONG_INFO);
3142     g_windowManager.Delete(WINDOW_DIALOG_SMART_PLAYLIST_EDITOR);
3143     g_windowManager.Delete(WINDOW_DIALOG_SMART_PLAYLIST_RULE);
3144     g_windowManager.Delete(WINDOW_DIALOG_BUSY);
3145     g_windowManager.Delete(WINDOW_DIALOG_PICTURE_INFO);
3146     g_windowManager.Delete(WINDOW_DIALOG_ADDON_INFO);
3147     g_windowManager.Delete(WINDOW_DIALOG_ADDON_SETTINGS);
3148     g_windowManager.Delete(WINDOW_DIALOG_ACCESS_POINTS);
3149     g_windowManager.Delete(WINDOW_DIALOG_SLIDER);
3150
3151     g_windowManager.Delete(WINDOW_DIALOG_OSD_TELETEXT);
3152     g_windowManager.Delete(WINDOW_DIALOG_TEXT_VIEWER);
3153
3154     g_windowManager.Delete(WINDOW_DIALOG_PLAY_EJECT);
3155
3156     g_windowManager.Delete(WINDOW_STARTUP_ANIM);
3157     g_windowManager.Delete(WINDOW_LOGIN_SCREEN);
3158     g_windowManager.Delete(WINDOW_VISUALISATION);
3159     g_windowManager.Delete(WINDOW_KARAOKELYRICS);
3160     g_windowManager.Delete(WINDOW_SETTINGS_MENU);
3161     g_windowManager.Delete(WINDOW_SETTINGS_PROFILES);
3162     g_windowManager.Delete(WINDOW_SETTINGS_MYPICTURES);  // all the settings categories
3163     g_windowManager.Delete(WINDOW_TEST_PATTERN);
3164     g_windowManager.Delete(WINDOW_SCREEN_CALIBRATION);
3165     g_windowManager.Delete(WINDOW_SYSTEM_INFORMATION);
3166     g_windowManager.Delete(WINDOW_SCREENSAVER);
3167     g_windowManager.Delete(WINDOW_DIALOG_VIDEO_OSD);
3168     g_windowManager.Delete(WINDOW_DIALOG_MUSIC_OVERLAY);
3169     g_windowManager.Delete(WINDOW_DIALOG_VIDEO_OVERLAY);
3170     g_windowManager.Delete(WINDOW_SLIDESHOW);
3171
3172     g_windowManager.Delete(WINDOW_HOME);
3173     g_windowManager.Delete(WINDOW_PROGRAMS);
3174     g_windowManager.Delete(WINDOW_PICTURES);
3175     g_windowManager.Delete(WINDOW_WEATHER);
3176
3177     g_windowManager.Delete(WINDOW_SETTINGS_MYPICTURES);
3178     g_windowManager.Remove(WINDOW_SETTINGS_MYPROGRAMS);
3179     g_windowManager.Remove(WINDOW_SETTINGS_MYWEATHER);
3180     g_windowManager.Remove(WINDOW_SETTINGS_MYMUSIC);
3181     g_windowManager.Remove(WINDOW_SETTINGS_SYSTEM);
3182     g_windowManager.Remove(WINDOW_SETTINGS_MYVIDEOS);
3183     g_windowManager.Remove(WINDOW_SETTINGS_NETWORK);
3184     g_windowManager.Remove(WINDOW_SETTINGS_APPEARANCE);
3185     g_windowManager.Remove(WINDOW_DIALOG_KAI_TOAST);
3186
3187     g_windowManager.Remove(WINDOW_DIALOG_SEEK_BAR);
3188     g_windowManager.Remove(WINDOW_DIALOG_VOLUME_BAR);
3189
3190     CAddonMgr::Get().DeInit();
3191
3192 #if defined(HAS_LIRC) || defined(HAS_IRSERVERSUITE)
3193     CLog::Log(LOGNOTICE, "closing down remote control service");
3194     g_RemoteControl.Disconnect();
3195 #endif
3196
3197     CLog::Log(LOGNOTICE, "unload sections");
3198
3199 #ifdef HAS_PERFORMANCE_SAMPLE
3200     CLog::Log(LOGNOTICE, "performance statistics");
3201     m_perfStats.DumpStats();
3202 #endif
3203
3204     //  Shutdown as much as possible of the
3205     //  application, to reduce the leaks dumped
3206     //  to the vc output window before calling
3207     //  _CrtDumpMemoryLeaks(). Most of the leaks
3208     //  shown are no real leaks, as parts of the app
3209     //  are still allocated.
3210
3211     g_localizeStrings.Clear();
3212     g_LangCodeExpander.Clear();
3213     g_charsetConverter.clear();
3214     g_directoryCache.Clear();
3215     CButtonTranslator::GetInstance().Clear();
3216     CLastfmScrobbler::RemoveInstance();
3217     CLibrefmScrobbler::RemoveInstance();
3218     CLastFmManager::RemoveInstance();
3219 #ifdef HAS_EVENT_SERVER
3220     CEventServer::RemoveInstance();
3221 #endif
3222 #ifdef HAS_DBUS_SERVER
3223     CDbusServer::RemoveInstance();
3224 #endif
3225     DllLoaderContainer::Clear();
3226     g_playlistPlayer.Clear();
3227     g_settings.Clear();
3228     g_guiSettings.Clear();
3229     g_advancedSettings.Clear();
3230
3231 #ifdef _LINUX
3232     CXHandle::DumpObjectTracker();
3233 #endif
3234
3235 #ifdef _CRTDBG_MAP_ALLOC
3236     _CrtDumpMemoryLeaks();
3237     while(1); // execution ends
3238 #endif
3239 #ifdef _WIN32
3240     WSACleanup();
3241
3242     //Uninitialize COM
3243     CoUninitialize();
3244 #endif
3245     return true;
3246   }
3247   catch (...)
3248   {
3249     CLog::Log(LOGERROR, "Exception in CApplication::Cleanup()");
3250     return false;
3251   }
3252 }
3253
3254 void CApplication::Stop(int exitCode)
3255 {
3256   try
3257   {
3258     CAnnouncementManager::Announce(System, "xbmc", "OnQuit");
3259
3260     // cancel any jobs from the jobmanager
3261     CJobManager::GetInstance().CancelJobs();
3262
3263     g_alarmClock.StopThread();
3264
3265 #ifdef HAS_HTTPAPI
3266     if (m_pXbmcHttp)
3267     {
3268       if (g_settings.m_HttpApiBroadcastLevel >= 1)
3269         getApplicationMessenger().HttpApi("broadcastlevel; ShutDown;1");
3270
3271       m_pXbmcHttp->shuttingDown = true;
3272     }
3273 #endif
3274
3275     if( m_bSystemScreenSaverEnable )
3276       g_Windowing.EnableSystemScreenSaver(true);
3277
3278     CLog::Log(LOGNOTICE, "Storing total System Uptime");
3279     g_settings.m_iSystemTimeTotalUp = g_settings.m_iSystemTimeTotalUp + (int)(CTimeUtils::GetFrameTime() / 60000);
3280
3281     // Update the settings information (volume, uptime etc. need saving)
3282     if (CFile::Exists(g_settings.GetSettingsFile()))
3283     {
3284       CLog::Log(LOGNOTICE, "Saving settings");
3285       g_settings.Save();
3286     }
3287     else
3288       CLog::Log(LOGNOTICE, "Not saving settings (settings.xml is not present)");
3289
3290     m_bStop = true;
3291     m_AppActive = false;
3292     m_AppFocused = false;
3293     m_ExitCode = exitCode;
3294     CLog::Log(LOGNOTICE, "stop all");
3295
3296     // stop scanning before we kill the network and so on
3297     CGUIDialogMusicScan *musicScan = (CGUIDialogMusicScan *)g_windowManager.GetWindow(WINDOW_DIALOG_MUSIC_SCAN);
3298     if (musicScan)
3299       musicScan->StopScanning();
3300
3301     CGUIDialogVideoScan *videoScan = (CGUIDialogVideoScan *)g_windowManager.GetWindow(WINDOW_DIALOG_VIDEO_SCAN);
3302     if (videoScan)
3303       videoScan->StopScanning();
3304
3305     m_applicationMessenger.Cleanup();
3306
3307     StopServices();
3308     //Sleep(5000);
3309
3310 #if defined(__APPLE__) && !defined(__arm__)
3311     XBMCHelper::GetInstance().ReleaseAllInput();
3312 #endif
3313
3314     if (m_pPlayer)
3315     {
3316       CLog::Log(LOGNOTICE, "stop player");
3317       delete m_pPlayer;
3318       m_pPlayer = NULL;
3319     }
3320
3321 #if HAS_FILESYTEM_DAAP
3322     CLog::Log(LOGNOTICE, "stop daap clients");
3323     g_DaapClient.Release();
3324 #endif
3325 #ifdef HAS_FILESYSTEM_SAP
3326     CLog::Log(LOGNOTICE, "stop sap announcement listener");
3327     g_sapsessions.StopThread();
3328 #endif
3329 #ifdef HAS_ZEROCONF
3330     if(CZeroconfBrowser::IsInstantiated())
3331     {
3332       CLog::Log(LOGNOTICE, "stop zeroconf browser");
3333       CZeroconfBrowser::GetInstance()->Stop();
3334       CZeroconfBrowser::ReleaseInstance();
3335     }
3336 #endif
3337
3338     CLog::Log(LOGNOTICE, "clean cached files!");
3339 #ifdef HAS_FILESYSTEM_RAR
3340     g_RarManager.ClearCache(true);
3341 #endif
3342
3343 #ifdef HAS_FILESYSTEM_SFTP
3344     CSFTPSessionManager::DisconnectAllSessions();
3345 #endif
3346
3347     CLog::Log(LOGNOTICE, "unload skin");
3348     UnloadSkin();
3349
3350 #if defined(__APPLE__) && !defined(__arm__)
3351     if (XBMCHelper::GetInstance().IsAlwaysOn() == false)
3352       XBMCHelper::GetInstance().Stop();
3353 #endif
3354
3355 #if defined(HAVE_LIBCRYSTALHD)
3356     CCrystalHD::RemoveInstance();
3357 #endif
3358
3359   g_mediaManager.Stop();
3360
3361   // Stop services before unloading Python
3362   CAddonMgr::Get().StopServices(false);
3363
3364 /* Python resource freeing must be done after skin has been unloaded, not before
3365    some windows still need it when deinitializing during skin unloading. */
3366 #ifdef HAS_PYTHON
3367   CLog::Log(LOGNOTICE, "stop python");
3368   g_pythonParser.FreeResources();
3369 #endif
3370 #ifdef HAS_LCD
3371     if (g_lcd)
3372     {
3373       g_lcd->Stop();
3374       delete g_lcd;
3375       g_lcd=NULL;
3376     }
3377 #endif
3378
3379     g_Windowing.DestroyRenderSystem();
3380     g_Windowing.DestroyWindow();
3381     g_Windowing.DestroyWindowSystem();
3382
3383     CLog::Log(LOGNOTICE, "stopped");
3384   }
3385   catch (...)
3386   {
3387     CLog::Log(LOGERROR, "Exception in CApplication::Stop()");
3388   }
3389
3390   // we may not get to finish the run cycle but exit immediately after a call to g_application.Stop()
3391   // so we may never get to Destroy() in CXBApplicationEx::Run(), we call it here.
3392   Destroy();
3393
3394   // 
3395   Sleep(200);
3396 }
3397
3398 bool CApplication::PlayMedia(const CFileItem& item, int iPlaylist)
3399 {
3400   //If item is a plugin, expand out now and run ourselves again
3401   if (item.IsPlugin())
3402   {
3403     CFileItem item_new(item);
3404     if (XFILE::CPluginDirectory::GetPluginResult(item.GetPath(), item_new))
3405       return PlayMedia(item_new, iPlaylist);
3406     return false;
3407   }
3408   if (item.IsLastFM())
3409   {
3410     g_partyModeManager.Disable();
3411     return CLastFmManager::GetInstance()->ChangeStation(item.GetAsUrl());
3412   }
3413   if (item.IsSmartPlayList())
3414   {
3415     CFileItemList items;
3416     CUtil::GetRecursiveListing(item.GetPath(), items, "");
3417     if (items.Size())
3418     {
3419       CSmartPlaylist smartpl;
3420       //get name and type of smartplaylist, this will always succeed as GetDirectory also did this.
3421       smartpl.OpenAndReadName(item.GetPath());
3422       CPlayList playlist;
3423       playlist.Add(items);
3424       return ProcessAndStartPlaylist(smartpl.GetName(), playlist, (smartpl.GetType() == "songs" || smartpl.GetType() == "albums") ? PLAYLIST_MUSIC:PLAYLIST_VIDEO);
3425     }
3426   }
3427   else if (item.IsPlayList() || item.IsInternetStream())
3428   {
3429     CGUIDialogCache* dlgCache = new CGUIDialogCache(5000, g_localizeStrings.Get(10214), item.GetLabel());
3430
3431     //is or could be a playlist
3432     auto_ptr<CPlayList> pPlayList (CPlayListFactory::Create(item));
3433     bool gotPlayList = (pPlayList.get() && pPlayList->Load(item.GetPath()));
3434
3435     if (dlgCache)
3436     {
3437        dlgCache->Close();
3438        if (dlgCache->IsCanceled())
3439           return true;
3440     }
3441
3442     if (gotPlayList)
3443     {
3444
3445       if (iPlaylist != PLAYLIST_NONE)
3446         return ProcessAndStartPlaylist(item.GetPath(), *pPlayList, iPlaylist);
3447       else
3448       {
3449         CLog::Log(LOGWARNING, "CApplication::PlayMedia called to play a playlist %s but no idea which playlist to use, playing first item", item.GetPath().c_str());
3450         if(pPlayList->size())
3451           return PlayFile(*(*pPlayList)[0], false);
3452       }
3453     }
3454   }
3455
3456   //nothing special just play
3457   return PlayFile(item, false);
3458 }
3459
3460 // PlayStack()
3461 // For playing a multi-file video.  Particularly inefficient
3462 // on startup, as we are required to calculate the length
3463 // of each video, so we open + close each one in turn.
3464 // A faster calculation of video time would improve this
3465 // substantially.
3466 bool CApplication::PlayStack(const CFileItem& item, bool bRestart)
3467 {
3468   if (!item.IsStack())
3469     return false;
3470
3471   // see if we have the info in the database
3472   // TODO: If user changes the time speed (FPS via framerate conversion stuff)
3473   //       then these times will be wrong.
3474   //       Also, this is really just a hack for the slow load up times we have
3475   //       A much better solution is a fast reader of FPS and fileLength
3476   //       that we can use on a file to get it's time.
3477   vector<int> times;
3478   bool haveTimes(false);
3479   CVideoDatabase dbs;
3480   if (dbs.Open())
3481   {
3482     dbs.GetVideoSettings(item.GetPath(), g_settings.m_currentVideoSettings);
3483     haveTimes = dbs.GetStackTimes(item.GetPath(), times);
3484     dbs.Close();
3485   }
3486
3487
3488   // calculate the total time of the stack
3489   CStackDirectory dir;
3490   dir.GetDirectory(item.GetPath(), *m_currentStack);
3491   long totalTime = 0;
3492   for (int i = 0; i < m_currentStack->Size(); i++)
3493   {
3494     if (haveTimes)
3495       (*m_currentStack)[i]->m_lEndOffset = times[i];
3496     else
3497     {
3498       int duration;
3499       if (!CDVDFileInfo::GetFileDuration((*m_currentStack)[i]->GetPath(), duration))
3500       {
3501         m_currentStack->Clear();
3502         return false;
3503       }
3504       totalTime += duration / 1000;
3505       (*m_currentStack)[i]->m_lEndOffset = totalTime;
3506       times.push_back(totalTime);
3507     }
3508   }
3509
3510   double seconds = item.m_lStartOffset / 75.0;
3511
3512   if (!haveTimes || item.m_lStartOffset == STARTOFFSET_RESUME )
3513   {  // have our times now, so update the dB
3514     if (dbs.Open())
3515     {
3516       if( !haveTimes )
3517         dbs.SetStackTimes(item.GetPath(), times);
3518
3519       if( item.m_lStartOffset == STARTOFFSET_RESUME )
3520       {
3521         // can only resume seek here, not dvdstate
3522         CBookmark bookmark;
3523         if( dbs.GetResumeBookMark(item.GetPath(), bookmark) )
3524           seconds = bookmark.timeInSeconds;
3525         else
3526           seconds = 0.0f;
3527       }
3528       dbs.Close();
3529     }
3530   }
3531
3532   *m_itemCurrentFile = item;
3533   m_currentStackPosition = 0;
3534   m_eCurrentPlayer = EPC_NONE; // must be reset on initial play otherwise last player will be used
3535
3536   if (seconds > 0)
3537   {
3538     // work out where to seek to
3539     for (int i = 0; i < m_currentStack->Size(); i++)
3540     {
3541       if (seconds < (*m_currentStack)[i]->m_lEndOffset)
3542       {
3543         CFileItem item(*(*m_currentStack)[i]);
3544         long start = (i > 0) ? (*m_currentStack)[i-1]->m_lEndOffset : 0;
3545         item.m_lStartOffset = (long)(seconds - start) * 75;
3546         m_currentStackPosition = i;
3547         return PlayFile(item, true);
3548       }
3549     }
3550   }
3551
3552   return PlayFile(*(*m_currentStack)[0], true);
3553 }
3554
3555 bool CApplication::PlayFile(const CFileItem& item, bool bRestart)
3556 {
3557   if (!bRestart)
3558   {
3559     SaveCurrentFileSettings();
3560
3561     OutputDebugString("new file set audiostream:0\n");
3562     // Switch to default options
3563     g_settings.m_currentVideoSettings = g_settings.m_defaultVideoSettings;
3564     // see if we have saved options in the database
3565
3566     m_iPlaySpeed = 1;
3567     *m_itemCurrentFile = item;
3568     m_nextPlaylistItem = -1;
3569     m_currentStackPosition = 0;
3570     m_currentStack->Clear();
3571
3572     if (item.IsVideo())
3573       CUtil::ClearSubtitles();
3574   }
3575
3576   if (item.IsDiscStub())
3577   {
3578 #ifdef HAS_DVD_DRIVE
3579     // Display the Play Eject dialog
3580     if (CGUIDialogPlayEject::ShowAndGetInput(item))
3581       return MEDIA_DETECT::CAutorun::PlayDisc(!MEDIA_DETECT::CAutorun::CanResumePlayDVD() || CGUIDialogYesNo::ShowAndGetInput(341, -1, -1, -1, 13404, 12021));
3582 #endif
3583     return true;
3584   }
3585
3586   if (item.IsPlayList())
3587     return false;
3588
3589   if (item.IsPlugin())
3590   { // we modify the item so that it becomes a real URL
3591     CFileItem item_new(item);
3592     if (XFILE::CPluginDirectory::GetPluginResult(item.GetPath(), item_new))
3593       return PlayFile(item_new, false);
3594     return false;
3595   }
3596
3597   if (URIUtils::IsUPnP(item.GetPath()))
3598   {
3599     CFileItem item_new(item);
3600     if (XFILE::CUPnPDirectory::GetResource(item.GetPath(), item_new))
3601       return PlayFile(item_new, false);
3602     return false;
3603   }
3604
3605   // if we have a stacked set of files, we need to setup our stack routines for
3606   // "seamless" seeking and total time of the movie etc.
3607   // will recall with restart set to true
3608   if (item.IsStack())
3609     return PlayStack(item, bRestart);
3610
3611   //Is TuxBox, this should probably be moved to CFileTuxBox
3612   if(item.IsTuxBox())
3613   {
3614     CLog::Log(LOGDEBUG, "%s - TuxBox URL Detected %s",__FUNCTION__, item.GetPath().c_str());
3615
3616     if(g_tuxboxService.IsRunning())
3617       g_tuxboxService.Stop();
3618
3619     CFileItem item_new;
3620     if(g_tuxbox.CreateNewItem(item, item_new))
3621     {
3622
3623       // Make sure it doesn't have a player
3624       // so we actually select one normally
3625       m_eCurrentPlayer = EPC_NONE;
3626
3627       // keep the tuxbox:// url as playing url
3628       // and give the new url to the player
3629       if(PlayFile(item_new, true))
3630       {
3631         if(!g_tuxboxService.IsRunning())
3632           g_tuxboxService.Start();
3633         return true;
3634       }
3635     }
3636     return false;
3637   }
3638
3639   CPlayerOptions options;
3640   
3641   if( item.HasProperty("StartPercent") )
3642   {
3643     options.startpercent = item.GetProperty("StartPercent").asDouble();
3644   }
3645   
3646   PLAYERCOREID eNewCore = EPC_NONE;
3647   if( bRestart )
3648   {
3649     // have to be set here due to playstack using this for starting the file
3650     options.starttime = item.m_lStartOffset / 75.0;
3651     if (m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0 && m_itemCurrentFile->m_lStartOffset != 0)
3652       m_itemCurrentFile->m_lStartOffset = STARTOFFSET_RESUME; // to force fullscreen switching
3653
3654     if( m_eForcedNextPlayer != EPC_NONE )
3655       eNewCore = m_eForcedNextPlayer;
3656     else if( m_eCurrentPlayer == EPC_NONE )
3657       eNewCore = CPlayerCoreFactory::GetDefaultPlayer(item);
3658     else
3659       eNewCore = m_eCurrentPlayer;
3660   }
3661   else
3662   {
3663     options.starttime = item.m_lStartOffset / 75.0;
3664
3665     if (item.IsVideo())
3666     {
3667       // open the d/b and retrieve the bookmarks for the current movie
3668       CVideoDatabase dbs;
3669       dbs.Open();
3670       dbs.GetVideoSettings(item.GetPath(), g_settings.m_currentVideoSettings);
3671
3672       if( item.m_lStartOffset == STARTOFFSET_RESUME )
3673       {
3674         options.starttime = 0.0f;
3675         CBookmark bookmark;
3676         CStdString path = item.GetPath();
3677         if (item.IsDVD()) 
3678           path = item.GetVideoInfoTag()->m_strFileNameAndPath;
3679         if(dbs.GetResumeBookMark(path, bookmark))
3680         {
3681           options.starttime = bookmark.timeInSeconds;
3682           options.state = bookmark.playerState;
3683         }
3684       }
3685       else if (item.HasVideoInfoTag())
3686       {
3687         const CVideoInfoTag *tag = item.GetVideoInfoTag();
3688
3689         if (tag->m_iBookmarkId != -1 && tag->m_iBookmarkId != 0)
3690         {
3691           CBookmark bookmark;
3692           dbs.GetBookMarkForEpisode(*tag, bookmark);
3693           options.starttime = bookmark.timeInSeconds;
3694           options.state = bookmark.playerState;
3695         }
3696       }
3697
3698       dbs.Close();
3699     }
3700
3701     if (m_eForcedNextPlayer != EPC_NONE)
3702       eNewCore = m_eForcedNextPlayer;
3703     else
3704       eNewCore = CPlayerCoreFactory::GetDefaultPlayer(item);
3705   }
3706
3707   // this really aught to be inside !bRestart, but since PlayStack
3708   // uses that to init playback, we have to keep it outside
3709   int playlist = g_playlistPlayer.GetCurrentPlaylist();
3710   if (playlist == PLAYLIST_VIDEO && g_playlistPlayer.GetPlaylist(playlist).size() > 1)
3711   { // playing from a playlist by the looks
3712     // don't switch to fullscreen if we are not playing the first item...
3713     options.fullscreen = !g_playlistPlayer.HasPlayedFirstFile() && g_advancedSettings.m_fullScreenOnMovieStart && !g_settings.m_bStartVideoWindowed;
3714   }
3715   else if(m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0)
3716   {
3717     // TODO - this will fail if user seeks back to first file in stack
3718     if(m_currentStackPosition == 0 || m_itemCurrentFile->m_lStartOffset == STARTOFFSET_RESUME)
3719       options.fullscreen = g_advancedSettings.m_fullScreenOnMovieStart && !g_settings.m_bStartVideoWindowed;
3720     else
3721       options.fullscreen = false;
3722     // reset this so we don't think we are resuming on seek
3723     m_itemCurrentFile->m_lStartOffset = 0;
3724   }
3725   else
3726     options.fullscreen = g_advancedSettings.m_fullScreenOnMovieStart && !g_settings.m_bStartVideoWindowed;
3727
3728   // reset m_bStartVideoWindowed as it's a temp setting
3729   g_settings.m_bStartVideoWindowed = false;
3730   // reset any forced player
3731   m_eForcedNextPlayer = EPC_NONE;
3732
3733 #ifdef HAS_KARAOKE
3734   //We have to stop parsing a cdg before mplayer is deallocated
3735   // WHY do we have to do this????
3736   if (m_pKaraokeMgr)
3737     m_pKaraokeMgr->Stop();
3738 #endif
3739
3740   // tell system we are starting a file
3741   m_bPlaybackStarting = true;
3742
3743   // We should restart the player, unless the previous and next tracks are using
3744   // one of the players that allows gapless playback (paplayer, dvdplayer)
3745   if (m_pPlayer)
3746   {
3747     if ( !(m_eCurrentPlayer == eNewCore && (m_eCurrentPlayer == EPC_DVDPLAYER || m_eCurrentPlayer  == EPC_PAPLAYER)) )
3748     {
3749       delete m_pPlayer;
3750       m_pPlayer = NULL;
3751     }
3752   }
3753
3754   if (!m_pPlayer)
3755   {
3756     m_eCurrentPlayer = eNewCore;
3757     m_pPlayer = CPlayerCoreFactory::CreatePlayer(eNewCore, *this);
3758   }
3759
3760   // Workaround for bug/quirk in SDL_Mixer on OSX.
3761   // TODO: Remove after GUI Sounds redux
3762 #if defined(__APPLE__)
3763   g_audioManager.Enable(false);
3764 #endif
3765
3766   bool bResult;
3767   if (m_pPlayer)
3768   {
3769     // don't hold graphicscontext here since player
3770     // may wait on another thread, that requires gfx
3771     CSingleExit ex(g_graphicsContext);
3772     bResult = m_pPlayer->OpenFile(item, options);
3773   }
3774   else
3775   {
3776     CLog::Log(LOGERROR, "Error creating player for item %s (File doesn't exist?)", item.GetPath().c_str());
3777     bResult = false;
3778   }
3779
3780   if(bResult)
3781   {
3782     if (m_iPlaySpeed != 1)
3783     {
3784       int iSpeed = m_iPlaySpeed;
3785       m_iPlaySpeed = 1;
3786       SetPlaySpeed(iSpeed);
3787     }
3788
3789     if( IsPlayingAudio() )
3790     {
3791       if (g_windowManager.GetActiveWindow() == WINDOW_FULLSCREEN_VIDEO)
3792         g_windowManager.ActivateWindow(WINDOW_VISUALISATION);
3793     }
3794
3795 #ifdef HAS_VIDEO_PLAYBACK
3796     if( IsPlayingVideo() )
3797     {
3798       if (g_windowManager.GetActiveWindow() == WINDOW_VISUALISATION)
3799         g_windowManager.ActivateWindow(WINDOW_FULLSCREEN_VIDEO);
3800
3801       // if player didn't manange to switch to fullscreen by itself do it here
3802       if( options.fullscreen && g_renderManager.IsStarted()
3803        && g_windowManager.GetActiveWindow() != WINDOW_FULLSCREEN_VIDEO )
3804        SwitchToFullScreen();
3805
3806       if (!item.IsDVDImage() && !item.IsDVDFile())
3807       {
3808         CVideoInfoTag *details = m_itemCurrentFile->GetVideoInfoTag();
3809         // Save information about the stream if we currently have no data
3810         if (!details->HasStreamDetails() ||
3811              details->m_streamDetails.GetVideoDuration() <= 0)
3812         {
3813           if (m_pPlayer->GetStreamDetails(details->m_streamDetails) && details->HasStreamDetails())
3814           {
3815             CVideoDatabase dbs;
3816             dbs.Open();
3817             dbs.SetStreamDetailsForFileId(details->m_streamDetails, details->m_iFileId);
3818             dbs.Close();
3819             CUtil::DeleteVideoDatabaseDirectoryCache();
3820           }
3821         }
3822       }
3823     }
3824 #endif
3825
3826 #if !defined(__APPLE__)
3827     g_audioManager.Enable(false);
3828 #endif
3829   }
3830   m_bPlaybackStarting = false;
3831   if(bResult)
3832   {
3833     // we must have started, otherwise player might send this later
3834     if(IsPlaying())
3835       OnPlayBackStarted();
3836     else
3837       OnPlayBackEnded();
3838   }
3839   else
3840   {
3841     // we send this if it isn't playlistplayer that is doing this
3842     int next = g_playlistPlayer.GetNextSong();
3843     int size = g_playlistPlayer.GetPlaylist(g_playlistPlayer.GetCurrentPlaylist()).size();
3844     if(next < 0
3845     || next >= size)
3846       OnPlayBackStopped();
3847   }
3848
3849   return bResult;
3850 }
3851
3852 void CApplication::OnPlayBackEnded()
3853 {
3854   if(m_bPlaybackStarting)
3855     return;
3856
3857   // informs python script currently running playback has ended
3858   // (does nothing if python is not loaded)
3859 #ifdef HAS_PYTHON
3860   g_pythonParser.OnPlayBackEnded();
3861 #endif
3862
3863 #ifdef HAS_HTTPAPI
3864   // Let's tell the outside world as well
3865   if (g_settings.m_HttpApiBroadcastLevel>=1)
3866     getApplicationMessenger().HttpApi("broadcastlevel; OnPlayBackEnded;1");
3867 #endif
3868
3869   CAnnouncementManager::Announce(Player, "xbmc", "OnStop");
3870
3871   if (IsPlayingAudio())
3872   {
3873     CLastfmScrobbler::GetInstance()->SubmitQueue();
3874     CLibrefmScrobbler::GetInstance()->SubmitQueue();
3875   }
3876
3877   CGUIMessage msg(GUI_MSG_PLAYBACK_ENDED, 0, 0);
3878   g_windowManager.SendThreadMessage(msg);
3879 }
3880
3881 void CApplication::OnPlayBackStarted()
3882 {
3883   if(m_bPlaybackStarting)
3884     return;
3885
3886 #ifdef HAS_PYTHON
3887   // informs python script currently running playback has started
3888   // (does nothing if python is not loaded)
3889   g_pythonParser.OnPlayBackStarted();
3890 #endif
3891
3892 #ifdef HAS_HTTPAPI
3893   // Let's tell the outside world as well
3894   if (g_settings.m_HttpApiBroadcastLevel>=1)
3895     getApplicationMessenger().HttpApi("broadcastlevel; OnPlayBackStarted;1");
3896 #endif
3897
3898   CGUIMessage msg(GUI_MSG_PLAYBACK_STARTED, 0, 0);
3899   g_windowManager.SendThreadMessage(msg);
3900 }
3901
3902 void CApplication::OnQueueNextItem()
3903 {
3904   // informs python script currently running that we are requesting the next track
3905   // (does nothing if python is not loaded)
3906 #ifdef HAS_PYTHON
3907   g_pythonParser.OnQueueNextItem(); // currently unimplemented
3908 #endif
3909
3910 #ifdef HAS_HTTPAPI
3911   // Let's tell the outside world as well
3912   if (g_settings.m_HttpApiBroadcastLevel>=1)
3913     getApplicationMessenger().HttpApi("broadcastlevel; OnQueueNextItem;1");
3914 #endif
3915
3916   if(IsPlayingAudio())
3917   {
3918     CLastfmScrobbler::GetInstance()->SubmitQueue();
3919     CLibrefmScrobbler::GetInstance()->SubmitQueue();
3920   }
3921
3922   CGUIMessage msg(GUI_MSG_QUEUE_NEXT_ITEM, 0, 0);
3923   g_windowManager.SendThreadMessage(msg);
3924 }
3925
3926 void CApplication::OnPlayBackStopped()
3927 {
3928   if(m_bPlaybackStarting)
3929     return;
3930
3931   // informs python script currently running playback has ended
3932   // (does nothing if python is not loaded)
3933 #ifdef HAS_PYTHON
3934   g_pythonParser.OnPlayBackStopped();
3935 #endif
3936
3937 #ifdef HAS_HTTPAPI
3938   // Let's tell the outside world as well
3939   if (g_settings.m_HttpApiBroadcastLevel>=1)
3940     getApplicationMessenger().HttpApi("broadcastlevel; OnPlayBackStopped;1");
3941 #endif
3942
3943   CAnnouncementManager::Announce(Player, "xbmc", "OnStop", m_itemCurrentFile);
3944
3945   CLastfmScrobbler::GetInstance()->SubmitQueue();
3946   CLibrefmScrobbler::GetInstance()->SubmitQueue();
3947
3948   CGUIMessage msg( GUI_MSG_PLAYBACK_STOPPED, 0, 0 );
3949   g_windowManager.SendThreadMessage(msg);
3950 }
3951
3952 void CApplication::OnPlayBackPaused()
3953 {
3954 #ifdef HAS_PYTHON
3955   g_pythonParser.OnPlayBackPaused();
3956 #endif
3957
3958 #ifdef HAS_HTTPAPI
3959   // Let's tell the outside world as well
3960   if (g_settings.m_HttpApiBroadcastLevel>=1)
3961     getApplicationMessenger().HttpApi("broadcastlevel; OnPlayBackPaused;1");
3962 #endif
3963
3964   CVariant param;
3965   param["player"]["speed"] = 0;
3966   param["player"]["playerid"] = g_playlistPlayer.GetCurrentPlaylist();
3967   CAnnouncementManager::Announce(Player, "xbmc", "OnPause", m_itemCurrentFile, param);
3968 }
3969
3970 void CApplication::OnPlayBackResumed()
3971 {
3972 #ifdef HAS_PYTHON
3973   g_pythonParser.OnPlayBackResumed();
3974 #endif
3975
3976 #ifdef HAS_HTTPAPI
3977   // Let's tell the outside world as well
3978   if (g_settings.m_HttpApiBroadcastLevel>=1)
3979     getApplicationMessenger().HttpApi("broadcastlevel; OnPlayBackResumed;1");
3980 #endif
3981
3982   CVariant param;
3983   param["player"]["speed"] = 1;
3984   param["player"]["playerid"] = g_playlistPlayer.GetCurrentPlaylist();
3985   CAnnouncementManager::Announce(Player, "xbmc", "OnPlay", m_itemCurrentFile, param);
3986 }
3987
3988 void CApplication::OnPlayBackSpeedChanged(int iSpeed)
3989 {
3990 #ifdef HAS_PYTHON
3991   g_pythonParser.OnPlayBackSpeedChanged(iSpeed);
3992 #endif
3993
3994 #ifdef HAS_HTTPAPI
3995   // Let's tell the outside world as well
3996   if (g_settings.m_HttpApiBroadcastLevel>=1)
3997   {
3998     CStdString tmp;
3999     tmp.Format("broadcastlevel; OnPlayBackSpeedChanged:%i;1",iSpeed);
4000     getApplicationMessenger().HttpApi(tmp);
4001   }
4002 #endif
4003
4004   CVariant param;
4005   param["player"]["speed"] = iSpeed;
4006   param["player"]["playerid"] = g_playlistPlayer.GetCurrentPlaylist();
4007   CAnnouncementManager::Announce(Player, "xbmc", "OnSpeedChanged", m_itemCurrentFile, param);
4008 }
4009
4010 void CApplication::OnPlayBackSeek(int iTime, int seekOffset)
4011 {
4012 #ifdef HAS_PYTHON
4013   g_pythonParser.OnPlayBackSeek(iTime, seekOffset);
4014 #endif
4015
4016 #ifdef HAS_HTTPAPI
4017   // Let's tell the outside world as well
4018   if (g_settings.m_HttpApiBroadcastLevel>=1)
4019   {
4020     CStdString tmp;
4021     tmp.Format("broadcastlevel; OnPlayBackSeek:%i;1",iTime);
4022     getApplicationMessenger().HttpApi(tmp);
4023   }
4024 #endif
4025
4026   CVariant param;
4027   CJSONUtils::MillisecondsToTimeObject(iTime, param["player"]["time"]);
4028   CJSONUtils::MillisecondsToTimeObject(seekOffset, param["player"]["seekoffset"]);;
4029   param["player"]["playerid"] = g_playlistPlayer.GetCurrentPlaylist();
4030   param["player"]["speed"] = GetPlaySpeed();
4031   CAnnouncementManager::Announce(Player, "xbmc", "OnSeek", m_itemCurrentFile, param);
4032   g_infoManager.SetDisplayAfterSeek(2500, seekOffset/1000);
4033 }
4034
4035 void CApplication::OnPlayBackSeekChapter(int iChapter)
4036 {
4037 #ifdef HAS_PYTHON
4038   g_pythonParser.OnPlayBackSeekChapter(iChapter);
4039 #endif
4040
4041 #ifdef HAS_HTTPAPI
4042   // Let's tell the outside world as well
4043   if (g_settings.m_HttpApiBroadcastLevel>=1)
4044   {
4045     CStdString tmp;
4046     tmp.Format("broadcastlevel; OnPlayBackSkeekChapter:%i;1",iChapter);
4047     getApplicationMessenger().HttpApi(tmp);
4048   }
4049 #endif
4050 }
4051
4052 bool CApplication::IsPlaying() const
4053 {
4054   if (!m_pPlayer)
4055     return false;
4056   if (!m_pPlayer->IsPlaying())
4057     return false;
4058   return true;
4059 }
4060
4061 bool CApplication::IsPaused() const
4062 {
4063   if (!m_pPlayer)
4064     return false;
4065   if (!m_pPlayer->IsPlaying())
4066     return false;
4067   return m_pPlayer->IsPaused();
4068 }
4069
4070 bool CApplication::IsPlayingAudio() const
4071 {
4072   if (!m_pPlayer)
4073     return false;
4074   if (!m_pPlayer->IsPlaying())
4075     return false;
4076   if (m_pPlayer->HasVideo())
4077     return false;
4078   if (m_pPlayer->HasAudio())
4079     return true;
4080   return false;
4081 }
4082
4083 bool CApplication::IsPlayingVideo() const
4084 {
4085   if (!m_pPlayer)
4086     return false;
4087   if (!m_pPlayer->IsPlaying())
4088     return false;
4089   if (m_pPlayer->HasVideo())
4090     return true;
4091
4092   return false;
4093 }
4094
4095 bool CApplication::IsPlayingFullScreenVideo() const
4096 {
4097   return IsPlayingVideo() && g_graphicsContext.IsFullScreenVideo();
4098 }
4099
4100 void CApplication::SaveFileState()
4101 {
4102   if (!g_settings.GetCurrentProfile().canWriteDatabases())
4103     return;
4104   CJob* job = new CSaveFileStateJob(*m_progressTrackingItem,
4105       m_progressTrackingVideoResumeBookmark,
4106       m_progressTrackingPlayCountUpdate);
4107   CJobManager::GetInstance().AddJob(job, NULL);
4108 }
4109
4110 void CApplication::UpdateFileState()
4111 {
4112   // Did the file change?
4113   if (m_progressTrackingItem->GetPath() != "" && m_progressTrackingItem->GetPath() != CurrentFile())
4114   {
4115     SaveFileState();
4116
4117     // Reset tracking item
4118     m_progressTrackingItem->Reset();
4119   }
4120   else
4121   {
4122     if (IsPlayingVideo() || IsPlayingAudio())
4123     {
4124       if (m_progressTrackingItem->GetPath() == "")
4125       {
4126         // Init some stuff
4127         *m_progressTrackingItem = CurrentFileItem();
4128         m_progressTrackingPlayCountUpdate = false;
4129       }
4130
4131       if ((m_progressTrackingItem->IsAudio() && g_advancedSettings.m_audioPlayCountMinimumPercent > 0 &&
4132           GetPercentage() >= g_advancedSettings.m_audioPlayCountMinimumPercent) ||
4133           (m_progressTrackingItem->IsVideo() && g_advancedSettings.m_videoPlayCountMinimumPercent > 0 &&
4134           GetPercentage() >= g_advancedSettings.m_videoPlayCountMinimumPercent))
4135       {
4136         m_progressTrackingPlayCountUpdate = true;
4137       }
4138
4139       if (m_progressTrackingItem->IsVideo())
4140       {
4141         if ((m_progressTrackingItem->IsDVDImage() || m_progressTrackingItem->IsDVDFile()) && m_pPlayer->GetTotalTime() > 15*60)
4142         {
4143           m_progressTrackingItem->GetVideoInfoTag()->m_streamDetails.Reset();
4144           m_pPlayer->GetStreamDetails(m_progressTrackingItem->GetVideoInfoTag()->m_streamDetails);
4145         }
4146         // Update bookmark for save
4147         m_progressTrackingVideoResumeBookmark.player = CPlayerCoreFactory::GetPlayerName(m_eCurrentPlayer);
4148         m_progressTrackingVideoResumeBookmark.playerState = m_pPlayer->GetPlayerState();
4149         m_progressTrackingVideoResumeBookmark.thumbNailImage.Empty();
4150
4151         if (g_advancedSettings.m_videoIgnorePercentAtEnd > 0 &&
4152             GetTotalTime() - GetTime() < 0.01f * g_advancedSettings.m_videoIgnorePercentAtEnd * GetTotalTime())
4153         {
4154           // Delete the bookmark
4155           m_progressTrackingVideoResumeBookmark.timeInSeconds = -1.0f;
4156         }
4157         else
4158         if (GetTime() > g_advancedSettings.m_videoIgnoreSecondsAtStart)
4159         {
4160           // Update the bookmark
4161           m_progressTrackingVideoResumeBookmark.timeInSeconds = GetTime();
4162           m_progressTrackingVideoResumeBookmark.totalTimeInSeconds = GetTotalTime();
4163         }
4164         else
4165         {
4166           // Do nothing
4167           m_progressTrackingVideoResumeBookmark.timeInSeconds = 0.0f;
4168         }
4169       }
4170     }
4171   }
4172 }
4173
4174 void CApplication::StopPlaying()
4175 {
4176   int iWin = g_windowManager.GetActiveWindow();
4177   if ( IsPlaying() )
4178   {
4179 #ifdef HAS_KARAOKE
4180     if( m_pKaraokeMgr )
4181       m_pKaraokeMgr->Stop();
4182 #endif
4183
4184     if (m_pPlayer)
4185       m_pPlayer->CloseFile();
4186
4187     // turn off visualisation window when stopping
4188     if (iWin == WINDOW_VISUALISATION
4189     ||  iWin == WINDOW_FULLSCREEN_VIDEO)
4190       g_windowManager.PreviousWindow();
4191
4192     g_partyModeManager.Disable();
4193   }
4194 }
4195
4196 void CApplication::ResetScreenSaver()
4197 {
4198   // reset our timers
4199   m_shutdownTimer.StartZero();
4200
4201   // screen saver timer is reset only if we're not already in screensaver or
4202   // DPMS mode
4203   if ((!m_bScreenSave && m_iScreenSaveLock == 0) && !m_dpmsIsActive)
4204     ResetScreenSaverTimer();
4205 }
4206
4207 void CApplication::ResetScreenSaverTimer()
4208 {
4209 #if defined(__APPLE__) && !defined(__arm__)
4210   Cocoa_UpdateSystemActivity();
4211 #endif
4212   m_screenSaverTimer.StartZero();
4213 }
4214
4215 void CApplication::StopScreenSaverTimer()
4216 {
4217   m_screenSaverTimer.Stop();
4218 }
4219
4220 bool CApplication::ToggleDPMS(bool manual)
4221 {
4222   if (manual || (m_dpmsIsManual == manual))
4223   {
4224     if (m_dpmsIsActive)
4225     {
4226       m_dpmsIsActive = false;
4227       m_dpmsIsManual = false;
4228       return m_dpms->DisablePowerSaving();
4229     }
4230     else
4231     {
4232       if (m_dpms->EnablePowerSaving(m_dpms->GetSupportedModes()[0]))
4233       {
4234         m_dpmsIsActive = true;
4235         m_dpmsIsManual = manual;
4236         return true;
4237       }
4238     }
4239   }
4240   return false;
4241 }
4242
4243 bool CApplication::WakeUpScreenSaverAndDPMS()
4244 {
4245
4246 #ifdef HAS_LCD
4247     // turn on lcd backlight
4248     if (g_lcd && g_advancedSettings.m_lcdDimOnScreenSave)
4249       g_lcd->SetBackLight(1);
4250 #endif
4251
4252   // First reset DPMS, if active
4253   if (m_dpmsIsActive)
4254   {
4255     if (m_dpmsIsManual)
4256       return false;
4257     // TODO: if screensaver lock is specified but screensaver is not active
4258     // (DPMS came first), activate screensaver now.
4259     ToggleDPMS(false);
4260     ResetScreenSaverTimer();
4261     return !m_bScreenSave || WakeUpScreenSaver();
4262   }
4263   else
4264     return WakeUpScreenSaver();
4265 }
4266
4267 bool CApplication::WakeUpScreenSaver()
4268 {
4269   if (m_iScreenSaveLock == 2)
4270     return false;
4271
4272   // if Screen saver is active
4273   if (m_bScreenSave && m_screenSaver)
4274   {
4275     if (m_iScreenSaveLock == 0)
4276       if (g_settings.GetMasterProfile().getLockMode() != LOCK_MODE_EVERYONE &&
4277           (g_settings.UsingLoginScreen() || g_guiSettings.GetBool("masterlock.startuplock")) &&
4278           g_settings.GetCurrentProfile().getLockMode() != LOCK_MODE_EVERYONE &&
4279           m_screenSaver->ID() != "screensaver.xbmc.builtin.dim" && m_screenSaver->ID() != "screensaver.xbmc.builtin.black" && m_screenSaver->ID() != "visualization")
4280       {
4281         m_iScreenSaveLock = 2;
4282         CGUIMessage msg(GUI_MSG_CHECK_LOCK,0,0);
4283         g_windowManager.GetWindow(WINDOW_SCREENSAVER)->OnMessage(msg);
4284       }
4285     if (m_iScreenSaveLock == -1)
4286     {
4287       m_iScreenSaveLock = 0;
4288       return true;
4289     }
4290
4291     // disable screensaver
4292     m_bScreenSave = false;
4293     m_iScreenSaveLock = 0;
4294     ResetScreenSaverTimer();
4295
4296     CAnnouncementManager::Announce(GUI, "xbmc", "OnScreensaverDeactivated");
4297
4298     if (m_screenSaver->ID() == "visualization" || m_screenSaver->ID() == "screensaver.xbmc.builtin.slideshow")
4299     {
4300       // we can just continue as usual from vis mode
4301       return false;
4302     }
4303     else if (m_screenSaver->ID() == "screensaver.xbmc.builtin.dim" || m_screenSaver->ID() == "screensaver.xbmc.builtin.black")
4304       return true;
4305     else if (!m_screenSaver->ID().IsEmpty())
4306     { // we're in screensaver window
4307       if (g_windowManager.GetActiveWindow() == WINDOW_SCREENSAVER)
4308         g_windowManager.PreviousWindow();  // show the previous window
4309     }
4310     return true;
4311   }
4312   else
4313     return false;
4314 }
4315
4316 void CApplication::CheckScreenSaverAndDPMS()
4317 {
4318   if (!m_dpmsIsActive)
4319     g_Windowing.ResetOSScreensaver();
4320
4321   bool maybeScreensaver =
4322       !m_dpmsIsActive && !m_bScreenSave
4323       && !g_guiSettings.GetString("screensaver.mode").IsEmpty();
4324   bool maybeDPMS =
4325       !m_dpmsIsActive && m_dpms->IsSupported()
4326       && g_guiSettings.GetInt("powermanagement.displaysoff") > 0;
4327
4328   // Has the screen saver window become active?
4329   if (maybeScreensaver && g_windowManager.IsWindowActive(WINDOW_SCREENSAVER))
4330   {
4331     m_bScreenSave = true;
4332     maybeScreensaver = false;
4333   }
4334
4335   if (!maybeScreensaver && !maybeDPMS) return;  // Nothing to do.
4336
4337   // See if we need to reset timer.
4338   // * Are we playing a video and it is not paused?
4339   if ((IsPlayingVideo() && !m_pPlayer->IsPaused())
4340       // * Are we playing some music in fullscreen vis?
4341       || (IsPlayingAudio() && g_windowManager.GetActiveWindow() == WINDOW_VISUALISATION))
4342   {
4343     ResetScreenSaverTimer();
4344     return;
4345   }
4346
4347   float elapsed = m_screenSaverTimer.GetElapsedSeconds();
4348
4349   // DPMS has priority (it makes the screensaver not needed)
4350   if (maybeDPMS
4351       && elapsed > g_guiSettings.GetInt("powermanagement.displaysoff") * 60)
4352   {
4353     ToggleDPMS(false);
4354     WakeUpScreenSaver();
4355   }
4356   else if (maybeScreensaver
4357            && elapsed > g_guiSettings.GetInt("screensaver.time") * 60)
4358   {
4359     ActivateScreenSaver();
4360   }
4361 }
4362
4363 // activate the screensaver.
4364 // if forceType is true, we ignore the various conditions that can alter
4365 // the type of screensaver displayed
4366 void CApplication::ActivateScreenSaver(bool forceType /*= false */)
4367 {
4368   m_bScreenSave = true;
4369
4370   // Get Screensaver Mode
4371   m_screenSaver.reset();
4372   if (!CAddonMgr::Get().GetAddon(g_guiSettings.GetString("screensaver.mode"), m_screenSaver))
4373     m_screenSaver.reset(new CScreenSaver(""));
4374
4375 #ifdef HAS_LCD
4376   // turn off lcd backlight if requested
4377   if (g_lcd && g_advancedSettings.m_lcdDimOnScreenSave)
4378     g_lcd->SetBackLight(0);
4379 #endif
4380
4381   CAnnouncementManager::Announce(GUI, "xbmc", "OnScreensaverActivated");
4382
4383   // disable screensaver lock from the login screen
4384   m_iScreenSaveLock = g_windowManager.GetActiveWindow() == WINDOW_LOGIN_SCREEN ? 1 : 0;
4385   if (!forceType)
4386   {
4387     // set to Dim in the case of a dialog on screen or playing video
4388     if (g_windowManager.HasModalDialog() || (IsPlayingVideo() && g_guiSettings.GetBool("screensaver.usedimonpause")))
4389     {
4390       if (!CAddonMgr::Get().GetAddon("screensaver.xbmc.builtin.dim", m_screenSaver))
4391         m_screenSaver.reset(new CScreenSaver(""));
4392     }
4393     // Check if we are Playing Audio and Vis instead Screensaver!
4394     else if (IsPlayingAudio() && g_guiSettings.GetBool("screensaver.usemusicvisinstead") && !g_guiSettings.GetString("musicplayer.visualisation").IsEmpty())
4395     { // activate the visualisation
4396       m_screenSaver.reset(new CScreenSaver("visualization"));
4397       g_windowManager.ActivateWindow(WINDOW_VISUALISATION);
4398       return;
4399     }
4400   }
4401   // Picture slideshow
4402   if (m_screenSaver->ID() == "screensaver.xbmc.builtin.slideshow")
4403   {
4404     // reset our codec info - don't want that on screen
4405     g_infoManager.SetShowCodec(false);
4406     CStdString type = m_screenSaver->GetSetting("type");
4407     CStdString path = m_screenSaver->GetSetting("path");
4408     if (type == "2" && path.IsEmpty())
4409       type = "0";
4410     if (type == "0")
4411       path = "special://profile/Thumbnails/Video/Fanart";
4412     if (type == "1")
4413       path = "special://profile/Thumbnails/Music/Fanart";
4414     m_applicationMessenger.PictureSlideShow(path, true, type != "2");
4415   }
4416   else if (m_screenSaver->ID() == "screensaver.xbmc.builtin.dim")
4417     return;
4418   else if (m_screenSaver->ID() == "screensaver.xbmc.builtin.black")
4419     return;
4420   else if (!m_screenSaver->ID().IsEmpty())
4421     g_windowManager.ActivateWindow(WINDOW_SCREENSAVER);
4422 }
4423
4424 void CApplication::CheckShutdown()
4425 {
4426   CGUIDialogMusicScan *pMusicScan = (CGUIDialogMusicScan *)g_windowManager.GetWindow(WINDOW_DIALOG_MUSIC_SCAN);
4427   CGUIDialogVideoScan *pVideoScan = (CGUIDialogVideoScan *)g_windowManager.GetWindow(WINDOW_DIALOG_VIDEO_SCAN);
4428
4429   // first check if we should reset the timer
4430   bool resetTimer = false;
4431   if (IsPlaying() || IsPaused()) // is something playing?
4432     resetTimer = true;
4433
4434   if (pMusicScan && pMusicScan->IsScanning()) // music scanning?
4435     resetTimer = true;
4436
4437   if (pVideoScan && pVideoScan->IsScanning()) // video scanning?
4438     resetTimer = true;
4439
4440   if (g_windowManager.IsWindowActive(WINDOW_DIALOG_PROGRESS)) // progress dialog is onscreen
4441     resetTimer = true;
4442
4443   if (resetTimer)
4444   {
4445     m_shutdownTimer.StartZero();
4446     return;
4447   }
4448
4449   if ( m_shutdownTimer.GetElapsedSeconds() > g_guiSettings.GetInt("powermanagement.shutdowntime") * 60 )
4450   {
4451     // Since it is a sleep instead of a shutdown, let's set everything to reset when we wake up.
4452     m_shutdownTimer.Stop();
4453
4454     // Sleep the box
4455     getApplicationMessenger().Shutdown();
4456   }
4457 }
4458
4459 bool CApplication::OnMessage(CGUIMessage& message)
4460 {
4461   switch ( message.GetMessage() )
4462   {
4463   case GUI_MSG_NOTIFY_ALL:
4464     {
4465       if (message.GetParam1()==GUI_MSG_REMOVED_MEDIA)
4466       {
4467         // Update general playlist: Remove DVD playlist items
4468         int nRemoved = g_playlistPlayer.RemoveDVDItems();
4469         if ( nRemoved > 0 )
4470         {
4471           CGUIMessage msg( GUI_MSG_PLAYLIST_CHANGED, 0, 0 );
4472           g_windowManager.SendMessage( msg );
4473         }
4474         // stop the file if it's on dvd (will set the resume point etc)
4475         if (m_itemCurrentFile->IsOnDVD())
4476           StopPlaying();
4477       }
4478     }
4479     break;
4480
4481   case GUI_MSG_PLAYBACK_STARTED:
4482     {
4483 #ifdef TARGET_DARWIN
4484       DarwinSetScheduling(message.GetMessage());
4485 #endif
4486       // Update our infoManager with the new details etc.
4487       if (m_nextPlaylistItem >= 0)
4488       { // we've started a previously queued item
4489         CFileItemPtr item = g_playlistPlayer.GetPlaylist(g_playlistPlayer.GetCurrentPlaylist())[m_nextPlaylistItem];
4490         // update the playlist manager
4491         int currentSong = g_playlistPlayer.GetCurrentSong();
4492         int param = ((currentSong & 0xffff) << 16) | (m_nextPlaylistItem & 0xffff);
4493         CGUIMessage msg(GUI_MSG_PLAYLISTPLAYER_CHANGED, 0, 0, g_playlistPlayer.GetCurrentPlaylist(), param, item);
4494         g_windowManager.SendThreadMessage(msg);
4495         g_playlistPlayer.SetCurrentSong(m_nextPlaylistItem);
4496         *m_itemCurrentFile = *item;
4497       }
4498       g_infoManager.SetCurrentItem(*m_itemCurrentFile);
4499       CLastFmManager::GetInstance()->OnSongChange(*m_itemCurrentFile);
4500       g_partyModeManager.OnSongChange(true);
4501
4502       CVariant param;
4503       param["player"]["speed"] = 1;
4504       param["player"]["playerid"] = g_playlistPlayer.GetCurrentPlaylist();
4505       CAnnouncementManager::Announce(Player, "xbmc", "OnPlay", m_itemCurrentFile, param);
4506
4507       DimLCDOnPlayback(true);
4508
4509       if (IsPlayingAudio())
4510       {
4511         // Start our cdg parser as appropriate
4512 #ifdef HAS_KARAOKE
4513         if (m_pKaraokeMgr && g_guiSettings.GetBool("karaoke.enabled") && !m_itemCurrentFile->IsInternetStream())
4514         {
4515           m_pKaraokeMgr->Stop();
4516           if (m_itemCurrentFile->IsMusicDb())
4517           {
4518             if (!m_itemCurrentFile->HasMusicInfoTag() || !m_itemCurrentFile->GetMusicInfoTag()->Loaded())
4519             {
4520               IMusicInfoTagLoader* tagloader = CMusicInfoTagLoaderFactory::CreateLoader(m_itemCurrentFile->GetPath());
4521               tagloader->Load(m_itemCurrentFile->GetPath(),*m_itemCurrentFile->GetMusicInfoTag());
4522               delete tagloader;
4523             }
4524             m_pKaraokeMgr->Start(m_itemCurrentFile->GetMusicInfoTag()->GetURL());
4525           }
4526           else
4527             m_pKaraokeMgr->Start(m_itemCurrentFile->GetPath());
4528         }
4529 #endif
4530         // Let scrobbler know about the track
4531         const CMusicInfoTag* tag=g_infoManager.GetCurrentSongTag();
4532         if (tag)
4533         {
4534           CLastfmScrobbler::GetInstance()->AddSong(*tag, CLastFmManager::GetInstance()->IsRadioEnabled());
4535           CLibrefmScrobbler::GetInstance()->AddSong(*tag, CLastFmManager::GetInstance()->IsRadioEnabled());
4536         }
4537       }
4538
4539       return true;
4540     }
4541     break;
4542
4543   case GUI_MSG_QUEUE_NEXT_ITEM:
4544     {
4545       // Check to see if our playlist player has a new item for us,
4546       // and if so, we check whether our current player wants the file
4547       int iNext = g_playlistPlayer.GetNextSong();
4548       CPlayList& playlist = g_playlistPlayer.GetPlaylist(g_playlistPlayer.GetCurrentPlaylist());
4549       if (iNext < 0 || iNext >= playlist.size())
4550       {
4551         if (m_pPlayer) m_pPlayer->OnNothingToQueueNotify();
4552         return true; // nothing to do
4553       }
4554       // ok, grab the next song
4555       CFileItemPtr item = playlist[iNext];
4556       // ok - send the file to the player if it wants it
4557       if (m_pPlayer && m_pPlayer->QueueNextFile(*item))
4558       { // player wants the next file
4559         m_nextPlaylistItem = iNext;
4560       }
4561       return true;
4562     }
4563     break;
4564
4565   case GUI_MSG_PLAYBACK_STOPPED:
4566   case GUI_MSG_PLAYBACK_ENDED:
4567   case GUI_MSG_PLAYLISTPLAYER_STOPPED:
4568     {
4569 #ifdef HAS_KARAOKE
4570       if (m_pKaraokeMgr )
4571         m_pKaraokeMgr->Stop();
4572 #endif
4573 #ifdef TARGET_DARWIN
4574       DarwinSetScheduling(message.GetMessage());
4575 #endif
4576       // first check if we still have items in the stack to play
4577       if (message.GetMessage() == GUI_MSG_PLAYBACK_ENDED)
4578       {
4579         if (m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0 && m_currentStackPosition < m_currentStack->Size() - 1)
4580         { // just play the next item in the stack
4581           PlayFile(*(*m_currentStack)[++m_currentStackPosition], true);
4582           return true;
4583         }
4584       }
4585       
4586       // In case playback ended due to user eg. skipping over the end, clear
4587       // our resume bookmark here
4588       if (message.GetMessage() == GUI_MSG_PLAYBACK_ENDED && m_progressTrackingPlayCountUpdate && g_advancedSettings.m_videoIgnorePercentAtEnd > 0)
4589       {
4590         // Delete the bookmark
4591         m_progressTrackingVideoResumeBookmark.timeInSeconds = -1.0f;
4592       }
4593
4594       // reset the current playing file
4595       m_itemCurrentFile->Reset();
4596       g_infoManager.ResetCurrentItem();
4597       m_currentStack->Clear();
4598
4599       if (message.GetMessage() == GUI_MSG_PLAYBACK_ENDED)
4600       {
4601         g_playlistPlayer.PlayNext(1, true);
4602       }
4603       else
4604       {
4605         // stop lastfm
4606         if (CLastFmManager::GetInstance()->IsRadioEnabled())
4607           CLastFmManager::GetInstance()->StopRadio();
4608
4609         delete m_pPlayer;
4610         m_pPlayer = 0;
4611
4612         // Reset playspeed
4613         m_iPlaySpeed = 1;
4614       }
4615
4616       if (!IsPlaying())
4617       {
4618         g_audioManager.Enable(true);
4619         DimLCDOnPlayback(false);
4620       }
4621
4622       if (!IsPlayingVideo() && g_windowManager.GetActiveWindow() == WINDOW_FULLSCREEN_VIDEO)
4623       {
4624         g_windowManager.PreviousWindow();
4625       }
4626
4627       if (!IsPlayingAudio() && g_playlistPlayer.GetCurrentPlaylist() == PLAYLIST_NONE && g_windowManager.GetActiveWindow() == WINDOW_VISUALISATION)
4628       {
4629         g_settings.Save();  // save vis settings
4630         WakeUpScreenSaverAndDPMS();
4631         g_windowManager.PreviousWindow();
4632       }
4633
4634       // DVD ejected while playing in vis ?
4635       if (!IsPlayingAudio() && (m_itemCurrentFile->IsCDDA() || m_itemCurrentFile->IsOnDVD()) && !g_mediaManager.IsDiscInDrive() && g_windowManager.GetActiveWindow() == WINDOW_VISUALISATION)
4636       {
4637         // yes, disable vis
4638         g_settings.Save();    // save vis settings
4639         WakeUpScreenSaverAndDPMS();
4640         g_windowManager.PreviousWindow();
4641       }
4642
4643       if (IsEnableTestMode()) g_application.getApplicationMessenger().Quit();
4644       return true;
4645     }
4646     break;
4647
4648   case GUI_MSG_PLAYLISTPLAYER_STARTED:
4649   case GUI_MSG_PLAYLISTPLAYER_CHANGED:
4650     {
4651       return true;
4652     }
4653     break;
4654   case GUI_MSG_FULLSCREEN:
4655     { // Switch to fullscreen, if we can
4656       SwitchToFullScreen();
4657       return true;
4658     }
4659     break;
4660   case GUI_MSG_EXECUTE:
4661     if (message.GetNumStringParams())
4662       return ExecuteXBMCAction(message.GetStringParam());
4663     break;
4664   }
4665   return false;
4666 }
4667
4668 bool CApplication::ExecuteXBMCAction(std::string actionStr)
4669     {
4670       // see if it is a user set string
4671       CLog::Log(LOGDEBUG,"%s : Translating %s", __FUNCTION__, actionStr.c_str());
4672       CGUIInfoLabel info(actionStr, "");
4673       actionStr = info.GetLabel(0);
4674       CLog::Log(LOGDEBUG,"%s : To %s", __FUNCTION__, actionStr.c_str());
4675
4676       // user has asked for something to be executed
4677       if (CBuiltins::HasCommand(actionStr))
4678         CBuiltins::Execute(actionStr);
4679       else
4680       {
4681         // try translating the action from our ButtonTranslator
4682         int actionID;
4683         if (CButtonTranslator::TranslateActionString(actionStr.c_str(), actionID))
4684         {
4685           OnAction(CAction(actionID));
4686           return true;
4687         }
4688         CFileItem item(actionStr, false);
4689 #ifdef HAS_PYTHON
4690         if (item.IsPythonScript())
4691         { // a python script
4692           g_pythonParser.evalFile(item.GetPath().c_str(),ADDON::AddonPtr());
4693         }
4694         else
4695 #endif
4696         if (item.IsAudio() || item.IsVideo())
4697         { // an audio or video file
4698           PlayFile(item);
4699         }
4700         else
4701           return false;
4702       }
4703       return true;
4704     }
4705
4706 void CApplication::Process()
4707 {
4708   MEASURE_FUNCTION;
4709
4710   // dispatch the messages generated by python or other threads to the current window
4711   g_windowManager.DispatchThreadMessages();
4712
4713   // process messages which have to be send to the gui
4714   // (this can only be done after g_windowManager.Render())
4715   m_applicationMessenger.ProcessWindowMessages();
4716
4717 #ifdef HAS_PYTHON
4718   // process any Python scripts
4719   g_pythonParser.Process();
4720 #endif
4721
4722   // process messages, even if a movie is playing
4723   m_applicationMessenger.ProcessMessages();
4724   if (g_application.m_bStop) return; //we're done, everything has been unloaded
4725
4726   // check if we can free unused memory
4727 #ifndef _LINUX
4728   g_audioManager.FreeUnused();
4729 #endif
4730
4731   // check how far we are through playing the current item
4732   // and do anything that needs doing (lastfm submission, playcount updates etc)
4733   CheckPlayingProgress();
4734
4735   // update sound
4736   if (m_pPlayer)
4737     m_pPlayer->DoAudioWork();
4738
4739   // do any processing that isn't needed on each run
4740   if( m_slowTimer.GetElapsedMilliseconds() > 500 )
4741   {
4742     m_slowTimer.Reset();
4743     ProcessSlow();
4744   }
4745
4746   g_cpuInfo.getUsedPercentage(); // must call it to recalculate pct values
4747 }
4748
4749 // We get called every 500ms
4750 void CApplication::ProcessSlow()
4751 {
4752   g_powerManager.ProcessEvents();
4753
4754 #if defined(__APPLE__) &&  !defined(__arm__)
4755   // There is an issue on OS X that several system services ask the cursor to become visible
4756   // during their startup routines.  Given that we can't control this, we hack it in by
4757   // forcing the
4758   if (g_Windowing.IsFullScreen())
4759   { // SDL thinks it's hidden
4760     Cocoa_HideMouse();
4761   }
4762 #endif
4763
4764   // Store our file state for use on close()
4765   UpdateFileState();
4766
4767   if (IsPlayingAudio())
4768   {
4769     CLastfmScrobbler::GetInstance()->UpdateStatus();
4770     CLibrefmScrobbler::GetInstance()->UpdateStatus();
4771   }
4772
4773   // Check if we need to activate the screensaver / DPMS.
4774   CheckScreenSaverAndDPMS();
4775
4776   // Check if we need to shutdown (if enabled).
4777 #ifdef __APPLE__
4778   if (g_guiSettings.GetInt("powermanagement.shutdowntime") && g_advancedSettings.m_fullScreen)
4779 #else
4780   if (g_guiSettings.GetInt("powermanagement.shutdowntime"))
4781 #endif
4782   {
4783     CheckShutdown();
4784   }
4785
4786   // check if we should restart the player
4787   CheckDelayedPlayerRestart();
4788
4789   //  check if we can unload any unreferenced dlls or sections
4790   if (!IsPlayingVideo())
4791     CSectionLoader::UnloadDelayed();
4792
4793   // check for any idle curl connections
4794   g_curlInterface.CheckIdle();
4795
4796   // check for any idle myth sessions
4797   CMythSession::CheckIdle();
4798
4799 #ifdef HAS_FILESYSTEM_HTSP
4800   // check for any idle htsp sessions
4801   HTSP::CHTSPDirectorySession::CheckIdle();
4802 #endif
4803
4804 #ifdef HAS_KARAOKE
4805   if ( m_pKaraokeMgr )
4806     m_pKaraokeMgr->ProcessSlow();
4807 #endif
4808
4809   // LED - LCD SwitchOn On Paused! m_bIsPaused=TRUE -> LED/LCD is ON!
4810   if(IsPaused() != m_bIsPaused)
4811   {
4812 #ifdef HAS_LCD
4813     DimLCDOnPlayback(m_bIsPaused);
4814 #endif
4815     m_bIsPaused = IsPaused();
4816   }
4817
4818   if (!IsPlayingVideo())
4819     g_largeTextureManager.CleanupUnusedImages();
4820
4821 #ifdef HAS_DVD_DRIVE
4822   // checks whats in the DVD drive and tries to autostart the content (xbox games, dvd, cdda, avi files...)
4823   if (!IsPlayingVideo())
4824     m_Autorun.HandleAutorun();
4825 #endif
4826
4827   // update upnp server/renderer states
4828   if(CUPnP::IsInstantiated())
4829     CUPnP::GetInstance()->UpdateState();
4830
4831   //Check to see if current playing Title has changed and whether we should broadcast the fact
4832   CheckForTitleChange();
4833
4834 #if defined(_LINUX) && defined(HAS_FILESYSTEM_SMB)
4835   smb.CheckIfIdle();
4836 #endif
4837   
4838 #ifdef HAS_FILESYSTEM_NFS
4839   gNfsConnection.CheckIfIdle();
4840 #endif
4841
4842 #ifdef HAS_FILESYSTEM_SFTP
4843   CSFTPSessionManager::ClearOutIdleSessions();
4844 #endif
4845
4846   g_mediaManager.ProcessEvents();
4847
4848 #ifdef HAS_LIRC
4849   if (g_RemoteControl.IsInUse() && !g_RemoteControl.IsInitialized())
4850     g_RemoteControl.Initialize();
4851 #endif
4852
4853 #ifdef HAS_LCD
4854   // attempt to reinitialize the LCD (e.g. after resuming from sleep)
4855   if (!IsPlayingVideo())
4856   {
4857     if (g_lcd && !g_lcd->IsConnected())
4858     {
4859       g_lcd->Stop();
4860       g_lcd->Initialize();
4861     }
4862   }
4863 #endif
4864   
4865   if (!IsPlayingVideo())
4866     CAddonInstaller::Get().UpdateRepos();
4867 }
4868
4869 // Global Idle Time in Seconds
4870 // idle time will be resetet if on any OnKey()
4871 // int return: system Idle time in seconds! 0 is no idle!
4872 int CApplication::GlobalIdleTime()
4873 {
4874   if(!m_idleTimer.IsRunning())
4875   {
4876     m_idleTimer.Stop();
4877     m_idleTimer.StartZero();
4878   }
4879   return (int)m_idleTimer.GetElapsedSeconds();
4880 }
4881
4882 float CApplication::NavigationIdleTime()
4883 {
4884   if (!m_navigationTimer.IsRunning())
4885   {
4886     m_navigationTimer.Stop();
4887     m_navigationTimer.StartZero();
4888   }
4889   return m_navigationTimer.GetElapsedSeconds();
4890 }
4891
4892 void CApplication::DelayedPlayerRestart()
4893 {
4894   m_restartPlayerTimer.StartZero();
4895 }
4896
4897 void CApplication::CheckDelayedPlayerRestart()
4898 {
4899   if (m_restartPlayerTimer.GetElapsedSeconds() > 3)
4900   {
4901     m_restartPlayerTimer.Stop();
4902     m_restartPlayerTimer.Reset();
4903     Restart(true);
4904   }
4905 }
4906
4907 void CApplication::Restart(bool bSamePosition)
4908 {
4909   // this function gets called when the user changes a setting (like noninterleaved)
4910   // and which means we gotta close & reopen the current playing file
4911
4912   // first check if we're playing a file
4913   if ( !IsPlayingVideo() && !IsPlayingAudio())
4914     return ;
4915
4916   if( !m_pPlayer )
4917     return ;
4918
4919   SaveFileState();
4920
4921   // do we want to return to the current position in the file
4922   if (false == bSamePosition)
4923   {
4924     // no, then just reopen the file and start at the beginning
4925     PlayFile(*m_itemCurrentFile, true);
4926     return ;
4927   }
4928
4929   // else get current position
4930   double time = GetTime();
4931
4932   // get player state, needed for dvd's
4933   CStdString state = m_pPlayer->GetPlayerState();
4934
4935   // set the requested starttime
4936   m_itemCurrentFile->m_lStartOffset = (long)(time * 75.0);
4937
4938   // reopen the file
4939   if ( PlayFile(*m_itemCurrentFile, true) && m_pPlayer )
4940     m_pPlayer->SetPlayerState(state);
4941 }
4942
4943 const CStdString& CApplication::CurrentFile()
4944 {
4945   return m_itemCurrentFile->GetPath();
4946 }
4947
4948 CFileItem& CApplication::CurrentFileItem()
4949 {
4950   return *m_itemCurrentFile;
4951 }
4952
4953 void CApplication::ShowVolumeBar(const CAction *action)
4954 {
4955   CGUIDialog *volumeBar = (CGUIDialog *)g_windowManager.GetWindow(WINDOW_DIALOG_VOLUME_BAR);
4956   if (volumeBar)
4957   {
4958     volumeBar->Show();
4959     if (action)
4960       volumeBar->OnAction(*action);
4961   }
4962 }
4963
4964 bool CApplication::IsMuted() const
4965 {
4966   return g_settings.m_bMute;
4967 }
4968
4969 void CApplication::ToggleMute(void)
4970 {
4971   if (g_settings.m_bMute)
4972     UnMute();
4973   else
4974     Mute();
4975 }
4976
4977 void CApplication::Mute()
4978 {
4979   g_settings.m_iPreMuteVolumeLevel = GetVolume();
4980   SetVolume(0);
4981   g_settings.m_bMute = true;
4982 }
4983
4984 void CApplication::UnMute()
4985 {
4986   SetVolume(g_settings.m_iPreMuteVolumeLevel);
4987   g_settings.m_iPreMuteVolumeLevel = 0;
4988   g_settings.m_bMute = false;
4989 }
4990
4991 void CApplication::SetVolume(long iValue, bool isPercentage /* = true */)
4992 {
4993   // convert the percentage to a mB (milliBell) value (*100 for dB)
4994   if (isPercentage)
4995     iValue = (long)((float)iValue * 0.01f * (VOLUME_MAXIMUM - VOLUME_MINIMUM) + VOLUME_MINIMUM);
4996
4997   SetHardwareVolume(iValue);
4998 #ifndef HAS_SDL_AUDIO
4999   g_audioManager.SetVolume(g_settings.m_nVolumeLevel);
5000 #else
5001   g_audioManager.SetVolume((int)(128.f * (g_settings.m_nVolumeLevel - VOLUME_MINIMUM) / (float)(VOLUME_MAXIMUM - VOLUME_MINIMUM)));
5002 #endif
5003 }
5004
5005 void CApplication::SetHardwareVolume(long hardwareVolume)
5006 {
5007   // TODO DRC
5008   if (hardwareVolume >= VOLUME_MAXIMUM) // + VOLUME_DRC_MAXIMUM
5009     hardwareVolume = VOLUME_MAXIMUM;// + VOLUME_DRC_MAXIMUM;
5010   if (hardwareVolume <= VOLUME_MINIMUM)
5011     hardwareVolume = VOLUME_MINIMUM;
5012
5013   // update our settings
5014   if (hardwareVolume > VOLUME_MAXIMUM)
5015   {
5016     g_settings.m_dynamicRangeCompressionLevel = hardwareVolume - VOLUME_MAXIMUM;
5017     g_settings.m_nVolumeLevel = VOLUME_MAXIMUM;
5018   }
5019   else
5020   {
5021     g_settings.m_dynamicRangeCompressionLevel = 0;
5022     g_settings.m_nVolumeLevel = hardwareVolume;
5023   }
5024
5025   // and tell our player to update the volume
5026   if (m_pPlayer)
5027   {
5028     m_pPlayer->SetVolume(g_settings.m_nVolumeLevel);
5029     // TODO DRC
5030 //    m_pPlayer->SetDynamicRangeCompression(g_settings.m_dynamicRangeCompressionLevel);
5031   }
5032 }
5033
5034 int CApplication::GetVolume() const
5035 {
5036   // converts the hardware volume (in mB) to a percentage
5037   return int(((float)(g_settings.m_nVolumeLevel + g_settings.m_dynamicRangeCompressionLevel - VOLUME_MINIMUM)) / (VOLUME_MAXIMUM - VOLUME_MINIMUM)*100.0f + 0.5f);
5038 }
5039
5040 int CApplication::GetSubtitleDelay() const
5041 {
5042   // converts subtitle delay to a percentage
5043   return int(((float)(g_settings.m_currentVideoSettings.m_SubtitleDelay + g_advancedSettings.m_videoSubsDelayRange)) / (2 * g_advancedSettings.m_videoSubsDelayRange)*100.0f + 0.5f);
5044 }
5045
5046 int CApplication::GetAudioDelay() const
5047 {
5048   // converts subtitle delay to a percentage
5049   return int(((float)(g_settings.m_currentVideoSettings.m_AudioDelay + g_advancedSettings.m_videoAudioDelayRange)) / (2 * g_advancedSettings.m_videoAudioDelayRange)*100.0f + 0.5f);
5050 }
5051
5052 void CApplication::SetPlaySpeed(int iSpeed)
5053 {
5054   if (!IsPlayingAudio() && !IsPlayingVideo())
5055     return ;
5056   if (m_iPlaySpeed == iSpeed)
5057     return ;
5058   if (!m_pPlayer->CanSeek())
5059     return;
5060   if (m_pPlayer->IsPaused())
5061   {
5062     if (
5063       ((m_iPlaySpeed > 1) && (iSpeed > m_iPlaySpeed)) ||
5064       ((m_iPlaySpeed < -1) && (iSpeed < m_iPlaySpeed))
5065     )
5066     {
5067       iSpeed = m_iPlaySpeed; // from pause to ff/rw, do previous ff/rw speed
5068     }
5069     m_pPlayer->Pause();
5070   }
5071   m_iPlaySpeed = iSpeed;
5072
5073   m_pPlayer->ToFFRW(m_iPlaySpeed);
5074   if (m_iPlaySpeed == 1)
5075   { // restore volume
5076     m_pPlayer->SetVolume(g_settings.m_nVolumeLevel);
5077   }
5078   else
5079   { // mute volume
5080     m_pPlayer->SetVolume(VOLUME_MINIMUM);
5081   }
5082 }
5083
5084 int CApplication::GetPlaySpeed() const
5085 {
5086   return m_iPlaySpeed;
5087 }
5088
5089 // Returns the total time in seconds of the current media.  Fractional
5090 // portions of a second are possible - but not necessarily supported by the
5091 // player class.  This returns a double to be consistent with GetTime() and
5092 // SeekTime().
5093 double CApplication::GetTotalTime() const
5094 {
5095   double rc = 0.0;
5096
5097   if (IsPlaying() && m_pPlayer)
5098   {
5099     if (m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0)
5100       rc = (*m_currentStack)[m_currentStack->Size() - 1]->m_lEndOffset;
5101     else
5102       rc = m_pPlayer->GetTotalTime();
5103   }
5104
5105   return rc;
5106 }
5107
5108 void CApplication::StopShutdownTimer()
5109 {
5110   if (m_shutdownTimer.IsRunning())
5111     m_shutdownTimer.Stop();
5112 }
5113
5114 void CApplication::ResetShutdownTimers()
5115 {
5116   // reset system shutdown timer
5117   m_shutdownTimer.StartZero();
5118
5119   // delete custom shutdown timer
5120   if (g_alarmClock.HasAlarm("shutdowntimer"))
5121     g_alarmClock.Stop("shutdowntimer", true);
5122 }
5123
5124 // Returns the current time in seconds of the currently playing media.
5125 // Fractional portions of a second are possible.  This returns a double to
5126 // be consistent with GetTotalTime() and SeekTime().
5127 double CApplication::GetTime() const
5128 {
5129   double rc = 0.0;
5130
5131   if (IsPlaying() && m_pPlayer)
5132   {
5133     if (m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0)
5134     {
5135       long startOfCurrentFile = (m_currentStackPosition > 0) ? (*m_currentStack)[m_currentStackPosition-1]->m_lEndOffset : 0;
5136       rc = (double)startOfCurrentFile + m_pPlayer->GetTime() * 0.001;
5137     }
5138     else
5139       rc = static_cast<double>(m_pPlayer->GetTime() * 0.001f);
5140   }
5141
5142   return rc;
5143 }
5144
5145 // Sets the current position of the currently playing media to the specified
5146 // time in seconds.  Fractional portions of a second are valid.  The passed
5147 // time is the time offset from the beginning of the file as opposed to a
5148 // delta from the current position.  This method accepts a double to be
5149 // consistent with GetTime() and GetTotalTime().
5150 void CApplication::SeekTime( double dTime )
5151 {
5152   if (IsPlaying() && m_pPlayer && (dTime >= 0.0))
5153   {
5154     if (!m_pPlayer->CanSeek()) return;
5155     if (m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0)
5156     {
5157       // find the item in the stack we are seeking to, and load the new
5158       // file if necessary, and calculate the correct seek within the new
5159       // file.  Otherwise, just fall through to the usual routine if the
5160       // time is higher than our total time.
5161       for (int i = 0; i < m_currentStack->Size(); i++)
5162       {
5163         if ((*m_currentStack)[i]->m_lEndOffset > dTime)
5164         {
5165           long startOfNewFile = (i > 0) ? (*m_currentStack)[i-1]->m_lEndOffset : 0;
5166           if (m_currentStackPosition == i)
5167             m_pPlayer->SeekTime((__int64)((dTime - startOfNewFile) * 1000.0));
5168           else
5169           { // seeking to a new file
5170             m_currentStackPosition = i;
5171             CFileItem item(*(*m_currentStack)[i]);
5172             item.m_lStartOffset = (long)((dTime - startOfNewFile) * 75.0);
5173             // don't just call "PlayFile" here, as we are quite likely called from the
5174             // player thread, so we won't be able to delete ourselves.
5175             m_applicationMessenger.PlayFile(item, true);
5176           }
5177           return;
5178         }
5179       }
5180     }
5181     // convert to milliseconds and perform seek
5182     m_pPlayer->SeekTime( static_cast<__int64>( dTime * 1000.0 ) );
5183   }
5184 }
5185
5186 float CApplication::GetPercentage() const
5187 {
5188   if (IsPlaying() && m_pPlayer)
5189   {
5190     if (IsPlayingAudio() && m_itemCurrentFile->HasMusicInfoTag())
5191     {
5192       const CMusicInfoTag& tag = *m_itemCurrentFile->GetMusicInfoTag();
5193       if (tag.GetDuration() > 0)
5194         return (float)(GetTime() / tag.GetDuration() * 100);
5195     }
5196
5197     if (m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0)
5198       return (float)(GetTime() / GetTotalTime() * 100);
5199     else
5200       return m_pPlayer->GetPercentage();
5201   }
5202   return 0.0f;
5203 }
5204
5205 float CApplication::GetCachePercentage() const
5206 {
5207   if (IsPlaying() && m_pPlayer)
5208     return m_pPlayer->GetCachePercentage();
5209
5210   return 0.0f;
5211 }
5212
5213 void CApplication::SeekPercentage(float percent)
5214 {
5215   if (IsPlaying() && m_pPlayer && (percent >= 0.0))
5216   {
5217     if (!m_pPlayer->CanSeek()) return;
5218     if (m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0)
5219       SeekTime(percent * 0.01 * GetTotalTime());
5220     else
5221       m_pPlayer->SeekPercentage(percent);
5222   }
5223 }
5224
5225 // SwitchToFullScreen() returns true if a switch is made, else returns false
5226 bool CApplication::SwitchToFullScreen()
5227 {
5228   // if playing from the video info window, close it first!
5229   if (g_windowManager.HasModalDialog() && g_windowManager.GetTopMostModalDialogID() == WINDOW_DIALOG_VIDEO_INFO)
5230   {
5231     CGUIDialogVideoInfo* pDialog = (CGUIDialogVideoInfo*)g_windowManager.GetWindow(WINDOW_DIALOG_VIDEO_INFO);
5232     if (pDialog) pDialog->Close(true);
5233   }
5234
5235   // don't switch if there is a dialog on screen or the slideshow is active
5236   if (/*g_windowManager.HasModalDialog() ||*/ g_windowManager.GetActiveWindow() == WINDOW_SLIDESHOW)
5237     return false;
5238
5239   // See if we're playing a video, and are in GUI mode
5240   if ( IsPlayingVideo() && g_windowManager.GetActiveWindow() != WINDOW_FULLSCREEN_VIDEO)
5241   {
5242     // Reset frame count so that timing is FPS will be correct.
5243     {
5244       CSingleLock lock(m_frameMutex);
5245       m_frameCount = 0;
5246     }
5247
5248     // then switch to fullscreen mode
5249     g_windowManager.ActivateWindow(WINDOW_FULLSCREEN_VIDEO);
5250     return true;
5251   }
5252   // special case for switching between GUI & visualisation mode. (only if we're playing an audio song)
5253   if (IsPlayingAudio() && g_windowManager.GetActiveWindow() != WINDOW_VISUALISATION)
5254   { // then switch to visualisation
5255     g_windowManager.ActivateWindow(WINDOW_VISUALISATION);
5256     return true;
5257   }
5258   return false;
5259 }
5260
5261 void CApplication::Minimize()
5262 {
5263   g_Windowing.Minimize();
5264 }
5265
5266 PLAYERCOREID CApplication::GetCurrentPlayer()
5267 {
5268   return m_eCurrentPlayer;
5269 }
5270
5271 // when a scan is initiated, save current settings
5272 // and enable tag reading and remote thums
5273 void CApplication::SaveMusicScanSettings()
5274 {
5275   CLog::Log(LOGINFO,"Music scan has started... Enabling tag reading, and remote thumbs");
5276   g_settings.m_bMyMusicIsScanning = true;
5277   g_settings.Save();
5278 }
5279
5280 void CApplication::RestoreMusicScanSettings()
5281 {
5282   g_settings.m_bMyMusicIsScanning = false;
5283   g_settings.Save();
5284 }
5285
5286 void CApplication::UpdateLibraries()
5287 {
5288   if (g_guiSettings.GetBool("videolibrary.updateonstartup"))
5289   {
5290     CLog::Log(LOGNOTICE, "%s - Starting video library startup scan", __FUNCTION__);
5291     CGUIDialogVideoScan *scanner = (CGUIDialogVideoScan *)g_windowManager.GetWindow(WINDOW_DIALOG_VIDEO_SCAN);
5292     if (scanner && !scanner->IsScanning())
5293       scanner->StartScanning("");
5294   }
5295
5296   if (g_guiSettings.GetBool("musiclibrary.updateonstartup"))
5297   {
5298     CLog::Log(LOGNOTICE, "%s - Starting music library startup scan", __FUNCTION__);
5299     CGUIDialogMusicScan *scanner = (CGUIDialogMusicScan *)g_windowManager.GetWindow(WINDOW_DIALOG_MUSIC_SCAN);
5300     if (scanner && !scanner->IsScanning())
5301       scanner->StartScanning("");
5302   }
5303 }
5304
5305 void CApplication::CheckPlayingProgress()
5306 {
5307   // check if we haven't rewound past the start of the file
5308   if (IsPlaying())
5309   {
5310     int iSpeed = g_application.GetPlaySpeed();
5311     if (iSpeed < 1)
5312     {
5313       iSpeed *= -1;
5314       int iPower = 0;
5315       while (iSpeed != 1)
5316       {
5317         iSpeed >>= 1;
5318         iPower++;
5319       }
5320       if (g_infoManager.GetPlayTime() / 1000 < iPower)
5321       {
5322         g_application.SetPlaySpeed(1);
5323         g_application.SeekTime(0);
5324       }
5325     }
5326   }
5327 }
5328
5329 bool CApplication::ProcessAndStartPlaylist(const CStdString& strPlayList, CPlayList& playlist, int iPlaylist)
5330 {
5331   CLog::Log(LOGDEBUG,"CApplication::ProcessAndStartPlaylist(%s, %i)",strPlayList.c_str(), iPlaylist);
5332
5333   // initial exit conditions
5334   // no songs in playlist just return
5335   if (playlist.size() == 0)
5336     return false;
5337
5338   // illegal playlist
5339   if (iPlaylist < PLAYLIST_MUSIC || iPlaylist > PLAYLIST_VIDEO)
5340     return false;
5341
5342   // setup correct playlist
5343   g_playlistPlayer.ClearPlaylist(iPlaylist);
5344
5345   // if the playlist contains an internet stream, this file will be used
5346   // to generate a thumbnail for musicplayer.cover
5347   g_application.m_strPlayListFile = strPlayList;
5348
5349   // add the items to the playlist player
5350   g_playlistPlayer.Add(iPlaylist, playlist);
5351
5352   // if we have a playlist
5353   if (g_playlistPlayer.GetPlaylist(iPlaylist).size())
5354   {
5355     // start playing it
5356     g_playlistPlayer.SetCurrentPlaylist(iPlaylist);
5357     g_playlistPlayer.Reset();
5358     g_playlistPlayer.Play();
5359     return true;
5360   }
5361   return false;
5362 }
5363
5364 void CApplication::SaveCurrentFileSettings()
5365 {
5366   if (m_itemCurrentFile->IsVideo())
5367   {
5368     // save video settings
5369     if (g_settings.m_currentVideoSettings != g_settings.m_defaultVideoSettings)
5370     {
5371       CVideoDatabase dbs;
5372       dbs.Open();
5373       dbs.SetVideoSettings(m_itemCurrentFile->GetPath(), g_settings.m_currentVideoSettings);
5374       dbs.Close();
5375     }
5376   }
5377 }
5378
5379 bool CApplication::AlwaysProcess(const CAction& action)
5380 {
5381   // check if this button is mapped to a built-in function
5382   if (!action.GetName().IsEmpty())
5383   {
5384     CStdString builtInFunction;
5385     vector<CStdString> params;
5386     CUtil::SplitExecFunction(action.GetName(), builtInFunction, params);
5387     builtInFunction.ToLower();
5388
5389     // should this button be handled normally or just cancel the screensaver?
5390     if (   builtInFunction.Equals("powerdown")
5391         || builtInFunction.Equals("reboot")
5392         || builtInFunction.Equals("restart")
5393         || builtInFunction.Equals("restartapp")
5394         || builtInFunction.Equals("suspend")
5395         || builtInFunction.Equals("hibernate")
5396         || builtInFunction.Equals("quit")
5397         || builtInFunction.Equals("shutdown"))
5398     {
5399       return true;
5400     }
5401   }
5402
5403   return false;
5404 }
5405
5406 CApplicationMessenger& CApplication::getApplicationMessenger()
5407 {
5408    return m_applicationMessenger;
5409 }
5410
5411 bool CApplication::IsCurrentThread() const
5412 {
5413   return CThread::IsCurrentThread(m_threadID);
5414 }
5415
5416 bool CApplication::IsPresentFrame()
5417 {
5418   CSingleLock lock(m_frameMutex);
5419   bool ret = m_bPresentFrame;
5420
5421   return ret;
5422 }
5423
5424 #if defined(HAS_LINUX_NETWORK)
5425 CNetworkLinux& CApplication::getNetwork()
5426 {
5427   return m_network;
5428 }
5429 #elif defined(HAS_WIN32_NETWORK)
5430 CNetworkWin32& CApplication::getNetwork()
5431 {
5432   return m_network;
5433 }
5434 #else
5435 CNetwork& CApplication::getNetwork()
5436 {
5437   return m_network;
5438 }
5439
5440 #endif
5441 #ifdef HAS_PERFORMANCE_SAMPLE
5442 CPerformanceStats &CApplication::GetPerformanceStats()
5443 {
5444   return m_perfStats;
5445 }
5446 #endif