Example #1
0
        public WebBoolResult SetPowerMode(WebPowerMode powerMode)
        {
            try
            {
                if (powerMode == WebPowerMode.Screensaver)
                {
                    ScreenSaver.StartScreenSaver();
                }
                else if (powerMode == WebPowerMode.Lock)
                {
                    LockWorkStation();
                }
                else if (powerMode == WebPowerMode.ScreenOff)
                {
                    SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, 2);
                }
                else if (powerMode == WebPowerMode.ScreenOn)
                {
                }
                else
                {
                    RestartOptions option = MapPowerMode(powerMode);
                    WindowsController.ExitWindows(option, false);
                }
            }
            catch (InvalidCastException)
            {
                Log.Warn("The powerMode " + powerMode + " is not valid");
            }

            return(new WebBoolResult(true));
        }
Example #2
0
        protected static void ExitWindowsDefaultThread(object _data)
        {
            ExitWindowsDefaultEnv env = (ExitWindowsDefaultEnv)_data;
            RestartOptions        how = env.how;
            bool force = env.force;

            Log.Debug("WindowsController: Performing ExitWindows {0}, force: {1}", how, force);
            bool res;

            switch (how)
            {
            case RestartOptions.Suspend:
                res = Application.SetSuspendState(PowerState.Suspend, force, false);
                break;

            case RestartOptions.Hibernate:
                res = Application.SetSuspendState(PowerState.Hibernate, force, false);
                break;

            default:
                res = ExitWindowsInt((int)how, force);
                break;
            }
            Log.Debug("WindowsController: ExitWindows performed, result: {0}", res);
            if (env.after != null)
            {
                env.after(how, force, res);
            }
        }
Example #3
0
        /// <summary>
        /// Default ExitWindows. Kicks off a thread which handles t
        /// </summary>
        /// <param name="how"></param>
        /// <param name="force"></param>
        /// <returns></returns>
        protected static void ExitWindowsDefault(RestartOptions how, bool force, AfterExitWindowsHandler after)
        {
            ExitWindowsDefaultEnv env = new ExitWindowsDefaultEnv();

            env.how   = how;
            env.force = force;
            env.after = after;
            Thread exitWinThread = new Thread(ExitWindowsDefaultThread);

            exitWinThread.Name = "WinController exit thread";
            exitWinThread.Start(env);
        }
Example #4
0
		/// <summary>
		/// Exits windows (and tries to enable any required access rights, if necesarry).
		/// </summary>
		/// <param name="how">One of the RestartOptions values that specifies how to exit windows.</param>
		/// <param name="force">True if the exit has to be forced, false otherwise.</param>
		/// <exception cref="PrivilegeException">There was an error while requesting a required privilege.</exception>
		/// <exception cref="PlatformNotSupportedException">The requested exit method is not supported on this platform.</exception>
		public static void ExitWindows(RestartOptions how , bool force ) {
			switch(how) {
				case RestartOptions.Suspend:
					SuspendSystem(false, force);
					break;
				case RestartOptions.Hibernate:
					SuspendSystem(true, force);
					break;
				default:
					ExitWindows((int)how, force);
					break;
			}
		}
Example #5
0
        private void timerTick_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            TimeSpan remaining = endTime - DateTime.Now;

            if (remaining.TotalSeconds < 0)
            {
                timerTick.Enabled = false;
                RestartOptions option = (RestartOptions)comboBoxRestartType.SelectedValue;
                WindowsController.ExitWindows(option, checkBoxForce.Checked);
            }

            maskedTextBoxTime.Text = remaining.ToString();
        }
Example #6
0
		private static void ExitWindows(RestartOptions how, bool force)
		{
			switch (how)
			{
				case RestartOptions.Suspend:
					SuspendSystem(false, force);
					break;
				case RestartOptions.Hibernate:
					SuspendSystem(true, force);
					break;
				default:
					ExitWindows(Convert.ToInt32(how), force);
					break;
			}
		}
Example #7
0
        private static void ExitWindows(RestartOptions how, bool force)
        {
            switch (how)
            {
            case RestartOptions.Suspend:
                SuspendSystem(false, force);
                break;

            case RestartOptions.Hibernate:
                SuspendSystem(true, force);
                break;

            default:
                ExitWindows(Convert.ToInt32(how), force);
                break;
            }
        }
Example #8
0
        /// <summary>
        /// Default ExitWindows. Kicks off a thread which handles t
        /// </summary>
        /// <param name="how"></param>
        /// <param name="force"></param>
        /// <returns></returns>
        protected static void ExitWindowsDefault(RestartOptions how, bool force, AfterExitWindowsHandler after)
        {
            ExitWindowsDefaultEnv env = new ExitWindowsDefaultEnv();

            env.how   = how;
            env.force = force;
            env.after = after;
            // If restart is Hibernate or Suspend then do is async
            if (how == RestartOptions.Hibernate || how == RestartOptions.Suspend)
            {
                (new Thread(ExitWindowsDefaultThread)).Start(env);
            }
            else
            {
                ExitWindowsDefaultThread(env);
            }
        }
    /// <summary>
    /// Thread that puts the system into sleep mode (Suspend/Hibernate)
    /// </summary>
    /// <param name="how">How to suspend, see MediaPortal.Util.RestartOptions</param>
    protected void SuspendSystemThread(string source, RestartOptions how, bool force)
    {
      Log.Debug("PS: Shutdown thread is running: how: {0}, force: {1}", how, force);

      Log.Debug("PS: Informing handlers about UserShutdownNow");
      ((IStandbyHandler)this).UserShutdownNow();

      if (source == "System")
      {
        // XP only: We just denied a QUERYSUSPEND message and called SuspendSystem() with source "System".
        // Before actually suspending, we have to wait for the outstanding QUERYSUSPENDFAILED message (only Windows XP).
        _QuerySuspendFailedCount++;
        Log.Debug("PS: {0} outstanding QUERYSUSPENDFAILED messages", _QuerySuspendFailedCount);
        do
        {
          System.Threading.Thread.Sleep(1000);
        } while (_QuerySuspendFailedCount > 0);
      }
      _denyQuerySuspend = false;

      // Activate standby
      Log.Info("PS: Entering shutdown: how: {0}, force: {1}", (RestartOptions)how, force);
      WindowsController.ExitWindows((RestartOptions)how, force);
    }
Example #10
0
 /// <summary>
 /// Default ExitWindows. Kicks off a thread which handles t
 /// </summary>
 /// <param name="how"></param>
 /// <param name="force"></param>
 /// <returns></returns>
 protected static void ExitWindowsDefault(RestartOptions how, bool force, AfterExitWindowsHandler after)
 {
     ExitWindowsDefaultEnv env = new ExitWindowsDefaultEnv();
       env.how = how;
       env.force = force;
       env.after = after;
       // If restart is Hibernate or Suspend then do is async
       if (how == RestartOptions.Hibernate || how == RestartOptions.Suspend)
     (new Thread(ExitWindowsDefaultThread)).Start(env);
       else
     ExitWindowsDefaultThread(env);
 }
Example #11
0
 public static void ExitWindows(RestartOptions how, bool force, AfterExitWindowsHandler after)
 {
     _exitWindows(how, force, after);
 }
Example #12
0
 /// <summary>
 /// Exits windows (and tries to enable any required access rights, if necesarry).
 /// This is routed thru a property/delegate to enabled someone to hook this function (PSClientPlugin).
 /// This function immediately returns, the request is executed asynchronously. (Otherwise it would block
 /// on suspend/hibernate until the system is resumed.)
 /// 
 /// The after handler: On hibernate/standby, this handler is called when the system was resumed again.
 /// On shutdown/restart, this handler is immeditely called after the system was requested to shutdown/restart.
 /// </summary>
 /// <param name="how">One of the RestartOptions values that specifies how to exit windows.</param>
 /// <param name="force">True if the exit has to be forced, false otherwise.</param>
 /// <param name="after">Handler that is called after ExitWindows</param>
 /// <exception cref="PrivilegeException">There was an error while requesting a required privilege.</exception>
 /// <exception cref="PlatformNotSupportedException">The requested exit method is not supported on this platform.</exception>
 public static void ExitWindows(RestartOptions how, bool force)
 {
     ExitWindows(how, force, null);
 }
Example #13
0
 public RestartTypeListOption(string display,
                              RestartOptions option)
 {
     displayName   = display;
     restartOption = option;
 }
    protected void SuspendSystemThread(string source, RestartOptions how, bool force)
    {
      Log.Debug("PowerScheduler: Shutdown thread is running: {0}, force: {1}", how, force);
      _isSuspendInProgress = true;
      Log.Debug("PowerScheduler: Informing handlers about UserShutdownNow");
      UserShutdownNow();

      // user is away, so we set _lastUserTime long time in the past to pretend that he didn't access system a long time
      _lastUserTime = DateTime.MinValue;

      // test if shutdown is allowed
      bool disallow = DisAllowShutdown(true);

      Log.Info("PowerScheduler: Source: {0}; shutdown is allowed {1} ; forced: {2}", source, !disallow, force);

      if (disallow && !force)
      {
        lock (this)
        {
          // allow further requests
          _ignoreSuspendUntil = DateTime.MinValue;
        }
        _isSuspendInProgress = false;
        return;
      }

      SetWakeupTimer();
      if (source == "System")
      {
        // Here we should wait for QuerySuspendFailed / QueryStandByFailed since we have rejected
        // the suspend request
        _querySuspendFailed++;
        Log.Info("PowerScheduler: _querySuspendFailed {0}", _querySuspendFailed);
        do
        {
          System.Threading.Thread.Sleep(1000);
        } while (_querySuspendFailed > 0);
      }
      // activate standby
      _denySuspendQuery = false;
      Log.Info("PowerScheduler: Entering shutdown {0} ; forced: {1}", (RestartOptions)how, force);
      WindowsController.ExitWindows((RestartOptions)how, force, SuspendSystemThreadAfter);
    }
Example #15
0
 /// <summary>
 /// Updates selected action when user changes value in ComboBox
 /// </summary>
 private void actionComboBox_SelectedValueChanged(object sender, EventArgs e)
 {
     selectedAction = (RestartOptions)actionComboBox.SelectedValue;
 }
 public void SafeExitWindowsThreadAfter(RestartOptions how, bool force, bool result)
 {
   that.SafeExitWindowsThreadAfter(how, force, result, after);
 }
Example #17
0
 /// <summary>
 /// 退出Windows,如果需要,申请相应权限
 /// </summary>
 /// <param name="how">重启选项,指示如何退出Windows</param>
 /// <param name="force">True表示强制退出</param>
 /// <exception cref="PrivilegeException">当申请权限时发生了一个错误</exception>
 /// <exception cref="PlatformNotSupportedException">系统不支持则引发异常</exception>
 public static void ExitWindows(RestartOptions how, bool force)
 {
     ExitWindows((int)how, force);
 }
Example #18
0
  /// <summary>
  /// 
  /// </summary>
  public MediaPortalApp()
  {
    // init attributes
    _xpos                  = 50;
    _lastOnresume          = DateTime.Now;
    _updateTimer           = DateTime.MinValue;
    _lastContextMenuAction = DateTime.MaxValue;
    _region                = new Rectangle[1];
    _restartOptions        = RestartOptions.Reboot;

    int screenNumber;
    using (Settings xmlreader = new MPSettings())
    {
      _suspendGracePeriodSec      = xmlreader.GetValueAsInt("general", "suspendgraceperiod", 5);
      _useScreenSaver             = xmlreader.GetValueAsBool("general", "IdleTimer", true);
      _timeScreenSaver            = xmlreader.GetValueAsInt("general", "IdleTimeValue", 300);
      _useIdleblankScreen         = xmlreader.GetValueAsBool("general", "IdleBlanking", false);
      _showLastActiveModule       = xmlreader.GetValueAsBool("general", "showlastactivemodule", false);
      screenNumber                = xmlreader.GetValueAsInt("screenselector", "screennumber", 0);
      _stopOnLostAudioRenderer    = xmlreader.GetValueAsBool("general", "stoponaudioremoval", true);
    }

    if (ScreenNumberOverride >= 0)
    {
      screenNumber = ScreenNumberOverride;
    }
    if (screenNumber < 0 || screenNumber >= Screen.AllScreens.Length)
    {
      screenNumber = 0;
    }

    GUIGraphicsContext.currentScreen = Screen.AllScreens[screenNumber];

    Log.Info("Main: MP is using screen: {0} (Position: {1},{2} Dimensions: {3}x{4})",
             GetCleanDisplayName(GUIGraphicsContext.currentScreen),
             GUIGraphicsContext.currentScreen.Bounds.Location.X, GUIGraphicsContext.currentScreen.Bounds.Location.Y,
             GUIGraphicsContext.currentScreen.Bounds.Width, GUIGraphicsContext.currentScreen.Bounds.Height);

    // move form to selected screen
    Location = new Point(Location.X + GUIGraphicsContext.currentScreen.Bounds.X, Location.Y + GUIGraphicsContext.currentScreen.Bounds.Y);

    // temporarily set new client size for initialization purposes
    ClientSize = new Size(0, 0);

    // check if MediaPortal is already running...
    Log.Info("Main: Checking for running MediaPortal instance");
    Log.Info(@"Main: Deleting old log\capture.log");
    Utils.FileDelete(Config.GetFile(Config.Dir.Log, "capture.log"));

    
    // ReSharper disable LocalizableElement
    Text = "MediaPortal";
    // ReSharper restore LocalizableElement
    GUIGraphicsContext.form = this;
    GUIGraphicsContext.graphics = null;
    GUIGraphicsContext.RenderGUI = this;

    using (Settings xmlreader = new MPSettings())
    {
      AutoHideMouse = xmlreader.GetValueAsBool("general", "autohidemouse", true);
      GUIGraphicsContext.MouseSupport = xmlreader.GetValueAsBool("gui", "mousesupport", false);
      GUIGraphicsContext.AllowRememberLastFocusedItem = xmlreader.GetValueAsBool("gui", "allowRememberLastFocusedItem", false);
      GUIGraphicsContext.DBLClickAsRightClick = xmlreader.GetValueAsBool("general", "dblclickasrightclick", false);
      MinimizeOnStartup = xmlreader.GetValueAsBool("general", "minimizeonstartup", false);
      MinimizeOnGuiExit = xmlreader.GetValueAsBool("general", "minimizeonexit", false);
      MinimizeOnFocusLoss = xmlreader.GetValueAsBool("general", "minimizeonfocusloss", false);
    }

    SetStyle(ControlStyles.Opaque, true);
    SetStyle(ControlStyles.UserPaint, true);
    SetStyle(ControlStyles.AllPaintingInWmPaint, true);
    SetStyle(ControlStyles.DoubleBuffer, false);

    Activated  += MediaPortalAppActivated;
    Deactivate += MediaPortalAppDeactivate;
    
    Log.Info("Main: Checking skin version");
    CheckSkinVersion();
    using (Settings xmlreader = new MPSettings())
    {
      var startFullscreen = !WindowedOverride && (FullscreenOverride || xmlreader.GetValueAsBool("general", "startfullscreen", false));
      Windowed = !startFullscreen;
    }

    DoStartupJobs();
  }
Example #19
0
 /// <summary>
 /// 退出Windows,如果需要,申请相应权限
 /// </summary>
 /// <param name="how">重启选项,指示如何退出Windows</param>
 /// <param name="force">True表示强制退出</param>
 /// <exception cref="PrivilegeException">当申请权限时发生了一个错误</exception>
 /// <exception cref="PlatformNotSupportedException">系统不支持则引发异常</exception>
 public static void ExitWindows(RestartOptions how, bool force)
 {
     Restart.ExitWindows(how, force);
 }
Example #20
0
  /// <summary>
  /// 
  /// </summary>
  public MediaPortalApp()
  {
    // init attributes
    _xpos                  = 50;
    _lastOnresume          = DateTime.Now;
    _updateTimer           = DateTime.MinValue;
    _lastContextMenuAction = DateTime.MaxValue;
    _region                = new Rectangle[1];
    _restartOptions        = RestartOptions.Reboot;

    int screenNumber;
    string screenDeviceId;
    using (Settings xmlreader = new MPSettings())
    {
      _suspendGracePeriodSec      = xmlreader.GetValueAsInt("general", "suspendgraceperiod", 5);
      _useScreenSaver             = xmlreader.GetValueAsBool("general", "IdleTimer", true);
      _timeScreenSaver            = xmlreader.GetValueAsInt("general", "IdleTimeValue", 300);
      _useIdleblankScreen         = xmlreader.GetValueAsBool("general", "IdleBlanking", false);
      _useIdlePluginScreen        = xmlreader.GetValueAsBool("general", "IdlePlugin", false);
      _idlePluginWindowId         = xmlreader.GetValueAsInt("general", "IdlePluginWindow", 0);
      _showLastActiveModule       = xmlreader.GetValueAsBool("general", "showlastactivemodule", false);
      screenNumber                = xmlreader.GetValueAsInt("screenselector", "screennumber", 0);
      _stopOnLostAudioRenderer    = xmlreader.GetValueAsBool("general", "stoponaudioremoval", true);
      _delayOnResume              = xmlreader.GetValueAsBool("general", "delay resume", false) ? xmlreader.GetValueAsInt("general", "delay", 0) : 0;
      screenDeviceId              = xmlreader.GetValueAsString("screenselector", "screendeviceid", "");
      _usePrimaryScreen           = xmlreader.GetValueAsBool("general", "useprimaryscreen", false);
      _screenDisplayName          = xmlreader.GetValueAsString("screenselector", "screendisplayname", "");
    }

    if (ScreenNumberOverride >= 0)
    {
      screenNumber = ScreenNumberOverride;
      if (screenNumber < 0 || screenNumber >= Screen.AllScreens.Length)
      {
        screenNumber = 0;
      }
      GUIGraphicsContext.currentScreen = Screen.AllScreens[screenNumber];
    }
    else
    {
      bool foundScreen = false;
      foreach (Screen screen in Screen.AllScreens)
      {
        const int dwf = 0;
        var info = new DISPLAY_DEVICE();
        string monitorname = null;
        string deviceId = null;
        info.cb = Marshal.SizeOf(info);
        if (EnumDisplayDevices(screen.DeviceName, 0, info, dwf))
        {
          monitorname = info.DeviceString;
          deviceId = info.DeviceID;
        }
        if (monitorname == null)
        {
          monitorname = "";
        }
        if (deviceId == null)
        {
          deviceId = "";
        }

        if (_usePrimaryScreen)
        {
          if (screen.Primary)
          {
            GUIGraphicsContext.currentScreen = screen;
            foundScreen = true;
            break;
          }
        }
        else
        {
          if (!string.IsNullOrEmpty(deviceId))
          {
            if (deviceId.Equals(screenDeviceId))
            {
              GUIGraphicsContext.currentScreen = screen;
              foundScreen = true;
              break;
            }
          }
          else
          {
            if (screen.DeviceName.Equals(_screenDisplayName))
            {
              GUIGraphicsContext.currentScreen = screen;
              foundScreen = true;
              break;
            }
          }
        }
      }
      if (!foundScreen)
      {
        GUIGraphicsContext.currentScreen = screenNumber >= Screen.AllScreens.Length ? Screen.AllScreens[0] : Screen.AllScreens[screenNumber];
      }
    }

    Log.Info("Main: MP is using screen: {0} (Position: {1},{2} Dimensions: {3}x{4})",
             GetCleanDisplayName(GUIGraphicsContext.currentScreen),
             GUIGraphicsContext.currentScreen.Bounds.Location.X, GUIGraphicsContext.currentScreen.Bounds.Location.Y,
             GUIGraphicsContext.currentScreen.Bounds.Width, GUIGraphicsContext.currentScreen.Bounds.Height);

    // move form to selected screen
    Location = new Point(Location.X + GUIGraphicsContext.currentScreen.Bounds.X, Location.Y + GUIGraphicsContext.currentScreen.Bounds.Y);

    // temporarily set new client size for initialization purposes
    ClientSize = new Size(0, 0);

    // check if MediaPortal is already running...
    Log.Info("Main: Checking for running MediaPortal instance");
    Log.Info(@"Main: Deleting old log\capture.log");
    Utils.FileDelete(Config.GetFile(Config.Dir.Log, "capture.log"));

    
    // ReSharper disable LocalizableElement
    Text = "MediaPortal";
    // ReSharper restore LocalizableElement
    GUIGraphicsContext.form = this;
    GUIGraphicsContext.graphics = null;
    GUIGraphicsContext.RenderGUI = this;
    GUIGraphicsContext.Render3DMode = GUIGraphicsContext.eRender3DMode.None;
    GUIGraphicsContext.DeviceAudioConnected = 0;
    GUIGraphicsContext.DeviceVideoConnected = 0;

    using (Settings xmlreader = new MPSettings())
    {
      AutoHideMouse = xmlreader.GetValueAsBool("general", "autohidemouse", true);
      GUIGraphicsContext.MouseSupport = xmlreader.GetValueAsBool("gui", "mousesupport", false);
      GUIGraphicsContext.AllowRememberLastFocusedItem = xmlreader.GetValueAsBool("gui", "allowRememberLastFocusedItem", false);
      GUIGraphicsContext.DBLClickAsRightClick = xmlreader.GetValueAsBool("general", "dblclickasrightclick", false);
      MinimizeOnStartup = xmlreader.GetValueAsBool("general", "minimizeonstartup", false);
      MinimizeOnGuiExit = xmlreader.GetValueAsBool("general", "minimizeonexit", false);
      MinimizeOnFocusLoss = xmlreader.GetValueAsBool("general", "minimizeonfocusloss", false);
    }

    SetStyle(ControlStyles.Opaque, true);
    SetStyle(ControlStyles.UserPaint, true);
    SetStyle(ControlStyles.AllPaintingInWmPaint, true);
    SetStyle(ControlStyles.DoubleBuffer, false);

    Activated  += MediaPortalAppActivated;
    Deactivate += MediaPortalAppDeactivate;
    
    Log.Info("Main: Checking skin version");
    CheckSkinVersion();
    using (Settings xmlreader = new MPSettings())
    {
      _keepstartfullscreen = xmlreader.GetValueAsBool("general", "keepstartfullscreen", false);
      var startFullscreen = !WindowedOverride && (FullscreenOverride || xmlreader.GetValueAsBool("general", "startfullscreen", false));
      if (_keepstartfullscreen)
      {
        Windowed = !_keepstartfullscreen;
      }
      else
      {
        Windowed = !startFullscreen;
      }
    }

    DoStartupJobs();
  }
 /// <summary>
 /// Default ExitWindows. Kicks off a thread which handles t
 /// </summary>
 /// <param name="how"></param>
 /// <param name="force"></param>
 /// <returns></returns>
 protected static void ExitWindowsDefault(RestartOptions how, bool force, AfterExitWindowsHandler after)
 {
   ExitWindowsDefaultEnv env = new ExitWindowsDefaultEnv();
   env.how = how;
   env.force = force;
   env.after = after;
   Thread exitWinThread = new Thread(ExitWindowsDefaultThread);
   exitWinThread.Name = "WinController exit thread";
   exitWinThread.Start(env);
 }
Example #22
0
 /// <summary>
 /// Exits windows (and tries to enable any required access rights, if necesarry).
 /// This is routed thru a property/delegate to enabled someone to hook this function (PSClientPlugin).
 /// This function immediately returns, the request is executed asynchronously. (Otherwise it would block
 /// on suspend/hibernate until the system is resumed.)
 ///
 /// The after handler: On hibernate/standby, this handler is called when the system was resumed again.
 /// On shutdown/restart, this handler is immeditely called after the system was requested to shutdown/restart.
 /// </summary>
 /// <param name="how">One of the RestartOptions values that specifies how to exit windows.</param>
 /// <param name="force">True if the exit has to be forced, false otherwise.</param>
 /// <param name="after">Handler that is called after ExitWindows</param>
 /// <exception cref="PrivilegeException">There was an error while requesting a required privilege.</exception>
 /// <exception cref="PlatformNotSupportedException">The requested exit method is not supported on this platform.</exception>
 public static void ExitWindows(RestartOptions how, bool force)
 {
     ExitWindows(how, force, null);
 }
    protected void SafeExitWindowsThread(RestartOptions how, bool force, WindowsController.AfterExitWindowsHandler after)
    {
      Log.Debug("PSClientPlugin: Shutdown thread is running: {0}, force: {1}", how, force);
      _isSuspendInProgress = true;
      Log.Debug("PSClientPlugin: Informing handlers about UserShutdownNow");
      UserShutdownNow();

      // user is away, so we set _lastUserTime long time in the past to pretend that he didn't access system a long time
      _lastUserTime = DateTime.MinValue;

      // test if shutdown is allowed
      bool disallow = DisAllowShutdown;

      Log.Info("PSClientPlugin: Shutdown is allowed {0} ; forced: {1}", !disallow, force);

      if (disallow && !force)
      {
        lock (this)
        {
          // allow further requests
          _ignoreSuspendUntil = DateTime.MinValue;
        }
        if (after != null)
        {
          after(how, force, false);
        }
        _isSuspendInProgress = false;
        return;
      }

      SetWakeupTimer();

      // activate standby
      _denySuspendQuery = false;
      Log.Info("PSClientPlugin: Entering shutdown {0} ; forced: {1}", (RestartOptions)how, force);

      SafeExitWindowsThreadAfterProxy env = new SafeExitWindowsThreadAfterProxy();
      env.that = this;
      env.after = after;
      _defaultExitWindows((RestartOptions)how, force, env.SafeExitWindowsThreadAfter);
    }
Example #24
0
 public static void ExitWindows(RestartOptions how, bool force, AfterExitWindowsHandler after)
 {
     _exitWindows(how, force, after);
 }
 protected void SafeExitWindowsThreadAfter(RestartOptions how, bool force, bool result,
                                           WindowsController.AfterExitWindowsHandler after)
 {
   _isSuspendInProgress = false;
   lock (this)
   {
     if (!result)
     {
       // allow further requests
       _ignoreSuspendUntil = DateTime.MinValue;
       return;
     }
     switch (how)
     {
       case RestartOptions.LogOff:
       case RestartOptions.Suspend:
       case RestartOptions.Hibernate:
         {
           // allow not before 5 seconds
           // *** this will block any about-to-suspend requests that have been pending before the shutdown was issued
           // *** (resolves the system-immediately-suspends-after-resume issue)
           _ignoreSuspendUntil = DateTime.Now.AddSeconds(5);
           break;
         }
       case RestartOptions.PowerOff:
       case RestartOptions.Reboot:
       case RestartOptions.ShutDown:
         {
           // allow not before 120 seconds, i.e. give enough time to shutdown the system (anyway this value is reset on reboot)
           _ignoreSuspendUntil = DateTime.Now.AddSeconds(120);
           break;
         }
     }
   }
   if (after != null)
   {
     after(how, force, result);
   }
 }
Example #26
0
 /// <summary>
 /// Exits windows (and tries to enable any required access rights, if necesarry).
 /// </summary>
 /// <param name="how">One of the RestartOptions values that specifies how to exit windows.</param>
 /// <param name="force">True if the exit has to be forced, false otherwise.</param>
 /// <exception cref="PrivilegeException">There was an error while requesting a required privilege.</exception>
 /// <exception cref="PlatformNotSupportedException">The requested exit method is not supported on this platform.</exception>
 public static void ExitWindows(RestartOptions how , bool force )
 {
     switch(how) {
         case RestartOptions.Suspend:
             SuspendSystem(false, force);
             break;
         case RestartOptions.Hibernate:
             SuspendSystem(true, force);
             break;
         default:
             ExitWindows((int)how, force);
             break;
     }
 }
  private void OnAction(Action action)
  {
    try
    {
      // hack/fix for lastactivemodulefullscreen
      // when recovering from hibernation/standby after closing with remote control somehow a F9 (keycode 120) onkeydown event is thrown from outside
      // we are currently filtering it away.
      // sometimes more than one F9 keydown event fired.
      // if these events are not filtered away the F9 context menu is shown on the restored/shown module.
      if ((action.wID == Action.ActionType.ACTION_CONTEXT_MENU || _suspended) && (showLastActiveModule))
      {
        //Log.Info("ACTION_CONTEXT_MENU, ignored = {0}, suspended = {1}", ignoreContextMenuAction, _suspended);      
        if (ignoreContextMenuAction)
        {
          ignoreContextMenuAction = false;
          lastContextMenuAction = DateTime.Now;
          return;
        }
        else if (lastContextMenuAction != DateTime.MaxValue)
        {
          TimeSpan ts = lastContextMenuAction - DateTime.Now;
          if (ts.TotalMilliseconds > -100)
          {
            ignoreContextMenuAction = false;
            lastContextMenuAction = DateTime.Now;
            return;
          }
        }
        lastContextMenuAction = DateTime.Now;
      }

      GUIWindow window;
      if (action.IsUserAction())
      {
        GUIGraphicsContext.ResetLastActivity();
      }
      switch (action.wID)
      {
          // record current tv program
        case Action.ActionType.ACTION_RECORD:
          if ((GUIGraphicsContext.IsTvWindow(GUIWindowManager.ActiveWindowEx) &&
               GUIWindowManager.ActiveWindowEx != (int)GUIWindow.Window.WINDOW_TVGUIDE) &&
              (GUIWindowManager.ActiveWindowEx != (int)GUIWindow.Window.WINDOW_DIALOG_TVGUIDE))
          {
            GUIWindow tvHome = GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_TV);
            if (tvHome != null)
            {
              if (tvHome.GetID != GUIWindowManager.ActiveWindow)
              {
                tvHome.OnAction(action);
                return;
              }
            }
          }
          break;

          //TV: zap to previous channel
        case Action.ActionType.ACTION_PREV_CHANNEL:
          if (!GUIWindowManager.IsRouted)
          {
            window = GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_TV);
            window.OnAction(action);
            return;
          }
          break;

          //TV: zap to next channel
        case Action.ActionType.ACTION_NEXT_CHANNEL:
          if (!GUIWindowManager.IsRouted)
          {
            window = GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_TV);
            window.OnAction(action);
            return;
          }
          break;

          //TV: zap to last channel viewed
        case Action.ActionType.ACTION_LAST_VIEWED_CHANNEL: // mPod
          if (!GUIWindowManager.IsRouted)
          {
            window = GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_TV);
            window.OnAction(action);
            return;
          }
          break;

          //toggle between directx windowed and exclusive mode
        case Action.ActionType.ACTION_TOGGLE_WINDOWED_FULLSCREEN:
          ToggleFullWindowed();
          return;
          //break;

          //mute or unmute audio
        case Action.ActionType.ACTION_VOLUME_MUTE:
          VolumeHandler.Instance.IsMuted = !VolumeHandler.Instance.IsMuted;
          break;

          //decrease volume 
        case Action.ActionType.ACTION_VOLUME_DOWN:
          VolumeHandler.Instance.Volume = VolumeHandler.Instance.Previous;
          break;

          //increase volume 
        case Action.ActionType.ACTION_VOLUME_UP:
          VolumeHandler.Instance.Volume = VolumeHandler.Instance.Next;
          break;

          //toggle live tv in background
        case Action.ActionType.ACTION_BACKGROUND_TOGGLE:
          //show livetv or video as background instead of the static GUI background
          // toggle livetv/video in background on/pff
          if (GUIGraphicsContext.ShowBackground)
          {
            Log.Info("Main: Using live TV as background");
            // if on, but we're not playing any video or watching tv
            if (GUIGraphicsContext.Vmr9Active)
            {
              GUIGraphicsContext.ShowBackground = false;
              //GUIGraphicsContext.Overlay = false;
            }
            else
            {
              //show warning message
              GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SHOW_WARNING, 0, 0, 0, 0, 0, 0);
              msg.Param1 = 727; //Live tv in background
              msg.Param2 = 728; //No Video/TV playing
              msg.Param3 = 729; //Make sure that something is playing
              GUIWindowManager.SendMessage(msg);
              return;
            }
          }
          else
          {
            Log.Info("Main: Using GUI as background");
            GUIGraphicsContext.ShowBackground = true;
            //GUIGraphicsContext.Overlay = true;
          }
          return;

          //switch between several home windows
        case Action.ActionType.ACTION_SWITCH_HOME:
          GUIMessage homeMsg;
          GUIWindow.Window newHome = _startWithBasicHome
                                       ? GUIWindow.Window.WINDOW_SECOND_HOME
                                       : GUIWindow.Window.WINDOW_HOME;
          // do we prefer to use only one home screen?
          if (_useOnlyOneHome)
          {
            // skip if we are already in there
            if (GUIWindowManager.ActiveWindow == (int)newHome)
            {
              return;
            }
          }
            // we like both 
          else
          {
            // if already in one home switch to the other
            if (GUIWindowManager.ActiveWindow == (int)GUIWindow.Window.WINDOW_HOME)
            {
              newHome = GUIWindow.Window.WINDOW_SECOND_HOME;
            }
            else if (GUIWindowManager.ActiveWindow == (int)GUIWindow.Window.WINDOW_SECOND_HOME)
            {
              newHome = GUIWindow.Window.WINDOW_HOME;
            }
          }
          homeMsg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_GOTO_WINDOW, 0, 0, 0, (int)newHome, 0, null);
          GUIWindowManager.SendThreadMessage(homeMsg);
          return;

          //exit mediaportal
        case Action.ActionType.ACTION_EXIT:
          Log.Info("Main: Exit requested");
          // is the minimize on gui option set?  If so, minimize to tray...
          if (_minimizeOnGuiExit && !_shuttingDown)
          {
            if (WindowState != FormWindowState.Minimized)
            {
              Log.Info("Main: Minimizing to tray on GUI exit and restoring taskbar");
            }
            WindowState = FormWindowState.Minimized;
            Hide();
            if (autoHideTaskbar)
            {
              // only re-show the startbar if MP is the one that has hidden it.
              Win32API.EnableStartBar(true);
              Win32API.ShowStartBar(true);
            }
            if (g_Player.IsVideo || g_Player.IsTV || g_Player.IsDVD)
            {
              if (g_Player.Volume > 0)
              {
                m_iVolume = g_Player.Volume;
                g_Player.Volume = 0;
              }
              if (g_Player.Paused == false && !GUIGraphicsContext.IsVMR9Exclusive)
              {
                g_Player.Pause();
              }
            }
            return;
          }
          GUIGraphicsContext.CurrentState = GUIGraphicsContext.State.STOPPING;
          return;

        case Action.ActionType.ACTION_MPRESTORE:
          {
            Log.Info("Main: Restore MP by action");
            Restore();
            if ((g_Player.IsVideo || g_Player.IsTV || g_Player.IsDVD) && m_iVolume > 0)
            {
              g_Player.Volume = m_iVolume;
              g_Player.ContinueGraph();
              if (g_Player.Paused && !GUIGraphicsContext.IsVMR9Exclusive)
              {
                g_Player.Pause();
              }
            }
          }
          return;

          //reboot pc
        case Action.ActionType.ACTION_POWER_OFF:
        case Action.ActionType.ACTION_SUSPEND:
        case Action.ActionType.ACTION_HIBERNATE:
        case Action.ActionType.ACTION_REBOOT:
          {
            //reboot
            Log.Info("Main: Reboot requested");
            bool okToChangePowermode = (action.fAmount1 == 1);

            if (!okToChangePowermode)
            {
              okToChangePowermode = PromptUserBeforeChangingPowermode(action);
            }

            if (okToChangePowermode)
            {
              switch (action.wID)
              {
                case Action.ActionType.ACTION_REBOOT:
                  restartOptions = RestartOptions.Reboot;
                  useRestartOptions = true;
                  GUIGraphicsContext.CurrentState = GUIGraphicsContext.State.STOPPING;
                  break;

                case Action.ActionType.ACTION_POWER_OFF:
                  restartOptions = RestartOptions.PowerOff;
                  useRestartOptions = true;
                  GUIGraphicsContext.CurrentState = GUIGraphicsContext.State.STOPPING;
                  base._shuttingDown = true;
                  break;

                case Action.ActionType.ACTION_SUSPEND:
                  if (IsSuspendOrHibernationAllowed())
                  {
                    restartOptions = RestartOptions.Suspend;
                    Utils.SuspendSystem(false);
                  }
                  else
                  {
                    Log.Info("Main: SUSPEND ignored since suspend graceperiod of {0} sec. is violated.", _suspendGracePeriodSec); 
                  }
                  break;

                case Action.ActionType.ACTION_HIBERNATE:
                  if (IsSuspendOrHibernationAllowed())
                  {
                    restartOptions = RestartOptions.Hibernate;
                    Utils.HibernateSystem(false);
                  }
                  else
                  {
                    Log.Info("Main: HIBERNATE ignored since hibernate graceperiod of {0} sec. is violated.", _suspendGracePeriodSec);
                  }
                  break;
              }
            }
          }
          return;

          //eject cd
        case Action.ActionType.ACTION_EJECTCD:
          Utils.EjectCDROM();
          return;

          //shutdown pc
        case Action.ActionType.ACTION_SHUTDOWN:
          {
            Log.Info("Main: Shutdown dialog");
            GUIDialogMenu dlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU);
            if (dlg != null)
            {
              dlg.Reset();
              dlg.SetHeading(GUILocalizeStrings.Get(498)); //Menu
              dlg.AddLocalizedString(1030); //PowerOff
              dlg.AddLocalizedString(1031); //Reboot
              dlg.AddLocalizedString(1032); //Suspend
              dlg.AddLocalizedString(1049); //Hibernate
              dlg.DoModal(GUIWindowManager.ActiveWindow);
              //RestartOptions option = RestartOptions.Suspend;
              if (dlg.SelectedId < 0)
              {
                GUIWindow win = GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_HOME);
                if (win != null)
                {
                  win.OnAction(new Action(Action.ActionType.ACTION_MOVE_LEFT, 0, 0));
                }
                return;
              }
              switch (dlg.SelectedId)
              {
                case 1030:
                  restartOptions = RestartOptions.PowerOff;
                  useRestartOptions = true;
                  GUIGraphicsContext.CurrentState = GUIGraphicsContext.State.STOPPING;
                  base._shuttingDown = true;
                  break;

                case 1031:
                  restartOptions = RestartOptions.Reboot;
                  useRestartOptions = true;
                  GUIGraphicsContext.CurrentState = GUIGraphicsContext.State.STOPPING;
                  base._shuttingDown = true;
                  break;

                case 1032:
                  restartOptions = RestartOptions.Suspend;
                  Utils.SuspendSystem(false);
                  break;

                case 1049:
                  restartOptions = RestartOptions.Hibernate;
                  Utils.HibernateSystem(false);
                  break;
              }
            }
            break;
          }

          //stop radio
        case Action.ActionType.ACTION_STOP:
          break;

          // Take Screenshot
        case Action.ActionType.ACTION_TAKE_SCREENSHOT:
          {
            try
            {
              string directory =
                string.Format("{0}\\MediaPortal Screenshots\\{1:0000}-{2:00}-{3:00}",
                              Environment.GetFolderPath(Environment.SpecialFolder.MyPictures),
                              DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
              if (!Directory.Exists(directory))
              {
                Log.Info("Main: Taking screenshot - Creating directory: {0}", directory);
                Directory.CreateDirectory(directory);
              }

              string fileName =
                string.Format("{0}\\{1:00}-{2:00}-{3:00}", directory, DateTime.Now.Hour,
                              DateTime.Now.Minute, DateTime.Now.Second);
              Log.Info("Main: Taking screenshot - Target: {0}.png", fileName);
              Surface backbuffer = GUIGraphicsContext.DX9Device.GetBackBuffer(0, 0, BackBufferType.Mono);
              SurfaceLoader.Save(fileName + ".png", ImageFileFormat.Png, backbuffer);
              backbuffer.Dispose();
              Log.Info("Main: Taking screenshot done");
            }
            catch (Exception ex)
            {
              Log.Info("Main: Error taking screenshot: {0}", ex.Message);
            }
          }
          break;

        case Action.ActionType.ACTION_SHOW_GUI:
          {
            // can we handle the switch to fullscreen?
            if (!GUIGraphicsContext.IsFullScreenVideo && g_Player.ShowFullScreenWindow())
            {
              return;
            }
          }
          break;
      }
      if (g_Player.Playing)
      {
        switch (action.wID)
        {
            //show DVD menu
          case Action.ActionType.ACTION_DVD_MENU:
            if (g_Player.IsDVD)
            {
              g_Player.OnAction(action);
              return;
            }
            break;

            //DVD: goto previous chapter
            //play previous item from playlist;
          case Action.ActionType.ACTION_PREV_ITEM:
          case Action.ActionType.ACTION_PREV_CHAPTER:
            if (g_Player.IsDVD || g_Player.HasChapters)
            {
              action = new Action(Action.ActionType.ACTION_PREV_CHAPTER, 0, 0);
              g_Player.OnAction(action);
              return;
            }

            if (!ActionTranslator.HasKeyMapped(GUIWindowManager.ActiveWindowEx, action.m_key))
            {
              playlistPlayer.PlayPrevious();
            }
            break;

            //play next item from playlist;
            //DVD: goto next chapter
          case Action.ActionType.ACTION_NEXT_CHAPTER:
          case Action.ActionType.ACTION_NEXT_ITEM:
            if (g_Player.IsDVD || g_Player.HasChapters)
            {
              action = new Action(Action.ActionType.ACTION_NEXT_CHAPTER, 0, 0);
              g_Player.OnAction(action);
              return;
            }

            if (!ActionTranslator.HasKeyMapped(GUIWindowManager.ActiveWindowEx, action.m_key))
            {
              playlistPlayer.PlayNext();
            }
            break;

            //stop playback
          case Action.ActionType.ACTION_STOP:

            //When MyPictures Plugin shows the pictures we want to stop the slide show only, not the player
            if (
              (GUIWindow.Window)(Enum.Parse(typeof (GUIWindow.Window), GUIWindowManager.ActiveWindow.ToString())) ==
              GUIWindow.Window.WINDOW_SLIDESHOW)
            {
              break;
            }

            if (!g_Player.IsTV || !GUIGraphicsContext.IsFullScreenVideo)
            {
              Log.Info("Main: Stopping media");
              g_Player.Stop();
              return;
            }
            break;

            //Jump to Music Now Playing
          case Action.ActionType.ACTION_JUMP_MUSIC_NOW_PLAYING:
            if (g_Player.IsMusic && GUIWindowManager.ActiveWindow != (int)GUIWindow.Window.WINDOW_MUSIC_PLAYING_NOW)
            {
              GUIWindowManager.ActivateWindow((int)GUIWindow.Window.WINDOW_MUSIC_PLAYING_NOW);
            }
            break;

            //play music
            //resume playback
          case Action.ActionType.ACTION_PLAY:
          case Action.ActionType.ACTION_MUSIC_PLAY:
            // Don't start playing from the beginning if we press play to return to normal speed
            if (g_Player.IsMusic && g_Player.Speed != 1)
            {
              // Attention: GUIMusicGenre / GUIMusicFiles need to be handled differently. we reset the speed there
              if (GUIWindowManager.ActiveWindow == (int)GUIWindow.Window.WINDOW_MUSIC_FILES ||
                  GUIWindowManager.ActiveWindow == (int)GUIWindow.Window.WINDOW_MUSIC_GENRE)
              {
                return;
              }
              g_Player.Speed = 1;
              return;
            }

            g_Player.StepNow();
            g_Player.Speed = 1;

            if (g_Player.Paused)
            {
              g_Player.Pause();
            }
            break;

            //pause (or resume playback)
          case Action.ActionType.ACTION_PAUSE:
            g_Player.Pause();
            break;

            //fast forward...
          case Action.ActionType.ACTION_FORWARD:
          case Action.ActionType.ACTION_MUSIC_FORWARD:
            {
              if (g_Player.Paused)
              {
                g_Player.Pause();
              }
              g_Player.Speed = Utils.GetNextForwardSpeed(g_Player.Speed);
              break;
            }

            //fast rewind...
          case Action.ActionType.ACTION_REWIND:
          case Action.ActionType.ACTION_MUSIC_REWIND:
            {
              if (g_Player.Paused)
              {
                g_Player.Pause();
              }
              g_Player.Speed = Utils.GetNextRewindSpeed(g_Player.Speed);
              break;
            }
        }
      }
      GUIWindowManager.OnAction(action);
    }
    catch (FileNotFoundException ex)
    {
      Log.Error(ex);
      MessageBox.Show("File not found:" + ex.FileName, "MediaPortal", MessageBoxButtons.OK, MessageBoxIcon.Error);
      Close();
    }
    catch (Exception ex)
    {
      Log.Error(ex);
      Log.Error("  exception: {0} {1} {2}", ex.Message, ex.Source, ex.StackTrace);
#if !DEBUG
      throw new Exception("exception occured", ex);
#endif
    }
  }
Example #28
0
  /// <summary>
  /// 
  /// </summary>
  /// <param name="action"></param>
  private void OnAction(Action action)
  {
    try
    {
      // hack/fix for lastactivemodulefullscreen
      // when recovering from hibernation/standby after closing with remote control somehow a F9 (keycode 120) onkeydown event is thrown from outside
      // we are currently filtering it away.
      // sometimes more than one F9 keydown event fired.
      // if these events are not filtered away the F9 context menu is shown on the restored/shown module.
      if ((action.wID == Action.ActionType.ACTION_CONTEXT_MENU || _suspended) && (_showLastActiveModule))
      {
        if (_ignoreContextMenuAction)
        {
          _ignoreContextMenuAction = false;
          _lastContextMenuAction = DateTime.Now;
          return;
        }
        
        if (_lastContextMenuAction != DateTime.MaxValue)
        {
          TimeSpan ts = _lastContextMenuAction - DateTime.Now;
          if (ts.TotalMilliseconds > -100)
          {
            _ignoreContextMenuAction = false;
            _lastContextMenuAction = DateTime.Now;
            return;
          }
        }
        _lastContextMenuAction = DateTime.Now;
      }

      GUIWindow window;
      if (action.IsUserAction())
      {
        GUIGraphicsContext.ResetLastActivity();
      }

      switch (action.wID)
      {
        // record current tv program
        case Action.ActionType.ACTION_RECORD:
          if ((GUIGraphicsContext.IsTvWindow(GUIWindowManager.ActiveWindowEx) &&
               GUIWindowManager.ActiveWindowEx != (int)GUIWindow.Window.WINDOW_TVGUIDE) &&
              (GUIWindowManager.ActiveWindowEx != (int)GUIWindow.Window.WINDOW_DIALOG_TVGUIDE))
          {
            GUIWindow tvHome = GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_TV);
            if (tvHome != null && tvHome.GetID != GUIWindowManager.ActiveWindow)
            {
              tvHome.OnAction(action);
              return;
            }
          }
          break;

        // TV: zap to previous channel
        case Action.ActionType.ACTION_PREV_CHANNEL:
          if (!GUIWindowManager.IsRouted)
          {
            window = GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_TV);
            window.OnAction(action);
            return;
          }
          break;

        // TV: zap to next channel
        case Action.ActionType.ACTION_NEXT_CHANNEL:
          if (!GUIWindowManager.IsRouted)
          {
            window = GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_TV);
            window.OnAction(action);
            return;
          }
          break;

        // TV: zap to last channel viewed
        case Action.ActionType.ACTION_LAST_VIEWED_CHANNEL: // mPod
          if (!GUIWindowManager.IsRouted)
          {
            window = GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_TV);
            window.OnAction(action);
            return;
          }
          break;

        // toggle between windowed and fullscreen mode
        case Action.ActionType.ACTION_TOGGLE_WINDOWED_FULLSCREEN:
          ToggleFullscreen();
          return;

        // mute or unmute audio
        case Action.ActionType.ACTION_VOLUME_MUTE:
          VolumeHandler.Instance.IsMuted = !VolumeHandler.Instance.IsMuted;
          break;

        // decrease volume 
        case Action.ActionType.ACTION_VOLUME_DOWN:
          VolumeHandler.Instance.Volume = VolumeHandler.Instance.Previous;
          break;

        // increase volume 
        case Action.ActionType.ACTION_VOLUME_UP:
          VolumeHandler.Instance.Volume = VolumeHandler.Instance.Next;
          break;

        // toggle live tv in background
        case Action.ActionType.ACTION_BACKGROUND_TOGGLE:
          // show livetv or video as background instead of the static GUI background
          // toggle livetv/video in background on/off
          if (GUIGraphicsContext.ShowBackground)
          {
            Log.Info("Main: Using live TV as background");
            // if on, but we're not playing any video or watching tv
            if (GUIGraphicsContext.Vmr9Active)
            {
              GUIGraphicsContext.ShowBackground = false;
            }
            else
            {
              // show warning message
              var msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SHOW_WARNING, 0, 0, 0, 0, 0, 0) {Param1 = 727, Param2 = 728, Param3 = 729};
              GUIWindowManager.SendMessage(msg);
              return;
            }
          }
          else
          {
            Log.Info("Main: Using GUI as background");
            GUIGraphicsContext.ShowBackground = true;
          }
          break;

        // switch between several home windows
        case Action.ActionType.ACTION_SWITCH_HOME:
          GUIWindow.Window newHome = _startWithBasicHome
                                       ? GUIWindow.Window.WINDOW_SECOND_HOME
                                       : GUIWindow.Window.WINDOW_HOME;
          // do we prefer to use only one home screen?
          if (_useOnlyOneHome)
          {
            // skip if we are already in there
            if (GUIWindowManager.ActiveWindow == (int)newHome)
            {
              break;
            }
          }
          // we like both 
          else
          {
            // if already in one home switch to the other
            switch (GUIWindowManager.ActiveWindow)
            {
              case (int)GUIWindow.Window.WINDOW_HOME:
                newHome = GUIWindow.Window.WINDOW_SECOND_HOME;
                break;

              case (int)GUIWindow.Window.WINDOW_SECOND_HOME:
                newHome = GUIWindow.Window.WINDOW_HOME;
                break;
            }
          }
          var homeMsg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_GOTO_WINDOW, 0, 0, 0, (int)newHome, 0, null);
          GUIWindowManager.SendThreadMessage(homeMsg);
          // Stop Video for MyPictures when going to home
          if (g_Player.IsPicture)
          {
            GUISlideShow._slideDirection = 0;
            g_Player.Stop();
          }
          break;

        case Action.ActionType.ACTION_MPRESTORE:
          Log.Info("Main: Restore MP by action");
          RestoreFromTray();
          if ((g_Player.IsVideo || g_Player.IsTV || g_Player.IsDVD) && Volume > 0)
          {
            g_Player.Volume = Volume;
            g_Player.ContinueGraph();
            if (g_Player.Paused && !GUIGraphicsContext.IsVMR9Exclusive)
            {
              g_Player.Pause();
            }
          }
          break;

        // reboot pc
        case Action.ActionType.ACTION_POWER_OFF:
        case Action.ActionType.ACTION_SUSPEND:
        case Action.ActionType.ACTION_HIBERNATE:
        case Action.ActionType.ACTION_REBOOT:
          // reboot
          Log.Info("Main: Reboot requested");
          bool okToChangePowermode = (Math.Abs(action.fAmount1 - 1) < float.Epsilon);

          if (!okToChangePowermode)
          {
            okToChangePowermode = PromptUserBeforeChangingPowermode(action);
          }

          if (okToChangePowermode)
          {
            switch (action.wID)
            {
              case Action.ActionType.ACTION_REBOOT:
                _restartOptions = RestartOptions.Reboot;
                _useRestartOptions = true;
                GUIGraphicsContext.CurrentState = GUIGraphicsContext.State.STOPPING;
                break;

              case Action.ActionType.ACTION_POWER_OFF:
                _restartOptions = RestartOptions.PowerOff;
                _useRestartOptions = true;
                GUIGraphicsContext.CurrentState = GUIGraphicsContext.State.STOPPING;
                ShuttingDown = true;
                break;

              case Action.ActionType.ACTION_SUSPEND:
                if (IsSuspendOrHibernationAllowed())
                {
                  _restartOptions = RestartOptions.Suspend;
                  Utils.SuspendSystem(false);
                }
                else
                {
                  Log.Info("Main: SUSPEND ignored since suspend graceperiod of {0} sec. is violated.", _suspendGracePeriodSec); 
                }
                break;

              case Action.ActionType.ACTION_HIBERNATE:
                if (IsSuspendOrHibernationAllowed())
                {
                  _restartOptions = RestartOptions.Hibernate;
                  Utils.HibernateSystem(false);
                }
                else
                {
                  Log.Info("Main: HIBERNATE ignored since hibernate graceperiod of {0} sec. is violated.", _suspendGracePeriodSec);
                }
                break;
            }
          }
          break;

        // eject cd
        case Action.ActionType.ACTION_EJECTCD:
          Utils.EjectCDROM();
          break;

        // shutdown pc
        case Action.ActionType.ACTION_SHUTDOWN:
          Log.Info("Main: Shutdown dialog");
          var dlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU);
          if (dlg != null)
          {
            dlg.Reset();
            dlg.SetHeading(GUILocalizeStrings.Get(498)); //Menu
            dlg.AddLocalizedString(1057); //Exit MediaPortal
            dlg.AddLocalizedString(1058); //Restart MediaPortal
            dlg.AddLocalizedString(1032); //Suspend
            dlg.AddLocalizedString(1049); //Hibernate
            dlg.AddLocalizedString(1031); //Reboot
            dlg.AddLocalizedString(1030); //PowerOff
            dlg.DoModal(GUIWindowManager.ActiveWindow);

            if (dlg.SelectedId >= 0)
            {
              switch (dlg.SelectedId)
              {
                case 1057:
                  ExitMP();
                  return;

                case 1058:
                  GUIGraphicsContext.CurrentState = GUIGraphicsContext.State.STOPPING;
                  Utils.RestartMePo();
                  break;

                case 1030:
                  _restartOptions = RestartOptions.PowerOff;
                  _useRestartOptions = true;
                  GUIGraphicsContext.CurrentState = GUIGraphicsContext.State.STOPPING;
                  ShuttingDown = true;
                  break;

                case 1031:
                  _restartOptions = RestartOptions.Reboot;
                  _useRestartOptions = true;
                  GUIGraphicsContext.CurrentState = GUIGraphicsContext.State.STOPPING;
                  ShuttingDown = true;
                  break;

                case 1032:
                  _restartOptions = RestartOptions.Suspend;
                  Utils.SuspendSystem(false);
                  break;

                case 1049:
                  _restartOptions = RestartOptions.Hibernate;
                  Utils.HibernateSystem(false);
                  break;
              }
            }
            else
            {
              GUIWindow win = GUIWindowManager.GetWindow((int) GUIWindow.Window.WINDOW_HOME);
              if (win != null)
              {
                win.OnAction(new Action(Action.ActionType.ACTION_MOVE_LEFT, 0, 0));
              }
            }
          }
          break;

        // exit Mediaportal
        case Action.ActionType.ACTION_EXIT:
          ExitMP();
          break;

        // stop radio
        case Action.ActionType.ACTION_STOP:
          break;

        // Take Screen shot
        case Action.ActionType.ACTION_TAKE_SCREENSHOT:
          try
          {
            string directory = string.Format("{0}\\MediaPortal Screenshots\\{1:0000}-{2:00}-{3:00}",
                                             Environment.GetFolderPath(Environment.SpecialFolder.MyPictures),
                                             DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            if (!Directory.Exists(directory))
            {
              Log.Info("Main: Taking screenshot - Creating directory: {0}", directory);
              Directory.CreateDirectory(directory);
            }

            string fileName = string.Format("{0}\\{1:00}-{2:00}-{3:00}", directory, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
            Log.Info("Main: Taking screenshot - Target: {0}.png", fileName);
            Surface backbuffer = GUIGraphicsContext.DX9Device.GetBackBuffer(0, 0, BackBufferType.Mono);
            SurfaceLoader.Save(fileName + ".png", ImageFileFormat.Png, backbuffer);
            backbuffer.Dispose();
            Log.Info("Main: Taking screenshot done");
          }
          catch (Exception ex)
          {
            Log.Info("Main: Error taking screenshot: {0}", ex.Message);
          }
          break;

        case Action.ActionType.ACTION_SHOW_GUI:
          // can we handle the switch to fullscreen?
          if (!GUIGraphicsContext.IsFullScreenVideo && g_Player.ShowFullScreenWindow())
          {
            return;
          }
          break;
      }

      if (g_Player.Playing)
      {
        string activeWindowName;
        GUIWindow.Window activeWindow;

        switch (action.wID)
        {
          // show DVD menu
          case Action.ActionType.ACTION_DVD_MENU:
            if (g_Player.IsDVD)
            {
              g_Player.OnAction(action);
              return;
            }
            break;

          // DVD: goto previous chapter
          // play previous item from playlist;
          case Action.ActionType.ACTION_PREV_ITEM:
          case Action.ActionType.ACTION_PREV_CHAPTER:
            if (g_Player.IsDVD || g_Player.HasChapters)
            {
              action = new Action(Action.ActionType.ACTION_PREV_CHAPTER, 0, 0);
              g_Player.OnAction(action);
              break;
            }
            // When MyPictures Plugin shows the pictures/videos we don't want to change music track
            activeWindowName = GUIWindowManager.ActiveWindow.ToString(CultureInfo.InvariantCulture);
            activeWindow = (GUIWindow.Window) Enum.Parse(typeof(GUIWindow.Window), activeWindowName);
            if (!ActionTranslator.HasKeyMapped(GUIWindowManager.ActiveWindowEx, action.m_key) &&
                (activeWindow != GUIWindow.Window.WINDOW_SLIDESHOW && !g_Player.IsPicture))
            {
              PlaylistPlayer.PlayPrevious();
            }
            break;

          // play next item from playlist;
          // DVD: goto next chapter
          case Action.ActionType.ACTION_NEXT_CHAPTER:
          case Action.ActionType.ACTION_NEXT_ITEM:
            if (g_Player.IsDVD || g_Player.HasChapters)
            {
              action = new Action(Action.ActionType.ACTION_NEXT_CHAPTER, 0, 0);
              g_Player.OnAction(action);
              break;
            }
            // When MyPictures Plugin shows the pictures/videos we don't want to change music track
            activeWindowName = GUIWindowManager.ActiveWindow.ToString(CultureInfo.InvariantCulture);
            activeWindow = (GUIWindow.Window) Enum.Parse(typeof(GUIWindow.Window), activeWindowName);
            if (!ActionTranslator.HasKeyMapped(GUIWindowManager.ActiveWindowEx, action.m_key) && (activeWindow != GUIWindow.Window.WINDOW_SLIDESHOW && !g_Player.IsPicture))
            {
              PlaylistPlayer.PlayNext();
            }
            break;

          // stop playback
          case Action.ActionType.ACTION_STOP:
            // When MyPictures Plugin shows the pictures we want to stop the slide show only, not the player
            activeWindowName = GUIWindowManager.ActiveWindow.ToString(CultureInfo.InvariantCulture);
            activeWindow = (GUIWindow.Window)Enum.Parse(typeof(GUIWindow.Window), activeWindowName);
            if ((activeWindow == GUIWindow.Window.WINDOW_SLIDESHOW) || (activeWindow == GUIWindow.Window.WINDOW_FULLSCREEN_VIDEO && g_Player.IsPicture) && g_Player.Playing)
            {
              break;
            }

            if (!g_Player.IsTV || !GUIGraphicsContext.IsFullScreenVideo)
            {
              Log.Info("Main: Stopping media");
              if (g_Player.IsPicture)
              {
                GUISlideShow._slideDirection = 0;
              }
              g_Player.Stop();
            }
            break;

          // Jump to Music Now Playing
          case Action.ActionType.ACTION_JUMP_MUSIC_NOW_PLAYING:
            if (g_Player.IsMusic)
            {
              if (GUIWindowManager.ActiveWindow == (int)GUIWindow.Window.WINDOW_MUSIC_PLAYING_NOW)
              {
                GUIWindowManager.ShowPreviousWindow();
            }
              else
              {
                GUIWindowManager.ActivateWindow((int) GUIWindow.Window.WINDOW_MUSIC_PLAYING_NOW);
              }
            }
            break;

          // play music
          // resume playback
          case Action.ActionType.ACTION_PLAY:
          case Action.ActionType.ACTION_MUSIC_PLAY:
            // Don't start playing from the beginning if we press play to return to normal speed
            if (g_Player.IsMusic && g_Player.Speed != 1 &&
                (GUIWindowManager.ActiveWindow != (int) GUIWindow.Window.WINDOW_MUSIC_FILES &&
                 GUIWindowManager.ActiveWindow != (int) GUIWindow.Window.WINDOW_MUSIC_GENRE))
            {
              g_Player.Speed = 1;
              break;
            }

            g_Player.StepNow();
            g_Player.Speed = 1;

            if (g_Player.Paused)
            {
              g_Player.Pause();
            }
            break;

          // pause (or resume playback)
          case Action.ActionType.ACTION_PAUSE:
            // When MyPictures Plugin shows the pictures we want to pause the slide show only, not the player
            activeWindowName = GUIWindowManager.ActiveWindow.ToString(CultureInfo.InvariantCulture);
            activeWindow = (GUIWindow.Window)Enum.Parse(typeof(GUIWindow.Window), activeWindowName);
            if ((activeWindow == GUIWindow.Window.WINDOW_SLIDESHOW) ||
                (activeWindow == GUIWindow.Window.WINDOW_FULLSCREEN_VIDEO && g_Player.IsPicture) && g_Player.Playing && !g_Player.IsVideo)
            {
              break;
            }
            g_Player.Pause();

            break;

          // fast forward...
          case Action.ActionType.ACTION_FORWARD:
            {
              if (g_Player.Paused)
              {
                g_Player.Pause();
              }
              g_Player.Speed = Utils.GetNextForwardSpeed(g_Player.Speed);
              break;
            }

          // Decide if we want to have CD style of FF or Skip steps
          case Action.ActionType.ACTION_MUSIC_FORWARD:
            // When MyPictures Plugin shows the pictures/videos we don't want to change music track
            activeWindowName = GUIWindowManager.ActiveWindow.ToString(CultureInfo.InvariantCulture);
            activeWindow = (GUIWindow.Window) Enum.Parse(typeof(GUIWindow.Window), activeWindowName);
            if (!ActionTranslator.HasKeyMapped(GUIWindowManager.ActiveWindowEx, action.m_key) && (activeWindow != GUIWindow.Window.WINDOW_SLIDESHOW && !g_Player.IsPicture || g_Player.IsVideo))
            {
              if (g_Player.Paused)
              {
                g_Player.Pause();
              }
              if (!MediaPortal.MusicPlayer.BASS.Config.UseSkipSteps)
              {
                g_Player.Speed = Utils.GetNextForwardSpeed(g_Player.Speed);
              }
            }
            break;
 
          // fast rewind...
          case Action.ActionType.ACTION_REWIND:
            {
              if (g_Player.Paused)
              {
                g_Player.Pause();
              }
              g_Player.Speed = Utils.GetNextRewindSpeed(g_Player.Speed);
              break;
            }

          // Decide if we want to have CD style of Rew or Skip steps
          case Action.ActionType.ACTION_MUSIC_REWIND:
            // When MyPictures Plugin shows the pictures/videos we don't want to change music track
            activeWindowName = GUIWindowManager.ActiveWindow.ToString(CultureInfo.InvariantCulture);
            activeWindow = (GUIWindow.Window) Enum.Parse(typeof(GUIWindow.Window), activeWindowName);
            if (!ActionTranslator.HasKeyMapped(GUIWindowManager.ActiveWindowEx, action.m_key) && (activeWindow != GUIWindow.Window.WINDOW_SLIDESHOW && !g_Player.IsPicture || g_Player.IsVideo))
            {
              if (g_Player.Paused)
              {
                g_Player.Pause();
              }
              if (!MediaPortal.MusicPlayer.BASS.Config.UseSkipSteps)
              {
                g_Player.Speed = Utils.GetNextRewindSpeed(g_Player.Speed);
              }
            }
            break;
         }
      }
      GUIWindowManager.OnAction(action);
    }
    catch (FileNotFoundException ex)
    {
      Log.Error(ex);
      // ReSharper disable LocalizableElement
      MessageBox.Show("File not found:" + ex.FileName, "MediaPortal", MessageBoxButtons.OK, MessageBoxIcon.Error);
      // ReSharper restore LocalizableElement
      Close();
    }
    catch (Exception ex)
    {
      Log.Error(ex);
      Log.Error("Exception: {0} {1} {2}", ex.Message, ex.Source, ex.StackTrace);
      #if !DEBUG
      throw new Exception("exception occurred", ex);
      #endif
    }
  }
    private void SafeExitWindows(RestartOptions how, bool force, WindowsController.AfterExitWindowsHandler after)
    {
      if (_settings.GetSetting("SingleSeat").Get<bool>())
      {
        // shutdown method and force mode are ignored by delegated suspend/hibernate requests
        Log.Debug("PSClientPlugin: Delegating shutdown request to tvserver: {0}", how);

        if (after != null)
        {
          Log.Error("PSClientPlugin: SafeExitWindows, after != null is not supported yet");
        }

        try
        {
          // persist the next wakeup datetime, this way 'resume last active module' feature is able to tell the difference between a wakeup done by 
          // a user or by the PS plugin
          using (Settings xmlwriter = new MPSettings())
          {
            DateTime nextWakeUp = GetNextWakeupTime(DateTime.Now);
            xmlwriter.SetValue("psclientplugin", "nextwakeup", nextWakeUp.ToString());
            string res = xmlwriter.GetValueAsString("psclientplugin", "nextwakeup", DateTime.MaxValue.ToString());
          }

          _isSuspendInProgress = true;
          Log.Debug("PSClientPlugin: Informing handlers about UserShutdownNow");
          UserShutdownNow();

          if (RemotePowerControl.Isconnected)
          {
            RemotePowerControl.Instance.SuspendSystem("PowerSchedulerClientPlugin", (int)how, force);
          }
        }
        catch (Exception e)
        {
          _isSuspendInProgress = false;
          Log.Error("PSClientPlugin: SuspendSystem failed! {0} {1}", e.Message, e.StackTrace);
        }
      }
      else
      {
        lock (this)
        {
          DateTime now = DateTime.Now;

          // block concurrent request?
          if (_ignoreSuspendUntil > now)
          {
            Log.Info("PSClientPlugin: Concurrent shutdown was ignored: {0} ; force: {1}", how, force);
            return;
          }

          // block any other request forever (for now)
          _ignoreSuspendUntil = DateTime.MaxValue;
        }
        Log.Info("PSClientPlugin: Entering shutdown {0} ; forced: {1} -- kick off shutdown thread", how, force);
        SafeExitWindowsThreadEnv data = new SafeExitWindowsThreadEnv();
        data.that = this;
        data.how = how;
        data.force = force;
        data.after = after;
        (new Thread(SafeExitWindowsThread)).Start(data);
      }
    }