BaseApplication.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. using MediaBrowser.Common.Kernel;
  2. using MediaBrowser.Common.Logging;
  3. using MediaBrowser.Common.Updates;
  4. using MediaBrowser.Model.Logging;
  5. using Microsoft.Win32;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.ComponentModel;
  9. using System.Deployment.Application;
  10. using System.Net.Cache;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. using System.Windows;
  14. using System.Windows.Controls;
  15. using System.Windows.Media;
  16. using System.Windows.Media.Imaging;
  17. namespace MediaBrowser.Common.UI
  18. {
  19. /// <summary>
  20. /// Serves as a base Application class for both the UI and Server apps.
  21. /// </summary>
  22. public abstract class BaseApplication : Application, INotifyPropertyChanged
  23. {
  24. /// <summary>
  25. /// The single instance mutex
  26. /// </summary>
  27. private Mutex SingleInstanceMutex;
  28. /// <summary>
  29. /// Gets the name of the publisher.
  30. /// </summary>
  31. /// <value>The name of the publisher.</value>
  32. protected abstract string PublisherName { get; }
  33. /// <summary>
  34. /// Gets the name of the suite.
  35. /// </summary>
  36. /// <value>The name of the suite.</value>
  37. protected abstract string SuiteName { get; }
  38. /// <summary>
  39. /// Gets the name of the product.
  40. /// </summary>
  41. /// <value>The name of the product.</value>
  42. protected abstract string ProductName { get; }
  43. /// <summary>
  44. /// Gets the name of the uninstaller file.
  45. /// </summary>
  46. /// <value>The name of the uninstaller file.</value>
  47. protected abstract string UninstallerFileName { get; }
  48. /// <summary>
  49. /// Gets or sets a value indicating whether [last run at startup value].
  50. /// </summary>
  51. /// <value><c>null</c> if [last run at startup value] contains no value, <c>true</c> if [last run at startup value]; otherwise, <c>false</c>.</value>
  52. private bool? LastRunAtStartupValue { get; set; }
  53. /// <summary>
  54. /// Gets or sets the kernel.
  55. /// </summary>
  56. /// <value>The kernel.</value>
  57. protected IKernel Kernel { get; set; }
  58. /// <summary>
  59. /// Instantiates the kernel.
  60. /// </summary>
  61. /// <returns>IKernel.</returns>
  62. protected abstract IKernel InstantiateKernel();
  63. /// <summary>
  64. /// Instantiates the main window.
  65. /// </summary>
  66. /// <returns>Window.</returns>
  67. protected abstract Window InstantiateMainWindow();
  68. /// <summary>
  69. /// Occurs when [property changed].
  70. /// </summary>
  71. public event PropertyChangedEventHandler PropertyChanged;
  72. /// <summary>
  73. /// Gets or sets the logger.
  74. /// </summary>
  75. /// <value>The logger.</value>
  76. protected ILogger Logger { get; set; }
  77. /// <summary>
  78. /// Initializes a new instance of the <see cref="BaseApplication" /> class.
  79. /// </summary>
  80. protected BaseApplication()
  81. {
  82. Logger = LogManager.GetLogger("App");
  83. }
  84. /// <summary>
  85. /// Called when [property changed].
  86. /// </summary>
  87. /// <param name="info">The info.</param>
  88. public void OnPropertyChanged(String info)
  89. {
  90. if (PropertyChanged != null)
  91. {
  92. try
  93. {
  94. PropertyChanged(this, new PropertyChangedEventArgs(info));
  95. }
  96. catch (Exception ex)
  97. {
  98. Logger.ErrorException("Error in event handler", ex);
  99. }
  100. }
  101. }
  102. /// <summary>
  103. /// Raises the <see cref="E:System.Windows.Application.Startup" /> event.
  104. /// </summary>
  105. /// <param name="e">A <see cref="T:System.Windows.StartupEventArgs" /> that contains the event data.</param>
  106. protected override void OnStartup(StartupEventArgs e)
  107. {
  108. bool createdNew;
  109. SingleInstanceMutex = new Mutex(true, @"Local\" + GetType().Assembly.GetName().Name, out createdNew);
  110. if (!createdNew)
  111. {
  112. SingleInstanceMutex = null;
  113. Shutdown();
  114. return;
  115. }
  116. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  117. LoadKernel();
  118. SystemEvents.SessionEnding += SystemEvents_SessionEnding;
  119. }
  120. /// <summary>
  121. /// Handles the UnhandledException event of the CurrentDomain control.
  122. /// </summary>
  123. /// <param name="sender">The source of the event.</param>
  124. /// <param name="e">The <see cref="UnhandledExceptionEventArgs" /> instance containing the event data.</param>
  125. void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  126. {
  127. var exception = (Exception) e.ExceptionObject;
  128. Logger.ErrorException("UnhandledException", exception);
  129. MessageBox.Show("Unhandled exception: " + exception.Message);
  130. }
  131. /// <summary>
  132. /// Handles the SessionEnding event of the SystemEvents control.
  133. /// </summary>
  134. /// <param name="sender">The source of the event.</param>
  135. /// <param name="e">The <see cref="SessionEndingEventArgs" /> instance containing the event data.</param>
  136. void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
  137. {
  138. // Try to shut down gracefully
  139. Shutdown();
  140. }
  141. /// <summary>
  142. /// Loads the kernel.
  143. /// </summary>
  144. protected virtual async void LoadKernel()
  145. {
  146. Kernel = InstantiateKernel();
  147. try
  148. {
  149. InstantiateMainWindow().Show();
  150. var now = DateTime.UtcNow;
  151. await Kernel.Init();
  152. var done = (DateTime.UtcNow - now);
  153. Logger.Info("Kernel.Init completed in {0}{1} minutes and {2} seconds.", done.Hours > 0 ? done.Hours + " Hours " : "", done.Minutes, done.Seconds);
  154. await OnKernelLoaded();
  155. }
  156. catch (Exception ex)
  157. {
  158. Logger.ErrorException("Error launching application", ex);
  159. MessageBox.Show("There was an error launching Media Browser: " + ex.Message);
  160. // Shutdown the app with an error code
  161. Shutdown(1);
  162. }
  163. }
  164. /// <summary>
  165. /// Called when [kernel loaded].
  166. /// </summary>
  167. /// <returns>Task.</returns>
  168. protected virtual Task OnKernelLoaded()
  169. {
  170. return Task.Run(() =>
  171. {
  172. Kernel.ApplicationRestartRequested += Kernel_ApplicationRestartRequested;
  173. Kernel.ConfigurationUpdated += Kernel_ConfigurationUpdated;
  174. ConfigureClickOnceStartup();
  175. });
  176. }
  177. /// <summary>
  178. /// Handles the ConfigurationUpdated event of the Kernel control.
  179. /// </summary>
  180. /// <param name="sender">The source of the event.</param>
  181. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  182. void Kernel_ConfigurationUpdated(object sender, EventArgs e)
  183. {
  184. if (!LastRunAtStartupValue.HasValue || LastRunAtStartupValue.Value != Kernel.Configuration.RunAtStartup)
  185. {
  186. ConfigureClickOnceStartup();
  187. }
  188. }
  189. /// <summary>
  190. /// Configures the click once startup.
  191. /// </summary>
  192. private void ConfigureClickOnceStartup()
  193. {
  194. if (!ApplicationDeployment.IsNetworkDeployed)
  195. {
  196. return;
  197. }
  198. try
  199. {
  200. var clickOnceHelper = new ClickOnceHelper(PublisherName, ProductName, SuiteName);
  201. if (Kernel.Configuration.RunAtStartup)
  202. {
  203. clickOnceHelper.UpdateUninstallParameters(UninstallerFileName);
  204. clickOnceHelper.AddShortcutToStartup();
  205. }
  206. else
  207. {
  208. clickOnceHelper.RemoveShortcutFromStartup();
  209. }
  210. LastRunAtStartupValue = Kernel.Configuration.RunAtStartup;
  211. }
  212. catch (Exception ex)
  213. {
  214. Logger.ErrorException("Error configuring ClickOnce", ex);
  215. }
  216. }
  217. /// <summary>
  218. /// Handles the ApplicationRestartRequested event of the Kernel control.
  219. /// </summary>
  220. /// <param name="sender">The source of the event.</param>
  221. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  222. void Kernel_ApplicationRestartRequested(object sender, EventArgs e)
  223. {
  224. Restart();
  225. }
  226. /// <summary>
  227. /// Restarts this instance.
  228. /// </summary>
  229. public void Restart()
  230. {
  231. Dispatcher.Invoke(ReleaseMutex);
  232. Kernel.Dispose();
  233. System.Windows.Forms.Application.Restart();
  234. Dispatcher.Invoke(Shutdown);
  235. }
  236. /// <summary>
  237. /// Releases the mutex.
  238. /// </summary>
  239. private void ReleaseMutex()
  240. {
  241. if (SingleInstanceMutex == null)
  242. {
  243. return;
  244. }
  245. SingleInstanceMutex.ReleaseMutex();
  246. SingleInstanceMutex.Close();
  247. SingleInstanceMutex.Dispose();
  248. SingleInstanceMutex = null;
  249. }
  250. /// <summary>
  251. /// Raises the <see cref="E:System.Windows.Application.Exit" /> event.
  252. /// </summary>
  253. /// <param name="e">An <see cref="T:System.Windows.ExitEventArgs" /> that contains the event data.</param>
  254. protected override void OnExit(ExitEventArgs e)
  255. {
  256. ReleaseMutex();
  257. base.OnExit(e);
  258. Kernel.Dispose();
  259. }
  260. /// <summary>
  261. /// Signals the external command line args.
  262. /// </summary>
  263. /// <param name="args">The args.</param>
  264. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  265. public bool SignalExternalCommandLineArgs(IList<string> args)
  266. {
  267. OnSecondInstanceLaunched(args);
  268. return true;
  269. }
  270. /// <summary>
  271. /// Called when [second instance launched].
  272. /// </summary>
  273. /// <param name="args">The args.</param>
  274. protected virtual void OnSecondInstanceLaunched(IList<string> args)
  275. {
  276. if (MainWindow.WindowState == WindowState.Minimized)
  277. {
  278. MainWindow.WindowState = WindowState.Maximized;
  279. }
  280. }
  281. /// <summary>
  282. /// Gets the image.
  283. /// </summary>
  284. /// <param name="uri">The URI.</param>
  285. /// <returns>Image.</returns>
  286. /// <exception cref="System.ArgumentNullException">uri</exception>
  287. public Image GetImage(string uri)
  288. {
  289. if (string.IsNullOrEmpty(uri))
  290. {
  291. throw new ArgumentNullException("uri");
  292. }
  293. return GetImage(new Uri(uri));
  294. }
  295. /// <summary>
  296. /// Gets the image.
  297. /// </summary>
  298. /// <param name="uri">The URI.</param>
  299. /// <returns>Image.</returns>
  300. /// <exception cref="System.ArgumentNullException">uri</exception>
  301. public Image GetImage(Uri uri)
  302. {
  303. if (uri == null)
  304. {
  305. throw new ArgumentNullException("uri");
  306. }
  307. return new Image { Source = GetBitmapImage(uri) };
  308. }
  309. /// <summary>
  310. /// Gets the bitmap image.
  311. /// </summary>
  312. /// <param name="uri">The URI.</param>
  313. /// <returns>BitmapImage.</returns>
  314. /// <exception cref="System.ArgumentNullException">uri</exception>
  315. public BitmapImage GetBitmapImage(string uri)
  316. {
  317. if (string.IsNullOrEmpty(uri))
  318. {
  319. throw new ArgumentNullException("uri");
  320. }
  321. return GetBitmapImage(new Uri(uri));
  322. }
  323. /// <summary>
  324. /// Gets the bitmap image.
  325. /// </summary>
  326. /// <param name="uri">The URI.</param>
  327. /// <returns>BitmapImage.</returns>
  328. /// <exception cref="System.ArgumentNullException">uri</exception>
  329. public BitmapImage GetBitmapImage(Uri uri)
  330. {
  331. if (uri == null)
  332. {
  333. throw new ArgumentNullException("uri");
  334. }
  335. var bitmap = new BitmapImage
  336. {
  337. CreateOptions = BitmapCreateOptions.DelayCreation,
  338. CacheOption = BitmapCacheOption.OnDemand,
  339. UriCachePolicy = new RequestCachePolicy(RequestCacheLevel.CacheIfAvailable)
  340. };
  341. bitmap.BeginInit();
  342. bitmap.UriSource = uri;
  343. bitmap.EndInit();
  344. RenderOptions.SetBitmapScalingMode(bitmap, BitmapScalingMode.Fant);
  345. return bitmap;
  346. }
  347. /// <summary>
  348. /// Runs the application.
  349. /// </summary>
  350. /// <typeparam name="TApplicationType">The type of the T application type.</typeparam>
  351. /// <param name="uniqueKey">The unique key.</param>
  352. public static void RunApplication<TApplicationType>(string uniqueKey)
  353. where TApplicationType : BaseApplication, IApplication, new()
  354. {
  355. var application = new TApplicationType();
  356. application.InitializeComponent();
  357. application.Run();
  358. }
  359. }
  360. /// <summary>
  361. /// Interface IApplication
  362. /// </summary>
  363. public interface IApplication
  364. {
  365. /// <summary>
  366. /// Initializes the component.
  367. /// </summary>
  368. void InitializeComponent();
  369. }
  370. }