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 int listenPort = g_advancedSettings.m_airPlayPort;
1295 CStdString password = g_guiSettings.GetString("services.airplaypassword");
1296 bool usePassword = g_guiSettings.GetBool("services.useairplaypassword");
1298 if (CAirPlayServer::StartServer(listenPort, true))
1300 CAirPlayServer::SetCredentials(usePassword, password);
1301 std::map<std::string, std::string> txt;
1302 txt["deviceid"] = m_network.GetFirstConnectedInterface()->GetMacAddress();
1303 txt["features"] = "0x77";
1304 txt["model"] = "AppleTV2,1";
1305 txt["srcvers"] = "101.28";
1306 CZeroconf::GetInstance()->PublishService("servers.airplay", "_airplay._tcp", "XBMC", listenPort, txt);
1311 if (g_guiSettings.GetBool("services.airplay") && m_network.IsAvailable())
1313 int listenPort = g_advancedSettings.m_airTunesPort;
1314 CStdString password = g_guiSettings.GetString("services.airplaypassword");
1315 bool usePassword = g_guiSettings.GetBool("services.useairplaypassword");
1317 if (!CAirTunesServer::StartServer(listenPort, true, usePassword, password))
1319 CLog::Log(LOGERROR, "Failed to start AirTunes Server");
1325 void CApplication::StopAirplayServer(bool bWait)
1328 CAirPlayServer::StopServer(bWait);
1329 CZeroconf::GetInstance()->RemoveService("servers.airplay");
1332 CAirTunesServer::StopServer(bWait);
1336 bool CApplication::StartJSONRPCServer()
1339 if (g_guiSettings.GetBool("services.esenabled"))
1341 CJSONRPC::Initialize();
1343 if (CTCPServer::StartServer(g_advancedSettings.m_jsonTcpPort, g_guiSettings.GetBool("services.esallinterfaces")))
1345 std::map<std::string, std::string> txt;
1346 CZeroconf::GetInstance()->PublishService("servers.jsonrpc", "_xbmc-jsonrpc._tcp", "XBMC JSONRPC", g_advancedSettings.m_jsonTcpPort, txt);
1357 void CApplication::StopJSONRPCServer(bool bWait)
1360 CTCPServer::StopServer(bWait);
1361 CZeroconf::GetInstance()->RemoveService("servers.jsonrpc");
1365 void CApplication::StartUPnP()
1369 StartUPnPRenderer();
1373 void CApplication::StopUPnP(bool bWait)
1376 if (CUPnP::IsInstantiated())
1378 CLog::Log(LOGNOTICE, "stopping upnp");
1379 CUPnP::ReleaseInstance(bWait);
1384 bool CApplication::StartEventServer()
1386 #ifdef HAS_EVENT_SERVER
1387 CEventServer* server = CEventServer::GetInstance();
1390 CLog::Log(LOGERROR, "ES: Out of memory");
1393 if (g_guiSettings.GetBool("services.esenabled"))
1395 CLog::Log(LOGNOTICE, "ES: Starting event server");
1396 server->StartServer();
1403 bool CApplication::StopEventServer(bool bWait, bool promptuser)
1405 #ifdef HAS_EVENT_SERVER
1406 CEventServer* server = CEventServer::GetInstance();
1409 CLog::Log(LOGERROR, "ES: Out of memory");
1414 if (server->GetNumberOfClients() > 0)
1416 bool cancelled = false;
1417 if (!CGUIDialogYesNo::ShowAndGetInput(13140, 13141, 13142, 20022,
1418 -1, -1, cancelled, 10000)
1421 CLog::Log(LOGNOTICE, "ES: Not stopping event server");
1425 CLog::Log(LOGNOTICE, "ES: Stopping event server with confirmation");
1427 CEventServer::GetInstance()->StopServer(true);
1432 CLog::Log(LOGNOTICE, "ES: Stopping event server");
1434 CEventServer::GetInstance()->StopServer(bWait);
1441 void CApplication::RefreshEventServer()
1443 #ifdef HAS_EVENT_SERVER
1444 if (g_guiSettings.GetBool("services.esenabled"))
1446 CEventServer::GetInstance()->RefreshSettings();
1451 void CApplication::StartDbusServer()
1453 #ifdef HAS_DBUS_SERVER
1454 CDbusServer* serverDbus = CDbusServer::GetInstance();
1457 CLog::Log(LOGERROR, "DS: Out of memory");
1460 CLog::Log(LOGNOTICE, "DS: Starting dbus server");
1461 serverDbus->StartServer( this );
1465 bool CApplication::StopDbusServer(bool bWait)
1467 #ifdef HAS_DBUS_SERVER
1468 CDbusServer* serverDbus = CDbusServer::GetInstance();
1471 CLog::Log(LOGERROR, "DS: Out of memory");
1474 CDbusServer::GetInstance()->StopServer(bWait);
1479 void CApplication::StartUPnPRenderer()
1482 if (g_guiSettings.GetBool("services.upnprenderer"))
1484 CLog::Log(LOGNOTICE, "starting upnp renderer");
1485 CUPnP::GetInstance()->StartRenderer();
1490 void CApplication::StopUPnPRenderer()
1493 if (CUPnP::IsInstantiated())
1495 CLog::Log(LOGNOTICE, "stopping upnp renderer");
1496 CUPnP::GetInstance()->StopRenderer();
1501 void CApplication::StartUPnPServer()
1504 if (g_guiSettings.GetBool("services.upnpserver"))
1506 CLog::Log(LOGNOTICE, "starting upnp server");
1507 CUPnP::GetInstance()->StartServer();
1512 void CApplication::StopUPnPServer()
1515 if (CUPnP::IsInstantiated())
1517 CLog::Log(LOGNOTICE, "stopping upnp server");
1518 CUPnP::GetInstance()->StopServer();
1523 void CApplication::StartZeroconf()
1526 //entry in guisetting only present if HAS_ZEROCONF is set
1527 if(g_guiSettings.GetBool("services.zeroconf"))
1529 CLog::Log(LOGNOTICE, "starting zeroconf publishing");
1530 CZeroconf::GetInstance()->Start();
1535 void CApplication::StopZeroconf()
1538 if(CZeroconf::IsInstantiated())
1540 CLog::Log(LOGNOTICE, "stopping zeroconf publishing");
1541 CZeroconf::GetInstance()->Stop();
1546 void CApplication::DimLCDOnPlayback(bool dim)
1552 g_lcd->DisableOnPlayback(IsPlayingVideo(), IsPlayingAudio());
1554 g_lcd->SetBackLight(1);
1559 void CApplication::StartServices()
1561 #if !defined(_WIN32) && defined(HAS_DVD_DRIVE)
1562 // Start Thread for DVD Mediatype detection
1563 CLog::Log(LOGNOTICE, "start dvd mediatype detection");
1564 m_DetectDVDType.Create(false, THREAD_MINSTACKSIZE);
1567 CLog::Log(LOGNOTICE, "initializing playlistplayer");
1568 g_playlistPlayer.SetRepeat(PLAYLIST_MUSIC, g_settings.m_bMyMusicPlaylistRepeat ? PLAYLIST::REPEAT_ALL : PLAYLIST::REPEAT_NONE);
1569 g_playlistPlayer.SetShuffle(PLAYLIST_MUSIC, g_settings.m_bMyMusicPlaylistShuffle);
1570 g_playlistPlayer.SetRepeat(PLAYLIST_VIDEO, g_settings.m_bMyVideoPlaylistRepeat ? PLAYLIST::REPEAT_ALL : PLAYLIST::REPEAT_NONE);
1571 g_playlistPlayer.SetShuffle(PLAYLIST_VIDEO, g_settings.m_bMyVideoPlaylistShuffle);
1572 CLog::Log(LOGNOTICE, "DONE initializing playlistplayer");
1575 CLCDFactory factory;
1576 g_lcd = factory.Create();
1579 g_lcd->Initialize();
1584 void CApplication::StopServices()
1586 m_network.NetworkMessage(CNetwork::SERVICES_DOWN, 0);
1588 #if !defined(_WIN32) && defined(HAS_DVD_DRIVE)
1589 CLog::Log(LOGNOTICE, "stop dvd detect media");
1590 m_DetectDVDType.StopThread();
1593 g_peripherals.Clear();
1596 void CApplication::ReloadSkin()
1598 m_skinReloading = false;
1599 CGUIMessage msg(GUI_MSG_LOAD_SKIN, -1, g_windowManager.GetActiveWindow());
1600 g_windowManager.SendMessage(msg);
1601 // Reload the skin, restoring the previously focused control. We need this as
1602 // the window unload will reset all control states.
1603 CGUIWindow* pWindow = g_windowManager.GetWindow(g_windowManager.GetActiveWindow());
1604 int iCtrlID = pWindow->GetFocusedControlID();
1605 g_application.LoadSkin(g_guiSettings.GetString("lookandfeel.skin"));
1606 pWindow = g_windowManager.GetWindow(g_windowManager.GetActiveWindow());
1607 if (pWindow && pWindow->HasSaveLastControl())
1609 CGUIMessage msg3(GUI_MSG_SETFOCUS, g_windowManager.GetActiveWindow(), iCtrlID, 0);
1610 pWindow->OnMessage(msg3);
1614 bool CApplication::LoadSkin(const CStdString& skinID)
1616 if (m_skinReloading)
1620 if (CAddonMgr::Get().GetAddon(skinID, addon, ADDON_SKIN))
1622 LoadSkin(boost::dynamic_pointer_cast<ADDON::CSkinInfo>(addon));
1628 void CApplication::LoadSkin(const SkinPtr& skin)
1632 CLog::Log(LOGERROR, "failed to load requested skin, fallback to \"%s\" skin", DEFAULT_SKIN);
1633 g_guiSettings.SetString("lookandfeel.skin", DEFAULT_SKIN);
1634 LoadSkin(DEFAULT_SKIN);
1638 bool bPreviousPlayingState=false;
1639 bool bPreviousRenderingState=false;
1640 if (g_application.m_pPlayer && g_application.IsPlayingVideo())
1642 bPreviousPlayingState = !g_application.m_pPlayer->IsPaused();
1643 if (bPreviousPlayingState)
1644 g_application.m_pPlayer->Pause();
1645 #ifdef HAS_VIDEO_PLAYBACK
1646 if (!g_renderManager.Paused())
1648 if (g_windowManager.GetActiveWindow() == WINDOW_FULLSCREEN_VIDEO)
1650 g_windowManager.ActivateWindow(WINDOW_HOME);
1651 bPreviousRenderingState = true;
1656 // close the music and video overlays (they're re-opened automatically later)
1657 CSingleLock lock(g_graphicsContext);
1659 // save the current window details
1660 int currentWindow = g_windowManager.GetActiveWindow();
1661 vector<int> currentModelessWindows;
1662 g_windowManager.GetActiveModelessWindows(currentModelessWindows);
1666 CLog::Log(LOGINFO, " load skin from:%s", skin->Path().c_str());
1668 g_SkinInfo->Start();
1670 CLog::Log(LOGINFO, " load fonts for skin...");
1671 g_graphicsContext.SetMediaDir(skin->Path());
1672 g_directoryCache.ClearSubPaths(skin->Path());
1673 if (g_langInfo.ForceUnicodeFont() && !g_fontManager.IsFontSetUnicode(g_guiSettings.GetString("lookandfeel.font")))
1675 CLog::Log(LOGINFO, " language needs a ttf font, loading first ttf font available");
1676 CStdString strFontSet;
1677 if (g_fontManager.GetFirstFontSetUnicode(strFontSet))
1679 CLog::Log(LOGINFO, " new font is '%s'", strFontSet.c_str());
1680 g_guiSettings.SetString("lookandfeel.font", strFontSet);
1684 CLog::Log(LOGERROR, " no ttf font found, but needed for the language %s.", g_guiSettings.GetString("locale.language").c_str());
1686 g_colorManager.Load(g_guiSettings.GetString("lookandfeel.skincolors"));
1688 g_fontManager.LoadFonts(g_guiSettings.GetString("lookandfeel.font"));
1690 // load in the skin strings
1691 CStdString langPath, skinEnglishPath;
1692 URIUtils::AddFileToFolder(skin->Path(), "language", langPath);
1693 URIUtils::AddFileToFolder(langPath, g_guiSettings.GetString("locale.language"), langPath);
1694 URIUtils::AddFileToFolder(langPath, "strings.xml", langPath);
1696 URIUtils::AddFileToFolder(skin->Path(), "language", skinEnglishPath);
1697 URIUtils::AddFileToFolder(skinEnglishPath, "English", skinEnglishPath);
1698 URIUtils::AddFileToFolder(skinEnglishPath, "strings.xml", skinEnglishPath);
1700 g_localizeStrings.LoadSkinStrings(langPath, skinEnglishPath);
1702 g_SkinInfo->LoadIncludes();
1705 start = CurrentHostCounter();
1707 CLog::Log(LOGINFO, " load new skin...");
1708 CGUIWindowHome *pHome = (CGUIWindowHome *)g_windowManager.GetWindow(WINDOW_HOME);
1709 if (!pHome || !pHome->Load("Home.xml"))
1711 // failed to load home.xml
1712 // fallback to default skin
1713 if ( strcmpi(skin->ID().c_str(), DEFAULT_SKIN) != 0)
1715 CLog::Log(LOGERROR, "failed to load home.xml for skin:%s, fallback to \"%s\" skin", skin->ID().c_str(), DEFAULT_SKIN);
1716 g_guiSettings.SetString("lookandfeel.skin", DEFAULT_SKIN);
1717 LoadSkin(DEFAULT_SKIN);
1722 // Load the user windows
1726 end = CurrentHostCounter();
1727 freq = CurrentHostFrequency();
1728 CLog::Log(LOGDEBUG,"Load Skin XML: %.2fms", 1000.f * (end - start) / freq);
1730 CLog::Log(LOGINFO, " initialize new skin...");
1731 g_windowManager.AddMsgTarget(this);
1732 g_windowManager.AddMsgTarget(&g_playlistPlayer);
1733 g_windowManager.AddMsgTarget(&g_infoManager);
1734 g_windowManager.AddMsgTarget(&g_fontManager);
1735 g_windowManager.SetCallback(*this);
1736 g_windowManager.Initialize();
1737 CTextureCache::Get().Initialize();
1738 g_audioManager.Enable(true);
1739 g_audioManager.Load();
1741 if (g_SkinInfo->HasSkinFile("DialogFullScreenInfo.xml"))
1742 g_windowManager.Add(new CGUIDialogFullScreenInfo);
1744 { // we can't register visible condition in dialog's ctor because infomanager is cleared when unloading skin
1745 CGUIDialog *overlay = (CGUIDialog *)g_windowManager.GetWindow(WINDOW_DIALOG_VIDEO_OVERLAY);
1746 if (overlay) overlay->SetVisibleCondition("skin.hasvideooverlay");
1747 overlay = (CGUIDialog *)g_windowManager.GetWindow(WINDOW_DIALOG_MUSIC_OVERLAY);
1748 if (overlay) overlay->SetVisibleCondition("skin.hasmusicoverlay");
1751 CLog::Log(LOGINFO, " skin loaded...");
1753 // leave the graphics lock
1757 if (currentWindow != WINDOW_INVALID)
1759 g_windowManager.ActivateWindow(currentWindow);
1760 for (unsigned int i = 0; i < currentModelessWindows.size(); i++)
1762 CGUIDialog *dialog = (CGUIDialog *)g_windowManager.GetWindow(currentModelessWindows[i]);
1763 if (dialog) dialog->Show();
1767 if (g_application.m_pPlayer && g_application.IsPlayingVideo())
1769 if (bPreviousPlayingState)
1770 g_application.m_pPlayer->Pause();
1771 if (bPreviousRenderingState)
1772 g_windowManager.ActivateWindow(WINDOW_FULLSCREEN_VIDEO);
1776 void CApplication::UnloadSkin(bool forReload /* = false */)
1778 m_skinReloading = forReload;
1780 CLog::Log(LOGINFO, "Unloading old skin %s...", forReload ? "for reload " : "");
1782 g_audioManager.Enable(false);
1784 g_windowManager.DeInitialize();
1785 CTextureCache::Get().Deinitialize();
1787 // remove the skin-dependent window
1788 g_windowManager.Delete(WINDOW_DIALOG_FULLSCREEN_INFO);
1790 g_TextureManager.Cleanup();
1791 g_largeTextureManager.CleanupUnusedImages(true);
1793 g_fontManager.Clear();
1795 g_colorManager.Clear();
1797 g_charsetConverter.reset();
1799 g_infoManager.Clear();
1802 bool CApplication::LoadUserWindows()
1804 // Start from wherever home.xml is
1805 std::vector<CStdString> vecSkinPath;
1806 g_SkinInfo->GetSkinPaths(vecSkinPath);
1807 for (unsigned int i = 0;i < vecSkinPath.size();++i)
1809 CLog::Log(LOGINFO, "Loading user windows, path %s", vecSkinPath[i].c_str());
1810 CFileItemList items;
1811 if (CDirectory::GetDirectory(vecSkinPath[i], items, ".xml", false))
1813 for (int i = 0; i < items.Size(); ++i)
1815 if (items[i]->m_bIsFolder)
1817 CStdString skinFile = URIUtils::GetFileName(items[i]->GetPath());
1818 if (skinFile.Left(6).CompareNoCase("custom") == 0)
1820 TiXmlDocument xmlDoc;
1821 if (!xmlDoc.LoadFile(items[i]->GetPath()))
1823 CLog::Log(LOGERROR, "unable to load:%s, Line %d\n%s", items[i]->GetPath().c_str(), xmlDoc.ErrorRow(), xmlDoc.ErrorDesc());
1827 // Root element should be <window>
1828 TiXmlElement* pRootElement = xmlDoc.RootElement();
1829 CStdString strValue = pRootElement->Value();
1830 if (!strValue.Equals("window"))
1832 CLog::Log(LOGERROR, "file :%s doesnt contain <window>", skinFile.c_str());
1836 // Read the <type> element to get the window type to create
1837 // If no type is specified, create a CGUIWindow as default
1838 CGUIWindow* pWindow = NULL;
1840 if (pRootElement->Attribute("type"))
1841 strType = pRootElement->Attribute("type");
1844 const TiXmlNode *pType = pRootElement->FirstChild("type");
1845 if (pType && pType->FirstChild())
1846 strType = pType->FirstChild()->Value();
1848 int id = WINDOW_INVALID;
1849 if (!pRootElement->Attribute("id", &id))
1851 const TiXmlNode *pType = pRootElement->FirstChild("id");
1852 if (pType && pType->FirstChild())
1853 id = atol(pType->FirstChild()->Value());
1855 CStdString visibleCondition;
1856 CGUIControlFactory::GetConditionalVisibility(pRootElement, visibleCondition);
1858 if (strType.Equals("dialog"))
1859 pWindow = new CGUIDialog(id + WINDOW_HOME, skinFile);
1860 else if (strType.Equals("submenu"))
1861 pWindow = new CGUIDialogSubMenu(id + WINDOW_HOME, skinFile);
1862 else if (strType.Equals("buttonmenu"))
1863 pWindow = new CGUIDialogButtonMenu(id + WINDOW_HOME, skinFile);
1865 pWindow = new CGUIStandardWindow(id + WINDOW_HOME, skinFile);
1867 // Check to make sure the pointer isn't still null
1868 if (pWindow == NULL)
1870 CLog::Log(LOGERROR, "Out of memory / Failed to create new object in LoadUserWindows");
1873 if (id == WINDOW_INVALID || g_windowManager.GetWindow(WINDOW_HOME + id))
1878 pWindow->SetVisibleCondition(visibleCondition);
1879 g_windowManager.AddCustomWindow(pWindow);
1887 bool CApplication::RenderNoPresent()
1891 // DXMERGE: This may have been important?
1892 // g_graphicsContext.AcquireCurrentContext();
1894 g_graphicsContext.Lock();
1896 // dont show GUI when playing full screen video
1897 if (g_graphicsContext.IsFullScreenVideo())
1899 if (m_bPresentFrame && IsPlaying() && !IsPaused())
1902 g_renderManager.Present();
1905 g_renderManager.RenderUpdate(true);
1907 // close window overlays
1908 CGUIDialog *overlay = (CGUIDialog *)g_windowManager.GetWindow(WINDOW_DIALOG_VIDEO_OVERLAY);
1909 if (overlay) overlay->Close(true);
1910 overlay = (CGUIDialog *)g_windowManager.GetWindow(WINDOW_DIALOG_MUSIC_OVERLAY);
1911 if (overlay) overlay->Close(true);
1915 bool hasRendered = g_windowManager.Render();
1917 // if we're recording an audio stream then show blinking REC
1918 if (!g_graphicsContext.IsFullScreenVideo())
1920 if (m_pPlayer && m_pPlayer->IsRecording() )
1922 static int iBlinkRecord = 0;
1924 if (iBlinkRecord > 25)
1926 CGUIFont* pFont = g_fontManager.GetFont("font13");
1927 CGUITextLayout::DrawText(pFont, 60, 50, 0xffff0000, 0, "REC", 0);
1930 if (iBlinkRecord > 50)
1935 g_graphicsContext.Unlock();
1940 float CApplication::GetDimScreenSaverLevel() const
1942 if (!m_bScreenSave || !m_screenSaver ||
1943 (m_screenSaver->ID() != "screensaver.xbmc.builtin.dim" &&
1944 m_screenSaver->ID() != "screensaver.xbmc.builtin.black" &&
1945 m_screenSaver->ID() != "screensaver.xbmc.builtin.slideshow"))
1948 if (!m_screenSaver->GetSetting("level").IsEmpty())
1949 return 100.0f - (float)atof(m_screenSaver->GetSetting("level"));
1953 bool CApplication::WaitFrame(unsigned int timeout)
1957 // Wait for all other frames to be presented
1958 CSingleLock lock(m_frameMutex);
1959 //wait until event is set, but modify remaining time
1961 TightConditionVariable<InversePredicate<int&> > cv(m_frameCond, InversePredicate<int&>(m_frameCount));
1962 cv.wait(lock,timeout);
1963 done = m_frameCount == 0;
1968 void CApplication::NewFrame()
1970 // We just posted another frame. Keep track and notify.
1972 CSingleLock lock(m_frameMutex);
1976 m_frameCond.notifyAll();
1979 void CApplication::Render()
1981 // do not render if we are stopped
1985 if (!m_AppActive && !m_bStop && (!IsPlayingVideo() || IsPaused()))
1994 int vsync_mode = g_guiSettings.GetInt("videoscreen.vsync");
1996 bool decrement = false;
1997 bool hasRendered = false;
1998 bool limitFrames = false;
1999 unsigned int singleFrameTime = 10; // default limit 100 fps
2003 bool lowfps = m_dpmsIsActive;
2004 // Whether externalplayer is playing and we're unfocused
2005 bool extPlayerActive = m_eCurrentPlayer >= EPC_EXTPLAYER && IsPlaying() && !m_AppFocused;
2007 m_bPresentFrame = false;
2008 if (!extPlayerActive && g_graphicsContext.IsFullScreenVideo() && !IsPaused())
2010 CSingleLock lock(m_frameMutex);
2012 TightConditionVariable<int&> cv(m_frameCond,m_frameCount);
2015 m_bPresentFrame = m_frameCount > 0;
2016 decrement = m_bPresentFrame;
2021 // engage the frame limiter as needed
2022 limitFrames = lowfps || extPlayerActive;
2023 // DXMERGE - we checked for g_videoConfig.GetVSyncMode() before this
2024 // perhaps allowing it to be set differently than the UI option??
2025 if (vsync_mode == VSYNC_DISABLED || vsync_mode == VSYNC_VIDEO)
2026 limitFrames = true; // not using vsync.
2027 else if ((g_infoManager.GetFPS() > g_graphicsContext.GetFPS() + 10) && g_infoManager.GetFPS() > 1000 / singleFrameTime)
2028 limitFrames = true; // using vsync, but it isn't working.
2032 if (extPlayerActive)
2034 ResetScreenSaver(); // Prevent screensaver dimming the screen
2035 singleFrameTime = 1000; // 1 fps, high wakeup latency but v.low CPU usage
2038 singleFrameTime = 200; // 5 fps, <=200 ms latency to wake up
2045 CSingleLock lock(g_graphicsContext);
2046 g_infoManager.UpdateFPS();
2048 if (g_graphicsContext.IsFullScreenVideo() && IsPlaying() && vsync_mode == VSYNC_VIDEO)
2049 g_Windowing.SetVSync(true);
2050 else if (vsync_mode == VSYNC_ALWAYS)
2051 g_Windowing.SetVSync(true);
2052 else if (vsync_mode != VSYNC_DRIVER)
2053 g_Windowing.SetVSync(false);
2055 if(!g_Windowing.BeginRender())
2058 if (RenderNoPresent())
2061 g_Windowing.EndRender();
2063 g_TextureManager.FreeUnusedTextures();
2065 // reset our info cache - we do this at the end of Render so that it is
2066 // fresh for the next process(), or after a windowclose animation (where process()
2068 g_infoManager.ResetCache();
2072 unsigned int now = XbmcThreads::SystemClockMillis();
2074 m_lastRenderTime = now;
2076 //when nothing has been rendered for m_guiDirtyRegionNoFlipTimeout milliseconds,
2077 //we don't call g_graphicsContext.Flip() anymore, this saves gpu and cpu usage
2079 if (g_advancedSettings.m_guiDirtyRegionNoFlipTimeout >= 0)
2080 flip = hasRendered || (now - m_lastRenderTime) < (unsigned int)g_advancedSettings.m_guiDirtyRegionNoFlipTimeout;
2084 //fps limiter, make sure each frame lasts at least singleFrameTime milliseconds
2085 if (limitFrames || !flip)
2088 singleFrameTime = 40; //if not flipping, loop at 25 fps
2090 unsigned int frameTime = now - m_lastFrameTime;
2091 if (frameTime < singleFrameTime)
2092 Sleep(singleFrameTime - frameTime);
2094 m_lastFrameTime = XbmcThreads::SystemClockMillis();
2097 g_graphicsContext.Flip(g_windowManager.GetDirty());
2098 CTimeUtils::UpdateFrameTime(flip);
2100 g_renderManager.UpdateResolution();
2101 g_renderManager.ManageCaptures();
2104 CSingleLock lock(m_frameMutex);
2105 if(m_frameCount > 0 && decrement)
2108 m_frameCond.notifyAll();
2111 void CApplication::SetStandAlone(bool value)
2113 g_advancedSettings.m_handleMounting = m_bStandalone = value;
2116 // OnKey() translates the key into a CAction which is sent on to our Window Manager.
2117 // The window manager will return true if the event is processed, false otherwise.
2118 // If not already processed, this routine handles global keypresses. It returns
2119 // true if the key has been processed, false otherwise.
2121 bool CApplication::OnKey(const CKey& key)
2124 // Turn the mouse off, as we've just got a keypress from controller or remote
2125 g_Mouse.SetActive(false);
2127 // get the current active window
2128 int iWin = g_windowManager.GetActiveWindow() & WINDOW_ID_MASK;
2130 // this will be checked for certain keycodes that need
2131 // special handling if the screensaver is active
2132 CAction action = CButtonTranslator::GetInstance().GetAction(iWin, key);
2134 // a key has been pressed.
2136 m_idleTimer.StartZero();
2137 bool processKey = AlwaysProcess(action);
2141 // allow some keys to be processed while the screensaver is active
2142 if (WakeUpScreenSaverAndDPMS() && !processKey)
2144 CLog::Log(LOGDEBUG, "%s: %s pressed, screen saver/dpms woken up", __FUNCTION__, g_Keyboard.GetKeyName((int) key.GetButtonCode()).c_str());
2148 // change this if we have a dialog up
2149 if (g_windowManager.HasModalDialog())
2151 iWin = g_windowManager.GetTopMostModalDialogID() & WINDOW_ID_MASK;
2153 if (iWin == WINDOW_DIALOG_FULLSCREEN_INFO)
2154 { // fullscreen info dialog - special case
2155 action = CButtonTranslator::GetInstance().GetAction(iWin, key);
2157 if (!key.IsAnalogButton())
2158 CLog::Log(LOGDEBUG, "%s: %s pressed, trying fullscreen info action %s", __FUNCTION__, g_Keyboard.GetKeyName((int) key.GetButtonCode()).c_str(), action.GetName().c_str());
2160 if (OnAction(action))
2163 // fallthrough to the main window
2164 iWin = WINDOW_FULLSCREEN_VIDEO;
2166 if (iWin == WINDOW_FULLSCREEN_VIDEO)
2168 // current active window is full screen video.
2169 if (g_application.m_pPlayer && g_application.m_pPlayer->IsInMenu())
2171 // if player is in some sort of menu, (ie DVDMENU) map buttons differently
2172 action = CButtonTranslator::GetInstance().GetAction(WINDOW_VIDEO_MENU, key);
2176 // no then use the fullscreen window section of keymap.xml to map key->action
2177 action = CButtonTranslator::GetInstance().GetAction(iWin, key);
2182 // current active window isnt the fullscreen window
2183 // just use corresponding section from keymap.xml
2184 // to map key->action
2186 // first determine if we should use keyboard input directly
2187 bool useKeyboard = key.FromKeyboard() && (iWin == WINDOW_DIALOG_KEYBOARD || iWin == WINDOW_DIALOG_NUMERIC);
2188 CGUIWindow *window = g_windowManager.GetWindow(iWin);
2191 CGUIControl *control = window->GetFocusedControl();
2194 // If this is an edit control set usekeyboard to true. This causes the
2195 // keypress to be processed directly not through the key mappings.
2196 if (control->GetControlType() == CGUIControl::GUICONTROL_EDIT)
2199 // If the key pressed is shift-A to shift-Z set usekeyboard to true.
2200 // This causes the keypress to be used for list navigation.
2201 if (control->IsContainer() && key.GetModifiers() == CKey::MODIFIER_SHIFT && key.GetVKey() >= XBMCVK_A && key.GetVKey() <= XBMCVK_Z)
2207 action = CAction(0); // reset our action
2208 if (g_guiSettings.GetBool("input.remoteaskeyboard"))
2210 // users remote is executing keyboard commands, so use the virtualkeyboard section of keymap.xml
2211 // and send those rather than actual keyboard presses. Only for navigation-type commands though
2212 action = CButtonTranslator::GetInstance().GetAction(WINDOW_DIALOG_KEYBOARD, key);
2213 if (!(action.GetID() == ACTION_MOVE_LEFT ||
2214 action.GetID() == ACTION_MOVE_RIGHT ||
2215 action.GetID() == ACTION_MOVE_UP ||
2216 action.GetID() == ACTION_MOVE_DOWN ||
2217 action.GetID() == ACTION_SELECT_ITEM ||
2218 action.GetID() == ACTION_ENTER ||
2219 action.GetID() == ACTION_PREVIOUS_MENU ||
2220 action.GetID() == ACTION_NAV_BACK))
2222 // the action isn't plain navigation - check for a keyboard-specific keymap
2223 action = CButtonTranslator::GetInstance().GetAction(WINDOW_DIALOG_KEYBOARD, key, false);
2224 if (!(action.GetID() >= REMOTE_0 && action.GetID() <= REMOTE_9) ||
2225 action.GetID() == ACTION_BACKSPACE ||
2226 action.GetID() == ACTION_SHIFT ||
2227 action.GetID() == ACTION_SYMBOLS ||
2228 action.GetID() == ACTION_CURSOR_LEFT ||
2229 action.GetID() == ACTION_CURSOR_RIGHT)
2230 action = CAction(0); // don't bother with this action
2233 if (!action.GetID())
2235 // keyboard entry - pass the keys through directly
2236 if (key.GetFromHttpApi())
2237 action = CAction(key.GetButtonCode() != KEY_INVALID ? key.GetButtonCode() : 0, key.GetUnicode());
2239 { // see if we've got an ascii key
2240 if (key.GetUnicode())
2241 action = CAction(key.GetAscii() | KEY_ASCII, key.GetUnicode());
2243 action = CAction(key.GetVKey() | KEY_VKEY);
2247 CLog::Log(LOGDEBUG, "%s: %s pressed, trying keyboard action %i", __FUNCTION__, g_Keyboard.GetKeyName((int) key.GetButtonCode()).c_str(), action.GetID());
2249 if (OnAction(action))
2251 // failed to handle the keyboard action, drop down through to standard action
2253 if (key.GetFromHttpApi())
2255 if (key.GetButtonCode() != KEY_INVALID)
2256 action = CButtonTranslator::GetInstance().GetAction(iWin, key);
2259 action = CButtonTranslator::GetInstance().GetAction(iWin, key);
2261 if (!key.IsAnalogButton())
2262 CLog::Log(LOGDEBUG, "%s: %s pressed, action is %s", __FUNCTION__, g_Keyboard.GetKeyName((int) key.GetButtonCode()).c_str(), action.GetName().c_str());
2264 // Play a sound based on the action
2265 g_audioManager.PlayActionSound(action);
2267 return OnAction(action);
2270 // OnAppCommand is called in response to a XBMC_APPCOMMAND event.
2271 // This needs to return true if it processed the appcommand or false if it didn't
2272 bool CApplication::OnAppCommand(const CAction &action)
2274 // Reset the screen saver
2277 // If we were currently in the screen saver wake up and don't process the appcommand
2278 if (WakeUpScreenSaverAndDPMS())
2281 // The action ID is the APPCOMMAND code. We need to retrieve the action
2282 // associated with this appcommand from the mapping table.
2283 uint32_t appcmd = action.GetID();
2284 CKey key(appcmd | KEY_APPCOMMAND, (unsigned int) 0);
2285 int iWin = g_windowManager.GetActiveWindow() & WINDOW_ID_MASK;
2286 CAction appcmdaction = CButtonTranslator::GetInstance().GetAction(iWin, key);
2288 // If we couldn't find an action return false to indicate we have not
2289 // handled this appcommand
2290 if (!appcmdaction.GetID())
2292 CLog::Log(LOGDEBUG, "%s: unknown appcommand %d", __FUNCTION__, appcmd);
2296 // Process the appcommand
2297 CLog::Log(LOGDEBUG, "%s: appcommand %d, trying action %s", __FUNCTION__, appcmd, appcmdaction.GetName().c_str());
2298 OnAction(appcmdaction);
2300 // Always return true regardless of whether the action succeeded or not.
2301 // This stops Windows handling the appcommand itself.
2305 bool CApplication::OnAction(const CAction &action)
2308 // Let's tell the outside world about this action, ignoring mouse moves
2309 if (g_settings.m_HttpApiBroadcastLevel>=2 && action.GetID() != ACTION_MOUSE_MOVE)
2312 tmp.Format("%i",action.GetID());
2313 getApplicationMessenger().HttpApi("broadcastlevel; OnAction:"+tmp+";2");
2317 // special case for switching between GUI & fullscreen mode.
2318 if (action.GetID() == ACTION_SHOW_GUI)
2319 { // Switch to fullscreen mode if we can
2320 if (SwitchToFullScreen())
2322 m_navigationTimer.StartZero();
2327 if (action.GetID() == ACTION_TOGGLE_FULLSCREEN)
2329 g_graphicsContext.ToggleFullScreenRoot();
2333 if (action.IsMouse())
2334 g_Mouse.SetActive(true);
2336 // The action PLAYPAUSE behaves as ACTION_PAUSE if we are currently
2337 // playing or ACTION_PLAYER_PLAY if we are not playing.
2338 if (action.GetID() == ACTION_PLAYER_PLAYPAUSE)
2341 return OnAction(CAction(ACTION_PAUSE));
2343 return OnAction(CAction(ACTION_PLAYER_PLAY));
2346 //if the action would start or stop inertial scrolling
2347 //by gesture - bypass the normal OnAction handler of current window
2348 if( !m_pInertialScrollingHandler->CheckForInertialScrolling(&action) )
2351 // just pass the action to the current window and let it handle it
2352 if (g_windowManager.OnAction(action))
2354 m_navigationTimer.StartZero();
2359 // handle extra global presses
2361 // screenshot : take a screenshot :)
2362 if (action.GetID() == ACTION_TAKE_SCREENSHOT)
2364 CUtil::TakeScreenshot();
2367 // built in functions : execute the built-in
2368 if (action.GetID() == ACTION_BUILT_IN_FUNCTION)
2370 CBuiltins::Execute(action.GetName());
2371 m_navigationTimer.StartZero();
2376 if (action.GetID() == ACTION_RELOAD_KEYMAPS)
2378 CButtonTranslator::GetInstance().Clear();
2379 CButtonTranslator::GetInstance().Load();
2382 // show info : Shows the current video or song information
2383 if (action.GetID() == ACTION_SHOW_INFO)
2385 g_infoManager.ToggleShowInfo();
2389 // codec info : Shows the current song, video or picture codec information
2390 if (action.GetID() == ACTION_SHOW_CODEC)
2392 g_infoManager.ToggleShowCodec();
2396 if ((action.GetID() == ACTION_INCREASE_RATING || action.GetID() == ACTION_DECREASE_RATING) && IsPlayingAudio())
2398 const CMusicInfoTag *tag = g_infoManager.GetCurrentSongTag();
2401 *m_itemCurrentFile->GetMusicInfoTag() = *tag;
2402 char rating = tag->GetRating();
2403 bool needsUpdate(false);
2404 if (rating > '0' && action.GetID() == ACTION_DECREASE_RATING)
2406 m_itemCurrentFile->GetMusicInfoTag()->SetRating(rating - 1);
2409 else if (rating < '5' && action.GetID() == ACTION_INCREASE_RATING)
2411 m_itemCurrentFile->GetMusicInfoTag()->SetRating(rating + 1);
2417 if (db.Open()) // OpenForWrite() ?
2419 db.SetSongRating(m_itemCurrentFile->GetPath(), m_itemCurrentFile->GetMusicInfoTag()->GetRating());
2422 // send a message to all windows to tell them to update the fileitem (eg playlistplayer, media windows)
2423 CGUIMessage msg(GUI_MSG_NOTIFY_ALL, 0, 0, GUI_MSG_UPDATE_ITEM, 0, m_itemCurrentFile);
2424 g_windowManager.SendMessage(msg);
2430 // stop : stops playing current audio song
2431 if (action.GetID() == ACTION_STOP)
2437 // previous : play previous song from playlist
2438 if (action.GetID() == ACTION_PREV_ITEM)
2440 // first check whether we're within 3 seconds of the start of the track
2441 // if not, we just revert to the start of the track
2442 if (m_pPlayer && m_pPlayer->CanSeek() && GetTime() > 3)
2449 g_playlistPlayer.PlayPrevious();
2454 // next : play next song from playlist
2455 if (action.GetID() == ACTION_NEXT_ITEM)
2457 if (IsPlaying() && m_pPlayer->SkipNext())
2460 g_playlistPlayer.PlayNext();
2467 // pause : pauses current audio song
2468 if (action.GetID() == ACTION_PAUSE && m_iPlaySpeed == 1)
2472 m_pKaraokeMgr->SetPaused( m_pPlayer->IsPaused() );
2474 if (!m_pPlayer->IsPaused())
2475 { // unpaused - set the playspeed back to normal
2478 g_audioManager.Enable(m_pPlayer->IsPaused() && !g_audioContext.IsPassthroughActive());
2481 if (!m_pPlayer->IsPaused())
2483 // if we do a FF/RW in my music then map PLAY action togo back to normal speed
2484 // if we are playing at normal speed, then allow play to pause
2485 if (action.GetID() == ACTION_PLAYER_PLAY || action.GetID() == ACTION_PAUSE)
2487 if (m_iPlaySpeed != 1)
2497 if (action.GetID() == ACTION_PLAYER_FORWARD || action.GetID() == ACTION_PLAYER_REWIND)
2499 int iPlaySpeed = m_iPlaySpeed;
2500 if (action.GetID() == ACTION_PLAYER_REWIND && iPlaySpeed == 1) // Enables Rewinding
2502 else if (action.GetID() == ACTION_PLAYER_REWIND && iPlaySpeed > 1) //goes down a notch if you're FFing
2504 else if (action.GetID() == ACTION_PLAYER_FORWARD && iPlaySpeed < 1) //goes up a notch if you're RWing
2509 if (action.GetID() == ACTION_PLAYER_FORWARD && iPlaySpeed == -1) //sets iSpeed back to 1 if -1 (didn't plan for a -1)
2511 if (iPlaySpeed > 32 || iPlaySpeed < -32)
2514 SetPlaySpeed(iPlaySpeed);
2517 else if ((action.GetAmount() || GetPlaySpeed() != 1) && (action.GetID() == ACTION_ANALOG_REWIND || action.GetID() == ACTION_ANALOG_FORWARD))
2519 // calculate the speed based on the amount the button is held down
2520 int iPower = (int)(action.GetAmount() * MAX_FFWD_SPEED + 0.5f);
2521 // returns 0 -> MAX_FFWD_SPEED
2522 int iSpeed = 1 << iPower;
2523 if (iSpeed != 1 && action.GetID() == ACTION_ANALOG_REWIND)
2525 g_application.SetPlaySpeed(iSpeed);
2527 CLog::Log(LOGDEBUG,"Resetting playspeed");
2531 // allow play to unpause
2534 if (action.GetID() == ACTION_PLAYER_PLAY)
2536 // unpause, and set the playspeed back to normal
2538 g_audioManager.Enable(m_pPlayer->IsPaused() && !g_audioContext.IsPassthroughActive());
2540 g_application.SetPlaySpeed(1);
2545 if (action.GetID() == ACTION_MUTE)
2551 if (action.GetID() == ACTION_TOGGLE_DIGITAL_ANALOG)
2553 switch(g_guiSettings.GetInt("audiooutput.mode"))
2555 case AUDIO_ANALOG: g_guiSettings.SetInt("audiooutput.mode", AUDIO_IEC958); break;
2556 case AUDIO_IEC958: g_guiSettings.SetInt("audiooutput.mode", AUDIO_HDMI ); break;
2557 case AUDIO_HDMI : g_guiSettings.SetInt("audiooutput.mode", AUDIO_ANALOG); break;
2560 g_application.Restart();
2561 if (g_windowManager.GetActiveWindow() == WINDOW_SETTINGS_SYSTEM)
2563 CGUIMessage msg(GUI_MSG_WINDOW_INIT, 0,0,WINDOW_INVALID,g_windowManager.GetActiveWindow());
2564 g_windowManager.SendMessage(msg);
2569 // Check for global volume control
2570 if (action.GetAmount() && (action.GetID() == ACTION_VOLUME_UP || action.GetID() == ACTION_VOLUME_DOWN))
2572 if (!m_pPlayer || !m_pPlayer->IsPassthrough())
2574 // increase or decrease the volume
2576 if (g_settings.m_bMute)
2578 volume = (int)((float)g_settings.m_iPreMuteVolumeLevel * 0.01f * (VOLUME_MAXIMUM - VOLUME_MINIMUM) + VOLUME_MINIMUM);
2582 volume = g_settings.m_nVolumeLevel + g_settings.m_dynamicRangeCompressionLevel;
2584 // calculate speed so that a full press will equal 1 second from min to max
2585 float speed = float(VOLUME_MAXIMUM - VOLUME_MINIMUM);
2586 if (action.GetRepeat())
2587 speed *= action.GetRepeat();
2589 speed /= 50; //50 fps
2591 if (action.GetID() == ACTION_VOLUME_UP)
2592 volume += (int)((float)fabs(action.GetAmount()) * action.GetAmount() * speed);
2594 volume -= (int)((float)fabs(action.GetAmount()) * action.GetAmount() * speed);
2596 SetVolume(volume, false);
2598 // show visual feedback of volume change...
2599 ShowVolumeBar(&action);
2602 // Check for global seek control
2603 if (IsPlaying() && action.GetAmount() && (action.GetID() == ACTION_ANALOG_SEEK_FORWARD || action.GetID() == ACTION_ANALOG_SEEK_BACK))
2605 if (!m_pPlayer->CanSeek()) return false;
2606 CGUIWindow *seekBar = g_windowManager.GetWindow(WINDOW_DIALOG_SEEK_BAR);
2608 seekBar->OnAction(action);
2611 if (action.GetID() == ACTION_GUIPROFILE_BEGIN)
2613 CGUIControlProfiler::Instance().SetOutputFile(_P("special://home/guiprofiler.xml"));
2614 CGUIControlProfiler::Instance().Start();
2617 if (action.GetID() == ACTION_SHOW_PLAYLIST)
2619 int iPlaylist = g_playlistPlayer.GetCurrentPlaylist();
2620 if (iPlaylist == PLAYLIST_VIDEO)
2621 g_windowManager.ActivateWindow(WINDOW_VIDEO_PLAYLIST);
2622 else if (iPlaylist == PLAYLIST_MUSIC)
2623 g_windowManager.ActivateWindow(WINDOW_MUSIC_PLAYLIST);
2629 void CApplication::UpdateLCD()
2632 static unsigned int lTickCount = 0;
2634 if (!g_lcd || !g_guiSettings.GetBool("videoscreen.haslcd"))
2636 unsigned int lTimeOut = 1000;
2637 if ( m_iPlaySpeed != 1)
2639 if ( (XbmcThreads::SystemClockMillis() - lTickCount) >= lTimeOut)
2641 if (g_application.NavigationIdleTime() < 5)
2642 g_lcd->Render(ILCD::LCD_MODE_NAVIGATION);
2643 else if (IsPlayingVideo())
2644 g_lcd->Render(ILCD::LCD_MODE_VIDEO);
2645 else if (IsPlayingAudio())
2646 g_lcd->Render(ILCD::LCD_MODE_MUSIC);
2647 else if (IsInScreenSaver())
2648 g_lcd->Render(ILCD::LCD_MODE_SCREENSAVER);
2650 g_lcd->Render(ILCD::LCD_MODE_GENERAL);
2653 lTickCount = XbmcThreads::SystemClockMillis();
2658 void CApplication::FrameMove(bool processEvents)
2664 // currently we calculate the repeat time (ie time from last similar keypress) just global as fps
2665 float frameTime = m_frameTime.GetElapsedSeconds();
2666 m_frameTime.StartZero();
2667 // never set a frametime less than 2 fps to avoid problems when debuggin and on breaks
2668 if( frameTime > 0.5 ) frameTime = 0.5;
2670 g_graphicsContext.Lock();
2671 // check if there are notifications to display
2672 CGUIDialogKaiToast *toast = (CGUIDialogKaiToast *)g_windowManager.GetWindow(WINDOW_DIALOG_KAI_TOAST);
2673 if (toast && toast->DoWork())
2675 if (!toast->IsDialogRunning())
2680 g_graphicsContext.Unlock();
2684 #if defined(HAS_LIRC) || defined(HAS_IRSERVERSUITE)
2685 // Read the input from a remote
2686 g_RemoteControl.Update();
2689 // process input actions
2690 CWinEvents::MessagePump();
2691 ProcessHTTPApiButtons();
2692 ProcessRemote(frameTime);
2693 ProcessGamepad(frameTime);
2694 ProcessEventServer(frameTime);
2695 ProcessPeripherals(frameTime);
2696 m_pInertialScrollingHandler->ProcessInertialScroll(frameTime);
2699 g_windowManager.Process(CTimeUtils::GetFrameTime());
2700 g_windowManager.FrameMove();
2703 bool CApplication::ProcessGamepad(float frameTime)
2705 #ifdef HAS_SDL_JOYSTICK
2708 int iWin = g_windowManager.GetActiveWindow() & WINDOW_ID_MASK;
2709 if (g_windowManager.HasModalDialog())
2711 iWin = g_windowManager.GetTopMostModalDialogID() & WINDOW_ID_MASK;
2714 g_Joystick.Update();
2715 if (g_Joystick.GetButton(bid))
2718 m_idleTimer.StartZero();
2721 if (WakeUpScreenSaverAndDPMS())
2723 g_Joystick.Reset(true);
2728 CStdString actionName;
2730 if (CButtonTranslator::GetInstance().TranslateJoystickString(iWin, g_Joystick.GetJoystick().c_str(), bid, JACTIVE_BUTTON, actionID, actionName, fullrange))
2732 CAction action(actionID, 1.0f, 0.0f, actionName);
2733 g_audioManager.PlayActionSound(action);
2735 g_Mouse.SetActive(false);
2736 return OnAction(action);
2743 if (g_Joystick.GetAxis(bid))
2745 if (g_Joystick.GetAmount() < 0)
2751 CStdString actionName;
2753 if (CButtonTranslator::GetInstance().TranslateJoystickString(iWin, g_Joystick.GetJoystick().c_str(), bid, JACTIVE_AXIS, actionID, actionName, fullrange))
2756 if (WakeUpScreenSaverAndDPMS())
2761 CAction action(actionID, fullrange ? (g_Joystick.GetAmount() + 1.0f)/2.0f : fabs(g_Joystick.GetAmount()), 0.0f, actionName);
2762 g_audioManager.PlayActionSound(action);
2764 g_Mouse.SetActive(false);
2765 return OnAction(action);
2769 g_Joystick.ResetAxis(abs(bid));
2773 if (g_Joystick.GetHat(bid, position))
2776 m_idleTimer.StartZero();
2779 if (WakeUpScreenSaverAndDPMS())
2786 CStdString actionName;
2789 bid = position<<16|bid;
2791 if (CButtonTranslator::GetInstance().TranslateJoystickString(iWin, g_Joystick.GetJoystick().c_str(), bid, JACTIVE_HAT, actionID, actionName, fullrange))
2793 CAction action(actionID, 1.0f, 0.0f, actionName);
2794 g_audioManager.PlayActionSound(action);
2796 g_Mouse.SetActive(false);
2797 return OnAction(action);
2804 bool CApplication::ProcessRemote(float frameTime)
2806 #if defined(HAS_LIRC) || defined(HAS_IRSERVERSUITE)
2807 if (g_RemoteControl.GetButton())
2809 CKey key(g_RemoteControl.GetButton(), g_RemoteControl.GetHoldTime());
2810 g_RemoteControl.Reset();
2817 bool CApplication::ProcessPeripherals(float frameTime)
2820 vector<CPeripheral *> peripherals;
2821 if (g_peripherals.GetPeripheralsWithFeature(peripherals, FEATURE_CEC))
2823 for (unsigned int iPeripheralPtr = 0; iPeripheralPtr < peripherals.size(); iPeripheralPtr++)
2825 CPeripheralCecAdapter *cecDevice = (CPeripheralCecAdapter *) peripherals.at(iPeripheralPtr);
2826 if (cecDevice && cecDevice->GetButton())
2828 CKey key(cecDevice->GetButton(), cecDevice->GetHoldTime());
2829 cecDevice->ResetButton();
2839 bool CApplication::ProcessMouse()
2843 if (!g_Mouse.IsActive() || !m_AppFocused)
2846 // Get the mouse command ID
2847 uint32_t mousecommand = g_Mouse.GetAction();
2848 if (mousecommand == ACTION_NOOP)
2851 // Reset the screensaver and idle timers
2852 m_idleTimer.StartZero();
2854 if (WakeUpScreenSaverAndDPMS())
2857 // Retrieve the corresponding action
2859 CKey key(mousecommand | KEY_MOUSE, (unsigned int) 0);
2860 if (g_windowManager.HasModalDialog())
2861 iWin = g_windowManager.GetTopMostModalDialogID() & WINDOW_ID_MASK;
2863 iWin = g_windowManager.GetActiveWindow() & WINDOW_ID_MASK;
2864 CAction mouseaction = CButtonTranslator::GetInstance().GetAction(iWin, key);
2866 // If we couldn't find an action return false to indicate we have not
2867 // handled this mouse action
2868 if (!mouseaction.GetID())
2870 CLog::Log(LOGDEBUG, "%s: unknown mouse command %d", __FUNCTION__, mousecommand);
2874 // Log mouse actions except for move and noop
2875 if (mouseaction.GetID() != ACTION_MOUSE_MOVE && mouseaction.GetID() != ACTION_NOOP)
2876 CLog::Log(LOGDEBUG, "%s: trying mouse action %s", __FUNCTION__, mouseaction.GetName().c_str());
2878 // The action might not be a mouse action. For example wheel moves might
2879 // be mapped to volume up/down in mouse.xml. In this case we do not want
2880 // the mouse position saved in the action.
2881 if (!mouseaction.IsMouse())
2882 return OnAction(mouseaction);
2884 // This is a mouse action so we need to record the mouse position
2885 return OnAction(CAction(mouseaction.GetID(),
2886 g_Mouse.GetHold(MOUSE_LEFT_BUTTON),
2887 (float)g_Mouse.GetX(),
2888 (float)g_Mouse.GetY(),
2889 (float)g_Mouse.GetDX(),
2890 (float)g_Mouse.GetDY(),
2891 mouseaction.GetName()));
2894 void CApplication::CheckForTitleChange()
2897 if (g_settings.m_HttpApiBroadcastLevel>=1)
2899 if (IsPlayingVideo())
2901 const CVideoInfoTag* tagVal = g_infoManager.GetCurrentMovieTag();
2902 if (m_pXbmcHttp && tagVal && !(tagVal->m_strTitle.IsEmpty()))
2904 CStdString msg=m_pXbmcHttp->GetOpenTag()+"MovieTitle:"+tagVal->m_strTitle+m_pXbmcHttp->GetCloseTag();
2905 if (m_prevMedia!=msg && g_settings.m_HttpApiBroadcastLevel>=1)
2907 getApplicationMessenger().HttpApi("broadcastlevel; MediaChanged:"+msg+";1");
2912 else if (IsPlayingAudio())
2914 const CMusicInfoTag* tagVal=g_infoManager.GetCurrentSongTag();
2915 if (m_pXbmcHttp && tagVal)
2918 if (!tagVal->GetTitle().IsEmpty())
2919 msg=m_pXbmcHttp->GetOpenTag()+"AudioTitle:"+tagVal->GetTitle()+m_pXbmcHttp->GetCloseTag();
2920 if (!tagVal->GetArtist().IsEmpty())
2921 msg+=m_pXbmcHttp->GetOpenTag()+"AudioArtist:"+tagVal->GetArtist()+m_pXbmcHttp->GetCloseTag();
2922 if (m_prevMedia!=msg)
2924 getApplicationMessenger().HttpApi("broadcastlevel; MediaChanged:"+msg+";1");
2933 bool CApplication::ProcessHTTPApiButtons()
2938 // copy key from webserver, and reset it in case we're called again before
2939 // whatever happens in OnKey()
2940 CKey keyHttp(m_pXbmcHttp->GetKey());
2941 m_pXbmcHttp->ResetKey();
2942 if (keyHttp.GetButtonCode() != KEY_INVALID)
2944 if (keyHttp.GetButtonCode() == KEY_VMOUSE) //virtual mouse
2946 int actionID = ACTION_MOUSE_MOVE;
2947 if (keyHttp.GetLeftTrigger() == 1)
2948 actionID = ACTION_MOUSE_LEFT_CLICK;
2949 else if (keyHttp.GetLeftTrigger() == 2)
2950 actionID = ACTION_MOUSE_RIGHT_CLICK;
2951 else if (keyHttp.GetLeftTrigger() == 3)
2952 actionID = ACTION_MOUSE_MIDDLE_CLICK;
2953 else if (keyHttp.GetRightTrigger() == 1)
2954 actionID = ACTION_MOUSE_DOUBLE_CLICK;
2955 CAction action(actionID, keyHttp.GetLeftThumbX(), keyHttp.GetLeftThumbY());
2967 bool CApplication::ProcessEventServer(float frameTime)
2969 #ifdef HAS_EVENT_SERVER
2970 CEventServer* es = CEventServer::GetInstance();
2971 if (!es || !es->Running() || es->GetNumberOfClients()==0)
2974 // process any queued up actions
2975 if (es->ExecuteNextAction())
2977 // reset idle timers
2978 m_idleTimer.StartZero();
2980 WakeUpScreenSaverAndDPMS();
2983 // now handle any buttons or axis
2984 std::string joystickName;
2985 bool isAxis = false;
2986 float fAmount = 0.0;
2988 WORD wKeyID = es->GetButtonCode(joystickName, isAxis, fAmount);
2992 if (joystickName.length() > 0)
2996 if (fabs(fAmount) >= 0.08)
2997 m_lastAxisMap[joystickName][wKeyID] = fAmount;
2999 m_lastAxisMap[joystickName].erase(wKeyID);
3002 return ProcessJoystickEvent(joystickName, wKeyID, isAxis, fAmount);
3007 if(wKeyID == KEY_BUTTON_LEFT_ANALOG_TRIGGER)
3008 key = CKey(wKeyID, (BYTE)(255*fAmount), 0, 0.0, 0.0, 0.0, 0.0, frameTime);
3009 else if(wKeyID == KEY_BUTTON_RIGHT_ANALOG_TRIGGER)
3010 key = CKey(wKeyID, 0, (BYTE)(255*fAmount), 0.0, 0.0, 0.0, 0.0, frameTime);
3011 else if(wKeyID == KEY_BUTTON_LEFT_THUMB_STICK_LEFT)
3012 key = CKey(wKeyID, 0, 0, -fAmount, 0.0, 0.0, 0.0, frameTime);
3013 else if(wKeyID == KEY_BUTTON_LEFT_THUMB_STICK_RIGHT)
3014 key = CKey(wKeyID, 0, 0, fAmount, 0.0, 0.0, 0.0, frameTime);
3015 else if(wKeyID == KEY_BUTTON_LEFT_THUMB_STICK_UP)
3016 key = CKey(wKeyID, 0, 0, 0.0, fAmount, 0.0, 0.0, frameTime);
3017 else if(wKeyID == KEY_BUTTON_LEFT_THUMB_STICK_DOWN)
3018 key = CKey(wKeyID, 0, 0, 0.0, -fAmount, 0.0, 0.0, frameTime);
3019 else if(wKeyID == KEY_BUTTON_RIGHT_THUMB_STICK_LEFT)
3020 key = CKey(wKeyID, 0, 0, 0.0, 0.0, -fAmount, 0.0, frameTime);
3021 else if(wKeyID == KEY_BUTTON_RIGHT_THUMB_STICK_RIGHT)
3022 key = CKey(wKeyID, 0, 0, 0.0, 0.0, fAmount, 0.0, frameTime);
3023 else if(wKeyID == KEY_BUTTON_RIGHT_THUMB_STICK_UP)
3024 key = CKey(wKeyID, 0, 0, 0.0, 0.0, 0.0, fAmount, frameTime);
3025 else if(wKeyID == KEY_BUTTON_RIGHT_THUMB_STICK_DOWN)
3026 key = CKey(wKeyID, 0, 0, 0.0, 0.0, 0.0, -fAmount, frameTime);
3033 if (m_lastAxisMap.size() > 0)
3035 // Process all the stored axis.
3036 for (map<std::string, map<int, float> >::iterator iter = m_lastAxisMap.begin(); iter != m_lastAxisMap.end(); ++iter)
3038 for (map<int, float>::iterator iterAxis = (*iter).second.begin(); iterAxis != (*iter).second.end(); ++iterAxis)
3039 ProcessJoystickEvent((*iter).first, (*iterAxis).first, true, (*iterAxis).second);
3045 if (es->GetMousePos(pos.x, pos.y) && g_Mouse.IsEnabled())
3046 return OnAction(CAction(ACTION_MOUSE_MOVE, pos.x, pos.y));
3052 bool CApplication::ProcessJoystickEvent(const std::string& joystickName, int wKeyID, bool isAxis, float fAmount)
3054 #if defined(HAS_EVENT_SERVER)
3055 m_idleTimer.StartZero();
3057 // Make sure to reset screen saver, mouse.
3059 if (WakeUpScreenSaverAndDPMS())
3062 #ifdef HAS_SDL_JOYSTICK
3065 g_Mouse.SetActive(false);
3067 // Figure out what window we're taking the event for.
3068 int iWin = g_windowManager.GetActiveWindow() & WINDOW_ID_MASK;
3069 if (g_windowManager.HasModalDialog())
3070 iWin = g_windowManager.GetTopMostModalDialogID() & WINDOW_ID_MASK;
3072 // This code is copied from the OnKey handler, it should be factored out.
3073 if (iWin == WINDOW_FULLSCREEN_VIDEO &&
3074 g_application.m_pPlayer &&
3075 g_application.m_pPlayer->IsInMenu())
3077 // If player is in some sort of menu, (ie DVDMENU) map buttons differently.
3078 iWin = WINDOW_VIDEO_MENU;
3082 CStdString actionName;
3083 bool fullRange = false;
3085 // Translate using regular joystick translator.
3086 if (CButtonTranslator::GetInstance().TranslateJoystickString(iWin, joystickName.c_str(), wKeyID, isAxis ? JACTIVE_AXIS : JACTIVE_BUTTON, actionID, actionName, fullRange))
3088 CAction action(actionID, fAmount, 0.0f, actionName);
3089 g_audioManager.PlayActionSound(action);
3090 return OnAction(action);
3094 CLog::Log(LOGDEBUG, "ERROR mapping joystick action. Joystick: %s %i",joystickName.c_str(), wKeyID);
3101 bool CApplication::Cleanup()
3105 g_windowManager.Delete(WINDOW_MUSIC_PLAYLIST);
3106 g_windowManager.Delete(WINDOW_MUSIC_PLAYLIST_EDITOR);
3107 g_windowManager.Delete(WINDOW_MUSIC_FILES);
3108 g_windowManager.Delete(WINDOW_MUSIC_NAV);
3109 g_windowManager.Delete(WINDOW_DIALOG_MUSIC_INFO);
3110 g_windowManager.Delete(WINDOW_DIALOG_VIDEO_INFO);
3111 g_windowManager.Delete(WINDOW_VIDEO_FILES);
3112 g_windowManager.Delete(WINDOW_VIDEO_PLAYLIST);
3113 g_windowManager.Delete(WINDOW_VIDEO_NAV);
3114 g_windowManager.Delete(WINDOW_FILES);
3115 g_windowManager.Delete(WINDOW_DIALOG_YES_NO);
3116 g_windowManager.Delete(WINDOW_DIALOG_PROGRESS);
3117 g_windowManager.Delete(WINDOW_DIALOG_NUMERIC);
3118 g_windowManager.Delete(WINDOW_DIALOG_GAMEPAD);
3119 g_windowManager.Delete(WINDOW_DIALOG_SUB_MENU);
3120 g_windowManager.Delete(WINDOW_DIALOG_BUTTON_MENU);
3121 g_windowManager.Delete(WINDOW_DIALOG_CONTEXT_MENU);
3122 g_windowManager.Delete(WINDOW_DIALOG_MUSIC_SCAN);
3123 g_windowManager.Delete(WINDOW_DIALOG_PLAYER_CONTROLS);
3124 g_windowManager.Delete(WINDOW_DIALOG_KARAOKE_SONGSELECT);
3125 g_windowManager.Delete(WINDOW_DIALOG_KARAOKE_SELECTOR);
3126 g_windowManager.Delete(WINDOW_DIALOG_MUSIC_OSD);
3127 g_windowManager.Delete(WINDOW_DIALOG_VIS_PRESET_LIST);
3128 g_windowManager.Delete(WINDOW_DIALOG_SELECT);
3129 g_windowManager.Delete(WINDOW_DIALOG_OK);
3130 g_windowManager.Delete(WINDOW_DIALOG_FILESTACKING);
3131 g_windowManager.Delete(WINDOW_DIALOG_KEYBOARD);
3132 g_windowManager.Delete(WINDOW_FULLSCREEN_VIDEO);
3133 g_windowManager.Delete(WINDOW_DIALOG_PROFILE_SETTINGS);
3134 g_windowManager.Delete(WINDOW_DIALOG_LOCK_SETTINGS);
3135 g_windowManager.Delete(WINDOW_DIALOG_NETWORK_SETUP);
3136 g_windowManager.Delete(WINDOW_DIALOG_MEDIA_SOURCE);
3137 g_windowManager.Delete(WINDOW_DIALOG_VIDEO_OSD_SETTINGS);
3138 g_windowManager.Delete(WINDOW_DIALOG_AUDIO_OSD_SETTINGS);
3139 g_windowManager.Delete(WINDOW_DIALOG_VIDEO_BOOKMARKS);
3140 g_windowManager.Delete(WINDOW_DIALOG_VIDEO_SCAN);
3141 g_windowManager.Delete(WINDOW_DIALOG_CONTENT_SETTINGS);
3142 g_windowManager.Delete(WINDOW_DIALOG_FAVOURITES);
3143 g_windowManager.Delete(WINDOW_DIALOG_SONG_INFO);
3144 g_windowManager.Delete(WINDOW_DIALOG_SMART_PLAYLIST_EDITOR);
3145 g_windowManager.Delete(WINDOW_DIALOG_SMART_PLAYLIST_RULE);
3146 g_windowManager.Delete(WINDOW_DIALOG_BUSY);
3147 g_windowManager.Delete(WINDOW_DIALOG_PICTURE_INFO);
3148 g_windowManager.Delete(WINDOW_DIALOG_ADDON_INFO);
3149 g_windowManager.Delete(WINDOW_DIALOG_ADDON_SETTINGS);
3150 g_windowManager.Delete(WINDOW_DIALOG_ACCESS_POINTS);
3151 g_windowManager.Delete(WINDOW_DIALOG_SLIDER);
3153 g_windowManager.Delete(WINDOW_DIALOG_OSD_TELETEXT);
3154 g_windowManager.Delete(WINDOW_DIALOG_TEXT_VIEWER);
3156 g_windowManager.Delete(WINDOW_DIALOG_PLAY_EJECT);
3158 g_windowManager.Delete(WINDOW_STARTUP_ANIM);
3159 g_windowManager.Delete(WINDOW_LOGIN_SCREEN);
3160 g_windowManager.Delete(WINDOW_VISUALISATION);
3161 g_windowManager.Delete(WINDOW_KARAOKELYRICS);
3162 g_windowManager.Delete(WINDOW_SETTINGS_MENU);
3163 g_windowManager.Delete(WINDOW_SETTINGS_PROFILES);
3164 g_windowManager.Delete(WINDOW_SETTINGS_MYPICTURES); // all the settings categories
3165 g_windowManager.Delete(WINDOW_TEST_PATTERN);
3166 g_windowManager.Delete(WINDOW_SCREEN_CALIBRATION);
3167 g_windowManager.Delete(WINDOW_SYSTEM_INFORMATION);
3168 g_windowManager.Delete(WINDOW_SCREENSAVER);
3169 g_windowManager.Delete(WINDOW_DIALOG_VIDEO_OSD);
3170 g_windowManager.Delete(WINDOW_DIALOG_MUSIC_OVERLAY);
3171 g_windowManager.Delete(WINDOW_DIALOG_VIDEO_OVERLAY);
3172 g_windowManager.Delete(WINDOW_SLIDESHOW);
3174 g_windowManager.Delete(WINDOW_HOME);
3175 g_windowManager.Delete(WINDOW_PROGRAMS);
3176 g_windowManager.Delete(WINDOW_PICTURES);
3177 g_windowManager.Delete(WINDOW_WEATHER);
3179 g_windowManager.Delete(WINDOW_SETTINGS_MYPICTURES);
3180 g_windowManager.Remove(WINDOW_SETTINGS_MYPROGRAMS);
3181 g_windowManager.Remove(WINDOW_SETTINGS_MYWEATHER);
3182 g_windowManager.Remove(WINDOW_SETTINGS_MYMUSIC);
3183 g_windowManager.Remove(WINDOW_SETTINGS_SYSTEM);
3184 g_windowManager.Remove(WINDOW_SETTINGS_MYVIDEOS);
3185 g_windowManager.Remove(WINDOW_SETTINGS_NETWORK);
3186 g_windowManager.Remove(WINDOW_SETTINGS_APPEARANCE);
3187 g_windowManager.Remove(WINDOW_DIALOG_KAI_TOAST);
3189 g_windowManager.Remove(WINDOW_DIALOG_SEEK_BAR);
3190 g_windowManager.Remove(WINDOW_DIALOG_VOLUME_BAR);
3192 CAddonMgr::Get().DeInit();
3194 #if defined(HAS_LIRC) || defined(HAS_IRSERVERSUITE)
3195 CLog::Log(LOGNOTICE, "closing down remote control service");
3196 g_RemoteControl.Disconnect();
3199 CLog::Log(LOGNOTICE, "unload sections");
3201 #ifdef HAS_PERFORMANCE_SAMPLE
3202 CLog::Log(LOGNOTICE, "performance statistics");
3203 m_perfStats.DumpStats();
3206 // Shutdown as much as possible of the
3207 // application, to reduce the leaks dumped
3208 // to the vc output window before calling
3209 // _CrtDumpMemoryLeaks(). Most of the leaks
3210 // shown are no real leaks, as parts of the app
3211 // are still allocated.
3213 g_localizeStrings.Clear();
3214 g_LangCodeExpander.Clear();
3215 g_charsetConverter.clear();
3216 g_directoryCache.Clear();
3217 CButtonTranslator::GetInstance().Clear();
3218 CLastfmScrobbler::RemoveInstance();
3219 CLibrefmScrobbler::RemoveInstance();
3220 CLastFmManager::RemoveInstance();
3221 #ifdef HAS_EVENT_SERVER
3222 CEventServer::RemoveInstance();
3224 #ifdef HAS_DBUS_SERVER
3225 CDbusServer::RemoveInstance();
3227 DllLoaderContainer::Clear();
3228 g_playlistPlayer.Clear();
3230 g_guiSettings.Clear();
3231 g_advancedSettings.Clear();
3234 CXHandle::DumpObjectTracker();
3237 #ifdef _CRTDBG_MAP_ALLOC
3238 _CrtDumpMemoryLeaks();
3239 while(1); // execution ends
3251 CLog::Log(LOGERROR, "Exception in CApplication::Cleanup()");
3256 void CApplication::Stop(int exitCode)
3260 CAnnouncementManager::Announce(System, "xbmc", "OnQuit");
3262 // cancel any jobs from the jobmanager
3263 CJobManager::GetInstance().CancelJobs();
3265 g_alarmClock.StopThread();
3270 if (g_settings.m_HttpApiBroadcastLevel >= 1)
3271 getApplicationMessenger().HttpApi("broadcastlevel; ShutDown;1");
3273 m_pXbmcHttp->shuttingDown = true;
3277 if( m_bSystemScreenSaverEnable )
3278 g_Windowing.EnableSystemScreenSaver(true);
3280 CLog::Log(LOGNOTICE, "Storing total System Uptime");
3281 g_settings.m_iSystemTimeTotalUp = g_settings.m_iSystemTimeTotalUp + (int)(CTimeUtils::GetFrameTime() / 60000);
3283 // Update the settings information (volume, uptime etc. need saving)
3284 if (CFile::Exists(g_settings.GetSettingsFile()))
3286 CLog::Log(LOGNOTICE, "Saving settings");
3290 CLog::Log(LOGNOTICE, "Not saving settings (settings.xml is not present)");
3293 m_AppActive = false;
3294 m_AppFocused = false;
3295 m_ExitCode = exitCode;
3296 CLog::Log(LOGNOTICE, "stop all");
3298 // stop scanning before we kill the network and so on
3299 CGUIDialogMusicScan *musicScan = (CGUIDialogMusicScan *)g_windowManager.GetWindow(WINDOW_DIALOG_MUSIC_SCAN);
3301 musicScan->StopScanning();
3303 CGUIDialogVideoScan *videoScan = (CGUIDialogVideoScan *)g_windowManager.GetWindow(WINDOW_DIALOG_VIDEO_SCAN);
3305 videoScan->StopScanning();
3307 m_applicationMessenger.Cleanup();
3312 #if defined(__APPLE__) && !defined(__arm__)
3313 XBMCHelper::GetInstance().ReleaseAllInput();
3318 CLog::Log(LOGNOTICE, "stop player");
3323 #if HAS_FILESYTEM_DAAP
3324 CLog::Log(LOGNOTICE, "stop daap clients");
3325 g_DaapClient.Release();
3327 #ifdef HAS_FILESYSTEM_SAP
3328 CLog::Log(LOGNOTICE, "stop sap announcement listener");
3329 g_sapsessions.StopThread();
3332 if(CZeroconfBrowser::IsInstantiated())
3334 CLog::Log(LOGNOTICE, "stop zeroconf browser");
3335 CZeroconfBrowser::GetInstance()->Stop();
3336 CZeroconfBrowser::ReleaseInstance();
3340 CLog::Log(LOGNOTICE, "clean cached files!");
3341 #ifdef HAS_FILESYSTEM_RAR
3342 g_RarManager.ClearCache(true);
3345 #ifdef HAS_FILESYSTEM_SFTP
3346 CSFTPSessionManager::DisconnectAllSessions();
3349 CLog::Log(LOGNOTICE, "unload skin");
3352 #if defined(__APPLE__) && !defined(__arm__)
3353 if (XBMCHelper::GetInstance().IsAlwaysOn() == false)
3354 XBMCHelper::GetInstance().Stop();
3357 #if defined(HAVE_LIBCRYSTALHD)
3358 CCrystalHD::RemoveInstance();
3361 g_mediaManager.Stop();
3363 // Stop services before unloading Python
3364 CAddonMgr::Get().StopServices(false);
3366 /* Python resource freeing must be done after skin has been unloaded, not before
3367 some windows still need it when deinitializing during skin unloading. */
3369 CLog::Log(LOGNOTICE, "stop python");
3370 g_pythonParser.FreeResources();
3381 g_Windowing.DestroyRenderSystem();
3382 g_Windowing.DestroyWindow();
3383 g_Windowing.DestroyWindowSystem();
3385 CLog::Log(LOGNOTICE, "stopped");
3389 CLog::Log(LOGERROR, "Exception in CApplication::Stop()");
3392 // we may not get to finish the run cycle but exit immediately after a call to g_application.Stop()
3393 // so we may never get to Destroy() in CXBApplicationEx::Run(), we call it here.
3400 bool CApplication::PlayMedia(const CFileItem& item, int iPlaylist)
3402 //If item is a plugin, expand out now and run ourselves again
3403 if (item.IsPlugin())
3405 CFileItem item_new(item);
3406 if (XFILE::CPluginDirectory::GetPluginResult(item.GetPath(), item_new))
3407 return PlayMedia(item_new, iPlaylist);
3410 if (item.IsLastFM())
3412 g_partyModeManager.Disable();
3413 return CLastFmManager::GetInstance()->ChangeStation(item.GetAsUrl());
3415 if (item.IsSmartPlayList())
3417 CFileItemList items;
3418 CUtil::GetRecursiveListing(item.GetPath(), items, "");
3421 CSmartPlaylist smartpl;
3422 //get name and type of smartplaylist, this will always succeed as GetDirectory also did this.
3423 smartpl.OpenAndReadName(item.GetPath());
3425 playlist.Add(items);
3426 return ProcessAndStartPlaylist(smartpl.GetName(), playlist, (smartpl.GetType() == "songs" || smartpl.GetType() == "albums") ? PLAYLIST_MUSIC:PLAYLIST_VIDEO);
3429 else if (item.IsPlayList() || item.IsInternetStream())
3431 CGUIDialogCache* dlgCache = new CGUIDialogCache(5000, g_localizeStrings.Get(10214), item.GetLabel());
3433 //is or could be a playlist
3434 auto_ptr<CPlayList> pPlayList (CPlayListFactory::Create(item));
3435 bool gotPlayList = (pPlayList.get() && pPlayList->Load(item.GetPath()));
3440 if (dlgCache->IsCanceled())
3447 if (iPlaylist != PLAYLIST_NONE)
3448 return ProcessAndStartPlaylist(item.GetPath(), *pPlayList, iPlaylist);
3451 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());
3452 if(pPlayList->size())
3453 return PlayFile(*(*pPlayList)[0], false);
3458 //nothing special just play
3459 return PlayFile(item, false);
3463 // For playing a multi-file video. Particularly inefficient
3464 // on startup, as we are required to calculate the length
3465 // of each video, so we open + close each one in turn.
3466 // A faster calculation of video time would improve this
3468 bool CApplication::PlayStack(const CFileItem& item, bool bRestart)
3470 if (!item.IsStack())
3473 // see if we have the info in the database
3474 // TODO: If user changes the time speed (FPS via framerate conversion stuff)
3475 // then these times will be wrong.
3476 // Also, this is really just a hack for the slow load up times we have
3477 // A much better solution is a fast reader of FPS and fileLength
3478 // that we can use on a file to get it's time.
3480 bool haveTimes(false);
3484 dbs.GetVideoSettings(item.GetPath(), g_settings.m_currentVideoSettings);
3485 haveTimes = dbs.GetStackTimes(item.GetPath(), times);
3490 // calculate the total time of the stack
3491 CStackDirectory dir;
3492 dir.GetDirectory(item.GetPath(), *m_currentStack);
3494 for (int i = 0; i < m_currentStack->Size(); i++)
3497 (*m_currentStack)[i]->m_lEndOffset = times[i];
3501 if (!CDVDFileInfo::GetFileDuration((*m_currentStack)[i]->GetPath(), duration))
3503 m_currentStack->Clear();
3506 totalTime += duration / 1000;
3507 (*m_currentStack)[i]->m_lEndOffset = totalTime;
3508 times.push_back(totalTime);
3512 double seconds = item.m_lStartOffset / 75.0;
3514 if (!haveTimes || item.m_lStartOffset == STARTOFFSET_RESUME )
3515 { // have our times now, so update the dB
3519 dbs.SetStackTimes(item.GetPath(), times);
3521 if( item.m_lStartOffset == STARTOFFSET_RESUME )
3523 // can only resume seek here, not dvdstate
3525 if( dbs.GetResumeBookMark(item.GetPath(), bookmark) )
3526 seconds = bookmark.timeInSeconds;
3534 *m_itemCurrentFile = item;
3535 m_currentStackPosition = 0;
3536 m_eCurrentPlayer = EPC_NONE; // must be reset on initial play otherwise last player will be used
3540 // work out where to seek to
3541 for (int i = 0; i < m_currentStack->Size(); i++)
3543 if (seconds < (*m_currentStack)[i]->m_lEndOffset)
3545 CFileItem item(*(*m_currentStack)[i]);
3546 long start = (i > 0) ? (*m_currentStack)[i-1]->m_lEndOffset : 0;
3547 item.m_lStartOffset = (long)(seconds - start) * 75;
3548 m_currentStackPosition = i;
3549 return PlayFile(item, true);
3554 return PlayFile(*(*m_currentStack)[0], true);
3557 bool CApplication::PlayFile(const CFileItem& item, bool bRestart)
3561 SaveCurrentFileSettings();
3563 OutputDebugString("new file set audiostream:0\n");
3564 // Switch to default options
3565 g_settings.m_currentVideoSettings = g_settings.m_defaultVideoSettings;
3566 // see if we have saved options in the database
3569 *m_itemCurrentFile = item;
3570 m_nextPlaylistItem = -1;
3571 m_currentStackPosition = 0;
3572 m_currentStack->Clear();
3575 CUtil::ClearSubtitles();
3578 if (item.IsDiscStub())
3580 #ifdef HAS_DVD_DRIVE
3581 // Display the Play Eject dialog
3582 if (CGUIDialogPlayEject::ShowAndGetInput(item))
3583 return MEDIA_DETECT::CAutorun::PlayDisc(!MEDIA_DETECT::CAutorun::CanResumePlayDVD() || CGUIDialogYesNo::ShowAndGetInput(341, -1, -1, -1, 13404, 12021));
3588 if (item.IsPlayList())
3591 if (item.IsPlugin())
3592 { // we modify the item so that it becomes a real URL
3593 CFileItem item_new(item);
3594 if (XFILE::CPluginDirectory::GetPluginResult(item.GetPath(), item_new))
3595 return PlayFile(item_new, false);
3599 if (URIUtils::IsUPnP(item.GetPath()))
3601 CFileItem item_new(item);
3602 if (XFILE::CUPnPDirectory::GetResource(item.GetPath(), item_new))
3603 return PlayFile(item_new, false);
3607 // if we have a stacked set of files, we need to setup our stack routines for
3608 // "seamless" seeking and total time of the movie etc.
3609 // will recall with restart set to true
3611 return PlayStack(item, bRestart);
3613 //Is TuxBox, this should probably be moved to CFileTuxBox
3616 CLog::Log(LOGDEBUG, "%s - TuxBox URL Detected %s",__FUNCTION__, item.GetPath().c_str());
3618 if(g_tuxboxService.IsRunning())
3619 g_tuxboxService.Stop();
3622 if(g_tuxbox.CreateNewItem(item, item_new))
3625 // Make sure it doesn't have a player
3626 // so we actually select one normally
3627 m_eCurrentPlayer = EPC_NONE;
3629 // keep the tuxbox:// url as playing url
3630 // and give the new url to the player
3631 if(PlayFile(item_new, true))
3633 if(!g_tuxboxService.IsRunning())
3634 g_tuxboxService.Start();
3641 CPlayerOptions options;
3643 if( item.HasProperty("StartPercent") )
3645 options.startpercent = item.GetProperty("StartPercent").asDouble();
3648 PLAYERCOREID eNewCore = EPC_NONE;
3651 // have to be set here due to playstack using this for starting the file
3652 options.starttime = item.m_lStartOffset / 75.0;
3653 if (m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0 && m_itemCurrentFile->m_lStartOffset != 0)
3654 m_itemCurrentFile->m_lStartOffset = STARTOFFSET_RESUME; // to force fullscreen switching
3656 if( m_eForcedNextPlayer != EPC_NONE )
3657 eNewCore = m_eForcedNextPlayer;
3658 else if( m_eCurrentPlayer == EPC_NONE )
3659 eNewCore = CPlayerCoreFactory::GetDefaultPlayer(item);
3661 eNewCore = m_eCurrentPlayer;
3665 options.starttime = item.m_lStartOffset / 75.0;
3669 // open the d/b and retrieve the bookmarks for the current movie
3672 dbs.GetVideoSettings(item.GetPath(), g_settings.m_currentVideoSettings);
3674 if( item.m_lStartOffset == STARTOFFSET_RESUME )
3676 options.starttime = 0.0f;
3678 CStdString path = item.GetPath();
3680 path = item.GetVideoInfoTag()->m_strFileNameAndPath;
3681 if(dbs.GetResumeBookMark(path, bookmark))
3683 options.starttime = bookmark.timeInSeconds;
3684 options.state = bookmark.playerState;
3687 else if (item.HasVideoInfoTag())
3689 const CVideoInfoTag *tag = item.GetVideoInfoTag();
3691 if (tag->m_iBookmarkId != -1 && tag->m_iBookmarkId != 0)
3694 dbs.GetBookMarkForEpisode(*tag, bookmark);
3695 options.starttime = bookmark.timeInSeconds;
3696 options.state = bookmark.playerState;
3703 if (m_eForcedNextPlayer != EPC_NONE)
3704 eNewCore = m_eForcedNextPlayer;
3706 eNewCore = CPlayerCoreFactory::GetDefaultPlayer(item);
3709 // this really aught to be inside !bRestart, but since PlayStack
3710 // uses that to init playback, we have to keep it outside
3711 int playlist = g_playlistPlayer.GetCurrentPlaylist();
3712 if (playlist == PLAYLIST_VIDEO && g_playlistPlayer.GetPlaylist(playlist).size() > 1)
3713 { // playing from a playlist by the looks
3714 // don't switch to fullscreen if we are not playing the first item...
3715 options.fullscreen = !g_playlistPlayer.HasPlayedFirstFile() && g_advancedSettings.m_fullScreenOnMovieStart && !g_settings.m_bStartVideoWindowed;
3717 else if(m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0)
3719 // TODO - this will fail if user seeks back to first file in stack
3720 if(m_currentStackPosition == 0 || m_itemCurrentFile->m_lStartOffset == STARTOFFSET_RESUME)
3721 options.fullscreen = g_advancedSettings.m_fullScreenOnMovieStart && !g_settings.m_bStartVideoWindowed;
3723 options.fullscreen = false;
3724 // reset this so we don't think we are resuming on seek
3725 m_itemCurrentFile->m_lStartOffset = 0;
3728 options.fullscreen = g_advancedSettings.m_fullScreenOnMovieStart && !g_settings.m_bStartVideoWindowed;
3730 // reset m_bStartVideoWindowed as it's a temp setting
3731 g_settings.m_bStartVideoWindowed = false;
3732 // reset any forced player
3733 m_eForcedNextPlayer = EPC_NONE;
3736 //We have to stop parsing a cdg before mplayer is deallocated
3737 // WHY do we have to do this????
3739 m_pKaraokeMgr->Stop();
3742 // tell system we are starting a file
3743 m_bPlaybackStarting = true;
3745 // We should restart the player, unless the previous and next tracks are using
3746 // one of the players that allows gapless playback (paplayer, dvdplayer)
3749 if ( !(m_eCurrentPlayer == eNewCore && (m_eCurrentPlayer == EPC_DVDPLAYER || m_eCurrentPlayer == EPC_PAPLAYER)) )
3758 m_eCurrentPlayer = eNewCore;
3759 m_pPlayer = CPlayerCoreFactory::CreatePlayer(eNewCore, *this);
3762 // Workaround for bug/quirk in SDL_Mixer on OSX.
3763 // TODO: Remove after GUI Sounds redux
3764 #if defined(__APPLE__)
3765 g_audioManager.Enable(false);
3771 // don't hold graphicscontext here since player
3772 // may wait on another thread, that requires gfx
3773 CSingleExit ex(g_graphicsContext);
3774 bResult = m_pPlayer->OpenFile(item, options);
3778 CLog::Log(LOGERROR, "Error creating player for item %s (File doesn't exist?)", item.GetPath().c_str());
3784 if (m_iPlaySpeed != 1)
3786 int iSpeed = m_iPlaySpeed;
3788 SetPlaySpeed(iSpeed);
3791 if( IsPlayingAudio() )
3793 if (g_windowManager.GetActiveWindow() == WINDOW_FULLSCREEN_VIDEO)
3794 g_windowManager.ActivateWindow(WINDOW_VISUALISATION);
3797 #ifdef HAS_VIDEO_PLAYBACK
3798 if( IsPlayingVideo() )
3800 if (g_windowManager.GetActiveWindow() == WINDOW_VISUALISATION)
3801 g_windowManager.ActivateWindow(WINDOW_FULLSCREEN_VIDEO);
3803 // if player didn't manange to switch to fullscreen by itself do it here
3804 if( options.fullscreen && g_renderManager.IsStarted()
3805 && g_windowManager.GetActiveWindow() != WINDOW_FULLSCREEN_VIDEO )
3806 SwitchToFullScreen();
3808 if (!item.IsDVDImage() && !item.IsDVDFile())
3810 CVideoInfoTag *details = m_itemCurrentFile->GetVideoInfoTag();
3811 // Save information about the stream if we currently have no data
3812 if (!details->HasStreamDetails() ||
3813 details->m_streamDetails.GetVideoDuration() <= 0)
3815 if (m_pPlayer->GetStreamDetails(details->m_streamDetails) && details->HasStreamDetails())
3819 dbs.SetStreamDetailsForFileId(details->m_streamDetails, details->m_iFileId);
3821 CUtil::DeleteVideoDatabaseDirectoryCache();
3828 #if !defined(__APPLE__)
3829 g_audioManager.Enable(false);
3832 m_bPlaybackStarting = false;
3835 // we must have started, otherwise player might send this later
3837 OnPlayBackStarted();
3843 // we send this if it isn't playlistplayer that is doing this
3844 int next = g_playlistPlayer.GetNextSong();
3845 int size = g_playlistPlayer.GetPlaylist(g_playlistPlayer.GetCurrentPlaylist()).size();
3848 OnPlayBackStopped();
3854 void CApplication::OnPlayBackEnded()
3856 if(m_bPlaybackStarting)
3859 // informs python script currently running playback has ended
3860 // (does nothing if python is not loaded)
3862 g_pythonParser.OnPlayBackEnded();
3866 // Let's tell the outside world as well
3867 if (g_settings.m_HttpApiBroadcastLevel>=1)
3868 getApplicationMessenger().HttpApi("broadcastlevel; OnPlayBackEnded;1");
3871 CAnnouncementManager::Announce(Player, "xbmc", "OnStop");
3873 if (IsPlayingAudio())
3875 CLastfmScrobbler::GetInstance()->SubmitQueue();
3876 CLibrefmScrobbler::GetInstance()->SubmitQueue();
3879 CGUIMessage msg(GUI_MSG_PLAYBACK_ENDED, 0, 0);
3880 g_windowManager.SendThreadMessage(msg);
3883 void CApplication::OnPlayBackStarted()
3885 if(m_bPlaybackStarting)
3889 // informs python script currently running playback has started
3890 // (does nothing if python is not loaded)
3891 g_pythonParser.OnPlayBackStarted();
3895 // Let's tell the outside world as well
3896 if (g_settings.m_HttpApiBroadcastLevel>=1)
3897 getApplicationMessenger().HttpApi("broadcastlevel; OnPlayBackStarted;1");
3900 CGUIMessage msg(GUI_MSG_PLAYBACK_STARTED, 0, 0);
3901 g_windowManager.SendThreadMessage(msg);
3904 void CApplication::OnQueueNextItem()
3906 // informs python script currently running that we are requesting the next track
3907 // (does nothing if python is not loaded)
3909 g_pythonParser.OnQueueNextItem(); // currently unimplemented
3913 // Let's tell the outside world as well
3914 if (g_settings.m_HttpApiBroadcastLevel>=1)
3915 getApplicationMessenger().HttpApi("broadcastlevel; OnQueueNextItem;1");
3918 if(IsPlayingAudio())
3920 CLastfmScrobbler::GetInstance()->SubmitQueue();
3921 CLibrefmScrobbler::GetInstance()->SubmitQueue();
3924 CGUIMessage msg(GUI_MSG_QUEUE_NEXT_ITEM, 0, 0);
3925 g_windowManager.SendThreadMessage(msg);
3928 void CApplication::OnPlayBackStopped()
3930 if(m_bPlaybackStarting)
3933 // informs python script currently running playback has ended
3934 // (does nothing if python is not loaded)
3936 g_pythonParser.OnPlayBackStopped();
3940 // Let's tell the outside world as well
3941 if (g_settings.m_HttpApiBroadcastLevel>=1)
3942 getApplicationMessenger().HttpApi("broadcastlevel; OnPlayBackStopped;1");
3945 CAnnouncementManager::Announce(Player, "xbmc", "OnStop", m_itemCurrentFile);
3947 CLastfmScrobbler::GetInstance()->SubmitQueue();
3948 CLibrefmScrobbler::GetInstance()->SubmitQueue();
3950 CGUIMessage msg( GUI_MSG_PLAYBACK_STOPPED, 0, 0 );
3951 g_windowManager.SendThreadMessage(msg);
3954 void CApplication::OnPlayBackPaused()
3957 g_pythonParser.OnPlayBackPaused();
3961 // Let's tell the outside world as well
3962 if (g_settings.m_HttpApiBroadcastLevel>=1)
3963 getApplicationMessenger().HttpApi("broadcastlevel; OnPlayBackPaused;1");
3967 param["player"]["speed"] = 0;
3968 param["player"]["playerid"] = g_playlistPlayer.GetCurrentPlaylist();
3969 CAnnouncementManager::Announce(Player, "xbmc", "OnPause", m_itemCurrentFile, param);
3972 void CApplication::OnPlayBackResumed()
3975 g_pythonParser.OnPlayBackResumed();
3979 // Let's tell the outside world as well
3980 if (g_settings.m_HttpApiBroadcastLevel>=1)
3981 getApplicationMessenger().HttpApi("broadcastlevel; OnPlayBackResumed;1");
3985 param["player"]["speed"] = 1;
3986 param["player"]["playerid"] = g_playlistPlayer.GetCurrentPlaylist();
3987 CAnnouncementManager::Announce(Player, "xbmc", "OnPlay", m_itemCurrentFile, param);
3990 void CApplication::OnPlayBackSpeedChanged(int iSpeed)
3993 g_pythonParser.OnPlayBackSpeedChanged(iSpeed);
3997 // Let's tell the outside world as well
3998 if (g_settings.m_HttpApiBroadcastLevel>=1)
4001 tmp.Format("broadcastlevel; OnPlayBackSpeedChanged:%i;1",iSpeed);
4002 getApplicationMessenger().HttpApi(tmp);
4007 param["player"]["speed"] = iSpeed;
4008 param["player"]["playerid"] = g_playlistPlayer.GetCurrentPlaylist();
4009 CAnnouncementManager::Announce(Player, "xbmc", "OnSpeedChanged", m_itemCurrentFile, param);
4012 void CApplication::OnPlayBackSeek(int iTime, int seekOffset)
4015 g_pythonParser.OnPlayBackSeek(iTime, seekOffset);
4019 // Let's tell the outside world as well
4020 if (g_settings.m_HttpApiBroadcastLevel>=1)
4023 tmp.Format("broadcastlevel; OnPlayBackSeek:%i;1",iTime);
4024 getApplicationMessenger().HttpApi(tmp);
4029 CJSONUtils::MillisecondsToTimeObject(iTime, param["player"]["time"]);
4030 CJSONUtils::MillisecondsToTimeObject(seekOffset, param["player"]["seekoffset"]);;
4031 param["player"]["playerid"] = g_playlistPlayer.GetCurrentPlaylist();
4032 param["player"]["speed"] = GetPlaySpeed();
4033 CAnnouncementManager::Announce(Player, "xbmc", "OnSeek", m_itemCurrentFile, param);
4034 g_infoManager.SetDisplayAfterSeek(2500, seekOffset/1000);
4037 void CApplication::OnPlayBackSeekChapter(int iChapter)
4040 g_pythonParser.OnPlayBackSeekChapter(iChapter);
4044 // Let's tell the outside world as well
4045 if (g_settings.m_HttpApiBroadcastLevel>=1)
4048 tmp.Format("broadcastlevel; OnPlayBackSkeekChapter:%i;1",iChapter);
4049 getApplicationMessenger().HttpApi(tmp);
4054 bool CApplication::IsPlaying() const
4058 if (!m_pPlayer->IsPlaying())
4063 bool CApplication::IsPaused() const
4067 if (!m_pPlayer->IsPlaying())
4069 return m_pPlayer->IsPaused();
4072 bool CApplication::IsPlayingAudio() const
4076 if (!m_pPlayer->IsPlaying())
4078 if (m_pPlayer->HasVideo())
4080 if (m_pPlayer->HasAudio())
4085 bool CApplication::IsPlayingVideo() const
4089 if (!m_pPlayer->IsPlaying())
4091 if (m_pPlayer->HasVideo())
4097 bool CApplication::IsPlayingFullScreenVideo() const
4099 return IsPlayingVideo() && g_graphicsContext.IsFullScreenVideo();
4102 void CApplication::SaveFileState()
4104 if (!g_settings.GetCurrentProfile().canWriteDatabases())
4106 CJob* job = new CSaveFileStateJob(*m_progressTrackingItem,
4107 m_progressTrackingVideoResumeBookmark,
4108 m_progressTrackingPlayCountUpdate);
4109 CJobManager::GetInstance().AddJob(job, NULL);
4112 void CApplication::UpdateFileState()
4114 // Did the file change?
4115 if (m_progressTrackingItem->GetPath() != "" && m_progressTrackingItem->GetPath() != CurrentFile())
4119 // Reset tracking item
4120 m_progressTrackingItem->Reset();
4124 if (IsPlayingVideo() || IsPlayingAudio())
4126 if (m_progressTrackingItem->GetPath() == "")
4129 *m_progressTrackingItem = CurrentFileItem();
4130 m_progressTrackingPlayCountUpdate = false;
4133 if ((m_progressTrackingItem->IsAudio() && g_advancedSettings.m_audioPlayCountMinimumPercent > 0 &&
4134 GetPercentage() >= g_advancedSettings.m_audioPlayCountMinimumPercent) ||
4135 (m_progressTrackingItem->IsVideo() && g_advancedSettings.m_videoPlayCountMinimumPercent > 0 &&
4136 GetPercentage() >= g_advancedSettings.m_videoPlayCountMinimumPercent))
4138 m_progressTrackingPlayCountUpdate = true;
4141 if (m_progressTrackingItem->IsVideo())
4143 if ((m_progressTrackingItem->IsDVDImage() || m_progressTrackingItem->IsDVDFile()) && m_pPlayer->GetTotalTime() > 15*60)
4145 m_progressTrackingItem->GetVideoInfoTag()->m_streamDetails.Reset();
4146 m_pPlayer->GetStreamDetails(m_progressTrackingItem->GetVideoInfoTag()->m_streamDetails);
4148 // Update bookmark for save
4149 m_progressTrackingVideoResumeBookmark.player = CPlayerCoreFactory::GetPlayerName(m_eCurrentPlayer);
4150 m_progressTrackingVideoResumeBookmark.playerState = m_pPlayer->GetPlayerState();
4151 m_progressTrackingVideoResumeBookmark.thumbNailImage.Empty();
4153 if (g_advancedSettings.m_videoIgnorePercentAtEnd > 0 &&
4154 GetTotalTime() - GetTime() < 0.01f * g_advancedSettings.m_videoIgnorePercentAtEnd * GetTotalTime())
4156 // Delete the bookmark
4157 m_progressTrackingVideoResumeBookmark.timeInSeconds = -1.0f;
4160 if (GetTime() > g_advancedSettings.m_videoIgnoreSecondsAtStart)
4162 // Update the bookmark
4163 m_progressTrackingVideoResumeBookmark.timeInSeconds = GetTime();
4164 m_progressTrackingVideoResumeBookmark.totalTimeInSeconds = GetTotalTime();
4169 m_progressTrackingVideoResumeBookmark.timeInSeconds = 0.0f;
4176 void CApplication::StopPlaying()
4178 int iWin = g_windowManager.GetActiveWindow();
4183 m_pKaraokeMgr->Stop();
4187 m_pPlayer->CloseFile();
4189 // turn off visualisation window when stopping
4190 if (iWin == WINDOW_VISUALISATION
4191 || iWin == WINDOW_FULLSCREEN_VIDEO)
4192 g_windowManager.PreviousWindow();
4194 g_partyModeManager.Disable();
4198 void CApplication::ResetScreenSaver()
4201 m_shutdownTimer.StartZero();
4203 // screen saver timer is reset only if we're not already in screensaver or
4205 if ((!m_bScreenSave && m_iScreenSaveLock == 0) && !m_dpmsIsActive)
4206 ResetScreenSaverTimer();
4209 void CApplication::ResetScreenSaverTimer()
4211 #if defined(__APPLE__) && !defined(__arm__)
4212 Cocoa_UpdateSystemActivity();
4214 m_screenSaverTimer.StartZero();
4217 void CApplication::StopScreenSaverTimer()
4219 m_screenSaverTimer.Stop();
4222 bool CApplication::ToggleDPMS(bool manual)
4224 if (manual || (m_dpmsIsManual == manual))
4228 m_dpmsIsActive = false;
4229 m_dpmsIsManual = false;
4230 return m_dpms->DisablePowerSaving();
4234 if (m_dpms->EnablePowerSaving(m_dpms->GetSupportedModes()[0]))
4236 m_dpmsIsActive = true;
4237 m_dpmsIsManual = manual;
4245 bool CApplication::WakeUpScreenSaverAndDPMS()
4249 // turn on lcd backlight
4250 if (g_lcd && g_advancedSettings.m_lcdDimOnScreenSave)
4251 g_lcd->SetBackLight(1);
4254 // First reset DPMS, if active
4259 // TODO: if screensaver lock is specified but screensaver is not active
4260 // (DPMS came first), activate screensaver now.
4262 ResetScreenSaverTimer();
4263 return !m_bScreenSave || WakeUpScreenSaver();
4266 return WakeUpScreenSaver();
4269 bool CApplication::WakeUpScreenSaver()
4271 if (m_iScreenSaveLock == 2)
4274 // if Screen saver is active
4275 if (m_bScreenSave && m_screenSaver)
4277 if (m_iScreenSaveLock == 0)
4278 if (g_settings.GetMasterProfile().getLockMode() != LOCK_MODE_EVERYONE &&
4279 (g_settings.UsingLoginScreen() || g_guiSettings.GetBool("masterlock.startuplock")) &&
4280 g_settings.GetCurrentProfile().getLockMode() != LOCK_MODE_EVERYONE &&
4281 m_screenSaver->ID() != "screensaver.xbmc.builtin.dim" && m_screenSaver->ID() != "screensaver.xbmc.builtin.black" && m_screenSaver->ID() != "visualization")
4283 m_iScreenSaveLock = 2;
4284 CGUIMessage msg(GUI_MSG_CHECK_LOCK,0,0);
4285 g_windowManager.GetWindow(WINDOW_SCREENSAVER)->OnMessage(msg);
4287 if (m_iScreenSaveLock == -1)
4289 m_iScreenSaveLock = 0;
4293 // disable screensaver
4294 m_bScreenSave = false;
4295 m_iScreenSaveLock = 0;
4296 ResetScreenSaverTimer();
4298 CAnnouncementManager::Announce(GUI, "xbmc", "OnScreensaverDeactivated");
4300 if (m_screenSaver->ID() == "visualization" || m_screenSaver->ID() == "screensaver.xbmc.builtin.slideshow")
4302 // we can just continue as usual from vis mode
4305 else if (m_screenSaver->ID() == "screensaver.xbmc.builtin.dim" || m_screenSaver->ID() == "screensaver.xbmc.builtin.black")
4307 else if (!m_screenSaver->ID().IsEmpty())
4308 { // we're in screensaver window
4309 if (g_windowManager.GetActiveWindow() == WINDOW_SCREENSAVER)
4310 g_windowManager.PreviousWindow(); // show the previous window
4318 void CApplication::CheckScreenSaverAndDPMS()
4320 if (!m_dpmsIsActive)
4321 g_Windowing.ResetOSScreensaver();
4323 bool maybeScreensaver =
4324 !m_dpmsIsActive && !m_bScreenSave
4325 && !g_guiSettings.GetString("screensaver.mode").IsEmpty();
4327 !m_dpmsIsActive && m_dpms->IsSupported()
4328 && g_guiSettings.GetInt("powermanagement.displaysoff") > 0;
4330 // Has the screen saver window become active?
4331 if (maybeScreensaver && g_windowManager.IsWindowActive(WINDOW_SCREENSAVER))
4333 m_bScreenSave = true;
4334 maybeScreensaver = false;
4337 if (!maybeScreensaver && !maybeDPMS) return; // Nothing to do.
4339 // See if we need to reset timer.
4340 // * Are we playing a video and it is not paused?
4341 if ((IsPlayingVideo() && !m_pPlayer->IsPaused())
4342 // * Are we playing some music in fullscreen vis?
4343 || (IsPlayingAudio() && g_windowManager.GetActiveWindow() == WINDOW_VISUALISATION
4344 && !g_guiSettings.GetString("musicplayer.visualisation").IsEmpty()))
4346 ResetScreenSaverTimer();
4350 float elapsed = m_screenSaverTimer.GetElapsedSeconds();
4352 // DPMS has priority (it makes the screensaver not needed)
4354 && elapsed > g_guiSettings.GetInt("powermanagement.displaysoff") * 60)
4357 WakeUpScreenSaver();
4359 else if (maybeScreensaver
4360 && elapsed > g_guiSettings.GetInt("screensaver.time") * 60)
4362 ActivateScreenSaver();
4366 // activate the screensaver.
4367 // if forceType is true, we ignore the various conditions that can alter
4368 // the type of screensaver displayed
4369 void CApplication::ActivateScreenSaver(bool forceType /*= false */)
4371 m_bScreenSave = true;
4373 // Get Screensaver Mode
4374 m_screenSaver.reset();
4375 if (!CAddonMgr::Get().GetAddon(g_guiSettings.GetString("screensaver.mode"), m_screenSaver))
4376 m_screenSaver.reset(new CScreenSaver(""));
4379 // turn off lcd backlight if requested
4380 if (g_lcd && g_advancedSettings.m_lcdDimOnScreenSave)
4381 g_lcd->SetBackLight(0);
4384 CAnnouncementManager::Announce(GUI, "xbmc", "OnScreensaverActivated");
4386 // disable screensaver lock from the login screen
4387 m_iScreenSaveLock = g_windowManager.GetActiveWindow() == WINDOW_LOGIN_SCREEN ? 1 : 0;
4390 // set to Dim in the case of a dialog on screen or playing video
4391 if (g_windowManager.HasModalDialog() || (IsPlayingVideo() && g_guiSettings.GetBool("screensaver.usedimonpause")))
4393 if (!CAddonMgr::Get().GetAddon("screensaver.xbmc.builtin.dim", m_screenSaver))
4394 m_screenSaver.reset(new CScreenSaver(""));
4396 // Check if we are Playing Audio and Vis instead Screensaver!
4397 else if (IsPlayingAudio() && g_guiSettings.GetBool("screensaver.usemusicvisinstead") && !g_guiSettings.GetString("musicplayer.visualisation").IsEmpty())
4398 { // activate the visualisation
4399 m_screenSaver.reset(new CScreenSaver("visualization"));
4400 g_windowManager.ActivateWindow(WINDOW_VISUALISATION);
4404 // Picture slideshow
4405 if (m_screenSaver->ID() == "screensaver.xbmc.builtin.slideshow")
4407 // reset our codec info - don't want that on screen
4408 g_infoManager.SetShowCodec(false);
4409 CStdString type = m_screenSaver->GetSetting("type");
4410 CStdString path = m_screenSaver->GetSetting("path");
4411 if (type == "2" && path.IsEmpty())
4414 path = "special://profile/Thumbnails/Video/Fanart";
4416 path = "special://profile/Thumbnails/Music/Fanart";
4417 m_applicationMessenger.PictureSlideShow(path, true, type != "2");
4419 else if (m_screenSaver->ID() == "screensaver.xbmc.builtin.dim")
4421 else if (m_screenSaver->ID() == "screensaver.xbmc.builtin.black")
4423 else if (!m_screenSaver->ID().IsEmpty())
4424 g_windowManager.ActivateWindow(WINDOW_SCREENSAVER);
4427 void CApplication::CheckShutdown()
4429 CGUIDialogMusicScan *pMusicScan = (CGUIDialogMusicScan *)g_windowManager.GetWindow(WINDOW_DIALOG_MUSIC_SCAN);
4430 CGUIDialogVideoScan *pVideoScan = (CGUIDialogVideoScan *)g_windowManager.GetWindow(WINDOW_DIALOG_VIDEO_SCAN);
4432 // first check if we should reset the timer
4433 bool resetTimer = false;
4434 if (IsPlaying() || IsPaused()) // is something playing?
4437 if (pMusicScan && pMusicScan->IsScanning()) // music scanning?
4440 if (pVideoScan && pVideoScan->IsScanning()) // video scanning?
4443 if (g_windowManager.IsWindowActive(WINDOW_DIALOG_PROGRESS)) // progress dialog is onscreen
4448 m_shutdownTimer.StartZero();
4452 if ( m_shutdownTimer.GetElapsedSeconds() > g_guiSettings.GetInt("powermanagement.shutdowntime") * 60 )
4454 // Since it is a sleep instead of a shutdown, let's set everything to reset when we wake up.
4455 m_shutdownTimer.Stop();
4458 getApplicationMessenger().Shutdown();
4462 bool CApplication::OnMessage(CGUIMessage& message)
4464 switch ( message.GetMessage() )
4466 case GUI_MSG_NOTIFY_ALL:
4468 if (message.GetParam1()==GUI_MSG_REMOVED_MEDIA)
4470 // Update general playlist: Remove DVD playlist items
4471 int nRemoved = g_playlistPlayer.RemoveDVDItems();
4474 CGUIMessage msg( GUI_MSG_PLAYLIST_CHANGED, 0, 0 );
4475 g_windowManager.SendMessage( msg );
4477 // stop the file if it's on dvd (will set the resume point etc)
4478 if (m_itemCurrentFile->IsOnDVD())
4484 case GUI_MSG_PLAYBACK_STARTED:
4486 #ifdef TARGET_DARWIN
4487 DarwinSetScheduling(message.GetMessage());
4489 // Update our infoManager with the new details etc.
4490 if (m_nextPlaylistItem >= 0)
4491 { // we've started a previously queued item
4492 CFileItemPtr item = g_playlistPlayer.GetPlaylist(g_playlistPlayer.GetCurrentPlaylist())[m_nextPlaylistItem];
4493 // update the playlist manager
4494 int currentSong = g_playlistPlayer.GetCurrentSong();
4495 int param = ((currentSong & 0xffff) << 16) | (m_nextPlaylistItem & 0xffff);
4496 CGUIMessage msg(GUI_MSG_PLAYLISTPLAYER_CHANGED, 0, 0, g_playlistPlayer.GetCurrentPlaylist(), param, item);
4497 g_windowManager.SendThreadMessage(msg);
4498 g_playlistPlayer.SetCurrentSong(m_nextPlaylistItem);
4499 *m_itemCurrentFile = *item;
4501 g_infoManager.SetCurrentItem(*m_itemCurrentFile);
4502 CLastFmManager::GetInstance()->OnSongChange(*m_itemCurrentFile);
4503 g_partyModeManager.OnSongChange(true);
4506 param["player"]["speed"] = 1;
4507 param["player"]["playerid"] = g_playlistPlayer.GetCurrentPlaylist();
4508 CAnnouncementManager::Announce(Player, "xbmc", "OnPlay", m_itemCurrentFile, param);
4510 DimLCDOnPlayback(true);
4512 if (IsPlayingAudio())
4514 // Start our cdg parser as appropriate
4516 if (m_pKaraokeMgr && g_guiSettings.GetBool("karaoke.enabled") && !m_itemCurrentFile->IsInternetStream())
4518 m_pKaraokeMgr->Stop();
4519 if (m_itemCurrentFile->IsMusicDb())
4521 if (!m_itemCurrentFile->HasMusicInfoTag() || !m_itemCurrentFile->GetMusicInfoTag()->Loaded())
4523 IMusicInfoTagLoader* tagloader = CMusicInfoTagLoaderFactory::CreateLoader(m_itemCurrentFile->GetPath());
4524 tagloader->Load(m_itemCurrentFile->GetPath(),*m_itemCurrentFile->GetMusicInfoTag());
4527 m_pKaraokeMgr->Start(m_itemCurrentFile->GetMusicInfoTag()->GetURL());
4530 m_pKaraokeMgr->Start(m_itemCurrentFile->GetPath());
4533 // Let scrobbler know about the track
4534 const CMusicInfoTag* tag=g_infoManager.GetCurrentSongTag();
4537 CLastfmScrobbler::GetInstance()->AddSong(*tag, CLastFmManager::GetInstance()->IsRadioEnabled());
4538 CLibrefmScrobbler::GetInstance()->AddSong(*tag, CLastFmManager::GetInstance()->IsRadioEnabled());
4546 case GUI_MSG_QUEUE_NEXT_ITEM:
4548 // Check to see if our playlist player has a new item for us,
4549 // and if so, we check whether our current player wants the file
4550 int iNext = g_playlistPlayer.GetNextSong();
4551 CPlayList& playlist = g_playlistPlayer.GetPlaylist(g_playlistPlayer.GetCurrentPlaylist());
4552 if (iNext < 0 || iNext >= playlist.size())
4554 if (m_pPlayer) m_pPlayer->OnNothingToQueueNotify();
4555 return true; // nothing to do
4557 // ok, grab the next song
4558 CFileItemPtr item = playlist[iNext];
4559 // ok - send the file to the player if it wants it
4560 if (m_pPlayer && m_pPlayer->QueueNextFile(*item))
4561 { // player wants the next file
4562 m_nextPlaylistItem = iNext;
4568 case GUI_MSG_PLAYBACK_STOPPED:
4569 case GUI_MSG_PLAYBACK_ENDED:
4570 case GUI_MSG_PLAYLISTPLAYER_STOPPED:
4574 m_pKaraokeMgr->Stop();
4576 #ifdef TARGET_DARWIN
4577 DarwinSetScheduling(message.GetMessage());
4579 // first check if we still have items in the stack to play
4580 if (message.GetMessage() == GUI_MSG_PLAYBACK_ENDED)
4582 if (m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0 && m_currentStackPosition < m_currentStack->Size() - 1)
4583 { // just play the next item in the stack
4584 PlayFile(*(*m_currentStack)[++m_currentStackPosition], true);
4589 // In case playback ended due to user eg. skipping over the end, clear
4590 // our resume bookmark here
4591 if (message.GetMessage() == GUI_MSG_PLAYBACK_ENDED && m_progressTrackingPlayCountUpdate && g_advancedSettings.m_videoIgnorePercentAtEnd > 0)
4593 // Delete the bookmark
4594 m_progressTrackingVideoResumeBookmark.timeInSeconds = -1.0f;
4597 // reset the current playing file
4598 m_itemCurrentFile->Reset();
4599 g_infoManager.ResetCurrentItem();
4600 m_currentStack->Clear();
4602 if (message.GetMessage() == GUI_MSG_PLAYBACK_ENDED)
4604 g_playlistPlayer.PlayNext(1, true);
4609 if (CLastFmManager::GetInstance()->IsRadioEnabled())
4610 CLastFmManager::GetInstance()->StopRadio();
4621 g_audioManager.Enable(true);
4622 DimLCDOnPlayback(false);
4625 if (!IsPlayingVideo() && g_windowManager.GetActiveWindow() == WINDOW_FULLSCREEN_VIDEO)
4627 g_windowManager.PreviousWindow();
4630 if (!IsPlayingAudio() && g_playlistPlayer.GetCurrentPlaylist() == PLAYLIST_NONE && g_windowManager.GetActiveWindow() == WINDOW_VISUALISATION)
4632 g_settings.Save(); // save vis settings
4633 WakeUpScreenSaverAndDPMS();
4634 g_windowManager.PreviousWindow();
4637 // DVD ejected while playing in vis ?
4638 if (!IsPlayingAudio() && (m_itemCurrentFile->IsCDDA() || m_itemCurrentFile->IsOnDVD()) && !g_mediaManager.IsDiscInDrive() && g_windowManager.GetActiveWindow() == WINDOW_VISUALISATION)
4641 g_settings.Save(); // save vis settings
4642 WakeUpScreenSaverAndDPMS();
4643 g_windowManager.PreviousWindow();
4646 if (IsEnableTestMode()) g_application.getApplicationMessenger().Quit();
4651 case GUI_MSG_PLAYLISTPLAYER_STARTED:
4652 case GUI_MSG_PLAYLISTPLAYER_CHANGED:
4657 case GUI_MSG_FULLSCREEN:
4658 { // Switch to fullscreen, if we can
4659 SwitchToFullScreen();
4663 case GUI_MSG_EXECUTE:
4664 if (message.GetNumStringParams())
4665 return ExecuteXBMCAction(message.GetStringParam());
4671 bool CApplication::ExecuteXBMCAction(std::string actionStr)
4673 // see if it is a user set string
4674 CLog::Log(LOGDEBUG,"%s : Translating %s", __FUNCTION__, actionStr.c_str());
4675 CGUIInfoLabel info(actionStr, "");
4676 actionStr = info.GetLabel(0);
4677 CLog::Log(LOGDEBUG,"%s : To %s", __FUNCTION__, actionStr.c_str());
4679 // user has asked for something to be executed
4680 if (CBuiltins::HasCommand(actionStr))
4681 CBuiltins::Execute(actionStr);
4684 // try translating the action from our ButtonTranslator
4686 if (CButtonTranslator::TranslateActionString(actionStr.c_str(), actionID))
4688 OnAction(CAction(actionID));
4691 CFileItem item(actionStr, false);
4693 if (item.IsPythonScript())
4694 { // a python script
4695 g_pythonParser.evalFile(item.GetPath().c_str(),ADDON::AddonPtr());
4699 if (item.IsAudio() || item.IsVideo())
4700 { // an audio or video file
4709 void CApplication::Process()
4713 // dispatch the messages generated by python or other threads to the current window
4714 g_windowManager.DispatchThreadMessages();
4716 // process messages which have to be send to the gui
4717 // (this can only be done after g_windowManager.Render())
4718 m_applicationMessenger.ProcessWindowMessages();
4721 // process any Python scripts
4722 g_pythonParser.Process();
4725 // process messages, even if a movie is playing
4726 m_applicationMessenger.ProcessMessages();
4727 if (g_application.m_bStop) return; //we're done, everything has been unloaded
4729 // check if we can free unused memory
4731 g_audioManager.FreeUnused();
4734 // check how far we are through playing the current item
4735 // and do anything that needs doing (lastfm submission, playcount updates etc)
4736 CheckPlayingProgress();
4740 m_pPlayer->DoAudioWork();
4742 // do any processing that isn't needed on each run
4743 if( m_slowTimer.GetElapsedMilliseconds() > 500 )
4745 m_slowTimer.Reset();
4749 g_cpuInfo.getUsedPercentage(); // must call it to recalculate pct values
4752 // We get called every 500ms
4753 void CApplication::ProcessSlow()
4755 g_powerManager.ProcessEvents();
4757 #if defined(__APPLE__) && !defined(__arm__)
4758 // There is an issue on OS X that several system services ask the cursor to become visible
4759 // during their startup routines. Given that we can't control this, we hack it in by
4761 if (g_Windowing.IsFullScreen())
4762 { // SDL thinks it's hidden
4767 // Store our file state for use on close()
4770 if (IsPlayingAudio())
4772 CLastfmScrobbler::GetInstance()->UpdateStatus();
4773 CLibrefmScrobbler::GetInstance()->UpdateStatus();
4776 // Check if we need to activate the screensaver / DPMS.
4777 CheckScreenSaverAndDPMS();
4779 // Check if we need to shutdown (if enabled).
4781 if (g_guiSettings.GetInt("powermanagement.shutdowntime") && g_advancedSettings.m_fullScreen)
4783 if (g_guiSettings.GetInt("powermanagement.shutdowntime"))
4789 // check if we should restart the player
4790 CheckDelayedPlayerRestart();
4792 // check if we can unload any unreferenced dlls or sections
4793 if (!IsPlayingVideo())
4794 CSectionLoader::UnloadDelayed();
4796 // check for any idle curl connections
4797 g_curlInterface.CheckIdle();
4799 // check for any idle myth sessions
4800 CMythSession::CheckIdle();
4802 #ifdef HAS_FILESYSTEM_HTSP
4803 // check for any idle htsp sessions
4804 HTSP::CHTSPDirectorySession::CheckIdle();
4808 if ( m_pKaraokeMgr )
4809 m_pKaraokeMgr->ProcessSlow();
4812 // LED - LCD SwitchOn On Paused! m_bIsPaused=TRUE -> LED/LCD is ON!
4813 if(IsPaused() != m_bIsPaused)
4816 DimLCDOnPlayback(m_bIsPaused);
4818 m_bIsPaused = IsPaused();
4821 if (!IsPlayingVideo())
4822 g_largeTextureManager.CleanupUnusedImages();
4824 #ifdef HAS_DVD_DRIVE
4825 // checks whats in the DVD drive and tries to autostart the content (xbox games, dvd, cdda, avi files...)
4826 if (!IsPlayingVideo())
4827 m_Autorun.HandleAutorun();
4830 // update upnp server/renderer states
4831 if(CUPnP::IsInstantiated())
4832 CUPnP::GetInstance()->UpdateState();
4834 //Check to see if current playing Title has changed and whether we should broadcast the fact
4835 CheckForTitleChange();
4837 #if defined(_LINUX) && defined(HAS_FILESYSTEM_SMB)
4841 #ifdef HAS_FILESYSTEM_NFS
4842 gNfsConnection.CheckIfIdle();
4845 #ifdef HAS_FILESYSTEM_SFTP
4846 CSFTPSessionManager::ClearOutIdleSessions();
4849 g_mediaManager.ProcessEvents();
4852 if (g_RemoteControl.IsInUse() && !g_RemoteControl.IsInitialized())
4853 g_RemoteControl.Initialize();
4857 // attempt to reinitialize the LCD (e.g. after resuming from sleep)
4858 if (!IsPlayingVideo())
4860 if (g_lcd && !g_lcd->IsConnected())
4863 g_lcd->Initialize();
4868 if (!IsPlayingVideo())
4869 CAddonInstaller::Get().UpdateRepos();
4872 // Global Idle Time in Seconds
4873 // idle time will be resetet if on any OnKey()
4874 // int return: system Idle time in seconds! 0 is no idle!
4875 int CApplication::GlobalIdleTime()
4877 if(!m_idleTimer.IsRunning())
4880 m_idleTimer.StartZero();
4882 return (int)m_idleTimer.GetElapsedSeconds();
4885 float CApplication::NavigationIdleTime()
4887 if (!m_navigationTimer.IsRunning())
4889 m_navigationTimer.Stop();
4890 m_navigationTimer.StartZero();
4892 return m_navigationTimer.GetElapsedSeconds();
4895 void CApplication::DelayedPlayerRestart()
4897 m_restartPlayerTimer.StartZero();
4900 void CApplication::CheckDelayedPlayerRestart()
4902 if (m_restartPlayerTimer.GetElapsedSeconds() > 3)
4904 m_restartPlayerTimer.Stop();
4905 m_restartPlayerTimer.Reset();
4910 void CApplication::Restart(bool bSamePosition)
4912 // this function gets called when the user changes a setting (like noninterleaved)
4913 // and which means we gotta close & reopen the current playing file
4915 // first check if we're playing a file
4916 if ( !IsPlayingVideo() && !IsPlayingAudio())
4924 // do we want to return to the current position in the file
4925 if (false == bSamePosition)
4927 // no, then just reopen the file and start at the beginning
4928 PlayFile(*m_itemCurrentFile, true);
4932 // else get current position
4933 double time = GetTime();
4935 // get player state, needed for dvd's
4936 CStdString state = m_pPlayer->GetPlayerState();
4938 // set the requested starttime
4939 m_itemCurrentFile->m_lStartOffset = (long)(time * 75.0);
4942 if ( PlayFile(*m_itemCurrentFile, true) && m_pPlayer )
4943 m_pPlayer->SetPlayerState(state);
4946 const CStdString& CApplication::CurrentFile()
4948 return m_itemCurrentFile->GetPath();
4951 CFileItem& CApplication::CurrentFileItem()
4953 return *m_itemCurrentFile;
4956 void CApplication::ShowVolumeBar(const CAction *action)
4958 CGUIDialog *volumeBar = (CGUIDialog *)g_windowManager.GetWindow(WINDOW_DIALOG_VOLUME_BAR);
4963 volumeBar->OnAction(*action);
4967 bool CApplication::IsMuted() const
4969 return g_settings.m_bMute;
4972 void CApplication::ToggleMute(void)
4974 if (g_settings.m_bMute)
4980 void CApplication::Mute()
4982 g_settings.m_iPreMuteVolumeLevel = GetVolume();
4984 g_settings.m_bMute = true;
4987 void CApplication::UnMute()
4989 SetVolume(g_settings.m_iPreMuteVolumeLevel);
4990 g_settings.m_iPreMuteVolumeLevel = 0;
4991 g_settings.m_bMute = false;
4994 void CApplication::SetVolume(long iValue, bool isPercentage /* = true */)
4996 // convert the percentage to a mB (milliBell) value (*100 for dB)
4998 iValue = (long)((float)iValue * 0.01f * (VOLUME_MAXIMUM - VOLUME_MINIMUM) + VOLUME_MINIMUM);
5000 SetHardwareVolume(iValue);
5001 #ifndef HAS_SDL_AUDIO
5002 g_audioManager.SetVolume(g_settings.m_nVolumeLevel);
5004 g_audioManager.SetVolume((int)(128.f * (g_settings.m_nVolumeLevel - VOLUME_MINIMUM) / (float)(VOLUME_MAXIMUM - VOLUME_MINIMUM)));
5008 void CApplication::SetHardwareVolume(long hardwareVolume)
5011 if (hardwareVolume >= VOLUME_MAXIMUM) // + VOLUME_DRC_MAXIMUM
5012 hardwareVolume = VOLUME_MAXIMUM;// + VOLUME_DRC_MAXIMUM;
5013 if (hardwareVolume <= VOLUME_MINIMUM)
5014 hardwareVolume = VOLUME_MINIMUM;
5016 // update our settings
5017 if (hardwareVolume > VOLUME_MAXIMUM)
5019 g_settings.m_dynamicRangeCompressionLevel = hardwareVolume - VOLUME_MAXIMUM;
5020 g_settings.m_nVolumeLevel = VOLUME_MAXIMUM;
5024 g_settings.m_dynamicRangeCompressionLevel = 0;
5025 g_settings.m_nVolumeLevel = hardwareVolume;
5028 // and tell our player to update the volume
5031 m_pPlayer->SetVolume(g_settings.m_nVolumeLevel);
5033 // m_pPlayer->SetDynamicRangeCompression(g_settings.m_dynamicRangeCompressionLevel);
5037 int CApplication::GetVolume() const
5039 // converts the hardware volume (in mB) to a percentage
5040 return int(((float)(g_settings.m_nVolumeLevel + g_settings.m_dynamicRangeCompressionLevel - VOLUME_MINIMUM)) / (VOLUME_MAXIMUM - VOLUME_MINIMUM)*100.0f + 0.5f);
5043 int CApplication::GetSubtitleDelay() const
5045 // converts subtitle delay to a percentage
5046 return int(((float)(g_settings.m_currentVideoSettings.m_SubtitleDelay + g_advancedSettings.m_videoSubsDelayRange)) / (2 * g_advancedSettings.m_videoSubsDelayRange)*100.0f + 0.5f);
5049 int CApplication::GetAudioDelay() const
5051 // converts subtitle delay to a percentage
5052 return int(((float)(g_settings.m_currentVideoSettings.m_AudioDelay + g_advancedSettings.m_videoAudioDelayRange)) / (2 * g_advancedSettings.m_videoAudioDelayRange)*100.0f + 0.5f);
5055 void CApplication::SetPlaySpeed(int iSpeed)
5057 if (!IsPlayingAudio() && !IsPlayingVideo())
5059 if (m_iPlaySpeed == iSpeed)
5061 if (!m_pPlayer->CanSeek())
5063 if (m_pPlayer->IsPaused())
5066 ((m_iPlaySpeed > 1) && (iSpeed > m_iPlaySpeed)) ||
5067 ((m_iPlaySpeed < -1) && (iSpeed < m_iPlaySpeed))
5070 iSpeed = m_iPlaySpeed; // from pause to ff/rw, do previous ff/rw speed
5074 m_iPlaySpeed = iSpeed;
5076 m_pPlayer->ToFFRW(m_iPlaySpeed);
5077 if (m_iPlaySpeed == 1)
5079 m_pPlayer->SetVolume(g_settings.m_nVolumeLevel);
5083 m_pPlayer->SetVolume(VOLUME_MINIMUM);
5087 int CApplication::GetPlaySpeed() const
5089 return m_iPlaySpeed;
5092 // Returns the total time in seconds of the current media. Fractional
5093 // portions of a second are possible - but not necessarily supported by the
5094 // player class. This returns a double to be consistent with GetTime() and
5096 double CApplication::GetTotalTime() const
5100 if (IsPlaying() && m_pPlayer)
5102 if (m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0)
5103 rc = (*m_currentStack)[m_currentStack->Size() - 1]->m_lEndOffset;
5105 rc = m_pPlayer->GetTotalTime();
5111 void CApplication::StopShutdownTimer()
5113 if (m_shutdownTimer.IsRunning())
5114 m_shutdownTimer.Stop();
5117 void CApplication::ResetShutdownTimers()
5119 // reset system shutdown timer
5120 m_shutdownTimer.StartZero();
5122 // delete custom shutdown timer
5123 if (g_alarmClock.HasAlarm("shutdowntimer"))
5124 g_alarmClock.Stop("shutdowntimer", true);
5127 // Returns the current time in seconds of the currently playing media.
5128 // Fractional portions of a second are possible. This returns a double to
5129 // be consistent with GetTotalTime() and SeekTime().
5130 double CApplication::GetTime() const
5134 if (IsPlaying() && m_pPlayer)
5136 if (m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0)
5138 long startOfCurrentFile = (m_currentStackPosition > 0) ? (*m_currentStack)[m_currentStackPosition-1]->m_lEndOffset : 0;
5139 rc = (double)startOfCurrentFile + m_pPlayer->GetTime() * 0.001;
5142 rc = static_cast<double>(m_pPlayer->GetTime() * 0.001f);
5148 // Sets the current position of the currently playing media to the specified
5149 // time in seconds. Fractional portions of a second are valid. The passed
5150 // time is the time offset from the beginning of the file as opposed to a
5151 // delta from the current position. This method accepts a double to be
5152 // consistent with GetTime() and GetTotalTime().
5153 void CApplication::SeekTime( double dTime )
5155 if (IsPlaying() && m_pPlayer && (dTime >= 0.0))
5157 if (!m_pPlayer->CanSeek()) return;
5158 if (m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0)
5160 // find the item in the stack we are seeking to, and load the new
5161 // file if necessary, and calculate the correct seek within the new
5162 // file. Otherwise, just fall through to the usual routine if the
5163 // time is higher than our total time.
5164 for (int i = 0; i < m_currentStack->Size(); i++)
5166 if ((*m_currentStack)[i]->m_lEndOffset > dTime)
5168 long startOfNewFile = (i > 0) ? (*m_currentStack)[i-1]->m_lEndOffset : 0;
5169 if (m_currentStackPosition == i)
5170 m_pPlayer->SeekTime((__int64)((dTime - startOfNewFile) * 1000.0));
5172 { // seeking to a new file
5173 m_currentStackPosition = i;
5174 CFileItem item(*(*m_currentStack)[i]);
5175 item.m_lStartOffset = (long)((dTime - startOfNewFile) * 75.0);
5176 // don't just call "PlayFile" here, as we are quite likely called from the
5177 // player thread, so we won't be able to delete ourselves.
5178 m_applicationMessenger.PlayFile(item, true);
5184 // convert to milliseconds and perform seek
5185 m_pPlayer->SeekTime( static_cast<__int64>( dTime * 1000.0 ) );
5189 float CApplication::GetPercentage() const
5191 if (IsPlaying() && m_pPlayer)
5193 if (IsPlayingAudio() && m_itemCurrentFile->HasMusicInfoTag())
5195 const CMusicInfoTag& tag = *m_itemCurrentFile->GetMusicInfoTag();
5196 if (tag.GetDuration() > 0)
5197 return (float)(GetTime() / tag.GetDuration() * 100);
5200 if (m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0)
5201 return (float)(GetTime() / GetTotalTime() * 100);
5203 return m_pPlayer->GetPercentage();
5208 float CApplication::GetCachePercentage() const
5210 if (IsPlaying() && m_pPlayer)
5211 return m_pPlayer->GetCachePercentage();
5216 void CApplication::SeekPercentage(float percent)
5218 if (IsPlaying() && m_pPlayer && (percent >= 0.0))
5220 if (!m_pPlayer->CanSeek()) return;
5221 if (m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0)
5222 SeekTime(percent * 0.01 * GetTotalTime());
5224 m_pPlayer->SeekPercentage(percent);
5228 // SwitchToFullScreen() returns true if a switch is made, else returns false
5229 bool CApplication::SwitchToFullScreen()
5231 // if playing from the video info window, close it first!
5232 if (g_windowManager.HasModalDialog() && g_windowManager.GetTopMostModalDialogID() == WINDOW_DIALOG_VIDEO_INFO)
5234 CGUIDialogVideoInfo* pDialog = (CGUIDialogVideoInfo*)g_windowManager.GetWindow(WINDOW_DIALOG_VIDEO_INFO);
5235 if (pDialog) pDialog->Close(true);
5238 // don't switch if there is a dialog on screen or the slideshow is active
5239 if (/*g_windowManager.HasModalDialog() ||*/ g_windowManager.GetActiveWindow() == WINDOW_SLIDESHOW)
5242 // See if we're playing a video, and are in GUI mode
5243 if ( IsPlayingVideo() && g_windowManager.GetActiveWindow() != WINDOW_FULLSCREEN_VIDEO)
5245 // Reset frame count so that timing is FPS will be correct.
5247 CSingleLock lock(m_frameMutex);
5251 // then switch to fullscreen mode
5252 g_windowManager.ActivateWindow(WINDOW_FULLSCREEN_VIDEO);
5255 // special case for switching between GUI & visualisation mode. (only if we're playing an audio song)
5256 if (IsPlayingAudio() && g_windowManager.GetActiveWindow() != WINDOW_VISUALISATION)
5257 { // then switch to visualisation
5258 g_windowManager.ActivateWindow(WINDOW_VISUALISATION);
5264 void CApplication::Minimize()
5266 g_Windowing.Minimize();
5269 PLAYERCOREID CApplication::GetCurrentPlayer()
5271 return m_eCurrentPlayer;
5274 // when a scan is initiated, save current settings
5275 // and enable tag reading and remote thums
5276 void CApplication::SaveMusicScanSettings()
5278 CLog::Log(LOGINFO,"Music scan has started... Enabling tag reading, and remote thumbs");
5279 g_settings.m_bMyMusicIsScanning = true;
5283 void CApplication::RestoreMusicScanSettings()
5285 g_settings.m_bMyMusicIsScanning = false;
5289 void CApplication::UpdateLibraries()
5291 if (g_guiSettings.GetBool("videolibrary.updateonstartup"))
5293 CLog::Log(LOGNOTICE, "%s - Starting video library startup scan", __FUNCTION__);
5294 CGUIDialogVideoScan *scanner = (CGUIDialogVideoScan *)g_windowManager.GetWindow(WINDOW_DIALOG_VIDEO_SCAN);
5295 if (scanner && !scanner->IsScanning())
5296 scanner->StartScanning("");
5299 if (g_guiSettings.GetBool("musiclibrary.updateonstartup"))
5301 CLog::Log(LOGNOTICE, "%s - Starting music library startup scan", __FUNCTION__);
5302 CGUIDialogMusicScan *scanner = (CGUIDialogMusicScan *)g_windowManager.GetWindow(WINDOW_DIALOG_MUSIC_SCAN);
5303 if (scanner && !scanner->IsScanning())
5304 scanner->StartScanning("");
5308 void CApplication::CheckPlayingProgress()
5310 // check if we haven't rewound past the start of the file
5313 int iSpeed = g_application.GetPlaySpeed();
5323 if (g_infoManager.GetPlayTime() / 1000 < iPower)
5325 g_application.SetPlaySpeed(1);
5326 g_application.SeekTime(0);
5332 bool CApplication::ProcessAndStartPlaylist(const CStdString& strPlayList, CPlayList& playlist, int iPlaylist)
5334 CLog::Log(LOGDEBUG,"CApplication::ProcessAndStartPlaylist(%s, %i)",strPlayList.c_str(), iPlaylist);
5336 // initial exit conditions
5337 // no songs in playlist just return
5338 if (playlist.size() == 0)
5342 if (iPlaylist < PLAYLIST_MUSIC || iPlaylist > PLAYLIST_VIDEO)
5345 // setup correct playlist
5346 g_playlistPlayer.ClearPlaylist(iPlaylist);
5348 // if the playlist contains an internet stream, this file will be used
5349 // to generate a thumbnail for musicplayer.cover
5350 g_application.m_strPlayListFile = strPlayList;
5352 // add the items to the playlist player
5353 g_playlistPlayer.Add(iPlaylist, playlist);
5355 // if we have a playlist
5356 if (g_playlistPlayer.GetPlaylist(iPlaylist).size())
5359 g_playlistPlayer.SetCurrentPlaylist(iPlaylist);
5360 g_playlistPlayer.Reset();
5361 g_playlistPlayer.Play();
5367 void CApplication::SaveCurrentFileSettings()
5369 if (m_itemCurrentFile->IsVideo())
5371 // save video settings
5372 if (g_settings.m_currentVideoSettings != g_settings.m_defaultVideoSettings)
5376 dbs.SetVideoSettings(m_itemCurrentFile->GetPath(), g_settings.m_currentVideoSettings);
5382 bool CApplication::AlwaysProcess(const CAction& action)
5384 // check if this button is mapped to a built-in function
5385 if (!action.GetName().IsEmpty())
5387 CStdString builtInFunction;
5388 vector<CStdString> params;
5389 CUtil::SplitExecFunction(action.GetName(), builtInFunction, params);
5390 builtInFunction.ToLower();
5392 // should this button be handled normally or just cancel the screensaver?
5393 if ( builtInFunction.Equals("powerdown")
5394 || builtInFunction.Equals("reboot")
5395 || builtInFunction.Equals("restart")
5396 || builtInFunction.Equals("restartapp")
5397 || builtInFunction.Equals("suspend")
5398 || builtInFunction.Equals("hibernate")
5399 || builtInFunction.Equals("quit")
5400 || builtInFunction.Equals("shutdown"))
5409 CApplicationMessenger& CApplication::getApplicationMessenger()
5411 return m_applicationMessenger;
5414 bool CApplication::IsCurrentThread() const
5416 return CThread::IsCurrentThread(m_threadID);
5419 bool CApplication::IsPresentFrame()
5421 CSingleLock lock(m_frameMutex);
5422 bool ret = m_bPresentFrame;
5427 #if defined(HAS_LINUX_NETWORK)
5428 CNetworkLinux& CApplication::getNetwork()
5432 #elif defined(HAS_WIN32_NETWORK)
5433 CNetworkWin32& CApplication::getNetwork()
5438 CNetwork& CApplication::getNetwork()
5444 #ifdef HAS_PERFORMANCE_SAMPLE
5445 CPerformanceStats &CApplication::GetPerformanceStats()