Index: /trunk/src/VBox/Main/idl/VirtualBox.xidl
===================================================================
--- /trunk/src/VBox/Main/idl/VirtualBox.xidl	(revision 46774)
+++ /trunk/src/VBox/Main/idl/VirtualBox.xidl	(revision 46775)
@@ -16847,7 +16847,29 @@
   -->
 
+  <enum
+    name="Reason"
+    uuid="e7e8e097-299d-4e98-8bbc-c31c2d47d0cc"
+    >
+    <desc>
+      Internal event reason type.
+    </desc>
+
+    <const name="Unspecified"       value="0">
+      <desc>Null value, means "no known reason".</desc>
+    </const>
+    <const name="HostSuspend"       value="1">
+      <desc>Host is being suspended (power management event).</desc>
+    </const>
+    <const name="HostResume"        value="2">
+      <desc>Host is being resumed (power management event).</desc>
+    </const>
+    <const name="HostBatteryLow"    value="3">
+      <desc>Host is running low on battery (power management event).</desc>
+    </const>
+  </enum>
+
   <interface
     name="IInternalSessionControl" extends="$unknown"
-    uuid="0ba8d8b3-204b-448e-99c2-242eaa666ea8"
+    uuid="cddf451c-a006-4c33-8245-63b3c9ae6586"
     internal="yes"
     wsmap="suppress"
@@ -17345,4 +17367,67 @@
       <param name="enable" type="boolean" dir="in">
         <desc>True enables statistics collection.</desc>
+      </param>
+    </method>
+
+    <method name="pauseWithReason">
+      <desc>
+        Internal method for triggering a VM pause with a specified reason code.
+        The reason code can be interpreted by device/drivers and thus it might
+        behave slightly differently than a normal VM pause.
+
+        <result name="VBOX_E_INVALID_VM_STATE">
+          Virtual machine not in Running state.
+        </result>
+        <result name="VBOX_E_VM_ERROR">
+          Virtual machine error in suspend operation.
+        </result>
+        <see><link to="Console::pause"/></see>
+      </desc>
+
+      <param name="reason" type="Reason" dir="in">
+        <desc>Specify the best matching reason code please.</desc>
+      </param>
+    </method>
+
+    <method name="resumeWithReason">
+      <desc>
+        Internal method for triggering a VM resume with a specified reason code.
+        The reason code can be interpreted by device/drivers and thus it might
+        behave slightly differently than a normal VM resume.
+
+        <result name="VBOX_E_INVALID_VM_STATE">
+          Virtual machine not in Paused state.
+        </result>
+        <result name="VBOX_E_VM_ERROR">
+          Virtual machine error in resume operation.
+        </result>
+        <see><link to="Console::resume"/></see>
+      </desc>
+
+      <param name="reason" type="Reason" dir="in">
+        <desc>Specify the best matching reason code please.</desc>
+      </param>
+    </method>
+
+    <method name="saveStateWithReason">
+      <desc>
+        Internal method for triggering a VM save state with a specified reason
+        code. The reason code can be interpreted by device/drivers and thus it
+        might behave slightly differently than a normal VM save state.
+
+        <result name="VBOX_E_INVALID_VM_STATE">
+          Virtual machine state neither Running nor Paused.
+        </result>
+        <result name="VBOX_E_FILE_ERROR">
+          Failed to create directory for saved state file.
+        </result>
+        <see><link to="Console::saveState"/></see>
+      </desc>
+
+      <param name="reason" type="Reason" dir="in">
+        <desc>Specify the best matching reason code please.</desc>
+      </param>
+      <param name="progress" type="IProgress" dir="return">
+        <desc>Progress object to track the operation completion.</desc>
       </param>
     </method>
Index: /trunk/src/VBox/Main/include/ConsoleImpl.h
===================================================================
--- /trunk/src/VBox/Main/include/ConsoleImpl.h	(revision 46774)
+++ /trunk/src/VBox/Main/include/ConsoleImpl.h	(revision 46775)
@@ -258,4 +258,8 @@
     }
     void enableVMMStatistics(BOOL aEnable);
+
+    HRESULT pause(Reason_T aReason);
+    HRESULT resume(Reason_T aReason);
+    HRESULT saveState(Reason_T aReason, IProgress **aProgress);
 
     // callback callers (partly; for some events console callbacks are notified
Index: /trunk/src/VBox/Main/include/Global.h
===================================================================
--- /trunk/src/VBox/Main/include/Global.h	(revision 46774)
+++ /trunk/src/VBox/Main/include/Global.h	(revision 46775)
@@ -194,4 +194,12 @@
 
     /**
+     * Stringify a reason.
+     *
+     * @returns Pointer to a read only string.
+     * @param   aReason     The reason code.
+     */
+    static const char *stringifyReason(Reason_T aReason);
+
+    /**
      * Try convert a COM status code to a VirtualBox status code (VBox/err.h).
      *
Index: /trunk/src/VBox/Main/include/HostPower.h
===================================================================
--- /trunk/src/VBox/Main/include/HostPower.h	(revision 46774)
+++ /trunk/src/VBox/Main/include/HostPower.h	(revision 46775)
@@ -5,5 +5,5 @@
 
 /*
- * Copyright (C) 2006-2010 Oracle Corporation
+ * Copyright (C) 2006-2013 Oracle Corporation
  *
  * This file is part of VirtualBox Open Source Edition (OSE), as
@@ -20,5 +20,4 @@
 
 #include "VirtualBoxBase.h"
-#include "MachineImpl.h"
 
 #include <vector>
@@ -29,25 +28,18 @@
 #endif /* RT_OS_DARWIN */
 
-typedef enum
-{
-    HostPowerEvent_Suspend,
-    HostPowerEvent_Resume,
-    HostPowerEvent_BatteryLow
-} HostPowerEvent;
-
 class HostPowerService
 {
 public:
 
-    HostPowerService (VirtualBox *aVirtualBox);
+    HostPowerService(VirtualBox *aVirtualBox);
     virtual ~HostPowerService();
 
-    void    notify (HostPowerEvent aEvent);
+    void notify(Reason_T aReason);
 
 protected:
 
-    VirtualBox              *mVirtualBox;
+    VirtualBox *mVirtualBox;
 
-    std::vector< ComPtr<IConsole> > mConsoles;
+    std::vector<ComPtr<IInternalSessionControl> > mSessionControls;
 };
 
@@ -65,5 +57,5 @@
 private:
 
-    static DECLCALLBACK(int) NotificationThread (RTTHREAD ThreadSelf, void *pInstance);
+    static DECLCALLBACK(int) NotificationThread(RTTHREAD ThreadSelf, void *pInstance);
     static LRESULT CALLBACK  WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
 
@@ -79,14 +71,14 @@
 public:
 
-    HostPowerServiceDarwin (VirtualBox *aVirtualBox);
+    HostPowerServiceDarwin(VirtualBox *aVirtualBox);
     virtual ~HostPowerServiceDarwin();
 
 private:
 
-    static DECLCALLBACK(int) powerChangeNotificationThread (RTTHREAD ThreadSelf, void *pInstance);
-    static void powerChangeNotificationHandler (void *pvData, io_service_t service, natural_t messageType, void *pMessageArgument);
-    static void lowPowerHandler (void *pvData);
+    static DECLCALLBACK(int) powerChangeNotificationThread(RTTHREAD ThreadSelf, void *pInstance);
+    static void powerChangeNotificationHandler(void *pvData, io_service_t service, natural_t messageType, void *pMessageArgument);
+    static void lowPowerHandler(void *pvData);
 
-    void checkBatteryCriticalLevel (bool *pfCriticalChanged = NULL);
+    void checkBatteryCriticalLevel(bool *pfCriticalChanged = NULL);
 
     /* Private member vars */
Index: /trunk/src/VBox/Main/include/SessionImpl.h
===================================================================
--- /trunk/src/VBox/Main/include/SessionImpl.h	(revision 46774)
+++ /trunk/src/VBox/Main/include/SessionImpl.h	(revision 46775)
@@ -5,5 +5,5 @@
 
 /*
- * Copyright (C) 2006-2012 Oracle Corporation
+ * Copyright (C) 2006-2013 Oracle Corporation
  *
  * This file is part of VirtualBox Open Source Edition (OSE), as
@@ -117,4 +117,7 @@
                                  IProgress *aProgress);
     STDMETHOD(EnableVMMStatistics)(BOOL aEnable);
+    STDMETHOD(PauseWithReason)(Reason_T aReason);
+    STDMETHOD(ResumeWithReason)(Reason_T aReason);
+    STDMETHOD(SaveStateWithReason)(Reason_T aReason, IProgress **aProgress);
 
 private:
Index: /trunk/src/VBox/Main/src-all/Global.cpp
===================================================================
--- /trunk/src/VBox/Main/src-all/Global.cpp	(revision 46774)
+++ /trunk/src/VBox/Main/src-all/Global.cpp	(revision 46775)
@@ -451,4 +451,24 @@
 }
 
+
+/*static*/ const char *
+Global::stringifyReason(Reason_T aReason)
+{
+    switch (aReason)
+    {
+        case Reason_Unspecified:      return "unspecified";
+        case Reason_HostSuspend:      return "host suspend";
+        case Reason_HostResume:       return "host resume";
+        case Reason_HostBatteryLow:   return "host battery low";
+        default:
+        {
+            AssertMsgFailed(("%d (%#x)\n", aReason, aReason));
+            static char s_szMsg[48];
+            RTStrPrintf(s_szMsg, sizeof(s_szMsg), "invalid reason %#010x\n", aReason);
+            return s_szMsg;
+        }
+    }
+}
+
 /*static*/ int
 Global::vboxStatusCodeFromCOM(HRESULT aComStatus)
Index: /trunk/src/VBox/Main/src-client/ConsoleImpl.cpp
===================================================================
--- /trunk/src/VBox/Main/src-client/ConsoleImpl.cpp	(revision 46774)
+++ /trunk/src/VBox/Main/src-client/ConsoleImpl.cpp	(revision 46775)
@@ -263,9 +263,11 @@
                const ComPtr<IProgress> &aServerProgress,
                const Utf8Str &aSavedStateFile,
-               MachineState_T aMachineStateBefore)
+               MachineState_T aMachineStateBefore,
+               Reason_T aReason)
         : VMTask(aConsole, NULL /* aProgress */, aServerProgress,
                  true /* aUsesVMPtr */),
           mSavedStateFile(aSavedStateFile),
-          mMachineStateBefore(aMachineStateBefore)
+          mMachineStateBefore(aMachineStateBefore),
+          mReason(aReason)
     {}
 
@@ -273,4 +275,6 @@
     /* The local machine state we had before. Required if something fails */
     MachineState_T mMachineStateBefore;
+    /* The reason for saving state */
+    Reason_T mReason;
 };
 
@@ -2074,5 +2078,4 @@
 {
     LogFlowThisFuncEnter();
-    LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
 
     CheckComArgOutPointerValid(aProgress);
@@ -2083,4 +2086,5 @@
     AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
 
+    LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
     switch (mMachineState)
     {
@@ -2206,5 +2210,4 @@
 {
     LogFlowThisFuncEnter();
-    LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
 
     AutoCaller autoCaller(this);
@@ -2213,4 +2216,5 @@
     AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
 
+    LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
     if (   mMachineState != MachineState_Running
         && mMachineState != MachineState_Teleporting
@@ -2257,5 +2261,4 @@
 
     LogFlowThisFuncEnter();
-    LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
 
     AutoCaller autoCaller(this);
@@ -2264,4 +2267,5 @@
     AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
 
+    LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
     AssertReturn(m_pVMMDev, E_FAIL);
     PPDMIVMMDEVPORT pVmmDevPort = m_pVMMDev->getVMMDevPort();
@@ -2401,5 +2405,4 @@
 
     LogFlowThisFuncEnter();
-    LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
 
     AutoCaller autoCaller(this);
@@ -2408,4 +2411,5 @@
     AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
 
+    LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
     if (   mMachineState != MachineState_Running
         && mMachineState != MachineState_Teleporting
@@ -2474,44 +2478,9 @@
     LogFlowThisFuncEnter();
 
-    AutoCaller autoCaller(this);
-    if (FAILED(autoCaller.rc())) return autoCaller.rc();
-
-    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
-
-    switch (mMachineState)
-    {
-        case MachineState_Running:
-        case MachineState_Teleporting:
-        case MachineState_LiveSnapshotting:
-            break;
-
-        case MachineState_Paused:
-        case MachineState_TeleportingPausedVM:
-        case MachineState_Saving:
-            return setError(VBOX_E_INVALID_VM_STATE, tr("Already paused"));
-
-        default:
-            return setInvalidMachineStateError();
-    }
-
-    /* get the VM handle. */
-    SafeVMPtr ptrVM(this);
-    if (!ptrVM.isOk())
-        return ptrVM.rc();
-
-    LogFlowThisFunc(("Sending PAUSE request...\n"));
-
-    /* release the lock before a VMR3* call (EMT will call us back)! */
-    alock.release();
-
-    int vrc = VMR3Suspend(ptrVM.rawUVM());
-
-    HRESULT hrc = S_OK;
-    if (RT_FAILURE(vrc))
-        hrc = setError(VBOX_E_VM_ERROR, tr("Could not suspend the machine execution (%Rrc)"), vrc);
-
-    LogFlowThisFunc(("hrc=%Rhrc\n", hrc));
+    HRESULT rc = pause(Reason_Unspecified);
+
+    LogFlowThisFunc(("rc=%Rhrc\n", rc));
     LogFlowThisFuncLeave();
-    return hrc;
+    return rc;
 }
 
@@ -2520,41 +2489,5 @@
     LogFlowThisFuncEnter();
 
-    AutoCaller autoCaller(this);
-    if (FAILED(autoCaller.rc())) return autoCaller.rc();
-
-    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
-
-    if (mMachineState != MachineState_Paused)
-        return setError(VBOX_E_INVALID_VM_STATE,
-                        tr("Cannot resume the machine as it is not paused (machine state: %s)"),
-                        Global::stringifyMachineState(mMachineState));
-
-    /* get the VM handle. */
-    SafeVMPtr ptrVM(this);
-    if (!ptrVM.isOk())
-        return ptrVM.rc();
-
-    LogFlowThisFunc(("Sending RESUME request...\n"));
-
-    /* release the lock before a VMR3* call (EMT will call us back)! */
-    alock.release();
-
-#ifdef VBOX_WITH_EXTPACK
-    int vrc = mptrExtPackManager->callAllVmPowerOnHooks(this, VMR3GetVM(ptrVM.rawUVM())); /** @todo called a few times too many... */
-#else
-    int vrc = VINF_SUCCESS;
-#endif
-    if (RT_SUCCESS(vrc))
-    {
-        if (VMR3GetStateU(ptrVM.rawUVM()) == VMSTATE_CREATED)
-            vrc = VMR3PowerOn(ptrVM.rawUVM()); /* (PowerUpPaused) */
-        else
-            vrc = VMR3Resume(ptrVM.rawUVM());
-    }
-
-    HRESULT rc = RT_SUCCESS(vrc) ? S_OK :
-        setError(VBOX_E_VM_ERROR,
-                 tr("Could not resume the machine execution (%Rrc)"),
-                 vrc);
+    HRESULT rc = resume(Reason_Unspecified);
 
     LogFlowThisFunc(("rc=%Rhrc\n", rc));
@@ -2757,148 +2690,6 @@
 {
     LogFlowThisFuncEnter();
-    LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
-
-    CheckComArgOutPointerValid(aProgress);
-
-    AutoCaller autoCaller(this);
-    if (FAILED(autoCaller.rc())) return autoCaller.rc();
-
-    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
-
-    if (   mMachineState != MachineState_Running
-        && mMachineState != MachineState_Paused)
-    {
-        return setError(VBOX_E_INVALID_VM_STATE,
-            tr("Cannot save the execution state as the machine is not running or paused (machine state: %s)"),
-            Global::stringifyMachineState(mMachineState));
-    }
-
-    /* memorize the current machine state */
-    MachineState_T lastMachineState = mMachineState;
-
-    if (mMachineState == MachineState_Running)
-    {
-        /* get the VM handle. */
-        SafeVMPtr ptrVM(this);
-        if (!ptrVM.isOk())
-            return ptrVM.rc();
-
-        /* release the lock before a VMR3* call (EMT will call us back)! */
-        alock.release();
-        int vrc = VMR3Suspend(ptrVM.rawUVM());
-        alock.acquire();
-
-        HRESULT hrc = S_OK;
-        if (RT_FAILURE(vrc))
-            hrc = setError(VBOX_E_VM_ERROR, tr("Could not suspend the machine execution (%Rrc)"), vrc);
-        if (FAILED(hrc))
-            return hrc;
-    }
-
-    HRESULT rc = S_OK;
-    bool fBeganSavingState = false;
-    bool fTaskCreationFailed = false;
-
-    do
-    {
-        ComPtr<IProgress> pProgress;
-        Bstr stateFilePath;
-
-        /*
-         * request a saved state file path from the server
-         * (this will set the machine state to Saving on the server to block
-         * others from accessing this machine)
-         */
-        rc = mControl->BeginSavingState(pProgress.asOutParam(),
-                                        stateFilePath.asOutParam());
-        if (FAILED(rc))
-            break;
-
-        fBeganSavingState = true;
-
-        /* sync the state with the server */
-        setMachineStateLocally(MachineState_Saving);
-
-        /* ensure the directory for the saved state file exists */
-        {
-            Utf8Str dir = stateFilePath;
-            dir.stripFilename();
-            if (!RTDirExists(dir.c_str()))
-            {
-                int vrc = RTDirCreateFullPath(dir.c_str(), 0700);
-                if (RT_FAILURE(vrc))
-                {
-                    rc = setError(VBOX_E_FILE_ERROR,
-                        tr("Could not create a directory '%s' to save the state to (%Rrc)"),
-                        dir.c_str(), vrc);
-                    break;
-                }
-            }
-        }
-
-        /* Create a task object early to ensure mpUVM protection is successful. */
-        std::auto_ptr<VMSaveTask> task(new VMSaveTask(this, pProgress,
-                                                      stateFilePath,
-                                                      lastMachineState));
-        rc = task->rc();
-        /*
-         * If we fail here it means a PowerDown() call happened on another
-         * thread while we were doing Pause() (which releases the Console lock).
-         * We assign PowerDown() a higher precedence than SaveState(),
-         * therefore just return the error to the caller.
-         */
-        if (FAILED(rc))
-        {
-            fTaskCreationFailed = true;
-            break;
-        }
-
-        /* create a thread to wait until the VM state is saved */
-        int vrc = RTThreadCreate(NULL, Console::saveStateThread, (void *)task.get(),
-                                 0, RTTHREADTYPE_MAIN_WORKER, 0, "VMSave");
-        if (RT_FAILURE(vrc))
-        {
-            rc = setError(E_FAIL, "Could not create VMSave thread (%Rrc)", vrc);
-            break;
-        }
-
-        /* task is now owned by saveStateThread(), so release it */
-        task.release();
-
-        /* return the progress to the caller */
-        pProgress.queryInterfaceTo(aProgress);
-    } while (0);
-
-    if (FAILED(rc) && !fTaskCreationFailed)
-    {
-        /* preserve existing error info */
-        ErrorInfoKeeper eik;
-
-        if (fBeganSavingState)
-        {
-            /*
-             * cancel the requested save state procedure.
-             * This will reset the machine state to the state it had right
-             * before calling mControl->BeginSavingState().
-             */
-            mControl->EndSavingState(eik.getResultCode(), eik.getText().raw());
-        }
-
-        if (lastMachineState == MachineState_Running)
-        {
-            /* restore the paused state if appropriate */
-            setMachineStateLocally(MachineState_Paused);
-            /* restore the running state if appropriate */
-            SafeVMPtr ptrVM(this);
-            if (ptrVM.isOk())
-            {
-                alock.release();
-                VMR3Resume(ptrVM.rawUVM());
-                alock.acquire();
-            }
-        }
-        else
-            setMachineStateLocally(lastMachineState);
-    }
+
+    HRESULT rc = saveState(Reason_Unspecified, aProgress);
 
     LogFlowThisFunc(("rc=%Rhrc\n", rc));
@@ -3361,5 +3152,4 @@
 {
     LogFlowThisFuncEnter();
-    LogFlowThisFunc(("aName='%ls' mMachineState=%d\n", aName, mMachineState));
 
     CheckComArgStrNotEmptyOrNull(aName);
@@ -3370,4 +3160,5 @@
 
     AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
+    LogFlowThisFunc(("aName='%ls' mMachineState=%d\n", aName, mMachineState));
 
     if (Global::IsTransient(mMachineState))
@@ -5921,4 +5712,273 @@
 
 /**
+ * Worker for Console::Pause and internal entry point for pausing a VM for
+ * a specific reason.
+ */
+HRESULT Console::pause(Reason_T aReason)
+{
+    LogFlowThisFuncEnter();
+
+    AutoCaller autoCaller(this);
+    if (FAILED(autoCaller.rc())) return autoCaller.rc();
+
+    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
+
+    switch (mMachineState)
+    {
+        case MachineState_Running:
+        case MachineState_Teleporting:
+        case MachineState_LiveSnapshotting:
+            break;
+
+        case MachineState_Paused:
+        case MachineState_TeleportingPausedVM:
+        case MachineState_Saving:
+            return setError(VBOX_E_INVALID_VM_STATE, tr("Already paused"));
+
+        default:
+            return setInvalidMachineStateError();
+    }
+
+    /* get the VM handle. */
+    SafeVMPtr ptrVM(this);
+    if (!ptrVM.isOk())
+        return ptrVM.rc();
+
+    /* release the lock before a VMR3* call (EMT will call us back)! */
+    alock.release();
+
+    LogFlowThisFunc(("Sending PAUSE request...\n"));
+    if (aReason != Reason_Unspecified)
+        LogRel(("Pausing VM execution, reason \"%s\"\n", Global::stringifyReason(aReason)));
+
+    /** @todo r=klaus make use of aReason */
+    int vrc = VMR3Suspend(ptrVM.rawUVM());
+
+    HRESULT hrc = S_OK;
+    if (RT_FAILURE(vrc))
+        hrc = setError(VBOX_E_VM_ERROR, tr("Could not suspend the machine execution (%Rrc)"), vrc);
+
+    LogFlowThisFunc(("hrc=%Rhrc\n", hrc));
+    LogFlowThisFuncLeave();
+    return hrc;
+}
+
+/**
+ * Worker for Console::Resume and internal entry point for resuming a VM for
+ * a specific reason.
+ */
+HRESULT Console::resume(Reason_T aReason)
+{
+    LogFlowThisFuncEnter();
+
+    AutoCaller autoCaller(this);
+    if (FAILED(autoCaller.rc())) return autoCaller.rc();
+
+    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
+
+    if (mMachineState != MachineState_Paused)
+        return setError(VBOX_E_INVALID_VM_STATE,
+                        tr("Cannot resume the machine as it is not paused (machine state: %s)"),
+                        Global::stringifyMachineState(mMachineState));
+
+    /* get the VM handle. */
+    SafeVMPtr ptrVM(this);
+    if (!ptrVM.isOk())
+        return ptrVM.rc();
+
+    /* release the lock before a VMR3* call (EMT will call us back)! */
+    alock.release();
+
+    LogFlowThisFunc(("Sending RESUME request...\n"));
+    if (aReason != Reason_Unspecified)
+        LogRel(("Resuming VM execution, reason \"%s\"\n", Global::stringifyReason(aReason)));
+
+    /** @todo r=klaus make use of aReason */
+    int vrc;
+    if (VMR3GetStateU(ptrVM.rawUVM()) == VMSTATE_CREATED)
+    {
+#ifdef VBOX_WITH_EXTPACK
+        vrc = mptrExtPackManager->callAllVmPowerOnHooks(this, VMR3GetVM(ptrVM.rawUVM()));
+#else
+        vrc = VINF_SUCCESS;
+#endif
+        if (RT_SUCCESS(vrc))
+            vrc = VMR3PowerOn(ptrVM.rawUVM()); /* (PowerUpPaused) */
+    }
+    else
+        vrc = VMR3Resume(ptrVM.rawUVM());
+
+    HRESULT rc = RT_SUCCESS(vrc) ? S_OK :
+        setError(VBOX_E_VM_ERROR,
+                 tr("Could not resume the machine execution (%Rrc)"),
+                 vrc);
+
+    LogFlowThisFunc(("rc=%Rhrc\n", rc));
+    LogFlowThisFuncLeave();
+    return rc;
+}
+
+/**
+ * Worker for Console::SaveState and internal entry point for saving state of
+ * a VM for a specific reason.
+ */
+HRESULT Console::saveState(Reason_T aReason, IProgress **aProgress)
+{
+    LogFlowThisFuncEnter();
+
+    CheckComArgOutPointerValid(aProgress);
+
+    AutoCaller autoCaller(this);
+    if (FAILED(autoCaller.rc())) return autoCaller.rc();
+
+    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
+
+    LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
+    if (   mMachineState != MachineState_Running
+        && mMachineState != MachineState_Paused)
+    {
+        return setError(VBOX_E_INVALID_VM_STATE,
+            tr("Cannot save the execution state as the machine is not running or paused (machine state: %s)"),
+            Global::stringifyMachineState(mMachineState));
+    }
+
+    if (aReason != Reason_Unspecified)
+        LogRel(("Saving state of VM, reason \"%s\"\n", Global::stringifyReason(aReason)));
+
+    /* memorize the current machine state */
+    MachineState_T lastMachineState = mMachineState;
+
+    if (mMachineState == MachineState_Running)
+    {
+        /* get the VM handle. */
+        SafeVMPtr ptrVM(this);
+        if (!ptrVM.isOk())
+            return ptrVM.rc();
+
+        /* release the lock before a VMR3* call (EMT will call us back)! */
+        alock.release();
+        int vrc = VMR3Suspend(ptrVM.rawUVM());
+        alock.acquire();
+
+        HRESULT hrc = S_OK;
+        if (RT_FAILURE(vrc))
+            hrc = setError(VBOX_E_VM_ERROR, tr("Could not suspend the machine execution (%Rrc)"), vrc);
+        if (FAILED(hrc))
+            return hrc;
+    }
+
+    HRESULT rc = S_OK;
+    bool fBeganSavingState = false;
+    bool fTaskCreationFailed = false;
+
+    do
+    {
+        ComPtr<IProgress> pProgress;
+        Bstr stateFilePath;
+
+        /*
+         * request a saved state file path from the server
+         * (this will set the machine state to Saving on the server to block
+         * others from accessing this machine)
+         */
+        rc = mControl->BeginSavingState(pProgress.asOutParam(),
+                                        stateFilePath.asOutParam());
+        if (FAILED(rc))
+            break;
+
+        fBeganSavingState = true;
+
+        /* sync the state with the server */
+        setMachineStateLocally(MachineState_Saving);
+
+        /* ensure the directory for the saved state file exists */
+        {
+            Utf8Str dir = stateFilePath;
+            dir.stripFilename();
+            if (!RTDirExists(dir.c_str()))
+            {
+                int vrc = RTDirCreateFullPath(dir.c_str(), 0700);
+                if (RT_FAILURE(vrc))
+                {
+                    rc = setError(VBOX_E_FILE_ERROR,
+                        tr("Could not create a directory '%s' to save the state to (%Rrc)"),
+                        dir.c_str(), vrc);
+                    break;
+                }
+            }
+        }
+
+        /* Create a task object early to ensure mpUVM protection is successful. */
+        std::auto_ptr<VMSaveTask> task(new VMSaveTask(this, pProgress,
+                                                      stateFilePath,
+                                                      lastMachineState,
+                                                      aReason));
+        rc = task->rc();
+        /*
+         * If we fail here it means a PowerDown() call happened on another
+         * thread while we were doing Pause() (which releases the Console lock).
+         * We assign PowerDown() a higher precedence than SaveState(),
+         * therefore just return the error to the caller.
+         */
+        if (FAILED(rc))
+        {
+            fTaskCreationFailed = true;
+            break;
+        }
+
+        /* create a thread to wait until the VM state is saved */
+        int vrc = RTThreadCreate(NULL, Console::saveStateThread, (void *)task.get(),
+                                 0, RTTHREADTYPE_MAIN_WORKER, 0, "VMSave");
+        if (RT_FAILURE(vrc))
+        {
+            rc = setError(E_FAIL, "Could not create VMSave thread (%Rrc)", vrc);
+            break;
+        }
+
+        /* task is now owned by saveStateThread(), so release it */
+        task.release();
+
+        /* return the progress to the caller */
+        pProgress.queryInterfaceTo(aProgress);
+    } while (0);
+
+    if (FAILED(rc) && !fTaskCreationFailed)
+    {
+        /* preserve existing error info */
+        ErrorInfoKeeper eik;
+
+        if (fBeganSavingState)
+        {
+            /*
+             * cancel the requested save state procedure.
+             * This will reset the machine state to the state it had right
+             * before calling mControl->BeginSavingState().
+             */
+            mControl->EndSavingState(eik.getResultCode(), eik.getText().raw());
+        }
+
+        if (lastMachineState == MachineState_Running)
+        {
+            /* restore the paused state if appropriate */
+            setMachineStateLocally(MachineState_Paused);
+            /* restore the running state if appropriate */
+            SafeVMPtr ptrVM(this);
+            if (ptrVM.isOk())
+            {
+                alock.release();
+                VMR3Resume(ptrVM.rawUVM());
+                alock.acquire();
+            }
+        }
+        else
+            setMachineStateLocally(lastMachineState);
+    }
+
+    LogFlowThisFunc(("rc=%Rhrc\n", rc));
+    LogFlowThisFuncLeave();
+    return rc;
+}
+
+/**
  * Gets called by Session::UpdateMachineState()
  * (IInternalSessionControl::updateMachineState()).
@@ -6391,5 +6451,4 @@
 
     LogFlowThisFuncEnter();
-    LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
 
     CheckComArgOutPointerValid(aProgress);
@@ -6400,4 +6459,5 @@
     AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
 
+    LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
     HRESULT rc = S_OK;
     ComObjPtr<Progress> pPowerupProgress;
@@ -9687,4 +9747,5 @@
     LogFlowFunc(("Saving the state to '%s'...\n", task->mSavedStateFile.c_str()));
 
+    /** @todo r=klaus make use of task->mReason */
     bool fSuspenededBySave;
     int vrc = VMR3Save(task->mpUVM,
Index: /trunk/src/VBox/Main/src-client/SessionImpl.cpp
===================================================================
--- /trunk/src/VBox/Main/src-client/SessionImpl.cpp	(revision 46774)
+++ /trunk/src/VBox/Main/src-client/SessionImpl.cpp	(revision 46775)
@@ -926,4 +926,43 @@
 
     return S_OK;
+}
+
+STDMETHODIMP Session::PauseWithReason(Reason_T aReason)
+{
+    AutoCaller autoCaller(this);
+    AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
+
+    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
+    AssertReturn(mState == SessionState_Locked, VBOX_E_INVALID_VM_STATE);
+    AssertReturn(mType == SessionType_WriteLock, VBOX_E_INVALID_OBJECT_STATE);
+    AssertReturn(mConsole, VBOX_E_INVALID_OBJECT_STATE);
+
+    return mConsole->pause(aReason);
+}
+
+STDMETHODIMP Session::ResumeWithReason(Reason_T aReason)
+{
+    AutoCaller autoCaller(this);
+    AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
+
+    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
+    AssertReturn(mState == SessionState_Locked, VBOX_E_INVALID_VM_STATE);
+    AssertReturn(mType == SessionType_WriteLock, VBOX_E_INVALID_OBJECT_STATE);
+    AssertReturn(mConsole, VBOX_E_INVALID_OBJECT_STATE);
+
+    return mConsole->resume(aReason);
+}
+
+STDMETHODIMP Session::SaveStateWithReason(Reason_T aReason, IProgress **aProgress)
+{
+    AutoCaller autoCaller(this);
+    AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
+
+    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
+    AssertReturn(mState == SessionState_Locked, VBOX_E_INVALID_VM_STATE);
+    AssertReturn(mType == SessionType_WriteLock, VBOX_E_INVALID_OBJECT_STATE);
+    AssertReturn(mConsole, VBOX_E_INVALID_OBJECT_STATE);
+
+    return mConsole->saveState(aReason, aProgress);
 }
 
Index: /trunk/src/VBox/Main/src-server/HostPower.cpp
===================================================================
--- /trunk/src/VBox/Main/src-server/HostPower.cpp	(revision 46774)
+++ /trunk/src/VBox/Main/src-server/HostPower.cpp	(revision 46775)
@@ -5,5 +5,5 @@
 
 /*
- * Copyright (C) 2006-2011 Oracle Corporation
+ * Copyright (C) 2006-2013 Oracle Corporation
  *
  * This file is part of VirtualBox Open Source Edition (OSE), as
@@ -27,8 +27,9 @@
 
 #include "VirtualBoxImpl.h"
+#include "MachineImpl.h"
 
 #include <iprt/mem.h>
 
-HostPowerService::HostPowerService (VirtualBox *aVirtualBox)
+HostPowerService::HostPowerService(VirtualBox *aVirtualBox)
 {
     Assert(aVirtualBox != NULL);
@@ -40,5 +41,5 @@
 }
 
-void HostPowerService::notify(HostPowerEvent aEvent)
+void HostPowerService::notify(Reason_T aReason)
 {
     SessionMachinesList machines;
@@ -47,9 +48,9 @@
     HRESULT rc = S_OK;
 
-    switch (aEvent)
+    switch (aReason)
     {
-        case HostPowerEvent_Suspend:
+        case Reason_HostSuspend:
         {
-            LogFunc (("SUSPEND\n"));
+            LogFunc(("SUSPEND\n"));
 
 #ifdef VBOX_WITH_RESOURCE_USAGE_API
@@ -69,34 +70,27 @@
                 ComPtr<IInternalSessionControl> pControl = *it;
 
-                /* get the remote console */
-                ComPtr<IConsole> console;
-                rc = pControl->GetRemoteConsole(console.asOutParam());
-                /* the VM could have been powered down and closed or whatever */
-                if (FAILED(rc))
-                    continue;
-
-                /* note that Pause() will simply return a failure if the VM is
-                 * in an inappropriate state */
-                rc = console->Pause();
+                /* PauseWithReason() will simply return a failure if
+                 * the VM is in an inappropriate state */
+                rc = pControl->PauseWithReason(Reason_HostSuspend);
                 if (FAILED(rc))
                     continue;
 
                 /* save the control to un-pause the VM later */
-                mConsoles.push_back(console);
+                mSessionControls.push_back(pControl);
             }
 
-            LogFunc (("Suspended %d VMs\n", mConsoles.size()));
+            LogFunc(("Suspended %d VMs\n", mSessionControls.size()));
 
             break;
         }
 
-        case HostPowerEvent_Resume:
+        case Reason_HostResume:
         {
-            LogFunc (("RESUME\n"));
+            LogFunc(("RESUME\n"));
 
             size_t resumed = 0;
 
             /* go through VMs we paused on Suspend */
-            for (size_t i = 0; i < mConsoles.size(); ++i)
+            for (size_t i = 0; i < mSessionControls.size(); ++i)
             {
                 /* note that Resume() will simply return a failure if the VM is
@@ -104,12 +98,12 @@
                  * been somehow closed by this time already so that the
                  * console reference we have is dead) */
-                rc = mConsoles[i]->Resume();
+                rc = mSessionControls[i]->ResumeWithReason(Reason_HostResume);
                 if (FAILED(rc))
                     continue;
 
-                ++ resumed;
+                ++resumed;
             }
 
-            LogFunc (("Resumed %d VMs\n", resumed));
+            LogFunc(("Resumed %d VMs\n", resumed));
 
 #ifdef VBOX_WITH_RESOURCE_USAGE_API
@@ -121,12 +115,12 @@
 #endif
 
-            mConsoles.clear();
+            mSessionControls.clear();
 
             break;
         }
 
-        case HostPowerEvent_BatteryLow:
+        case Reason_HostBatteryLow:
         {
-            LogFunc (("BATTERY LOW\n"));
+            LogFunc(("BATTERY LOW\n"));
 
             mVirtualBox->getOpenedMachines(machines, &controls);
@@ -140,16 +134,10 @@
             {
                 ComPtr<IInternalSessionControl> pControl = *it;
-                /* get the remote console */
-                ComPtr<IConsole> console;
-                rc = pControl->GetRemoteConsole (console.asOutParam());
-                /* the VM could have been powered down and closed or whatever */
-                if (FAILED(rc))
-                    continue;
 
                 ComPtr<IProgress> progress;
 
-                /* note that SaveState() will simply return a failure if the VM
-                 * is in an inappropriate state */
-                rc = console->SaveState (progress.asOutParam());
+                /* note that SaveStateWithReason() will simply return a failure
+                 * if the VM is in an inappropriate state */
+                rc = pControl->SaveStateWithReason(Reason_HostBatteryLow, progress.asOutParam());
                 if (FAILED(rc))
                     continue;
@@ -164,15 +152,17 @@
                 }
 
-                AssertMsg (SUCCEEDED(rc), ("SaveState WaitForCompletion "
-                                            "failed with %Rhrc (%#08X)\n", rc, rc));
+                AssertMsg(SUCCEEDED(rc), ("SaveState WaitForCompletion failed with %Rhrc (%#08X)\n", rc, rc));
 
                 if (SUCCEEDED(rc))
-                    ++ saved;
+                    ++saved;
             }
 
-            LogFunc (("Saved %d VMs\n", saved));
+            LogFunc(("Saved %d VMs\n", saved));
 
             break;
         }
+
+        default:
+            /* nothing */;
     }
 }
Index: /trunk/src/VBox/Main/src-server/darwin/HostPowerDarwin.cpp
===================================================================
--- /trunk/src/VBox/Main/src-server/darwin/HostPowerDarwin.cpp	(revision 46774)
+++ /trunk/src/VBox/Main/src-server/darwin/HostPowerDarwin.cpp	(revision 46775)
@@ -5,5 +5,5 @@
 
 /*
- * Copyright (C) 2008-2010 Oracle Corporation
+ * Copyright (C) 2008-2013 Oracle Corporation
  *
  * This file is part of VirtualBox Open Source Edition (OSE), as
@@ -26,18 +26,18 @@
 #define POWER_SOURCE_BATTERY 2
 
-HostPowerServiceDarwin::HostPowerServiceDarwin (VirtualBox *aVirtualBox)
-  : HostPowerService (aVirtualBox)
-  , mThread (NULL)
-  , mRootPort (MACH_PORT_NULL)
-  , mNotifyPort (nil)
-  , mRunLoop (nil)
-  , mCritical (false)
+HostPowerServiceDarwin::HostPowerServiceDarwin(VirtualBox *aVirtualBox)
+  : HostPowerService(aVirtualBox)
+  , mThread(NULL)
+  , mRootPort(MACH_PORT_NULL)
+  , mNotifyPort(nil)
+  , mRunLoop(nil)
+  , mCritical(false)
 {
     /* Create the new worker thread. */
-    int rc = RTThreadCreate (&mThread, HostPowerServiceDarwin::powerChangeNotificationThread, this, 65536,
-                             RTTHREADTYPE_IO, RTTHREADFLAGS_WAITABLE, "MainPower");
+    int rc = RTThreadCreate(&mThread, HostPowerServiceDarwin::powerChangeNotificationThread, this, 65536,
+                            RTTHREADTYPE_IO, RTTHREADFLAGS_WAITABLE, "MainPower");
 
     if (RT_FAILURE(rc))
-        LogFlow (("RTThreadCreate failed with %Rrc\n", rc));
+        LogFlow(("RTThreadCreate failed with %Rrc\n", rc));
 }
 
@@ -45,22 +45,22 @@
 {
     /* Jump out of the run loop. */
-    CFRunLoopStop (mRunLoop);
+    CFRunLoopStop(mRunLoop);
     /* Remove the sleep notification port from the application runloop. */
-    CFRunLoopRemoveSource (CFRunLoopGetCurrent(),
-                           IONotificationPortGetRunLoopSource (mNotifyPort),
-                           kCFRunLoopCommonModes);
+    CFRunLoopRemoveSource(CFRunLoopGetCurrent(),
+                          IONotificationPortGetRunLoopSource(mNotifyPort),
+                          kCFRunLoopCommonModes);
     /* Deregister for system sleep notifications. */
-    IODeregisterForSystemPower (&mNotifierObject);
+    IODeregisterForSystemPower(&mNotifierObject);
     /* IORegisterForSystemPower implicitly opens the Root Power Domain
      * IOService so we close it here. */
-    IOServiceClose (mRootPort);
+    IOServiceClose(mRootPort);
     /* Destroy the notification port allocated by IORegisterForSystemPower */
-    IONotificationPortDestroy (mNotifyPort);
-}
-
-
-DECLCALLBACK(int) HostPowerServiceDarwin::powerChangeNotificationThread (RTTHREAD /* ThreadSelf */, void *pInstance)
-{
-    HostPowerServiceDarwin *pPowerObj = static_cast<HostPowerServiceDarwin *> (pInstance);
+    IONotificationPortDestroy(mNotifyPort);
+}
+
+
+DECLCALLBACK(int) HostPowerServiceDarwin::powerChangeNotificationThread(RTTHREAD /* ThreadSelf */, void *pInstance)
+{
+    HostPowerServiceDarwin *pPowerObj = static_cast<HostPowerServiceDarwin *>(pInstance);
 
     /* We have to initial set the critical state of the battery, cause we want
@@ -70,17 +70,17 @@
 
     /* Register to receive system sleep notifications */
-    pPowerObj->mRootPort = IORegisterForSystemPower (pPowerObj, &pPowerObj->mNotifyPort,
-                                                     HostPowerServiceDarwin::powerChangeNotificationHandler,
-                                                     &pPowerObj->mNotifierObject);
+    pPowerObj->mRootPort = IORegisterForSystemPower(pPowerObj, &pPowerObj->mNotifyPort,
+                                                    HostPowerServiceDarwin::powerChangeNotificationHandler,
+                                                    &pPowerObj->mNotifierObject);
     if (pPowerObj->mRootPort == MACH_PORT_NULL)
     {
-        LogFlow (("IORegisterForSystemPower failed\n"));
+        LogFlow(("IORegisterForSystemPower failed\n"));
         return VERR_NOT_SUPPORTED;
     }
     pPowerObj->mRunLoop = CFRunLoopGetCurrent();
     /* Add the notification port to the application runloop */
-    CFRunLoopAddSource (pPowerObj->mRunLoop,
-                        IONotificationPortGetRunLoopSource (pPowerObj->mNotifyPort),
-                        kCFRunLoopCommonModes);
+    CFRunLoopAddSource(pPowerObj->mRunLoop,
+                       IONotificationPortGetRunLoopSource(pPowerObj->mNotifyPort),
+                       kCFRunLoopCommonModes);
 
     /* Register for all battery change events. The handler will check for low
@@ -97,8 +97,8 @@
 }
 
-void HostPowerServiceDarwin::powerChangeNotificationHandler (void *pvData, io_service_t /* service */, natural_t messageType, void *pMessageArgument)
-{
-    HostPowerServiceDarwin *pPowerObj = static_cast<HostPowerServiceDarwin *> (pvData);
-    Log (( "powerChangeNotificationHandler: messageType %08lx, arg %08lx\n", (long unsigned int)messageType, (long unsigned int)pMessageArgument));
+void HostPowerServiceDarwin::powerChangeNotificationHandler(void *pvData, io_service_t /* service */, natural_t messageType, void *pMessageArgument)
+{
+    HostPowerServiceDarwin *pPowerObj = static_cast<HostPowerServiceDarwin *>(pvData);
+    Log(( "powerChangeNotificationHandler: messageType %08lx, arg %08lx\n", (long unsigned int)messageType, (long unsigned int)pMessageArgument));
 
     switch (messageType)
@@ -114,5 +114,5 @@
                  * IOAllowPowerChange or IOCancelPowerChange, the system will
                  * wait 30 seconds then go to sleep. */
-                IOAllowPowerChange (pPowerObj->mRootPort, reinterpret_cast<long> (pMessageArgument));
+                IOAllowPowerChange(pPowerObj->mRootPort, reinterpret_cast<long>(pMessageArgument));
                 break;
             }
@@ -120,10 +120,10 @@
             {
                 /* The system will go for sleep. */
-                pPowerObj->notify (HostPowerEvent_Suspend);
+                pPowerObj->notify(Reason_HostSuspend);
                 /* If you do not call IOAllowPowerChange or IOCancelPowerChange to
                  * acknowledge this message, sleep will be delayed by 30 seconds.
                  * NOTE: If you call IOCancelPowerChange to deny sleep it returns
                  * kIOReturnSuccess, however the system WILL still go to sleep. */
-                IOAllowPowerChange (pPowerObj->mRootPort, reinterpret_cast<long> (pMessageArgument));
+                IOAllowPowerChange(pPowerObj->mRootPort, reinterpret_cast<long>(pMessageArgument));
                 break;
             }
@@ -136,5 +136,5 @@
             {
                 /* System has finished the wake up process. */
-                pPowerObj->notify (HostPowerEvent_Resume);
+                pPowerObj->notify(Reason_HostResume);
                 break;
             }
@@ -144,9 +144,9 @@
 }
 
-void HostPowerServiceDarwin::lowPowerHandler (void *pvData)
-{
-    HostPowerServiceDarwin *pPowerObj = static_cast<HostPowerServiceDarwin *> (pvData);
-
-    /* Following role for sending the BatteryLow event (5% is critical):
+void HostPowerServiceDarwin::lowPowerHandler(void *pvData)
+{
+    HostPowerServiceDarwin *pPowerObj = static_cast<HostPowerServiceDarwin *>(pvData);
+
+    /* Following role for sending the BatteryLow event(5% is critical):
      * - Not at VM start even if the battery is in an critical state already.
      * - When the power cord is removed so the power supply change from AC to
@@ -157,13 +157,13 @@
      *   normal triggers nothing. */
     bool fCriticalStateChanged = false;
-    pPowerObj->checkBatteryCriticalLevel (&fCriticalStateChanged);
+    pPowerObj->checkBatteryCriticalLevel(&fCriticalStateChanged);
     if (fCriticalStateChanged)
-        pPowerObj->notify (HostPowerEvent_BatteryLow);
-}
-
-void HostPowerServiceDarwin::checkBatteryCriticalLevel (bool *pfCriticalChanged)
+        pPowerObj->notify(Reason_HostBatteryLow);
+}
+
+void HostPowerServiceDarwin::checkBatteryCriticalLevel(bool *pfCriticalChanged)
 {
     CFTypeRef pBlob = IOPSCopyPowerSourcesInfo();
-    CFArrayRef pSources = IOPSCopyPowerSourcesList (pBlob);
+    CFArrayRef pSources = IOPSCopyPowerSourcesList(pBlob);
 
     CFDictionaryRef pSource = NULL;
@@ -173,9 +173,9 @@
     bool critical = false;
 
-    if (CFArrayGetCount (pSources) > 0)
+    if (CFArrayGetCount(pSources) > 0)
     {
-        for (int i = 0; i < CFArrayGetCount (pSources); ++i)
+        for (int i = 0; i < CFArrayGetCount(pSources); ++i)
         {
-            pSource = IOPSGetPowerSourceDescription (pBlob, CFArrayGetValueAtIndex (pSources, i));
+            pSource = IOPSGetPowerSourceDescription(pBlob, CFArrayGetValueAtIndex(pSources, i));
             /* If the source is empty skip over to the next one. */
             if (!pSource)
@@ -183,18 +183,18 @@
             /* Skip all power sources which are currently not present like a
              * second battery. */
-            if (CFDictionaryGetValue (pSource, CFSTR (kIOPSIsPresentKey)) == kCFBooleanFalse)
+            if (CFDictionaryGetValue(pSource, CFSTR(kIOPSIsPresentKey)) == kCFBooleanFalse)
                 continue;
             /* Only internal power types are of interest. */
-            result = CFDictionaryGetValueIfPresent (pSource, CFSTR (kIOPSTransportTypeKey), &psValue);
+            result = CFDictionaryGetValueIfPresent(pSource, CFSTR(kIOPSTransportTypeKey), &psValue);
             if (result &&
-                CFStringCompare ((CFStringRef)psValue, CFSTR (kIOPSInternalType), 0) == kCFCompareEqualTo)
+                CFStringCompare((CFStringRef)psValue, CFSTR(kIOPSInternalType), 0) == kCFCompareEqualTo)
             {
                 /* First check which power source we are connect on. */
-                result = CFDictionaryGetValueIfPresent (pSource, CFSTR (kIOPSPowerSourceStateKey), &psValue);
+                result = CFDictionaryGetValueIfPresent(pSource, CFSTR(kIOPSPowerSourceStateKey), &psValue);
                 if (result &&
-                    CFStringCompare ((CFStringRef)psValue, CFSTR (kIOPSACPowerValue), 0) == kCFCompareEqualTo)
+                    CFStringCompare((CFStringRef)psValue, CFSTR(kIOPSACPowerValue), 0) == kCFCompareEqualTo)
                     powerSource = POWER_SOURCE_OUTLET;
                 else if (result &&
-                         CFStringCompare ((CFStringRef)psValue, CFSTR (kIOPSBatteryPowerValue), 0) == kCFCompareEqualTo)
+                         CFStringCompare((CFStringRef)psValue, CFSTR(kIOPSBatteryPowerValue), 0) == kCFCompareEqualTo)
                     powerSource = POWER_SOURCE_BATTERY;
 
@@ -204,11 +204,11 @@
 
                 /* Fetch the current capacity value of the power source */
-                result = CFDictionaryGetValueIfPresent (pSource, CFSTR (kIOPSCurrentCapacityKey), &psValue);
+                result = CFDictionaryGetValueIfPresent(pSource, CFSTR(kIOPSCurrentCapacityKey), &psValue);
                 if (result)
-                    CFNumberGetValue ((CFNumberRef)psValue, kCFNumberSInt32Type, &curCapacity);
+                    CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &curCapacity);
                 /* Fetch the maximum capacity value of the power source */
-                result = CFDictionaryGetValueIfPresent (pSource, CFSTR (kIOPSMaxCapacityKey), &psValue);
+                result = CFDictionaryGetValueIfPresent(pSource, CFSTR(kIOPSMaxCapacityKey), &psValue);
                 if (result)
-                    CFNumberGetValue ((CFNumberRef)psValue, kCFNumberSInt32Type, &maxCapacity);
+                    CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &maxCapacity);
 
                 /* Calculate the remaining capacity in percent */
@@ -217,7 +217,7 @@
                 /* Check for critical. 5 percent is default. */
                 int criticalValue = 5;
-                result = CFDictionaryGetValueIfPresent (pSource, CFSTR (kIOPSDeadWarnLevelKey), &psValue);
+                result = CFDictionaryGetValueIfPresent(pSource, CFSTR(kIOPSDeadWarnLevelKey), &psValue);
                 if (result)
-                    CFNumberGetValue ((CFNumberRef)psValue, kCFNumberSInt32Type, &criticalValue);
+                    CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &criticalValue);
                 critical = (remCapacity < criticalValue);
                 /* We have to take action only if we are on battery, the
@@ -229,5 +229,5 @@
                     pfCriticalChanged)
                     *pfCriticalChanged = true;
-                Log (("checkBatteryCriticalLevel: Remains: %d.%d%% Critical: %d Critical State Changed: %d\n", (int)remCapacity, (int)(remCapacity * 10) % 10, critical, pfCriticalChanged?*pfCriticalChanged:-1));
+                Log(("checkBatteryCriticalLevel: Remains: %d.%d%% Critical: %d Critical State Changed: %d\n", (int)remCapacity, (int)(remCapacity * 10) % 10, critical, pfCriticalChanged?*pfCriticalChanged:-1));
             }
         }
@@ -236,6 +236,6 @@
     mCritical = critical;
 
-    CFRelease (pBlob);
-    CFRelease (pSources);
-}
-
+    CFRelease(pBlob);
+    CFRelease(pSources);
+}
+
Index: /trunk/src/VBox/Main/src-server/win/HostPowerWin.cpp
===================================================================
--- /trunk/src/VBox/Main/src-server/win/HostPowerWin.cpp	(revision 46774)
+++ /trunk/src/VBox/Main/src-server/win/HostPowerWin.cpp	(revision 46775)
@@ -5,5 +5,5 @@
 
 /*
- * Copyright (C) 2006-2010 Oracle Corporation
+ * Copyright (C) 2006-2013 Oracle Corporation
  *
  * This file is part of VirtualBox Open Source Edition (OSE), as
@@ -36,6 +36,6 @@
     mHwnd = 0;
 
-    int rc = RTThreadCreate (&mThread, HostPowerServiceWin::NotificationThread, this, 65536,
-                             RTTHREADTYPE_GUI, RTTHREADFLAGS_WAITABLE, "MainPower");
+    int rc = RTThreadCreate(&mThread, HostPowerServiceWin::NotificationThread, this, 65536,
+                            RTTHREADTYPE_GUI, RTTHREADFLAGS_WAITABLE, "MainPower");
 
     if (RT_FAILURE(rc))
@@ -63,5 +63,5 @@
 
 
-DECLCALLBACK(int) HostPowerServiceWin::NotificationThread (RTTHREAD ThreadSelf, void *pInstance)
+DECLCALLBACK(int) HostPowerServiceWin::NotificationThread(RTTHREAD ThreadSelf, void *pInstance)
 {
     HostPowerServiceWin *pPowerObj = (HostPowerServiceWin *)pInstance;
@@ -71,5 +71,5 @@
     int rc = VINF_SUCCESS;
 
-    HINSTANCE hInstance = (HINSTANCE)GetModuleHandle (NULL);
+    HINSTANCE hInstance = (HINSTANCE)GetModuleHandle(NULL);
 
     /* Register the Window Class. */
@@ -97,8 +97,8 @@
     {
         /* Create the window. */
-        hwnd = pPowerObj->mHwnd = CreateWindowEx (WS_EX_TOOLWINDOW | WS_EX_TRANSPARENT | WS_EX_TOPMOST,
-                                                  gachWindowClassName, gachWindowClassName,
-                                                  WS_POPUPWINDOW,
-                                                 -200, -200, 100, 100, NULL, NULL, hInstance, NULL);
+        hwnd = pPowerObj->mHwnd = CreateWindowEx(WS_EX_TOOLWINDOW | WS_EX_TRANSPARENT | WS_EX_TOPMOST,
+                                                 gachWindowClassName, gachWindowClassName,
+                                                 WS_POPUPWINDOW,
+                                                -200, -200, 100, 100, NULL, NULL, hInstance, NULL);
 
         if (hwnd == NULL)
@@ -124,9 +124,9 @@
     Log(("HostPowerServiceWin::NotificationThread: exit thread\n"));
     if (hwnd)
-        DestroyWindow (hwnd);
+        DestroyWindow(hwnd);
 
     if (atomWindowClass != 0)
     {
-        UnregisterClass (gachWindowClassName, hInstance);
+        UnregisterClass(gachWindowClassName, hInstance);
         atomWindowClass = 0;
     }
@@ -149,9 +149,9 @@
                 {
                 case PBT_APMSUSPEND:
-                    pPowerObj->notify(HostPowerEvent_Suspend);
+                    pPowerObj->notify(Reason_HostSuspend);
                     break;
 
                 case PBT_APMRESUMEAUTOMATIC:
-                    pPowerObj->notify(HostPowerEvent_Resume);
+                    pPowerObj->notify(Reason_HostResume);
                     break;
 
@@ -180,5 +180,5 @@
                                     &&  BatteryState.EstimatedTime < 60*5)
                                 {
-                                    pPowerObj->notify(HostPowerEvent_BatteryLow);
+                                    pPowerObj->notify(Reason_HostBatteryLow);
                                 }
                             }
@@ -187,5 +187,5 @@
                             if (SystemPowerStatus.BatteryFlag == 4      /* critical battery status; less than 5% */)
                             {
-                                pPowerObj->notify(HostPowerEvent_BatteryLow);
+                                pPowerObj->notify(Reason_HostBatteryLow);
                             }
                         }
@@ -194,5 +194,5 @@
                 }
                 default:
-                    return DefWindowProc (hwnd, msg, wParam, lParam);
+                    return DefWindowProc(hwnd, msg, wParam, lParam);
                 }
             }
@@ -201,5 +201,5 @@
 
         default:
-            return DefWindowProc (hwnd, msg, wParam, lParam);
-    }
-}
+            return DefWindowProc(hwnd, msg, wParam, lParam);
+    }
+}
