2 * Copyright (C) 2005-2008 Team XBMC
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)
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.
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
22 #include "threads/SystemClock.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"
31 #include "pictures/Picture.h"
32 #include "guilib/TextureManager.h"
33 #include "cores/dvdplayer/DVDFileInfo.h"
34 #include "PlayListPlayer.h"
37 #include "utils/LCDFactory.h"
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"
48 #include "interfaces/python/XBPython.h"
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"
69 #ifdef HAS_FILESYSTEM_HTSP
70 #include "filesystem/HTSPDirectory.h"
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"
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"
91 #include "input/KeyboardStat.h"
92 #include "input/XBMC_vkeys.h"
93 #include "input/MouseStat.h"
95 #if defined(FILESYSTEM) && !defined(_LINUX)
96 #include "filesystem/FileDAAP.h"
99 #include "network/UPnP.h"
100 #include "filesystem/UPnPDirectory.h"
102 #if defined(_LINUX) && defined(HAS_FILESYSTEM_SMB)
103 #include "filesystem/SMBDirectory.h"
105 #ifdef HAS_FILESYSTEM_NFS
106 #include "filesystem/FileNFS.h"
108 #ifdef HAS_FILESYSTEM_SFTP
109 #include "filesystem/FileSFTP.h"
111 #include "PartyModeManager.h"
112 #ifdef HAS_VIDEO_PLAYBACK
113 #include "cores/VideoRenderers/RenderManager.h"
116 #include "music/karaoke/karaokelyricsmanager.h"
117 #include "music/karaoke/GUIDialogKaraokeSongSelector.h"
118 #include "music/karaoke/GUIWindowKaraokeLyrics.h"
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"
127 #include "utils/Win32Exception.h"
129 #ifdef HAS_EVENT_SERVER
130 #include "network/EventServer.h"
132 #ifdef HAS_DBUS_SERVER
133 #include "interfaces/DbusServer.h"
136 #include "interfaces/http-api/XBMChttp.h"
139 #include "interfaces/json-rpc/JSONRPC.h"
140 #include "network/TCPServer.h"
143 #include "network/AirPlayServer.h"
146 #include "network/AirTunesServer.h"
148 #if defined(HAVE_LIBCRYSTALHD)
149 #include "cores/dvdplayer/DVDCodecs/Video/CrystalHD.h"
151 #include "interfaces/AnnouncementManager.h"
152 #include "peripherals/Peripherals.h"
154 #include "peripherals/devices/PeripheralCecAdapter.h"
156 #include "peripherals/dialogs/GUIDialogPeripheralManager.h"
157 #include "peripherals/dialogs/GUIDialogPeripheralSettings.h"
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"
176 #include "rendering/gl/GUIWindowTestPatternGL.h"
179 #include "rendering/dx/GUIWindowTestPatternDX.h"
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"
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"
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"
250 #ifdef HAS_PERFORMANCE_SAMPLE
251 #include "utils/PerformanceSample.h"
253 #define MEASURE_FUNCTION
257 #include <SDL/SDL_mixer.h>
261 #include "win32util.h"
264 #include "windowing/X11/XRandR.h"
267 #ifdef TARGET_DARWIN_OSX
268 #include "CocoaInterface.h"
269 #include "XBMCHelper.h"
272 #include "DarwinUtils.h"
276 #include <cdio/logging.h>
280 #include "linux/HALManager.h"
283 #include "storage/MediaManager.h"
284 #include "utils/JobManager.h"
285 #include "utils/SaveFileStateJob.h"
286 #include "utils/AlarmClock.h"
293 #include "input/linux/LIRC.h"
295 #ifdef HAS_IRSERVERSUITE
296 #include "input/windows/IRServerSuite.h"
300 using namespace ADDON;
301 using namespace XFILE;
303 using namespace MEDIA_DETECT;
305 using namespace PLAYLIST;
306 using namespace VIDEO;
307 using namespace MUSIC_INFO;
308 #ifdef HAS_EVENT_SERVER
309 using namespace EVENTSERVER;
311 #ifdef HAS_DBUS_SERVER
312 using namespace DBUSSERVER;
315 using namespace JSONRPC;
317 using namespace ANNOUNCEMENT;
318 using namespace PERIPHERALS;
320 using namespace XbmcThreads;
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
326 #define MAX_FFWD_SPEED 5
328 //extern IDirectSoundRenderer* m_pAudioDecoder;
329 CApplication::CApplication(void) : m_itemCurrentFile(new CFileItem), m_progressTrackingItem(new CFileItem)
333 m_bScreenSave = false;
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;
349 //true while we in IsPaused mode! Workaround for OnPaused, which must be add. after v2.0
352 /* for now always keep this around */
354 m_pKaraokeMgr = new CKaraokeLyricsManager();
356 m_currentStack = new CFileItemList;
360 m_bPresentFrame = false;
361 m_bPlatformDirectories = true;
363 m_bStandalone = false;
364 m_bEnableLegacyRes = false;
365 m_bSystemScreenSaverEnable = false;
366 m_pInertialScrollingHandler = new CInertialScrollingHandler();
369 CApplication::~CApplication(void)
371 delete m_currentStack;
374 delete m_pKaraokeMgr;
378 delete m_pInertialScrollingHandler;
381 bool CApplication::OnEvent(XBMC_Event& newEvent)
383 switch(newEvent.type)
386 if (!g_application.m_bStop)
387 g_application.getApplicationMessenger().Quit();
390 g_application.OnKey(g_Keyboard.ProcessKeyDown(newEvent.key.keysym));
393 g_Keyboard.ProcessKeyUp();
395 case XBMC_MOUSEBUTTONDOWN:
396 case XBMC_MOUSEBUTTONUP:
397 case XBMC_MOUSEMOTION:
398 g_Mouse.HandleEvent(newEvent);
399 g_application.ProcessMouse();
401 case XBMC_VIDEORESIZE:
402 if (!g_application.m_bInitializing &&
403 !g_advancedSettings.m_fullScreen)
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);
413 g_application.getApplicationMessenger().UserEvent(newEvent.user.code);
415 case XBMC_APPCOMMAND:
416 return g_application.OnAppCommand(newEvent.appcommand.action);
421 // This function does not return!
422 void CApplication::FatalErrorHandler(bool WindowSystemInitialized, bool MapDrives, bool InitNetwork)
424 fprintf(stderr, "Fatal error encountered, aborting\n");
425 fprintf(stderr, "Error log at %sxbmc.log\n", g_settings.m_logFolder.c_str());
429 extern "C" void __stdcall init_emu_environ();
430 extern "C" void __stdcall update_emu_environ();
433 // Utility function used to copy files from the application bundle
434 // over to the user data directory in Application Support/XBMC.
436 static void CopyUserDataIfNeeded(const CStdString &strPath, const CStdString &file)
438 CStdString destPath = URIUtils::AddFileToFolder(strPath, file);
439 if (!CFile::Exists(destPath))
441 // need to copy it across
442 CStdString srcPath = URIUtils::AddFileToFolder("special://xbmc/userdata/", file);
443 CFile::Cache(srcPath, destPath);
447 void CApplication::Preflight()
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();
455 // run any platform preflight scripts.
456 #if defined(__APPLE__) && !defined(__arm__)
457 CStdString install_path;
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());
466 bool CApplication::Create()
468 g_settings.Initialize(); //Initialize default AdvancedSettings
470 m_bSystemScreenSaverEnable = g_Windowing.IsSystemScreenSaverEnabled();
471 g_Windowing.EnableSystemScreenSaver(false);
474 tzset(); // Initialize timezone information variables
477 // Grab a handle to our thread to be used later in identifying the render thread.
478 m_threadID = CThread::GetCurrentThreadId();
481 //floating point precision to 24 bits (faster performance)
482 _controlfp(_PC_24, _MCW_PC);
484 /* install win32 exception translator, win32 exceptions
485 * can now be caught using c++ try catch */
486 win32_exception::install_handler();
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();
494 inited = InitDirectoriesOSX();
496 inited = InitDirectoriesWin32();
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");
504 if (!CLog::Init(_P(g_settings.m_logFolder).c_str()))
506 fprintf(stderr,"Could not init logging classes. Permission errors on ~/.xbmc?\n");
510 g_settings.LoadProfiles(PROFILES_FILE);
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");
526 CSpecialProtocol::LogPaths();
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, "-----------------------------------------------------------------------");
533 CStdString strExecutablePath;
534 CUtil::GetHomePath(strExecutablePath);
536 // if we are running from DVD our UserData location will be TDATA
537 if (URIUtils::IsDVD(strExecutablePath))
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
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()));
547 g_settings.m_logFolder = "special://masterprofile/";
551 g_xrandr.LoadCustomModeLinesToAllOutputs();
554 // Init our DllLoaders emu env
559 CLog::Log(LOGNOTICE, "Setup SDL");
561 /* Clean up on exit, exit on window close and interrupt */
564 uint32_t sdlFlags = 0;
566 #if defined(HAS_SDL_OPENGL) || (HAS_GLES == 2)
567 sdlFlags |= SDL_INIT_VIDEO;
571 sdlFlags |= SDL_INIT_AUDIO;
574 #ifdef HAS_SDL_JOYSTICK
575 sdlFlags |= SDL_INIT_JOYSTICK;
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);
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);
595 if (SDL_Init(sdlFlags) != 0)
597 CLog::Log(LOGFATAL, "XBAppEx: Unable to initialize SDL: %s", SDL_GetError());
602 // for python scripts that check the OS
604 setenv("OS","OS X",true);
605 #elif defined(_LINUX)
606 setenv("OS","Linux",true);
607 #elif defined(_WIN32)
608 SetEnvironmentVariable("OS","win32");
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())
616 CLog::Log(LOGFATAL, "CApplication::Create: Unable to init windowing system");
620 g_powerManager.Initialize();
622 CLog::Log(LOGNOTICE, "load settings...");
624 g_guiSettings.Initialize(); // Initialize default Settings - don't move
625 g_powerManager.SetDefaults();
626 if (!g_settings.Load())
627 FatalErrorHandler(true, true, true);
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();
637 update_emu_environ();//apply the GUI settings
639 // initialize our charset converter
640 g_charsetConverter.reset();
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]);
646 CStdString strLangInfoPath;
647 strLangInfoPath.Format("special://xbmc/language/%s/langinfo.xml", strLanguage.c_str());
649 CLog::Log(LOGINFO, "load language info file: %s", strLangInfoPath.c_str());
650 g_langInfo.Load(strLangInfoPath);
652 CStdString strLanguagePath;
653 strLanguagePath.Format("special://xbmc/language/%s/strings.xml", strLanguage.c_str());
655 CLog::Log(LOGINFO, "load language file:%s", strLanguagePath.c_str());
656 if (!g_localizeStrings.Load(strLanguagePath))
657 FatalErrorHandler(false, false, true);
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())
663 CLog::Log(LOGFATAL, "CApplication::Create: Unable to start CAddonMgr");
664 FatalErrorHandler(true, true, true);
667 g_peripherals.Initialise();
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"));
674 g_Keyboard.Initialize();
675 #if defined(HAS_LIRC) || defined(HAS_IRSERVERSUITE)
676 g_RemoteControl.Initialize();
678 #ifdef HAS_SDL_JOYSTICK
679 g_Joystick.Initialize();
682 #if defined(__APPLE__) && !defined(__arm__)
683 // Configure and possible manually start the helper.
684 XBMCHelper::GetInstance().Configure();
687 // update the window resolution
688 g_Windowing.SetWindowResolution(g_guiSettings.GetInt("window.width"), g_guiSettings.GetInt("window.height"));
690 if (g_advancedSettings.m_startFullScreen && g_guiSettings.m_LookAndFeelResolution == RES_WINDOW)
691 g_guiSettings.m_LookAndFeelResolution = RES_DESKTOP;
693 if (!g_graphicsContext.IsValidResolution(g_guiSettings.m_LookAndFeelResolution))
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;
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))
706 CLog::Log(LOGFATAL, "CApplication::Create: Unable to create window");
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))
713 CLog::Log(LOGFATAL, "CApplication::Create: Unable to create window");
718 if (!g_Windowing.InitRenderSystem())
720 CLog::Log(LOGFATAL, "CApplication::Create: Unable to init rendering system");
724 // set GUI res and force the clear of the screen
725 g_graphicsContext.SetVideoResolution(g_guiSettings.m_LookAndFeelResolution);
727 if (g_advancedSettings.m_splashImage)
729 CStdString strUserSplash = "special://home/media/Splash.png";
730 if (CFile::Exists(strUserSplash))
732 CLog::Log(LOGINFO, "load user splash image: %s", CSpecialProtocol::TranslatePath(strUserSplash).c_str());
733 m_splash = new CSplash(strUserSplash);
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");
743 CLog::Log(LOGINFO, "load keymapping");
744 if (!CButtonTranslator::GetInstance().Load())
745 FatalErrorHandler(false, false, true);
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();
754 CUtil::InitRandomSeed();
756 g_mediaManager.Initialize();
758 m_lastFrameTime = XbmcThreads::SystemClockMillis();
759 m_lastRenderTime = m_lastFrameTime;
764 bool CApplication::InitDirectoriesLinux()
767 The following is the directory mapping for Platform Specific Mode:
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.
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.
780 NOTE: All these root directories are lowercase. Some of the sub-directories
784 #if defined(_LINUX) && !defined(__APPLE__)
787 userName = getenv("USER");
793 userHome = getenv("HOME");
797 CStdString xbmcBinPath, xbmcPath;
798 CUtil::GetHomePath(xbmcBinPath, "XBMC_BIN_HOME");
799 xbmcPath = getenv("XBMC_HOME");
801 if (xbmcPath.IsEmpty())
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")))
808 /* Attempt to locate arch independent data files. */
809 CUtil::GetHomePath(xbmcPath);
810 if (!CFile::Exists(URIUtils::AddFileToFolder(xbmcPath, "language")))
812 fprintf(stderr, "Unable to find path to XBMC data files!\n");
818 /* Set some environment variables */
819 setenv("XBMC_BIN_HOME", xbmcBinPath.c_str(), 0);
820 setenv("XBMC_HOME", xbmcPath.c_str(), 0);
822 if (m_bPlatformDirectories)
824 // map our special drives
825 CSpecialProtocol::SetXBMCBinPath(xbmcBinPath);
826 CSpecialProtocol::SetXBMCPath(xbmcPath);
827 CSpecialProtocol::SetHomePath(userHome + "/.xbmc");
828 CSpecialProtocol::SetMasterProfilePath(userHome + "/.xbmc/userdata");
830 CStdString strTempPath = URIUtils::AddFileToFolder(userHome, ".xbmc/temp");
831 CSpecialProtocol::SetTempPath(strTempPath);
833 URIUtils::AddSlashAtEnd(strTempPath);
834 g_settings.m_logFolder = strTempPath;
841 URIUtils::AddSlashAtEnd(xbmcPath);
842 g_settings.m_logFolder = xbmcPath;
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"));
849 CStdString strTempPath = URIUtils::AddFileToFolder(xbmcPath, "portable_data/temp");
850 CSpecialProtocol::SetTempPath(strTempPath);
853 URIUtils::AddSlashAtEnd(strTempPath);
854 g_settings.m_logFolder = strTempPath;
863 bool CApplication::InitDirectoriesOSX()
868 userName = getenv("USER");
874 userHome = getenv("HOME");
879 CUtil::GetHomePath(xbmcPath);
880 setenv("XBMC_HOME", xbmcPath.c_str(), 0);
883 CStdString fontconfigPath;
884 fontconfigPath = xbmcPath + "/system/players/dvdplayer/etc/fonts/fonts.conf";
885 setenv("FONTCONFIG_FILE", fontconfigPath.c_str(), 0);
888 // setup path to our internal dylibs so loader can find them
889 CStdString frameworksPath = CUtil::GetFrameworksPath();
890 CSpecialProtocol::SetXBMCFrameworksPath(frameworksPath);
892 // OSX always runs with m_bPlatformDirectories == true
893 if (m_bPlatformDirectories)
895 // map our special drives
896 CSpecialProtocol::SetXBMCBinPath(xbmcPath);
897 CSpecialProtocol::SetXBMCPath(xbmcPath);
899 CSpecialProtocol::SetHomePath(userHome + "/Library/Preferences/XBMC");
900 CSpecialProtocol::SetMasterProfilePath(userHome + "/Library/Preferences/XBMC/userdata");
902 CSpecialProtocol::SetHomePath(userHome + "/Library/Application Support/XBMC");
903 CSpecialProtocol::SetMasterProfilePath(userHome + "/Library/Application Support/XBMC/userdata");
906 // location for temp files
908 CStdString strTempPath = URIUtils::AddFileToFolder(userHome, "Library/Preferences/XBMC/temp");
910 CStdString strTempPath = URIUtils::AddFileToFolder(userHome, ".xbmc/");
911 CDirectory::Create(strTempPath);
912 strTempPath = URIUtils::AddFileToFolder(userHome, ".xbmc/temp");
914 CSpecialProtocol::SetTempPath(strTempPath);
916 // xbmc.log file location
918 strTempPath = userHome + "/Library/Preferences";
920 strTempPath = userHome + "/Library/Logs";
922 URIUtils::AddSlashAtEnd(strTempPath);
923 g_settings.m_logFolder = strTempPath;
929 URIUtils::AddSlashAtEnd(xbmcPath);
930 g_settings.m_logFolder = xbmcPath;
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"));
937 CStdString strTempPath = URIUtils::AddFileToFolder(xbmcPath, "portable_data/temp");
938 CSpecialProtocol::SetTempPath(strTempPath);
940 URIUtils::AddSlashAtEnd(strTempPath);
941 g_settings.m_logFolder = strTempPath;
950 bool CApplication::InitDirectoriesWin32()
955 CUtil::GetHomePath(xbmcPath);
956 SetEnvironmentVariable("XBMC_HOME", xbmcPath.c_str());
957 CSpecialProtocol::SetXBMCBinPath(xbmcPath);
958 CSpecialProtocol::SetXBMCPath(xbmcPath);
960 if (m_bPlatformDirectories)
963 CStdString strWin32UserFolder = CWIN32Util::GetProfilePath();
965 // create user/app data/XBMC
966 CStdString homePath = URIUtils::AddFileToFolder(strWin32UserFolder, "XBMC");
968 // move log to platform dirs
969 g_settings.m_logFolder = homePath;
970 URIUtils::AddSlashAtEnd(g_settings.m_logFolder);
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());
979 CSpecialProtocol::SetTempPath(URIUtils::AddFileToFolder(homePath,"cache"));
986 URIUtils::AddSlashAtEnd(xbmcPath);
987 g_settings.m_logFolder = xbmcPath;
989 CSpecialProtocol::SetHomePath(URIUtils::AddFileToFolder(xbmcPath, "portable_data"));
990 CSpecialProtocol::SetMasterProfilePath(URIUtils::AddFileToFolder(xbmcPath, "portable_data/userdata"));
992 CStdString strTempPath = URIUtils::AddFileToFolder(xbmcPath, "portable_data/temp");
993 CSpecialProtocol::SetTempPath(strTempPath);
997 SetEnvironmentVariable("XBMC_PROFILE_USERDATA",_P("special://masterprofile/").c_str());
1000 // Expand the DLL search path with our directories
1001 CWIN32Util::ExtendDllPath();
1003 // check for a DVD drive
1005 CWIN32Util::GetDrivesByType(vShare, DVD_DRIVES);
1007 g_mediaManager.SetHasOpticalDrive(true);
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);
1022 void CApplication::CreateUserDirs()
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
1035 bool CApplication::Initialize()
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;
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)
1048 CDirectory::Create("special://xbmc/language");
1049 CDirectory::Create("special://xbmc/addons");
1050 CDirectory::Create("special://xbmc/sounds");
1055 // Init DPMS, before creating the corresponding setting control.
1056 m_dpms = new DPMSSupport();
1057 g_guiSettings.GetSetting("powermanagement.displaysoff")->SetVisible(m_dpms->IsSupported());
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
1066 g_windowManager.Add(new CGUIWindowTestPatternGL); // window id = 8
1069 g_windowManager.Add(new CGUIWindowTestPatternDX); // window id = 8
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
1097 g_windowManager.Add(new CGUIDialogKaraokeSongSelectorSmall); // window id 143
1098 g_windowManager.Add(new CGUIDialogKaraokeSongSelectorLarge); // window id 144
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
1123 g_windowManager.Add(new CGUIDialogLockSettings); // window id = 131
1125 g_windowManager.Add(new CGUIDialogContentSettings); // window id = 132
1127 g_windowManager.Add(new CGUIDialogPlayEject);
1129 g_windowManager.Add(new CGUIDialogPeripheralManager);
1130 g_windowManager.Add(new CGUIDialogPeripheralSettings);
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
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
1147 g_windowManager.Add(new CGUIWindowKaraokeLyrics); // window id = 2009
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)
1157 /* window id's 3000 - 3100 are reserved for python */
1159 // Make sure we have at least the default skin
1160 if (!LoadSkin(g_guiSettings.GetString("lookandfeel.skin")) && !LoadSkin(DEFAULT_SKIN))
1162 CLog::Log(LOGERROR, "Default skin '%s' not found! Terminating..", DEFAULT_SKIN);
1163 FatalErrorHandler(true, true, true);
1166 if (g_advancedSettings.m_splashImage)
1167 SAFE_DELETE(m_splash);
1169 if (g_guiSettings.GetBool("masterlock.startuplock") &&
1170 g_settings.GetMasterProfile().getLockMode() != LOCK_MODE_EVERYONE &&
1171 !g_settings.GetMasterProfile().getLockCode().IsEmpty())
1173 g_passwordManager.CheckStartUpLock();
1176 // check if we should use the login screen
1177 if (g_settings.UsingLoginScreen())
1178 g_windowManager.ActivateWindow(WINDOW_LOGIN_SCREEN);
1180 g_windowManager.ActivateWindow(g_SkinInfo->GetFirstWindow());
1182 g_sysinfo.Refresh();
1184 CLog::Log(LOGINFO, "removing tempfiles");
1185 CUtil::RemoveTempFiles();
1188 if (g_settings.m_bMute)
1191 // if the user shutoff the xbox during music scan
1192 // restore the settings
1193 if (g_settings.m_bMyMusicIsScanning)
1195 CLog::Log(LOGWARNING,"System rebooted during music scan! ... restoring UseTags and FindRemoteThumbs");
1196 RestoreMusicScanSettings();
1199 if (!g_settings.UsingLoginScreen())
1203 g_pythonParser.m_bLogin = true;
1207 m_slowTimer.StartZero();
1209 #if defined(__APPLE__) && !defined(__arm__)
1210 XBMCHelper::GetInstance().CaptureAllInput();
1212 #if defined(HAVE_LIBCRYSTALHD)
1213 CCrystalHD::GetInstance();
1216 CAddonMgr::Get().StartServices(false);
1218 CLog::Log(LOGNOTICE, "initialize done");
1220 m_bInitializing = false;
1222 // reset our screensaver (starts timers etc.)
1227 bool CApplication::StartWebServer()
1229 #ifdef HAS_WEB_SERVER
1230 if (g_guiSettings.GetBool("services.webserver") && m_network.IsAvailable())
1232 int webPort = atoi(g_guiSettings.GetString("services.webserverport"));
1233 CLog::Log(LOGNOTICE, "Webserver: Starting...");
1235 if (webPort < 1024 && geteuid() != 0)
1237 CLog::Log(LOGERROR, "Cannot start Web Server as port is smaller than 1024 and user is not root");
1242 bool started = false;
1243 if (m_WebServer.Start(webPort, g_guiSettings.GetString("services.webserverusername"), g_guiSettings.GetString("services.webserverpassword")))
1245 std::map<std::string, std::string> txt;
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);
1252 CZeroconf::GetInstance()->PublishService("servers.webapi", "_xbmc-web._tcp", "XBMC HTTP API", webPort, txt);
1255 CZeroconf::GetInstance()->PublishService("servers.webjsonrpc", "_xbmc-jsonrpc._tcp", "XBMC JSONRPC", webPort, txt);
1259 if (g_settings.m_HttpApiBroadcastLevel >= 1)
1260 getApplicationMessenger().HttpApi("broadcastlevel; StartUp;1");
1270 void CApplication::StopWebServer()
1272 #ifdef HAS_WEB_SERVER
1273 if (m_WebServer.IsStarted())
1275 CLog::Log(LOGNOTICE, "Webserver: Stopping...");
1277 if(! m_WebServer.IsStarted() )
1279 CLog::Log(LOGNOTICE, "Webserver: Stopped...");
1280 CZeroconf::GetInstance()->RemoveService("servers.webserver");
1281 CZeroconf::GetInstance()->RemoveService("servers.webjsonrpc");
1282 CZeroconf::GetInstance()->RemoveService("servers.webapi");
1284 CLog::Log(LOGWARNING, "Webserver: Failed to stop.");
1289 void CApplication::StartAirplayServer()
1292 if (g_guiSettings.GetBool("services.airplay") && m_network.IsAvailable())
1294 CStdString password = g_guiSettings.GetString("services.airplaypassword");
1295 bool usePassword = g_guiSettings.GetBool("services.useairplaypassword");
1297 if (CAirPlayServer::StartServer(9091, true))
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);
1310 if (g_guiSettings.GetBool("services.airplay") && m_network.IsAvailable())
1312 CStdString password = g_guiSettings.GetString("services.airplaypassword");
1313 bool usePassword = g_guiSettings.GetBool("services.useairplaypassword");
1315 if (!CAirTunesServer::StartServer(5000, true, usePassword, password))
1317 CLog::Log(LOGERROR, "Failed to start AirTunes Server");
1323 void CApplication::StopAirplayServer(bool bWait)
1326 CAirPlayServer::StopServer(bWait);
1327 CZeroconf::GetInstance()->RemoveService("servers.airplay");
1330 CAirTunesServer::StopServer(bWait);
1334 bool CApplication::StartJSONRPCServer()
1337 if (g_guiSettings.GetBool("services.esenabled"))
1339 CJSONRPC::Initialize();
1341 if (CTCPServer::StartServer(g_advancedSettings.m_jsonTcpPort, g_guiSettings.GetBool("services.esallinterfaces")))
1343 std::map<std::string, std::string> txt;
1344 CZeroconf::GetInstance()->PublishService("servers.jsonrpc", "_xbmc-jsonrpc._tcp", "XBMC JSONRPC", g_advancedSettings.m_jsonTcpPort, txt);
1355 void CApplication::StopJSONRPCServer(bool bWait)
1358 CTCPServer::StopServer(bWait);
1359 CZeroconf::GetInstance()->RemoveService("servers.jsonrpc");
1363 void CApplication::StartUPnP()
1367 StartUPnPRenderer();
1371 void CApplication::StopUPnP(bool bWait)
1374 if (CUPnP::IsInstantiated())
1376 CLog::Log(LOGNOTICE, "stopping upnp");
1377 CUPnP::ReleaseInstance(bWait);
1382 bool CApplication::StartEventServer()
1384 #ifdef HAS_EVENT_SERVER
1385 CEventServer* server = CEventServer::GetInstance();
1388 CLog::Log(LOGERROR, "ES: Out of memory");
1391 if (g_guiSettings.GetBool("services.esenabled"))
1393 CLog::Log(LOGNOTICE, "ES: Starting event server");
1394 server->StartServer();
1401 bool CApplication::StopEventServer(bool bWait, bool promptuser)
1403 #ifdef HAS_EVENT_SERVER
1404 CEventServer* server = CEventServer::GetInstance();
1407 CLog::Log(LOGERROR, "ES: Out of memory");
1412 if (server->GetNumberOfClients() > 0)
1414 bool cancelled = false;
1415 if (!CGUIDialogYesNo::ShowAndGetInput(13140, 13141, 13142, 20022,
1416 -1, -1, cancelled, 10000)
1419 CLog::Log(LOGNOTICE, "ES: Not stopping event server");
1423 CLog::Log(LOGNOTICE, "ES: Stopping event server with confirmation");
1425 CEventServer::GetInstance()->StopServer(true);
1430 CLog::Log(LOGNOTICE, "ES: Stopping event server");
1432 CEventServer::GetInstance()->StopServer(bWait);
1439 void CApplication::RefreshEventServer()
1441 #ifdef HAS_EVENT_SERVER
1442 if (g_guiSettings.GetBool("services.esenabled"))
1444 CEventServer::GetInstance()->RefreshSettings();
1449 void CApplication::StartDbusServer()
1451 #ifdef HAS_DBUS_SERVER
1452 CDbusServer* serverDbus = CDbusServer::GetInstance();
1455 CLog::Log(LOGERROR, "DS: Out of memory");
1458 CLog::Log(LOGNOTICE, "DS: Starting dbus server");
1459 serverDbus->StartServer( this );
1463 bool CApplication::StopDbusServer(bool bWait)
1465 #ifdef HAS_DBUS_SERVER
1466 CDbusServer* serverDbus = CDbusServer::GetInstance();
1469 CLog::Log(LOGERROR, "DS: Out of memory");
1472 CDbusServer::GetInstance()->StopServer(bWait);
1477 void CApplication::StartUPnPRenderer()
1480 if (g_guiSettings.GetBool("services.upnprenderer"))
1482 CLog::Log(LOGNOTICE, "starting upnp renderer");
1483 CUPnP::GetInstance()->StartRenderer();
1488 void CApplication::StopUPnPRenderer()
1491 if (CUPnP::IsInstantiated())
1493 CLog::Log(LOGNOTICE, "stopping upnp renderer");
1494 CUPnP::GetInstance()->StopRenderer();
1499 void CApplication::StartUPnPServer()
1502 if (g_guiSettings.GetBool("services.upnpserver"))
1504 CLog::Log(LOGNOTICE, "starting upnp server");
1505 CUPnP::GetInstance()->StartServer();
1510 void CApplication::StopUPnPServer()
1513 if (CUPnP::IsInstantiated())
1515 CLog::Log(LOGNOTICE, "stopping upnp server");
1516 CUPnP::GetInstance()->StopServer();
1521 void CApplication::StartZeroconf()
1524 //entry in guisetting only present if HAS_ZEROCONF is set
1525 if(g_guiSettings.GetBool("services.zeroconf"))
1527 CLog::Log(LOGNOTICE, "starting zeroconf publishing");
1528 CZeroconf::GetInstance()->Start();
1533 void CApplication::StopZeroconf()
1536 if(CZeroconf::IsInstantiated())
1538 CLog::Log(LOGNOTICE, "stopping zeroconf publishing");
1539 CZeroconf::GetInstance()->Stop();
1544 void CApplication::DimLCDOnPlayback(bool dim)
1550 g_lcd->DisableOnPlayback(IsPlayingVideo(), IsPlayingAudio());
1552 g_lcd->SetBackLight(1);
1557 void CApplication::StartServices()
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);
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");
1573 CLCDFactory factory;
1574 g_lcd = factory.Create();
1577 g_lcd->Initialize();
1582 void CApplication::StopServices()
1584 m_network.NetworkMessage(CNetwork::SERVICES_DOWN, 0);
1586 #if !defined(_WIN32) && defined(HAS_DVD_DRIVE)
1587 CLog::Log(LOGNOTICE, "stop dvd detect media");
1588 m_DetectDVDType.StopThread();
1591 g_peripherals.Clear();
1594 void CApplication::ReloadSkin()
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())
1607 CGUIMessage msg3(GUI_MSG_SETFOCUS, g_windowManager.GetActiveWindow(), iCtrlID, 0);
1608 pWindow->OnMessage(msg3);
1612 bool CApplication::LoadSkin(const CStdString& skinID)
1614 if (m_skinReloading)
1618 if (CAddonMgr::Get().GetAddon(skinID, addon, ADDON_SKIN))
1620 LoadSkin(boost::dynamic_pointer_cast<ADDON::CSkinInfo>(addon));
1626 void CApplication::LoadSkin(const SkinPtr& skin)
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);
1636 bool bPreviousPlayingState=false;
1637 bool bPreviousRenderingState=false;
1638 if (g_application.m_pPlayer && g_application.IsPlayingVideo())
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())
1646 if (g_windowManager.GetActiveWindow() == WINDOW_FULLSCREEN_VIDEO)
1648 g_windowManager.ActivateWindow(WINDOW_HOME);
1649 bPreviousRenderingState = true;
1654 // close the music and video overlays (they're re-opened automatically later)
1655 CSingleLock lock(g_graphicsContext);
1657 // save the current window details
1658 int currentWindow = g_windowManager.GetActiveWindow();
1659 vector<int> currentModelessWindows;
1660 g_windowManager.GetActiveModelessWindows(currentModelessWindows);
1664 CLog::Log(LOGINFO, " load skin from:%s", skin->Path().c_str());
1666 g_SkinInfo->Start();
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")))
1673 CLog::Log(LOGINFO, " language needs a ttf font, loading first ttf font available");
1674 CStdString strFontSet;
1675 if (g_fontManager.GetFirstFontSetUnicode(strFontSet))
1677 CLog::Log(LOGINFO, " new font is '%s'", strFontSet.c_str());
1678 g_guiSettings.SetString("lookandfeel.font", strFontSet);
1682 CLog::Log(LOGERROR, " no ttf font found, but needed for the language %s.", g_guiSettings.GetString("locale.language").c_str());
1684 g_colorManager.Load(g_guiSettings.GetString("lookandfeel.skincolors"));
1686 g_fontManager.LoadFonts(g_guiSettings.GetString("lookandfeel.font"));
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);
1694 URIUtils::AddFileToFolder(skin->Path(), "language", skinEnglishPath);
1695 URIUtils::AddFileToFolder(skinEnglishPath, "English", skinEnglishPath);
1696 URIUtils::AddFileToFolder(skinEnglishPath, "strings.xml", skinEnglishPath);
1698 g_localizeStrings.LoadSkinStrings(langPath, skinEnglishPath);
1700 g_SkinInfo->LoadIncludes();
1703 start = CurrentHostCounter();
1705 CLog::Log(LOGINFO, " load new skin...");
1706 CGUIWindowHome *pHome = (CGUIWindowHome *)g_windowManager.GetWindow(WINDOW_HOME);
1707 if (!pHome || !pHome->Load("Home.xml"))
1709 // failed to load home.xml
1710 // fallback to default skin
1711 if ( strcmpi(skin->ID().c_str(), DEFAULT_SKIN) != 0)
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);
1720 // Load the user windows
1724 end = CurrentHostCounter();
1725 freq = CurrentHostFrequency();
1726 CLog::Log(LOGDEBUG,"Load Skin XML: %.2fms", 1000.f * (end - start) / freq);
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();
1739 if (g_SkinInfo->HasSkinFile("DialogFullScreenInfo.xml"))
1740 g_windowManager.Add(new CGUIDialogFullScreenInfo);
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");
1749 CLog::Log(LOGINFO, " skin loaded...");
1751 // leave the graphics lock
1755 if (currentWindow != WINDOW_INVALID)
1757 g_windowManager.ActivateWindow(currentWindow);
1758 for (unsigned int i = 0; i < currentModelessWindows.size(); i++)
1760 CGUIDialog *dialog = (CGUIDialog *)g_windowManager.GetWindow(currentModelessWindows[i]);
1761 if (dialog) dialog->Show();
1765 if (g_application.m_pPlayer && g_application.IsPlayingVideo())
1767 if (bPreviousPlayingState)
1768 g_application.m_pPlayer->Pause();
1769 if (bPreviousRenderingState)
1770 g_windowManager.ActivateWindow(WINDOW_FULLSCREEN_VIDEO);
1774 void CApplication::UnloadSkin(bool forReload /* = false */)
1776 m_skinReloading = forReload;
1778 CLog::Log(LOGINFO, "Unloading old skin %s...", forReload ? "for reload " : "");
1780 g_audioManager.Enable(false);
1782 g_windowManager.DeInitialize();
1783 CTextureCache::Get().Deinitialize();
1785 // remove the skin-dependent window
1786 g_windowManager.Delete(WINDOW_DIALOG_FULLSCREEN_INFO);
1788 g_TextureManager.Cleanup();
1789 g_largeTextureManager.CleanupUnusedImages(true);
1791 g_fontManager.Clear();
1793 g_colorManager.Clear();
1795 g_charsetConverter.reset();
1797 g_infoManager.Clear();
1800 bool CApplication::LoadUserWindows()
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)
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))
1811 for (int i = 0; i < items.Size(); ++i)
1813 if (items[i]->m_bIsFolder)
1815 CStdString skinFile = URIUtils::GetFileName(items[i]->GetPath());
1816 if (skinFile.Left(6).CompareNoCase("custom") == 0)
1818 TiXmlDocument xmlDoc;
1819 if (!xmlDoc.LoadFile(items[i]->GetPath()))
1821 CLog::Log(LOGERROR, "unable to load:%s, Line %d\n%s", items[i]->GetPath().c_str(), xmlDoc.ErrorRow(), xmlDoc.ErrorDesc());
1825 // Root element should be <window>
1826 TiXmlElement* pRootElement = xmlDoc.RootElement();
1827 CStdString strValue = pRootElement->Value();
1828 if (!strValue.Equals("window"))
1830 CLog::Log(LOGERROR, "file :%s doesnt contain <window>", skinFile.c_str());
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;
1838 if (pRootElement->Attribute("type"))
1839 strType = pRootElement->Attribute("type");
1842 const TiXmlNode *pType = pRootElement->FirstChild("type");
1843 if (pType && pType->FirstChild())
1844 strType = pType->FirstChild()->Value();
1846 int id = WINDOW_INVALID;
1847 if (!pRootElement->Attribute("id", &id))
1849 const TiXmlNode *pType = pRootElement->FirstChild("id");
1850 if (pType && pType->FirstChild())
1851 id = atol(pType->FirstChild()->Value());
1853 CStdString visibleCondition;
1854 CGUIControlFactory::GetConditionalVisibility(pRootElement, visibleCondition);
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);
1863 pWindow = new CGUIStandardWindow(id + WINDOW_HOME, skinFile);
1865 // Check to make sure the pointer isn't still null
1866 if (pWindow == NULL)
1868 CLog::Log(LOGERROR, "Out of memory / Failed to create new object in LoadUserWindows");
1871 if (id == WINDOW_INVALID || g_windowManager.GetWindow(WINDOW_HOME + id))
1876 pWindow->SetVisibleCondition(visibleCondition);
1877 g_windowManager.AddCustomWindow(pWindow);
1885 bool CApplication::RenderNoPresent()
1889 // DXMERGE: This may have been important?
1890 // g_graphicsContext.AcquireCurrentContext();
1892 g_graphicsContext.Lock();
1894 // dont show GUI when playing full screen video
1895 if (g_graphicsContext.IsFullScreenVideo())
1897 if (m_bPresentFrame && IsPlaying() && !IsPaused())
1900 g_renderManager.Present();
1903 g_renderManager.RenderUpdate(true);
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);
1913 bool hasRendered = g_windowManager.Render();
1915 // if we're recording an audio stream then show blinking REC
1916 if (!g_graphicsContext.IsFullScreenVideo())
1918 if (m_pPlayer && m_pPlayer->IsRecording() )
1920 static int iBlinkRecord = 0;
1922 if (iBlinkRecord > 25)
1924 CGUIFont* pFont = g_fontManager.GetFont("font13");
1925 CGUITextLayout::DrawText(pFont, 60, 50, 0xffff0000, 0, "REC", 0);
1928 if (iBlinkRecord > 50)
1933 g_graphicsContext.Unlock();
1938 float CApplication::GetDimScreenSaverLevel() const
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"))
1946 if (!m_screenSaver->GetSetting("level").IsEmpty())
1947 return 100.0f - (float)atof(m_screenSaver->GetSetting("level"));
1951 bool CApplication::WaitFrame(unsigned int timeout)
1955 // Wait for all other frames to be presented
1956 CSingleLock lock(m_frameMutex);
1957 //wait until event is set, but modify remaining time
1959 TightConditionVariable<InversePredicate<int&> > cv(m_frameCond, InversePredicate<int&>(m_frameCount));
1960 cv.wait(lock,timeout);
1961 done = m_frameCount == 0;
1966 void CApplication::NewFrame()
1968 // We just posted another frame. Keep track and notify.
1970 CSingleLock lock(m_frameMutex);
1974 m_frameCond.notifyAll();
1977 void CApplication::Render()
1979 // do not render if we are stopped
1983 if (!m_AppActive && !m_bStop && (!IsPlayingVideo() || IsPaused()))
1992 int vsync_mode = g_guiSettings.GetInt("videoscreen.vsync");
1994 bool decrement = false;
1995 bool hasRendered = false;
1996 bool limitFrames = false;
1997 unsigned int singleFrameTime = 10; // default limit 100 fps
2001 bool lowfps = m_dpmsIsActive;
2002 // Whether externalplayer is playing and we're unfocused
2003 bool extPlayerActive = m_eCurrentPlayer >= EPC_EXTPLAYER && IsPlaying() && !m_AppFocused;
2005 m_bPresentFrame = false;
2006 if (!extPlayerActive && g_graphicsContext.IsFullScreenVideo() && !IsPaused())
2008 CSingleLock lock(m_frameMutex);
2010 TightConditionVariable<int&> cv(m_frameCond,m_frameCount);
2013 m_bPresentFrame = m_frameCount > 0;
2014 decrement = m_bPresentFrame;
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.
2030 if (extPlayerActive)
2032 ResetScreenSaver(); // Prevent screensaver dimming the screen
2033 singleFrameTime = 1000; // 1 fps, high wakeup latency but v.low CPU usage
2036 singleFrameTime = 200; // 5 fps, <=200 ms latency to wake up
2043 CSingleLock lock(g_graphicsContext);
2044 g_infoManager.UpdateFPS();
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);
2053 if(!g_Windowing.BeginRender())
2056 if (RenderNoPresent())
2059 g_Windowing.EndRender();
2061 g_TextureManager.FreeUnusedTextures();
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()
2066 g_infoManager.ResetCache();
2070 unsigned int now = XbmcThreads::SystemClockMillis();
2072 m_lastRenderTime = now;
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
2077 if (g_advancedSettings.m_guiDirtyRegionNoFlipTimeout >= 0)
2078 flip = hasRendered || (now - m_lastRenderTime) < (unsigned int)g_advancedSettings.m_guiDirtyRegionNoFlipTimeout;
2082 //fps limiter, make sure each frame lasts at least singleFrameTime milliseconds
2083 if (limitFrames || !flip)
2086 singleFrameTime = 40; //if not flipping, loop at 25 fps
2088 unsigned int frameTime = now - m_lastFrameTime;
2089 if (frameTime < singleFrameTime)
2090 Sleep(singleFrameTime - frameTime);
2092 m_lastFrameTime = XbmcThreads::SystemClockMillis();
2095 g_graphicsContext.Flip(g_windowManager.GetDirty());
2096 CTimeUtils::UpdateFrameTime(flip);
2098 g_renderManager.UpdateResolution();
2099 g_renderManager.ManageCaptures();
2102 CSingleLock lock(m_frameMutex);
2103 if(m_frameCount > 0 && decrement)
2106 m_frameCond.notifyAll();
2109 void CApplication::SetStandAlone(bool value)
2111 g_advancedSettings.m_handleMounting = m_bStandalone = value;
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.
2119 bool CApplication::OnKey(const CKey& key)
2122 // Turn the mouse off, as we've just got a keypress from controller or remote
2123 g_Mouse.SetActive(false);
2125 // get the current active window
2126 int iWin = g_windowManager.GetActiveWindow() & WINDOW_ID_MASK;
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);
2132 // a key has been pressed.
2134 m_idleTimer.StartZero();
2135 bool processKey = AlwaysProcess(action);
2139 // allow some keys to be processed while the screensaver is active
2140 if (WakeUpScreenSaverAndDPMS() && !processKey)
2142 CLog::Log(LOGDEBUG, "%s: %s pressed, screen saver/dpms woken up", __FUNCTION__, g_Keyboard.GetKeyName((int) key.GetButtonCode()).c_str());
2146 // change this if we have a dialog up
2147 if (g_windowManager.HasModalDialog())
2149 iWin = g_windowManager.GetTopMostModalDialogID() & WINDOW_ID_MASK;
2151 if (iWin == WINDOW_DIALOG_FULLSCREEN_INFO)
2152 { // fullscreen info dialog - special case
2153 action = CButtonTranslator::GetInstance().GetAction(iWin, key);
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());
2158 if (OnAction(action))
2161 // fallthrough to the main window
2162 iWin = WINDOW_FULLSCREEN_VIDEO;
2164 if (iWin == WINDOW_FULLSCREEN_VIDEO)
2166 // current active window is full screen video.
2167 if (g_application.m_pPlayer && g_application.m_pPlayer->IsInMenu())
2169 // if player is in some sort of menu, (ie DVDMENU) map buttons differently
2170 action = CButtonTranslator::GetInstance().GetAction(WINDOW_VIDEO_MENU, key);
2174 // no then use the fullscreen window section of keymap.xml to map key->action
2175 action = CButtonTranslator::GetInstance().GetAction(iWin, key);
2180 // current active window isnt the fullscreen window
2181 // just use corresponding section from keymap.xml
2182 // to map key->action
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);
2189 CGUIControl *control = window->GetFocusedControl();
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)
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)
2205 action = CAction(0); // reset our action
2206 if (g_guiSettings.GetBool("input.remoteaskeyboard"))
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))
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
2231 if (!action.GetID())
2233 // keyboard entry - pass the keys through directly
2234 if (key.GetFromHttpApi())
2235 action = CAction(key.GetButtonCode() != KEY_INVALID ? key.GetButtonCode() : 0, key.GetUnicode());
2237 { // see if we've got an ascii key
2238 if (key.GetUnicode())
2239 action = CAction(key.GetAscii() | KEY_ASCII, key.GetUnicode());
2241 action = CAction(key.GetVKey() | KEY_VKEY);
2245 CLog::Log(LOGDEBUG, "%s: %s pressed, trying keyboard action %i", __FUNCTION__, g_Keyboard.GetKeyName((int) key.GetButtonCode()).c_str(), action.GetID());
2247 if (OnAction(action))
2249 // failed to handle the keyboard action, drop down through to standard action
2251 if (key.GetFromHttpApi())
2253 if (key.GetButtonCode() != KEY_INVALID)
2254 action = CButtonTranslator::GetInstance().GetAction(iWin, key);
2257 action = CButtonTranslator::GetInstance().GetAction(iWin, key);
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());
2262 // Play a sound based on the action
2263 g_audioManager.PlayActionSound(action);
2265 return OnAction(action);
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)
2272 // Reset the screen saver
2275 // If we were currently in the screen saver wake up and don't process the appcommand
2276 if (WakeUpScreenSaverAndDPMS())
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);
2286 // If we couldn't find an action return false to indicate we have not
2287 // handled this appcommand
2288 if (!appcmdaction.GetID())
2290 CLog::Log(LOGDEBUG, "%s: unknown appcommand %d", __FUNCTION__, appcmd);
2294 // Process the appcommand
2295 CLog::Log(LOGDEBUG, "%s: appcommand %d, trying action %s", __FUNCTION__, appcmd, appcmdaction.GetName().c_str());
2296 OnAction(appcmdaction);
2298 // Always return true regardless of whether the action succeeded or not.
2299 // This stops Windows handling the appcommand itself.
2303 bool CApplication::OnAction(const CAction &action)
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)
2310 tmp.Format("%i",action.GetID());
2311 getApplicationMessenger().HttpApi("broadcastlevel; OnAction:"+tmp+";2");
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())
2320 m_navigationTimer.StartZero();
2325 if (action.GetID() == ACTION_TOGGLE_FULLSCREEN)
2327 g_graphicsContext.ToggleFullScreenRoot();
2331 if (action.IsMouse())
2332 g_Mouse.SetActive(true);
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)
2339 return OnAction(CAction(ACTION_PAUSE));
2341 return OnAction(CAction(ACTION_PLAYER_PLAY));
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) )
2349 // just pass the action to the current window and let it handle it
2350 if (g_windowManager.OnAction(action))
2352 m_navigationTimer.StartZero();
2357 // handle extra global presses
2359 // screenshot : take a screenshot :)
2360 if (action.GetID() == ACTION_TAKE_SCREENSHOT)
2362 CUtil::TakeScreenshot();
2365 // built in functions : execute the built-in
2366 if (action.GetID() == ACTION_BUILT_IN_FUNCTION)
2368 CBuiltins::Execute(action.GetName());
2369 m_navigationTimer.StartZero();
2374 if (action.GetID() == ACTION_RELOAD_KEYMAPS)
2376 CButtonTranslator::GetInstance().Clear();
2377 CButtonTranslator::GetInstance().Load();
2380 // show info : Shows the current video or song information
2381 if (action.GetID() == ACTION_SHOW_INFO)
2383 g_infoManager.ToggleShowInfo();
2387 // codec info : Shows the current song, video or picture codec information
2388 if (action.GetID() == ACTION_SHOW_CODEC)
2390 g_infoManager.ToggleShowCodec();
2394 if ((action.GetID() == ACTION_INCREASE_RATING || action.GetID() == ACTION_DECREASE_RATING) && IsPlayingAudio())
2396 const CMusicInfoTag *tag = g_infoManager.GetCurrentSongTag();
2399 *m_itemCurrentFile->GetMusicInfoTag() = *tag;
2400 char rating = tag->GetRating();
2401 bool needsUpdate(false);
2402 if (rating > '0' && action.GetID() == ACTION_DECREASE_RATING)
2404 m_itemCurrentFile->GetMusicInfoTag()->SetRating(rating - 1);
2407 else if (rating < '5' && action.GetID() == ACTION_INCREASE_RATING)
2409 m_itemCurrentFile->GetMusicInfoTag()->SetRating(rating + 1);
2415 if (db.Open()) // OpenForWrite() ?
2417 db.SetSongRating(m_itemCurrentFile->GetPath(), m_itemCurrentFile->GetMusicInfoTag()->GetRating());
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);
2428 // stop : stops playing current audio song
2429 if (action.GetID() == ACTION_STOP)
2435 // previous : play previous song from playlist
2436 if (action.GetID() == ACTION_PREV_ITEM)
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)
2447 g_playlistPlayer.PlayPrevious();
2452 // next : play next song from playlist
2453 if (action.GetID() == ACTION_NEXT_ITEM)
2455 if (IsPlaying() && m_pPlayer->SkipNext())
2458 g_playlistPlayer.PlayNext();
2465 // pause : pauses current audio song
2466 if (action.GetID() == ACTION_PAUSE && m_iPlaySpeed == 1)
2470 m_pKaraokeMgr->SetPaused( m_pPlayer->IsPaused() );
2472 if (!m_pPlayer->IsPaused())
2473 { // unpaused - set the playspeed back to normal
2476 g_audioManager.Enable(m_pPlayer->IsPaused() && !g_audioContext.IsPassthroughActive());
2479 if (!m_pPlayer->IsPaused())
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)
2485 if (m_iPlaySpeed != 1)
2495 if (action.GetID() == ACTION_PLAYER_FORWARD || action.GetID() == ACTION_PLAYER_REWIND)
2497 int iPlaySpeed = m_iPlaySpeed;
2498 if (action.GetID() == ACTION_PLAYER_REWIND && iPlaySpeed == 1) // Enables Rewinding
2500 else if (action.GetID() == ACTION_PLAYER_REWIND && iPlaySpeed > 1) //goes down a notch if you're FFing
2502 else if (action.GetID() == ACTION_PLAYER_FORWARD && iPlaySpeed < 1) //goes up a notch if you're RWing
2507 if (action.GetID() == ACTION_PLAYER_FORWARD && iPlaySpeed == -1) //sets iSpeed back to 1 if -1 (didn't plan for a -1)
2509 if (iPlaySpeed > 32 || iPlaySpeed < -32)
2512 SetPlaySpeed(iPlaySpeed);
2515 else if ((action.GetAmount() || GetPlaySpeed() != 1) && (action.GetID() == ACTION_ANALOG_REWIND || action.GetID() == ACTION_ANALOG_FORWARD))
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)
2523 g_application.SetPlaySpeed(iSpeed);
2525 CLog::Log(LOGDEBUG,"Resetting playspeed");
2529 // allow play to unpause
2532 if (action.GetID() == ACTION_PLAYER_PLAY)
2534 // unpause, and set the playspeed back to normal
2536 g_audioManager.Enable(m_pPlayer->IsPaused() && !g_audioContext.IsPassthroughActive());
2538 g_application.SetPlaySpeed(1);
2543 if (action.GetID() == ACTION_MUTE)
2549 if (action.GetID() == ACTION_TOGGLE_DIGITAL_ANALOG)
2551 switch(g_guiSettings.GetInt("audiooutput.mode"))
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;
2558 g_application.Restart();
2559 if (g_windowManager.GetActiveWindow() == WINDOW_SETTINGS_SYSTEM)
2561 CGUIMessage msg(GUI_MSG_WINDOW_INIT, 0,0,WINDOW_INVALID,g_windowManager.GetActiveWindow());
2562 g_windowManager.SendMessage(msg);
2567 // Check for global volume control
2568 if (action.GetAmount() && (action.GetID() == ACTION_VOLUME_UP || action.GetID() == ACTION_VOLUME_DOWN))
2570 if (!m_pPlayer || !m_pPlayer->IsPassthrough())
2572 // increase or decrease the volume
2574 if (g_settings.m_bMute)
2576 volume = (int)((float)g_settings.m_iPreMuteVolumeLevel * 0.01f * (VOLUME_MAXIMUM - VOLUME_MINIMUM) + VOLUME_MINIMUM);
2580 volume = g_settings.m_nVolumeLevel + g_settings.m_dynamicRangeCompressionLevel;
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();
2587 speed /= 50; //50 fps
2589 if (action.GetID() == ACTION_VOLUME_UP)
2590 volume += (int)((float)fabs(action.GetAmount()) * action.GetAmount() * speed);
2592 volume -= (int)((float)fabs(action.GetAmount()) * action.GetAmount() * speed);
2594 SetVolume(volume, false);
2596 // show visual feedback of volume change...
2597 ShowVolumeBar(&action);
2600 // Check for global seek control
2601 if (IsPlaying() && action.GetAmount() && (action.GetID() == ACTION_ANALOG_SEEK_FORWARD || action.GetID() == ACTION_ANALOG_SEEK_BACK))
2603 if (!m_pPlayer->CanSeek()) return false;
2604 CGUIWindow *seekBar = g_windowManager.GetWindow(WINDOW_DIALOG_SEEK_BAR);
2606 seekBar->OnAction(action);
2609 if (action.GetID() == ACTION_GUIPROFILE_BEGIN)
2611 CGUIControlProfiler::Instance().SetOutputFile(_P("special://home/guiprofiler.xml"));
2612 CGUIControlProfiler::Instance().Start();
2615 if (action.GetID() == ACTION_SHOW_PLAYLIST)
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);
2627 void CApplication::UpdateLCD()
2630 static unsigned int lTickCount = 0;
2632 if (!g_lcd || !g_guiSettings.GetBool("videoscreen.haslcd"))
2634 unsigned int lTimeOut = 1000;
2635 if ( m_iPlaySpeed != 1)
2637 if ( (XbmcThreads::SystemClockMillis() - lTickCount) >= lTimeOut)
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);
2648 g_lcd->Render(ILCD::LCD_MODE_GENERAL);
2651 lTickCount = XbmcThreads::SystemClockMillis();
2656 void CApplication::FrameMove(bool processEvents)
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;
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())
2673 if (!toast->IsDialogRunning())
2678 g_graphicsContext.Unlock();
2682 #if defined(HAS_LIRC) || defined(HAS_IRSERVERSUITE)
2683 // Read the input from a remote
2684 g_RemoteControl.Update();
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);
2697 g_windowManager.Process(CTimeUtils::GetFrameTime());
2698 g_windowManager.FrameMove();
2701 bool CApplication::ProcessGamepad(float frameTime)
2703 #ifdef HAS_SDL_JOYSTICK
2706 int iWin = g_windowManager.GetActiveWindow() & WINDOW_ID_MASK;
2707 if (g_windowManager.HasModalDialog())
2709 iWin = g_windowManager.GetTopMostModalDialogID() & WINDOW_ID_MASK;
2712 g_Joystick.Update();
2713 if (g_Joystick.GetButton(bid))
2716 m_idleTimer.StartZero();
2719 if (WakeUpScreenSaverAndDPMS())
2721 g_Joystick.Reset(true);
2726 CStdString actionName;
2728 if (CButtonTranslator::GetInstance().TranslateJoystickString(iWin, g_Joystick.GetJoystick().c_str(), bid, JACTIVE_BUTTON, actionID, actionName, fullrange))
2730 CAction action(actionID, 1.0f, 0.0f, actionName);
2731 g_audioManager.PlayActionSound(action);
2733 g_Mouse.SetActive(false);
2734 return OnAction(action);
2741 if (g_Joystick.GetAxis(bid))
2743 if (g_Joystick.GetAmount() < 0)
2749 CStdString actionName;
2751 if (CButtonTranslator::GetInstance().TranslateJoystickString(iWin, g_Joystick.GetJoystick().c_str(), bid, JACTIVE_AXIS, actionID, actionName, fullrange))
2754 if (WakeUpScreenSaverAndDPMS())
2759 CAction action(actionID, fullrange ? (g_Joystick.GetAmount() + 1.0f)/2.0f : fabs(g_Joystick.GetAmount()), 0.0f, actionName);
2760 g_audioManager.PlayActionSound(action);
2762 g_Mouse.SetActive(false);
2763 return OnAction(action);
2767 g_Joystick.ResetAxis(abs(bid));
2771 if (g_Joystick.GetHat(bid, position))
2774 m_idleTimer.StartZero();
2777 if (WakeUpScreenSaverAndDPMS())
2784 CStdString actionName;
2787 bid = position<<16|bid;
2789 if (CButtonTranslator::GetInstance().TranslateJoystickString(iWin, g_Joystick.GetJoystick().c_str(), bid, JACTIVE_HAT, actionID, actionName, fullrange))
2791 CAction action(actionID, 1.0f, 0.0f, actionName);
2792 g_audioManager.PlayActionSound(action);
2794 g_Mouse.SetActive(false);
2795 return OnAction(action);
2802 bool CApplication::ProcessRemote(float frameTime)
2804 #if defined(HAS_LIRC) || defined(HAS_IRSERVERSUITE)
2805 if (g_RemoteControl.GetButton())
2807 CKey key(g_RemoteControl.GetButton(), g_RemoteControl.GetHoldTime());
2808 g_RemoteControl.Reset();
2815 bool CApplication::ProcessPeripherals(float frameTime)
2818 vector<CPeripheral *> peripherals;
2819 if (g_peripherals.GetPeripheralsWithFeature(peripherals, FEATURE_CEC))
2821 for (unsigned int iPeripheralPtr = 0; iPeripheralPtr < peripherals.size(); iPeripheralPtr++)
2823 CPeripheralCecAdapter *cecDevice = (CPeripheralCecAdapter *) peripherals.at(iPeripheralPtr);
2824 if (cecDevice && cecDevice->GetButton())
2826 CKey key(cecDevice->GetButton(), cecDevice->GetHoldTime());
2827 cecDevice->ResetButton();
2837 bool CApplication::ProcessMouse()
2841 if (!g_Mouse.IsActive() || !m_AppFocused)
2844 // Get the mouse command ID
2845 uint32_t mousecommand = g_Mouse.GetAction();
2846 if (mousecommand == ACTION_NOOP)
2849 // Reset the screensaver and idle timers
2850 m_idleTimer.StartZero();
2852 if (WakeUpScreenSaverAndDPMS())
2855 // Retrieve the corresponding action
2857 CKey key(mousecommand | KEY_MOUSE, (unsigned int) 0);
2858 if (g_windowManager.HasModalDialog())
2859 iWin = g_windowManager.GetTopMostModalDialogID() & WINDOW_ID_MASK;
2861 iWin = g_windowManager.GetActiveWindow() & WINDOW_ID_MASK;
2862 CAction mouseaction = CButtonTranslator::GetInstance().GetAction(iWin, key);
2864 // If we couldn't find an action return false to indicate we have not
2865 // handled this mouse action
2866 if (!mouseaction.GetID())
2868 CLog::Log(LOGDEBUG, "%s: unknown mouse command %d", __FUNCTION__, mousecommand);
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());
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);
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()));
2892 void CApplication::CheckForTitleChange()
2895 if (g_settings.m_HttpApiBroadcastLevel>=1)
2897 if (IsPlayingVideo())
2899 const CVideoInfoTag* tagVal = g_infoManager.GetCurrentMovieTag();
2900 if (m_pXbmcHttp && tagVal && !(tagVal->m_strTitle.IsEmpty()))
2902 CStdString msg=m_pXbmcHttp->GetOpenTag()+"MovieTitle:"+tagVal->m_strTitle+m_pXbmcHttp->GetCloseTag();
2903 if (m_prevMedia!=msg && g_settings.m_HttpApiBroadcastLevel>=1)
2905 getApplicationMessenger().HttpApi("broadcastlevel; MediaChanged:"+msg+";1");
2910 else if (IsPlayingAudio())
2912 const CMusicInfoTag* tagVal=g_infoManager.GetCurrentSongTag();
2913 if (m_pXbmcHttp && tagVal)
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)
2922 getApplicationMessenger().HttpApi("broadcastlevel; MediaChanged:"+msg+";1");
2931 bool CApplication::ProcessHTTPApiButtons()
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)
2942 if (keyHttp.GetButtonCode() == KEY_VMOUSE) //virtual mouse
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());
2965 bool CApplication::ProcessEventServer(float frameTime)
2967 #ifdef HAS_EVENT_SERVER
2968 CEventServer* es = CEventServer::GetInstance();
2969 if (!es || !es->Running() || es->GetNumberOfClients()==0)
2972 // process any queued up actions
2973 if (es->ExecuteNextAction())
2975 // reset idle timers
2976 m_idleTimer.StartZero();
2978 WakeUpScreenSaverAndDPMS();
2981 // now handle any buttons or axis
2982 std::string joystickName;
2983 bool isAxis = false;
2984 float fAmount = 0.0;
2986 WORD wKeyID = es->GetButtonCode(joystickName, isAxis, fAmount);
2990 if (joystickName.length() > 0)
2994 if (fabs(fAmount) >= 0.08)
2995 m_lastAxisMap[joystickName][wKeyID] = fAmount;
2997 m_lastAxisMap[joystickName].erase(wKeyID);
3000 return ProcessJoystickEvent(joystickName, wKeyID, isAxis, fAmount);
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);
3031 if (m_lastAxisMap.size() > 0)
3033 // Process all the stored axis.
3034 for (map<std::string, map<int, float> >::iterator iter = m_lastAxisMap.begin(); iter != m_lastAxisMap.end(); ++iter)
3036 for (map<int, float>::iterator iterAxis = (*iter).second.begin(); iterAxis != (*iter).second.end(); ++iterAxis)
3037 ProcessJoystickEvent((*iter).first, (*iterAxis).first, true, (*iterAxis).second);
3043 if (es->GetMousePos(pos.x, pos.y) && g_Mouse.IsEnabled())
3044 return OnAction(CAction(ACTION_MOUSE_MOVE, pos.x, pos.y));
3050 bool CApplication::ProcessJoystickEvent(const std::string& joystickName, int wKeyID, bool isAxis, float fAmount)
3052 #if defined(HAS_EVENT_SERVER)
3053 m_idleTimer.StartZero();
3055 // Make sure to reset screen saver, mouse.
3057 if (WakeUpScreenSaverAndDPMS())
3060 #ifdef HAS_SDL_JOYSTICK
3063 g_Mouse.SetActive(false);
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;
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())
3075 // If player is in some sort of menu, (ie DVDMENU) map buttons differently.
3076 iWin = WINDOW_VIDEO_MENU;
3080 CStdString actionName;
3081 bool fullRange = false;
3083 // Translate using regular joystick translator.
3084 if (CButtonTranslator::GetInstance().TranslateJoystickString(iWin, joystickName.c_str(), wKeyID, isAxis ? JACTIVE_AXIS : JACTIVE_BUTTON, actionID, actionName, fullRange))
3086 CAction action(actionID, fAmount, 0.0f, actionName);
3087 g_audioManager.PlayActionSound(action);
3088 return OnAction(action);
3092 CLog::Log(LOGDEBUG, "ERROR mapping joystick action. Joystick: %s %i",joystickName.c_str(), wKeyID);
3099 bool CApplication::Cleanup()
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);
3151 g_windowManager.Delete(WINDOW_DIALOG_OSD_TELETEXT);
3152 g_windowManager.Delete(WINDOW_DIALOG_TEXT_VIEWER);
3154 g_windowManager.Delete(WINDOW_DIALOG_PLAY_EJECT);
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);
3172 g_windowManager.Delete(WINDOW_HOME);
3173 g_windowManager.Delete(WINDOW_PROGRAMS);
3174 g_windowManager.Delete(WINDOW_PICTURES);
3175 g_windowManager.Delete(WINDOW_WEATHER);
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);
3187 g_windowManager.Remove(WINDOW_DIALOG_SEEK_BAR);
3188 g_windowManager.Remove(WINDOW_DIALOG_VOLUME_BAR);
3190 CAddonMgr::Get().DeInit();
3192 #if defined(HAS_LIRC) || defined(HAS_IRSERVERSUITE)
3193 CLog::Log(LOGNOTICE, "closing down remote control service");
3194 g_RemoteControl.Disconnect();
3197 CLog::Log(LOGNOTICE, "unload sections");
3199 #ifdef HAS_PERFORMANCE_SAMPLE
3200 CLog::Log(LOGNOTICE, "performance statistics");
3201 m_perfStats.DumpStats();
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.
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();
3222 #ifdef HAS_DBUS_SERVER
3223 CDbusServer::RemoveInstance();
3225 DllLoaderContainer::Clear();
3226 g_playlistPlayer.Clear();
3228 g_guiSettings.Clear();
3229 g_advancedSettings.Clear();
3232 CXHandle::DumpObjectTracker();
3235 #ifdef _CRTDBG_MAP_ALLOC
3236 _CrtDumpMemoryLeaks();
3237 while(1); // execution ends
3249 CLog::Log(LOGERROR, "Exception in CApplication::Cleanup()");
3254 void CApplication::Stop(int exitCode)
3258 CAnnouncementManager::Announce(System, "xbmc", "OnQuit");
3260 // cancel any jobs from the jobmanager
3261 CJobManager::GetInstance().CancelJobs();
3263 g_alarmClock.StopThread();
3268 if (g_settings.m_HttpApiBroadcastLevel >= 1)
3269 getApplicationMessenger().HttpApi("broadcastlevel; ShutDown;1");
3271 m_pXbmcHttp->shuttingDown = true;
3275 if( m_bSystemScreenSaverEnable )
3276 g_Windowing.EnableSystemScreenSaver(true);
3278 CLog::Log(LOGNOTICE, "Storing total System Uptime");
3279 g_settings.m_iSystemTimeTotalUp = g_settings.m_iSystemTimeTotalUp + (int)(CTimeUtils::GetFrameTime() / 60000);
3281 // Update the settings information (volume, uptime etc. need saving)
3282 if (CFile::Exists(g_settings.GetSettingsFile()))
3284 CLog::Log(LOGNOTICE, "Saving settings");
3288 CLog::Log(LOGNOTICE, "Not saving settings (settings.xml is not present)");
3291 m_AppActive = false;
3292 m_AppFocused = false;
3293 m_ExitCode = exitCode;
3294 CLog::Log(LOGNOTICE, "stop all");
3296 // stop scanning before we kill the network and so on
3297 CGUIDialogMusicScan *musicScan = (CGUIDialogMusicScan *)g_windowManager.GetWindow(WINDOW_DIALOG_MUSIC_SCAN);
3299 musicScan->StopScanning();
3301 CGUIDialogVideoScan *videoScan = (CGUIDialogVideoScan *)g_windowManager.GetWindow(WINDOW_DIALOG_VIDEO_SCAN);
3303 videoScan->StopScanning();
3305 m_applicationMessenger.Cleanup();
3310 #if defined(__APPLE__) && !defined(__arm__)
3311 XBMCHelper::GetInstance().ReleaseAllInput();
3316 CLog::Log(LOGNOTICE, "stop player");
3321 #if HAS_FILESYTEM_DAAP
3322 CLog::Log(LOGNOTICE, "stop daap clients");
3323 g_DaapClient.Release();
3325 #ifdef HAS_FILESYSTEM_SAP
3326 CLog::Log(LOGNOTICE, "stop sap announcement listener");
3327 g_sapsessions.StopThread();
3330 if(CZeroconfBrowser::IsInstantiated())
3332 CLog::Log(LOGNOTICE, "stop zeroconf browser");
3333 CZeroconfBrowser::GetInstance()->Stop();
3334 CZeroconfBrowser::ReleaseInstance();
3338 CLog::Log(LOGNOTICE, "clean cached files!");
3339 #ifdef HAS_FILESYSTEM_RAR
3340 g_RarManager.ClearCache(true);
3343 #ifdef HAS_FILESYSTEM_SFTP
3344 CSFTPSessionManager::DisconnectAllSessions();
3347 CLog::Log(LOGNOTICE, "unload skin");
3350 #if defined(__APPLE__) && !defined(__arm__)
3351 if (XBMCHelper::GetInstance().IsAlwaysOn() == false)
3352 XBMCHelper::GetInstance().Stop();
3355 #if defined(HAVE_LIBCRYSTALHD)
3356 CCrystalHD::RemoveInstance();
3359 g_mediaManager.Stop();
3361 // Stop services before unloading Python
3362 CAddonMgr::Get().StopServices(false);
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. */
3367 CLog::Log(LOGNOTICE, "stop python");
3368 g_pythonParser.FreeResources();
3379 g_Windowing.DestroyRenderSystem();
3380 g_Windowing.DestroyWindow();
3381 g_Windowing.DestroyWindowSystem();
3383 CLog::Log(LOGNOTICE, "stopped");
3387 CLog::Log(LOGERROR, "Exception in CApplication::Stop()");
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.
3398 bool CApplication::PlayMedia(const CFileItem& item, int iPlaylist)
3400 //If item is a plugin, expand out now and run ourselves again
3401 if (item.IsPlugin())
3403 CFileItem item_new(item);
3404 if (XFILE::CPluginDirectory::GetPluginResult(item.GetPath(), item_new))
3405 return PlayMedia(item_new, iPlaylist);
3408 if (item.IsLastFM())
3410 g_partyModeManager.Disable();
3411 return CLastFmManager::GetInstance()->ChangeStation(item.GetAsUrl());
3413 if (item.IsSmartPlayList())
3415 CFileItemList items;
3416 CUtil::GetRecursiveListing(item.GetPath(), items, "");
3419 CSmartPlaylist smartpl;
3420 //get name and type of smartplaylist, this will always succeed as GetDirectory also did this.
3421 smartpl.OpenAndReadName(item.GetPath());
3423 playlist.Add(items);
3424 return ProcessAndStartPlaylist(smartpl.GetName(), playlist, (smartpl.GetType() == "songs" || smartpl.GetType() == "albums") ? PLAYLIST_MUSIC:PLAYLIST_VIDEO);
3427 else if (item.IsPlayList() || item.IsInternetStream())
3429 CGUIDialogCache* dlgCache = new CGUIDialogCache(5000, g_localizeStrings.Get(10214), item.GetLabel());
3431 //is or could be a playlist
3432 auto_ptr<CPlayList> pPlayList (CPlayListFactory::Create(item));
3433 bool gotPlayList = (pPlayList.get() && pPlayList->Load(item.GetPath()));
3438 if (dlgCache->IsCanceled())
3445 if (iPlaylist != PLAYLIST_NONE)
3446 return ProcessAndStartPlaylist(item.GetPath(), *pPlayList, iPlaylist);
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);
3456 //nothing special just play
3457 return PlayFile(item, false);
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
3466 bool CApplication::PlayStack(const CFileItem& item, bool bRestart)
3468 if (!item.IsStack())
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.
3478 bool haveTimes(false);
3482 dbs.GetVideoSettings(item.GetPath(), g_settings.m_currentVideoSettings);
3483 haveTimes = dbs.GetStackTimes(item.GetPath(), times);
3488 // calculate the total time of the stack
3489 CStackDirectory dir;
3490 dir.GetDirectory(item.GetPath(), *m_currentStack);
3492 for (int i = 0; i < m_currentStack->Size(); i++)
3495 (*m_currentStack)[i]->m_lEndOffset = times[i];
3499 if (!CDVDFileInfo::GetFileDuration((*m_currentStack)[i]->GetPath(), duration))
3501 m_currentStack->Clear();
3504 totalTime += duration / 1000;
3505 (*m_currentStack)[i]->m_lEndOffset = totalTime;
3506 times.push_back(totalTime);
3510 double seconds = item.m_lStartOffset / 75.0;
3512 if (!haveTimes || item.m_lStartOffset == STARTOFFSET_RESUME )
3513 { // have our times now, so update the dB
3517 dbs.SetStackTimes(item.GetPath(), times);
3519 if( item.m_lStartOffset == STARTOFFSET_RESUME )
3521 // can only resume seek here, not dvdstate
3523 if( dbs.GetResumeBookMark(item.GetPath(), bookmark) )
3524 seconds = bookmark.timeInSeconds;
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
3538 // work out where to seek to
3539 for (int i = 0; i < m_currentStack->Size(); i++)
3541 if (seconds < (*m_currentStack)[i]->m_lEndOffset)
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);
3552 return PlayFile(*(*m_currentStack)[0], true);
3555 bool CApplication::PlayFile(const CFileItem& item, bool bRestart)
3559 SaveCurrentFileSettings();
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
3567 *m_itemCurrentFile = item;
3568 m_nextPlaylistItem = -1;
3569 m_currentStackPosition = 0;
3570 m_currentStack->Clear();
3573 CUtil::ClearSubtitles();
3576 if (item.IsDiscStub())
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));
3586 if (item.IsPlayList())
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);
3597 if (URIUtils::IsUPnP(item.GetPath()))
3599 CFileItem item_new(item);
3600 if (XFILE::CUPnPDirectory::GetResource(item.GetPath(), item_new))
3601 return PlayFile(item_new, false);
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
3609 return PlayStack(item, bRestart);
3611 //Is TuxBox, this should probably be moved to CFileTuxBox
3614 CLog::Log(LOGDEBUG, "%s - TuxBox URL Detected %s",__FUNCTION__, item.GetPath().c_str());
3616 if(g_tuxboxService.IsRunning())
3617 g_tuxboxService.Stop();
3620 if(g_tuxbox.CreateNewItem(item, item_new))
3623 // Make sure it doesn't have a player
3624 // so we actually select one normally
3625 m_eCurrentPlayer = EPC_NONE;
3627 // keep the tuxbox:// url as playing url
3628 // and give the new url to the player
3629 if(PlayFile(item_new, true))
3631 if(!g_tuxboxService.IsRunning())
3632 g_tuxboxService.Start();
3639 CPlayerOptions options;
3641 if( item.HasProperty("StartPercent") )
3643 options.startpercent = item.GetProperty("StartPercent").asDouble();
3646 PLAYERCOREID eNewCore = EPC_NONE;
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
3654 if( m_eForcedNextPlayer != EPC_NONE )
3655 eNewCore = m_eForcedNextPlayer;
3656 else if( m_eCurrentPlayer == EPC_NONE )
3657 eNewCore = CPlayerCoreFactory::GetDefaultPlayer(item);
3659 eNewCore = m_eCurrentPlayer;
3663 options.starttime = item.m_lStartOffset / 75.0;
3667 // open the d/b and retrieve the bookmarks for the current movie
3670 dbs.GetVideoSettings(item.GetPath(), g_settings.m_currentVideoSettings);
3672 if( item.m_lStartOffset == STARTOFFSET_RESUME )
3674 options.starttime = 0.0f;
3676 CStdString path = item.GetPath();
3678 path = item.GetVideoInfoTag()->m_strFileNameAndPath;
3679 if(dbs.GetResumeBookMark(path, bookmark))
3681 options.starttime = bookmark.timeInSeconds;
3682 options.state = bookmark.playerState;
3685 else if (item.HasVideoInfoTag())
3687 const CVideoInfoTag *tag = item.GetVideoInfoTag();
3689 if (tag->m_iBookmarkId != -1 && tag->m_iBookmarkId != 0)
3692 dbs.GetBookMarkForEpisode(*tag, bookmark);
3693 options.starttime = bookmark.timeInSeconds;
3694 options.state = bookmark.playerState;
3701 if (m_eForcedNextPlayer != EPC_NONE)
3702 eNewCore = m_eForcedNextPlayer;
3704 eNewCore = CPlayerCoreFactory::GetDefaultPlayer(item);
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;
3715 else if(m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0)
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;
3721 options.fullscreen = false;
3722 // reset this so we don't think we are resuming on seek
3723 m_itemCurrentFile->m_lStartOffset = 0;
3726 options.fullscreen = g_advancedSettings.m_fullScreenOnMovieStart && !g_settings.m_bStartVideoWindowed;
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;
3734 //We have to stop parsing a cdg before mplayer is deallocated
3735 // WHY do we have to do this????
3737 m_pKaraokeMgr->Stop();
3740 // tell system we are starting a file
3741 m_bPlaybackStarting = true;
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)
3747 if ( !(m_eCurrentPlayer == eNewCore && (m_eCurrentPlayer == EPC_DVDPLAYER || m_eCurrentPlayer == EPC_PAPLAYER)) )
3756 m_eCurrentPlayer = eNewCore;
3757 m_pPlayer = CPlayerCoreFactory::CreatePlayer(eNewCore, *this);
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);
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);
3776 CLog::Log(LOGERROR, "Error creating player for item %s (File doesn't exist?)", item.GetPath().c_str());
3782 if (m_iPlaySpeed != 1)
3784 int iSpeed = m_iPlaySpeed;
3786 SetPlaySpeed(iSpeed);
3789 if( IsPlayingAudio() )
3791 if (g_windowManager.GetActiveWindow() == WINDOW_FULLSCREEN_VIDEO)
3792 g_windowManager.ActivateWindow(WINDOW_VISUALISATION);
3795 #ifdef HAS_VIDEO_PLAYBACK
3796 if( IsPlayingVideo() )
3798 if (g_windowManager.GetActiveWindow() == WINDOW_VISUALISATION)
3799 g_windowManager.ActivateWindow(WINDOW_FULLSCREEN_VIDEO);
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();
3806 if (!item.IsDVDImage() && !item.IsDVDFile())
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)
3813 if (m_pPlayer->GetStreamDetails(details->m_streamDetails) && details->HasStreamDetails())
3817 dbs.SetStreamDetailsForFileId(details->m_streamDetails, details->m_iFileId);
3819 CUtil::DeleteVideoDatabaseDirectoryCache();
3826 #if !defined(__APPLE__)
3827 g_audioManager.Enable(false);
3830 m_bPlaybackStarting = false;
3833 // we must have started, otherwise player might send this later
3835 OnPlayBackStarted();
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();
3846 OnPlayBackStopped();
3852 void CApplication::OnPlayBackEnded()
3854 if(m_bPlaybackStarting)
3857 // informs python script currently running playback has ended
3858 // (does nothing if python is not loaded)
3860 g_pythonParser.OnPlayBackEnded();
3864 // Let's tell the outside world as well
3865 if (g_settings.m_HttpApiBroadcastLevel>=1)
3866 getApplicationMessenger().HttpApi("broadcastlevel; OnPlayBackEnded;1");
3869 CAnnouncementManager::Announce(Player, "xbmc", "OnStop");
3871 if (IsPlayingAudio())
3873 CLastfmScrobbler::GetInstance()->SubmitQueue();
3874 CLibrefmScrobbler::GetInstance()->SubmitQueue();
3877 CGUIMessage msg(GUI_MSG_PLAYBACK_ENDED, 0, 0);
3878 g_windowManager.SendThreadMessage(msg);
3881 void CApplication::OnPlayBackStarted()
3883 if(m_bPlaybackStarting)
3887 // informs python script currently running playback has started
3888 // (does nothing if python is not loaded)
3889 g_pythonParser.OnPlayBackStarted();
3893 // Let's tell the outside world as well
3894 if (g_settings.m_HttpApiBroadcastLevel>=1)
3895 getApplicationMessenger().HttpApi("broadcastlevel; OnPlayBackStarted;1");
3898 CGUIMessage msg(GUI_MSG_PLAYBACK_STARTED, 0, 0);
3899 g_windowManager.SendThreadMessage(msg);
3902 void CApplication::OnQueueNextItem()
3904 // informs python script currently running that we are requesting the next track
3905 // (does nothing if python is not loaded)
3907 g_pythonParser.OnQueueNextItem(); // currently unimplemented
3911 // Let's tell the outside world as well
3912 if (g_settings.m_HttpApiBroadcastLevel>=1)
3913 getApplicationMessenger().HttpApi("broadcastlevel; OnQueueNextItem;1");
3916 if(IsPlayingAudio())
3918 CLastfmScrobbler::GetInstance()->SubmitQueue();
3919 CLibrefmScrobbler::GetInstance()->SubmitQueue();
3922 CGUIMessage msg(GUI_MSG_QUEUE_NEXT_ITEM, 0, 0);
3923 g_windowManager.SendThreadMessage(msg);
3926 void CApplication::OnPlayBackStopped()
3928 if(m_bPlaybackStarting)
3931 // informs python script currently running playback has ended
3932 // (does nothing if python is not loaded)
3934 g_pythonParser.OnPlayBackStopped();
3938 // Let's tell the outside world as well
3939 if (g_settings.m_HttpApiBroadcastLevel>=1)
3940 getApplicationMessenger().HttpApi("broadcastlevel; OnPlayBackStopped;1");
3943 CAnnouncementManager::Announce(Player, "xbmc", "OnStop", m_itemCurrentFile);
3945 CLastfmScrobbler::GetInstance()->SubmitQueue();
3946 CLibrefmScrobbler::GetInstance()->SubmitQueue();
3948 CGUIMessage msg( GUI_MSG_PLAYBACK_STOPPED, 0, 0 );
3949 g_windowManager.SendThreadMessage(msg);
3952 void CApplication::OnPlayBackPaused()
3955 g_pythonParser.OnPlayBackPaused();
3959 // Let's tell the outside world as well
3960 if (g_settings.m_HttpApiBroadcastLevel>=1)
3961 getApplicationMessenger().HttpApi("broadcastlevel; OnPlayBackPaused;1");
3965 param["player"]["speed"] = 0;
3966 param["player"]["playerid"] = g_playlistPlayer.GetCurrentPlaylist();
3967 CAnnouncementManager::Announce(Player, "xbmc", "OnPause", m_itemCurrentFile, param);
3970 void CApplication::OnPlayBackResumed()
3973 g_pythonParser.OnPlayBackResumed();
3977 // Let's tell the outside world as well
3978 if (g_settings.m_HttpApiBroadcastLevel>=1)
3979 getApplicationMessenger().HttpApi("broadcastlevel; OnPlayBackResumed;1");
3983 param["player"]["speed"] = 1;
3984 param["player"]["playerid"] = g_playlistPlayer.GetCurrentPlaylist();
3985 CAnnouncementManager::Announce(Player, "xbmc", "OnPlay", m_itemCurrentFile, param);
3988 void CApplication::OnPlayBackSpeedChanged(int iSpeed)
3991 g_pythonParser.OnPlayBackSpeedChanged(iSpeed);
3995 // Let's tell the outside world as well
3996 if (g_settings.m_HttpApiBroadcastLevel>=1)
3999 tmp.Format("broadcastlevel; OnPlayBackSpeedChanged:%i;1",iSpeed);
4000 getApplicationMessenger().HttpApi(tmp);
4005 param["player"]["speed"] = iSpeed;
4006 param["player"]["playerid"] = g_playlistPlayer.GetCurrentPlaylist();
4007 CAnnouncementManager::Announce(Player, "xbmc", "OnSpeedChanged", m_itemCurrentFile, param);
4010 void CApplication::OnPlayBackSeek(int iTime, int seekOffset)
4013 g_pythonParser.OnPlayBackSeek(iTime, seekOffset);
4017 // Let's tell the outside world as well
4018 if (g_settings.m_HttpApiBroadcastLevel>=1)
4021 tmp.Format("broadcastlevel; OnPlayBackSeek:%i;1",iTime);
4022 getApplicationMessenger().HttpApi(tmp);
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);
4035 void CApplication::OnPlayBackSeekChapter(int iChapter)
4038 g_pythonParser.OnPlayBackSeekChapter(iChapter);
4042 // Let's tell the outside world as well
4043 if (g_settings.m_HttpApiBroadcastLevel>=1)
4046 tmp.Format("broadcastlevel; OnPlayBackSkeekChapter:%i;1",iChapter);
4047 getApplicationMessenger().HttpApi(tmp);
4052 bool CApplication::IsPlaying() const
4056 if (!m_pPlayer->IsPlaying())
4061 bool CApplication::IsPaused() const
4065 if (!m_pPlayer->IsPlaying())
4067 return m_pPlayer->IsPaused();
4070 bool CApplication::IsPlayingAudio() const
4074 if (!m_pPlayer->IsPlaying())
4076 if (m_pPlayer->HasVideo())
4078 if (m_pPlayer->HasAudio())
4083 bool CApplication::IsPlayingVideo() const
4087 if (!m_pPlayer->IsPlaying())
4089 if (m_pPlayer->HasVideo())
4095 bool CApplication::IsPlayingFullScreenVideo() const
4097 return IsPlayingVideo() && g_graphicsContext.IsFullScreenVideo();
4100 void CApplication::SaveFileState()
4102 if (!g_settings.GetCurrentProfile().canWriteDatabases())
4104 CJob* job = new CSaveFileStateJob(*m_progressTrackingItem,
4105 m_progressTrackingVideoResumeBookmark,
4106 m_progressTrackingPlayCountUpdate);
4107 CJobManager::GetInstance().AddJob(job, NULL);
4110 void CApplication::UpdateFileState()
4112 // Did the file change?
4113 if (m_progressTrackingItem->GetPath() != "" && m_progressTrackingItem->GetPath() != CurrentFile())
4117 // Reset tracking item
4118 m_progressTrackingItem->Reset();
4122 if (IsPlayingVideo() || IsPlayingAudio())
4124 if (m_progressTrackingItem->GetPath() == "")
4127 *m_progressTrackingItem = CurrentFileItem();
4128 m_progressTrackingPlayCountUpdate = false;
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))
4136 m_progressTrackingPlayCountUpdate = true;
4139 if (m_progressTrackingItem->IsVideo())
4141 if ((m_progressTrackingItem->IsDVDImage() || m_progressTrackingItem->IsDVDFile()) && m_pPlayer->GetTotalTime() > 15*60)
4143 m_progressTrackingItem->GetVideoInfoTag()->m_streamDetails.Reset();
4144 m_pPlayer->GetStreamDetails(m_progressTrackingItem->GetVideoInfoTag()->m_streamDetails);
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();
4151 if (g_advancedSettings.m_videoIgnorePercentAtEnd > 0 &&
4152 GetTotalTime() - GetTime() < 0.01f * g_advancedSettings.m_videoIgnorePercentAtEnd * GetTotalTime())
4154 // Delete the bookmark
4155 m_progressTrackingVideoResumeBookmark.timeInSeconds = -1.0f;
4158 if (GetTime() > g_advancedSettings.m_videoIgnoreSecondsAtStart)
4160 // Update the bookmark
4161 m_progressTrackingVideoResumeBookmark.timeInSeconds = GetTime();
4162 m_progressTrackingVideoResumeBookmark.totalTimeInSeconds = GetTotalTime();
4167 m_progressTrackingVideoResumeBookmark.timeInSeconds = 0.0f;
4174 void CApplication::StopPlaying()
4176 int iWin = g_windowManager.GetActiveWindow();
4181 m_pKaraokeMgr->Stop();
4185 m_pPlayer->CloseFile();
4187 // turn off visualisation window when stopping
4188 if (iWin == WINDOW_VISUALISATION
4189 || iWin == WINDOW_FULLSCREEN_VIDEO)
4190 g_windowManager.PreviousWindow();
4192 g_partyModeManager.Disable();
4196 void CApplication::ResetScreenSaver()
4199 m_shutdownTimer.StartZero();
4201 // screen saver timer is reset only if we're not already in screensaver or
4203 if ((!m_bScreenSave && m_iScreenSaveLock == 0) && !m_dpmsIsActive)
4204 ResetScreenSaverTimer();
4207 void CApplication::ResetScreenSaverTimer()
4209 #if defined(__APPLE__) && !defined(__arm__)
4210 Cocoa_UpdateSystemActivity();
4212 m_screenSaverTimer.StartZero();
4215 void CApplication::StopScreenSaverTimer()
4217 m_screenSaverTimer.Stop();
4220 bool CApplication::ToggleDPMS(bool manual)
4222 if (manual || (m_dpmsIsManual == manual))
4226 m_dpmsIsActive = false;
4227 m_dpmsIsManual = false;
4228 return m_dpms->DisablePowerSaving();
4232 if (m_dpms->EnablePowerSaving(m_dpms->GetSupportedModes()[0]))
4234 m_dpmsIsActive = true;
4235 m_dpmsIsManual = manual;
4243 bool CApplication::WakeUpScreenSaverAndDPMS()
4247 // turn on lcd backlight
4248 if (g_lcd && g_advancedSettings.m_lcdDimOnScreenSave)
4249 g_lcd->SetBackLight(1);
4252 // First reset DPMS, if active
4257 // TODO: if screensaver lock is specified but screensaver is not active
4258 // (DPMS came first), activate screensaver now.
4260 ResetScreenSaverTimer();
4261 return !m_bScreenSave || WakeUpScreenSaver();
4264 return WakeUpScreenSaver();
4267 bool CApplication::WakeUpScreenSaver()
4269 if (m_iScreenSaveLock == 2)
4272 // if Screen saver is active
4273 if (m_bScreenSave && m_screenSaver)
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")
4281 m_iScreenSaveLock = 2;
4282 CGUIMessage msg(GUI_MSG_CHECK_LOCK,0,0);
4283 g_windowManager.GetWindow(WINDOW_SCREENSAVER)->OnMessage(msg);
4285 if (m_iScreenSaveLock == -1)
4287 m_iScreenSaveLock = 0;
4291 // disable screensaver
4292 m_bScreenSave = false;
4293 m_iScreenSaveLock = 0;
4294 ResetScreenSaverTimer();
4296 CAnnouncementManager::Announce(GUI, "xbmc", "OnScreensaverDeactivated");
4298 if (m_screenSaver->ID() == "visualization" || m_screenSaver->ID() == "screensaver.xbmc.builtin.slideshow")
4300 // we can just continue as usual from vis mode
4303 else if (m_screenSaver->ID() == "screensaver.xbmc.builtin.dim" || m_screenSaver->ID() == "screensaver.xbmc.builtin.black")
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
4316 void CApplication::CheckScreenSaverAndDPMS()
4318 if (!m_dpmsIsActive)
4319 g_Windowing.ResetOSScreensaver();
4321 bool maybeScreensaver =
4322 !m_dpmsIsActive && !m_bScreenSave
4323 && !g_guiSettings.GetString("screensaver.mode").IsEmpty();
4325 !m_dpmsIsActive && m_dpms->IsSupported()
4326 && g_guiSettings.GetInt("powermanagement.displaysoff") > 0;
4328 // Has the screen saver window become active?
4329 if (maybeScreensaver && g_windowManager.IsWindowActive(WINDOW_SCREENSAVER))
4331 m_bScreenSave = true;
4332 maybeScreensaver = false;
4335 if (!maybeScreensaver && !maybeDPMS) return; // Nothing to do.
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))
4343 ResetScreenSaverTimer();
4347 float elapsed = m_screenSaverTimer.GetElapsedSeconds();
4349 // DPMS has priority (it makes the screensaver not needed)
4351 && elapsed > g_guiSettings.GetInt("powermanagement.displaysoff") * 60)
4354 WakeUpScreenSaver();
4356 else if (maybeScreensaver
4357 && elapsed > g_guiSettings.GetInt("screensaver.time") * 60)
4359 ActivateScreenSaver();
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 */)
4368 m_bScreenSave = true;
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(""));
4376 // turn off lcd backlight if requested
4377 if (g_lcd && g_advancedSettings.m_lcdDimOnScreenSave)
4378 g_lcd->SetBackLight(0);
4381 CAnnouncementManager::Announce(GUI, "xbmc", "OnScreensaverActivated");
4383 // disable screensaver lock from the login screen
4384 m_iScreenSaveLock = g_windowManager.GetActiveWindow() == WINDOW_LOGIN_SCREEN ? 1 : 0;
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")))
4390 if (!CAddonMgr::Get().GetAddon("screensaver.xbmc.builtin.dim", m_screenSaver))
4391 m_screenSaver.reset(new CScreenSaver(""));
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);
4401 // Picture slideshow
4402 if (m_screenSaver->ID() == "screensaver.xbmc.builtin.slideshow")
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())
4411 path = "special://profile/Thumbnails/Video/Fanart";
4413 path = "special://profile/Thumbnails/Music/Fanart";
4414 m_applicationMessenger.PictureSlideShow(path, true, type != "2");
4416 else if (m_screenSaver->ID() == "screensaver.xbmc.builtin.dim")
4418 else if (m_screenSaver->ID() == "screensaver.xbmc.builtin.black")
4420 else if (!m_screenSaver->ID().IsEmpty())
4421 g_windowManager.ActivateWindow(WINDOW_SCREENSAVER);
4424 void CApplication::CheckShutdown()
4426 CGUIDialogMusicScan *pMusicScan = (CGUIDialogMusicScan *)g_windowManager.GetWindow(WINDOW_DIALOG_MUSIC_SCAN);
4427 CGUIDialogVideoScan *pVideoScan = (CGUIDialogVideoScan *)g_windowManager.GetWindow(WINDOW_DIALOG_VIDEO_SCAN);
4429 // first check if we should reset the timer
4430 bool resetTimer = false;
4431 if (IsPlaying() || IsPaused()) // is something playing?
4434 if (pMusicScan && pMusicScan->IsScanning()) // music scanning?
4437 if (pVideoScan && pVideoScan->IsScanning()) // video scanning?
4440 if (g_windowManager.IsWindowActive(WINDOW_DIALOG_PROGRESS)) // progress dialog is onscreen
4445 m_shutdownTimer.StartZero();
4449 if ( m_shutdownTimer.GetElapsedSeconds() > g_guiSettings.GetInt("powermanagement.shutdowntime") * 60 )
4451 // Since it is a sleep instead of a shutdown, let's set everything to reset when we wake up.
4452 m_shutdownTimer.Stop();
4455 getApplicationMessenger().Shutdown();
4459 bool CApplication::OnMessage(CGUIMessage& message)
4461 switch ( message.GetMessage() )
4463 case GUI_MSG_NOTIFY_ALL:
4465 if (message.GetParam1()==GUI_MSG_REMOVED_MEDIA)
4467 // Update general playlist: Remove DVD playlist items
4468 int nRemoved = g_playlistPlayer.RemoveDVDItems();
4471 CGUIMessage msg( GUI_MSG_PLAYLIST_CHANGED, 0, 0 );
4472 g_windowManager.SendMessage( msg );
4474 // stop the file if it's on dvd (will set the resume point etc)
4475 if (m_itemCurrentFile->IsOnDVD())
4481 case GUI_MSG_PLAYBACK_STARTED:
4483 #ifdef TARGET_DARWIN
4484 DarwinSetScheduling(message.GetMessage());
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;
4498 g_infoManager.SetCurrentItem(*m_itemCurrentFile);
4499 CLastFmManager::GetInstance()->OnSongChange(*m_itemCurrentFile);
4500 g_partyModeManager.OnSongChange(true);
4503 param["player"]["speed"] = 1;
4504 param["player"]["playerid"] = g_playlistPlayer.GetCurrentPlaylist();
4505 CAnnouncementManager::Announce(Player, "xbmc", "OnPlay", m_itemCurrentFile, param);
4507 DimLCDOnPlayback(true);
4509 if (IsPlayingAudio())
4511 // Start our cdg parser as appropriate
4513 if (m_pKaraokeMgr && g_guiSettings.GetBool("karaoke.enabled") && !m_itemCurrentFile->IsInternetStream())
4515 m_pKaraokeMgr->Stop();
4516 if (m_itemCurrentFile->IsMusicDb())
4518 if (!m_itemCurrentFile->HasMusicInfoTag() || !m_itemCurrentFile->GetMusicInfoTag()->Loaded())
4520 IMusicInfoTagLoader* tagloader = CMusicInfoTagLoaderFactory::CreateLoader(m_itemCurrentFile->GetPath());
4521 tagloader->Load(m_itemCurrentFile->GetPath(),*m_itemCurrentFile->GetMusicInfoTag());
4524 m_pKaraokeMgr->Start(m_itemCurrentFile->GetMusicInfoTag()->GetURL());
4527 m_pKaraokeMgr->Start(m_itemCurrentFile->GetPath());
4530 // Let scrobbler know about the track
4531 const CMusicInfoTag* tag=g_infoManager.GetCurrentSongTag();
4534 CLastfmScrobbler::GetInstance()->AddSong(*tag, CLastFmManager::GetInstance()->IsRadioEnabled());
4535 CLibrefmScrobbler::GetInstance()->AddSong(*tag, CLastFmManager::GetInstance()->IsRadioEnabled());
4543 case GUI_MSG_QUEUE_NEXT_ITEM:
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())
4551 if (m_pPlayer) m_pPlayer->OnNothingToQueueNotify();
4552 return true; // nothing to do
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;
4565 case GUI_MSG_PLAYBACK_STOPPED:
4566 case GUI_MSG_PLAYBACK_ENDED:
4567 case GUI_MSG_PLAYLISTPLAYER_STOPPED:
4571 m_pKaraokeMgr->Stop();
4573 #ifdef TARGET_DARWIN
4574 DarwinSetScheduling(message.GetMessage());
4576 // first check if we still have items in the stack to play
4577 if (message.GetMessage() == GUI_MSG_PLAYBACK_ENDED)
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);
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)
4590 // Delete the bookmark
4591 m_progressTrackingVideoResumeBookmark.timeInSeconds = -1.0f;
4594 // reset the current playing file
4595 m_itemCurrentFile->Reset();
4596 g_infoManager.ResetCurrentItem();
4597 m_currentStack->Clear();
4599 if (message.GetMessage() == GUI_MSG_PLAYBACK_ENDED)
4601 g_playlistPlayer.PlayNext(1, true);
4606 if (CLastFmManager::GetInstance()->IsRadioEnabled())
4607 CLastFmManager::GetInstance()->StopRadio();
4618 g_audioManager.Enable(true);
4619 DimLCDOnPlayback(false);
4622 if (!IsPlayingVideo() && g_windowManager.GetActiveWindow() == WINDOW_FULLSCREEN_VIDEO)
4624 g_windowManager.PreviousWindow();
4627 if (!IsPlayingAudio() && g_playlistPlayer.GetCurrentPlaylist() == PLAYLIST_NONE && g_windowManager.GetActiveWindow() == WINDOW_VISUALISATION)
4629 g_settings.Save(); // save vis settings
4630 WakeUpScreenSaverAndDPMS();
4631 g_windowManager.PreviousWindow();
4634 // DVD ejected while playing in vis ?
4635 if (!IsPlayingAudio() && (m_itemCurrentFile->IsCDDA() || m_itemCurrentFile->IsOnDVD()) && !g_mediaManager.IsDiscInDrive() && g_windowManager.GetActiveWindow() == WINDOW_VISUALISATION)
4638 g_settings.Save(); // save vis settings
4639 WakeUpScreenSaverAndDPMS();
4640 g_windowManager.PreviousWindow();
4643 if (IsEnableTestMode()) g_application.getApplicationMessenger().Quit();
4648 case GUI_MSG_PLAYLISTPLAYER_STARTED:
4649 case GUI_MSG_PLAYLISTPLAYER_CHANGED:
4654 case GUI_MSG_FULLSCREEN:
4655 { // Switch to fullscreen, if we can
4656 SwitchToFullScreen();
4660 case GUI_MSG_EXECUTE:
4661 if (message.GetNumStringParams())
4662 return ExecuteXBMCAction(message.GetStringParam());
4668 bool CApplication::ExecuteXBMCAction(std::string actionStr)
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());
4676 // user has asked for something to be executed
4677 if (CBuiltins::HasCommand(actionStr))
4678 CBuiltins::Execute(actionStr);
4681 // try translating the action from our ButtonTranslator
4683 if (CButtonTranslator::TranslateActionString(actionStr.c_str(), actionID))
4685 OnAction(CAction(actionID));
4688 CFileItem item(actionStr, false);
4690 if (item.IsPythonScript())
4691 { // a python script
4692 g_pythonParser.evalFile(item.GetPath().c_str(),ADDON::AddonPtr());
4696 if (item.IsAudio() || item.IsVideo())
4697 { // an audio or video file
4706 void CApplication::Process()
4710 // dispatch the messages generated by python or other threads to the current window
4711 g_windowManager.DispatchThreadMessages();
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();
4718 // process any Python scripts
4719 g_pythonParser.Process();
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
4726 // check if we can free unused memory
4728 g_audioManager.FreeUnused();
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();
4737 m_pPlayer->DoAudioWork();
4739 // do any processing that isn't needed on each run
4740 if( m_slowTimer.GetElapsedMilliseconds() > 500 )
4742 m_slowTimer.Reset();
4746 g_cpuInfo.getUsedPercentage(); // must call it to recalculate pct values
4749 // We get called every 500ms
4750 void CApplication::ProcessSlow()
4752 g_powerManager.ProcessEvents();
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
4758 if (g_Windowing.IsFullScreen())
4759 { // SDL thinks it's hidden
4764 // Store our file state for use on close()
4767 if (IsPlayingAudio())
4769 CLastfmScrobbler::GetInstance()->UpdateStatus();
4770 CLibrefmScrobbler::GetInstance()->UpdateStatus();
4773 // Check if we need to activate the screensaver / DPMS.
4774 CheckScreenSaverAndDPMS();
4776 // Check if we need to shutdown (if enabled).
4778 if (g_guiSettings.GetInt("powermanagement.shutdowntime") && g_advancedSettings.m_fullScreen)
4780 if (g_guiSettings.GetInt("powermanagement.shutdowntime"))
4786 // check if we should restart the player
4787 CheckDelayedPlayerRestart();
4789 // check if we can unload any unreferenced dlls or sections
4790 if (!IsPlayingVideo())
4791 CSectionLoader::UnloadDelayed();
4793 // check for any idle curl connections
4794 g_curlInterface.CheckIdle();
4796 // check for any idle myth sessions
4797 CMythSession::CheckIdle();
4799 #ifdef HAS_FILESYSTEM_HTSP
4800 // check for any idle htsp sessions
4801 HTSP::CHTSPDirectorySession::CheckIdle();
4805 if ( m_pKaraokeMgr )
4806 m_pKaraokeMgr->ProcessSlow();
4809 // LED - LCD SwitchOn On Paused! m_bIsPaused=TRUE -> LED/LCD is ON!
4810 if(IsPaused() != m_bIsPaused)
4813 DimLCDOnPlayback(m_bIsPaused);
4815 m_bIsPaused = IsPaused();
4818 if (!IsPlayingVideo())
4819 g_largeTextureManager.CleanupUnusedImages();
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();
4827 // update upnp server/renderer states
4828 if(CUPnP::IsInstantiated())
4829 CUPnP::GetInstance()->UpdateState();
4831 //Check to see if current playing Title has changed and whether we should broadcast the fact
4832 CheckForTitleChange();
4834 #if defined(_LINUX) && defined(HAS_FILESYSTEM_SMB)
4838 #ifdef HAS_FILESYSTEM_NFS
4839 gNfsConnection.CheckIfIdle();
4842 #ifdef HAS_FILESYSTEM_SFTP
4843 CSFTPSessionManager::ClearOutIdleSessions();
4846 g_mediaManager.ProcessEvents();
4849 if (g_RemoteControl.IsInUse() && !g_RemoteControl.IsInitialized())
4850 g_RemoteControl.Initialize();
4854 // attempt to reinitialize the LCD (e.g. after resuming from sleep)
4855 if (!IsPlayingVideo())
4857 if (g_lcd && !g_lcd->IsConnected())
4860 g_lcd->Initialize();
4865 if (!IsPlayingVideo())
4866 CAddonInstaller::Get().UpdateRepos();
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()
4874 if(!m_idleTimer.IsRunning())
4877 m_idleTimer.StartZero();
4879 return (int)m_idleTimer.GetElapsedSeconds();
4882 float CApplication::NavigationIdleTime()
4884 if (!m_navigationTimer.IsRunning())
4886 m_navigationTimer.Stop();
4887 m_navigationTimer.StartZero();
4889 return m_navigationTimer.GetElapsedSeconds();
4892 void CApplication::DelayedPlayerRestart()
4894 m_restartPlayerTimer.StartZero();
4897 void CApplication::CheckDelayedPlayerRestart()
4899 if (m_restartPlayerTimer.GetElapsedSeconds() > 3)
4901 m_restartPlayerTimer.Stop();
4902 m_restartPlayerTimer.Reset();
4907 void CApplication::Restart(bool bSamePosition)
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
4912 // first check if we're playing a file
4913 if ( !IsPlayingVideo() && !IsPlayingAudio())
4921 // do we want to return to the current position in the file
4922 if (false == bSamePosition)
4924 // no, then just reopen the file and start at the beginning
4925 PlayFile(*m_itemCurrentFile, true);
4929 // else get current position
4930 double time = GetTime();
4932 // get player state, needed for dvd's
4933 CStdString state = m_pPlayer->GetPlayerState();
4935 // set the requested starttime
4936 m_itemCurrentFile->m_lStartOffset = (long)(time * 75.0);
4939 if ( PlayFile(*m_itemCurrentFile, true) && m_pPlayer )
4940 m_pPlayer->SetPlayerState(state);
4943 const CStdString& CApplication::CurrentFile()
4945 return m_itemCurrentFile->GetPath();
4948 CFileItem& CApplication::CurrentFileItem()
4950 return *m_itemCurrentFile;
4953 void CApplication::ShowVolumeBar(const CAction *action)
4955 CGUIDialog *volumeBar = (CGUIDialog *)g_windowManager.GetWindow(WINDOW_DIALOG_VOLUME_BAR);
4960 volumeBar->OnAction(*action);
4964 bool CApplication::IsMuted() const
4966 return g_settings.m_bMute;
4969 void CApplication::ToggleMute(void)
4971 if (g_settings.m_bMute)
4977 void CApplication::Mute()
4979 g_settings.m_iPreMuteVolumeLevel = GetVolume();
4981 g_settings.m_bMute = true;
4984 void CApplication::UnMute()
4986 SetVolume(g_settings.m_iPreMuteVolumeLevel);
4987 g_settings.m_iPreMuteVolumeLevel = 0;
4988 g_settings.m_bMute = false;
4991 void CApplication::SetVolume(long iValue, bool isPercentage /* = true */)
4993 // convert the percentage to a mB (milliBell) value (*100 for dB)
4995 iValue = (long)((float)iValue * 0.01f * (VOLUME_MAXIMUM - VOLUME_MINIMUM) + VOLUME_MINIMUM);
4997 SetHardwareVolume(iValue);
4998 #ifndef HAS_SDL_AUDIO
4999 g_audioManager.SetVolume(g_settings.m_nVolumeLevel);
5001 g_audioManager.SetVolume((int)(128.f * (g_settings.m_nVolumeLevel - VOLUME_MINIMUM) / (float)(VOLUME_MAXIMUM - VOLUME_MINIMUM)));
5005 void CApplication::SetHardwareVolume(long hardwareVolume)
5008 if (hardwareVolume >= VOLUME_MAXIMUM) // + VOLUME_DRC_MAXIMUM
5009 hardwareVolume = VOLUME_MAXIMUM;// + VOLUME_DRC_MAXIMUM;
5010 if (hardwareVolume <= VOLUME_MINIMUM)
5011 hardwareVolume = VOLUME_MINIMUM;
5013 // update our settings
5014 if (hardwareVolume > VOLUME_MAXIMUM)
5016 g_settings.m_dynamicRangeCompressionLevel = hardwareVolume - VOLUME_MAXIMUM;
5017 g_settings.m_nVolumeLevel = VOLUME_MAXIMUM;
5021 g_settings.m_dynamicRangeCompressionLevel = 0;
5022 g_settings.m_nVolumeLevel = hardwareVolume;
5025 // and tell our player to update the volume
5028 m_pPlayer->SetVolume(g_settings.m_nVolumeLevel);
5030 // m_pPlayer->SetDynamicRangeCompression(g_settings.m_dynamicRangeCompressionLevel);
5034 int CApplication::GetVolume() const
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);
5040 int CApplication::GetSubtitleDelay() const
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);
5046 int CApplication::GetAudioDelay() const
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);
5052 void CApplication::SetPlaySpeed(int iSpeed)
5054 if (!IsPlayingAudio() && !IsPlayingVideo())
5056 if (m_iPlaySpeed == iSpeed)
5058 if (!m_pPlayer->CanSeek())
5060 if (m_pPlayer->IsPaused())
5063 ((m_iPlaySpeed > 1) && (iSpeed > m_iPlaySpeed)) ||
5064 ((m_iPlaySpeed < -1) && (iSpeed < m_iPlaySpeed))
5067 iSpeed = m_iPlaySpeed; // from pause to ff/rw, do previous ff/rw speed
5071 m_iPlaySpeed = iSpeed;
5073 m_pPlayer->ToFFRW(m_iPlaySpeed);
5074 if (m_iPlaySpeed == 1)
5076 m_pPlayer->SetVolume(g_settings.m_nVolumeLevel);
5080 m_pPlayer->SetVolume(VOLUME_MINIMUM);
5084 int CApplication::GetPlaySpeed() const
5086 return m_iPlaySpeed;
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
5093 double CApplication::GetTotalTime() const
5097 if (IsPlaying() && m_pPlayer)
5099 if (m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0)
5100 rc = (*m_currentStack)[m_currentStack->Size() - 1]->m_lEndOffset;
5102 rc = m_pPlayer->GetTotalTime();
5108 void CApplication::StopShutdownTimer()
5110 if (m_shutdownTimer.IsRunning())
5111 m_shutdownTimer.Stop();
5114 void CApplication::ResetShutdownTimers()
5116 // reset system shutdown timer
5117 m_shutdownTimer.StartZero();
5119 // delete custom shutdown timer
5120 if (g_alarmClock.HasAlarm("shutdowntimer"))
5121 g_alarmClock.Stop("shutdowntimer", true);
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
5131 if (IsPlaying() && m_pPlayer)
5133 if (m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0)
5135 long startOfCurrentFile = (m_currentStackPosition > 0) ? (*m_currentStack)[m_currentStackPosition-1]->m_lEndOffset : 0;
5136 rc = (double)startOfCurrentFile + m_pPlayer->GetTime() * 0.001;
5139 rc = static_cast<double>(m_pPlayer->GetTime() * 0.001f);
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 )
5152 if (IsPlaying() && m_pPlayer && (dTime >= 0.0))
5154 if (!m_pPlayer->CanSeek()) return;
5155 if (m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0)
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++)
5163 if ((*m_currentStack)[i]->m_lEndOffset > dTime)
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));
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);
5181 // convert to milliseconds and perform seek
5182 m_pPlayer->SeekTime( static_cast<__int64>( dTime * 1000.0 ) );
5186 float CApplication::GetPercentage() const
5188 if (IsPlaying() && m_pPlayer)
5190 if (IsPlayingAudio() && m_itemCurrentFile->HasMusicInfoTag())
5192 const CMusicInfoTag& tag = *m_itemCurrentFile->GetMusicInfoTag();
5193 if (tag.GetDuration() > 0)
5194 return (float)(GetTime() / tag.GetDuration() * 100);
5197 if (m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0)
5198 return (float)(GetTime() / GetTotalTime() * 100);
5200 return m_pPlayer->GetPercentage();
5205 float CApplication::GetCachePercentage() const
5207 if (IsPlaying() && m_pPlayer)
5208 return m_pPlayer->GetCachePercentage();
5213 void CApplication::SeekPercentage(float percent)
5215 if (IsPlaying() && m_pPlayer && (percent >= 0.0))
5217 if (!m_pPlayer->CanSeek()) return;
5218 if (m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0)
5219 SeekTime(percent * 0.01 * GetTotalTime());
5221 m_pPlayer->SeekPercentage(percent);
5225 // SwitchToFullScreen() returns true if a switch is made, else returns false
5226 bool CApplication::SwitchToFullScreen()
5228 // if playing from the video info window, close it first!
5229 if (g_windowManager.HasModalDialog() && g_windowManager.GetTopMostModalDialogID() == WINDOW_DIALOG_VIDEO_INFO)
5231 CGUIDialogVideoInfo* pDialog = (CGUIDialogVideoInfo*)g_windowManager.GetWindow(WINDOW_DIALOG_VIDEO_INFO);
5232 if (pDialog) pDialog->Close(true);
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)
5239 // See if we're playing a video, and are in GUI mode
5240 if ( IsPlayingVideo() && g_windowManager.GetActiveWindow() != WINDOW_FULLSCREEN_VIDEO)
5242 // Reset frame count so that timing is FPS will be correct.
5244 CSingleLock lock(m_frameMutex);
5248 // then switch to fullscreen mode
5249 g_windowManager.ActivateWindow(WINDOW_FULLSCREEN_VIDEO);
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);
5261 void CApplication::Minimize()
5263 g_Windowing.Minimize();
5266 PLAYERCOREID CApplication::GetCurrentPlayer()
5268 return m_eCurrentPlayer;
5271 // when a scan is initiated, save current settings
5272 // and enable tag reading and remote thums
5273 void CApplication::SaveMusicScanSettings()
5275 CLog::Log(LOGINFO,"Music scan has started... Enabling tag reading, and remote thumbs");
5276 g_settings.m_bMyMusicIsScanning = true;
5280 void CApplication::RestoreMusicScanSettings()
5282 g_settings.m_bMyMusicIsScanning = false;
5286 void CApplication::UpdateLibraries()
5288 if (g_guiSettings.GetBool("videolibrary.updateonstartup"))
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("");
5296 if (g_guiSettings.GetBool("musiclibrary.updateonstartup"))
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("");
5305 void CApplication::CheckPlayingProgress()
5307 // check if we haven't rewound past the start of the file
5310 int iSpeed = g_application.GetPlaySpeed();
5320 if (g_infoManager.GetPlayTime() / 1000 < iPower)
5322 g_application.SetPlaySpeed(1);
5323 g_application.SeekTime(0);
5329 bool CApplication::ProcessAndStartPlaylist(const CStdString& strPlayList, CPlayList& playlist, int iPlaylist)
5331 CLog::Log(LOGDEBUG,"CApplication::ProcessAndStartPlaylist(%s, %i)",strPlayList.c_str(), iPlaylist);
5333 // initial exit conditions
5334 // no songs in playlist just return
5335 if (playlist.size() == 0)
5339 if (iPlaylist < PLAYLIST_MUSIC || iPlaylist > PLAYLIST_VIDEO)
5342 // setup correct playlist
5343 g_playlistPlayer.ClearPlaylist(iPlaylist);
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;
5349 // add the items to the playlist player
5350 g_playlistPlayer.Add(iPlaylist, playlist);
5352 // if we have a playlist
5353 if (g_playlistPlayer.GetPlaylist(iPlaylist).size())
5356 g_playlistPlayer.SetCurrentPlaylist(iPlaylist);
5357 g_playlistPlayer.Reset();
5358 g_playlistPlayer.Play();
5364 void CApplication::SaveCurrentFileSettings()
5366 if (m_itemCurrentFile->IsVideo())
5368 // save video settings
5369 if (g_settings.m_currentVideoSettings != g_settings.m_defaultVideoSettings)
5373 dbs.SetVideoSettings(m_itemCurrentFile->GetPath(), g_settings.m_currentVideoSettings);
5379 bool CApplication::AlwaysProcess(const CAction& action)
5381 // check if this button is mapped to a built-in function
5382 if (!action.GetName().IsEmpty())
5384 CStdString builtInFunction;
5385 vector<CStdString> params;
5386 CUtil::SplitExecFunction(action.GetName(), builtInFunction, params);
5387 builtInFunction.ToLower();
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"))
5406 CApplicationMessenger& CApplication::getApplicationMessenger()
5408 return m_applicationMessenger;
5411 bool CApplication::IsCurrentThread() const
5413 return CThread::IsCurrentThread(m_threadID);
5416 bool CApplication::IsPresentFrame()
5418 CSingleLock lock(m_frameMutex);
5419 bool ret = m_bPresentFrame;
5424 #if defined(HAS_LINUX_NETWORK)
5425 CNetworkLinux& CApplication::getNetwork()
5429 #elif defined(HAS_WIN32_NETWORK)
5430 CNetworkWin32& CApplication::getNetwork()
5435 CNetwork& CApplication::getNetwork()
5441 #ifdef HAS_PERFORMANCE_SAMPLE
5442 CPerformanceStats &CApplication::GetPerformanceStats()