rainmeter-studio/Library/System.cpp

1412 lines
35 KiB
C++
Raw Normal View History

/*
Copyright (C) 2010 spx
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "StdAfx.h"
#include "System.h"
#include "Litestep.h"
#include "Rainmeter.h"
2010-09-04 08:04:13 +00:00
#include "MeterWindow.h"
#include "MeasureNet.h"
#include "Error.h"
#include "../Common/PathUtil.h"
using namespace Gdiplus;
#define DEBUG_VERBOSE (0) // Set 1 if you need verbose logging.
2011-09-03 21:51:25 +00:00
#define ZPOS_FLAGS (SWP_NOMOVE | SWP_NOSIZE | SWP_NOOWNERZORDER | SWP_NOACTIVATE | SWP_NOSENDCHANGING)
enum TIMER
{
TIMER_SHOWDESKTOP = 1,
TIMER_RESUME = 2
};
enum INTERVAL
{
2011-11-10 13:44:19 +00:00
INTERVAL_SHOWDESKTOP = 250,
INTERVAL_RESTOREWINDOWS = 100,
INTERVAL_RESUME = 1000
};
2013-05-31 14:18:52 +00:00
MultiMonitorInfo System::c_Monitors = { 0 };
2013-05-31 14:28:39 +00:00
HWND System::c_Window = nullptr;
HWND System::c_HelperWindow = nullptr;
2013-05-31 14:28:39 +00:00
HWINEVENTHOOK System::c_WinEventHook = nullptr;
2013-05-31 14:18:52 +00:00
bool System::c_ShowDesktop = false;
2013-05-31 14:18:52 +00:00
std::wstring System::c_WorkingDirectory;
2011-05-22 16:02:43 +00:00
2013-05-31 14:18:52 +00:00
std::vector<std::wstring> System::c_IniFileMappings;
2011-11-10 13:44:19 +00:00
2013-05-31 14:18:52 +00:00
extern Rainmeter* g_Rainmeter;
/*
** Creates a helper window to detect changes in the system.
**
*/
2013-05-31 14:18:52 +00:00
void System::Initialize(HINSTANCE instance)
{
WNDCLASS wc = {0};
wc.lpfnWndProc = (WNDPROC)WndProc;
wc.hInstance = instance;
2012-06-01 13:21:25 +00:00
wc.lpszClassName = L"RainmeterSystem";
ATOM className = RegisterClass(&wc);
c_Window = CreateWindowEx(
WS_EX_TOOLWINDOW,
2012-06-01 13:21:25 +00:00
MAKEINTATOM(className),
L"System",
2011-09-03 21:51:25 +00:00
WS_POPUP | WS_DISABLED,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
2013-05-31 14:28:39 +00:00
nullptr,
nullptr,
instance,
2013-05-31 14:28:39 +00:00
nullptr);
c_HelperWindow = CreateWindowEx(
WS_EX_TOOLWINDOW,
2012-06-01 13:21:25 +00:00
MAKEINTATOM(className),
L"PositioningHelper",
2011-09-03 21:51:25 +00:00
WS_POPUP | WS_DISABLED,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
2013-05-31 14:28:39 +00:00
nullptr,
nullptr,
instance,
2013-05-31 14:28:39 +00:00
nullptr);
2011-09-03 21:51:25 +00:00
SetWindowPos(c_Window, HWND_BOTTOM, 0, 0, 0, 0, ZPOS_FLAGS);
SetWindowPos(c_HelperWindow, HWND_BOTTOM, 0, 0, 0, 0, ZPOS_FLAGS);
2011-11-18 22:40:58 +00:00
c_Monitors.monitors.reserve(4);
SetMultiMonitorInfo();
2012-03-23 16:45:35 +00:00
WCHAR directory[MAX_PATH];
DWORD len = GetCurrentDirectory(MAX_PATH, directory);
c_WorkingDirectory.assign(directory, len <= MAX_PATH ? len : 0);
c_WinEventHook = SetWinEventHook(
EVENT_SYSTEM_FOREGROUND,
EVENT_SYSTEM_FOREGROUND,
2013-05-31 14:28:39 +00:00
nullptr,
MyWinEventProc,
0,
0,
WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS);
2013-05-31 14:28:39 +00:00
SetTimer(c_Window, TIMER_SHOWDESKTOP, INTERVAL_SHOWDESKTOP, nullptr);
}
/*
** Destroys a window.
**
*/
2013-05-31 14:18:52 +00:00
void System::Finalize()
{
KillTimer(c_Window, TIMER_SHOWDESKTOP);
KillTimer(c_Window, TIMER_RESUME);
if (c_WinEventHook)
{
UnhookWinEvent(c_WinEventHook);
2013-05-31 14:28:39 +00:00
c_WinEventHook = nullptr;
}
if (c_HelperWindow)
{
DestroyWindow(c_HelperWindow);
2013-05-31 14:28:39 +00:00
c_HelperWindow = nullptr;
}
if (c_Window)
{
DestroyWindow(c_Window);
2013-05-31 14:28:39 +00:00
c_Window = nullptr;
}
}
2011-11-19 11:32:23 +00:00
/*
** Retrieves the multi-monitor information.
**
*/
BOOL CALLBACK MyInfoEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData)
{
2012-06-01 13:13:01 +00:00
MultiMonitorInfo* m = (MultiMonitorInfo*)dwData;
MONITORINFOEX info;
info.cbSize = sizeof(MONITORINFOEX);
GetMonitorInfo(hMonitor, &info);
2013-05-31 14:18:52 +00:00
if (g_Rainmeter->GetDebug())
{
2013-05-30 14:19:42 +00:00
LogDebug(info.szDevice);
LogDebugF(L" Flags : %s(0x%08X)", (info.dwFlags & MONITORINFOF_PRIMARY) ? L"PRIMARY " : L"", info.dwFlags);
LogDebugF(L" Handle : 0x%p", hMonitor);
LogDebugF(L" ScrArea : L=%i, T=%i, R=%i, B=%i (W=%i, H=%i)",
lprcMonitor->left, lprcMonitor->top, lprcMonitor->right, lprcMonitor->bottom,
lprcMonitor->right - lprcMonitor->left, lprcMonitor->bottom - lprcMonitor->top);
2013-05-30 14:19:42 +00:00
LogDebugF(L" WorkArea : L=%i, T=%i, R=%i, B=%i (W=%i, H=%i)",
info.rcWork.left, info.rcWork.top, info.rcWork.right, info.rcWork.bottom,
info.rcWork.right - info.rcWork.left, info.rcWork.bottom - info.rcWork.top);
}
2013-05-31 14:28:39 +00:00
if (m == nullptr) return TRUE;
if (m->useEnumDisplayDevices)
{
for (auto iter = m->monitors.begin(); iter != m->monitors.end(); ++iter)
{
2013-05-31 14:28:39 +00:00
if ((*iter).handle == nullptr && _wcsicmp(info.szDevice, (*iter).deviceName.c_str()) == 0)
{
(*iter).handle = hMonitor;
(*iter).screen = *lprcMonitor;
(*iter).work = info.rcWork;
break;
}
}
}
else // use only EnumDisplayMonitors
{
2012-06-01 13:13:01 +00:00
MonitorInfo monitor;
monitor.active = true;
monitor.handle = hMonitor;
monitor.screen = *lprcMonitor;
monitor.work = info.rcWork;
2011-12-09 19:49:06 +00:00
monitor.deviceName = info.szDevice; // E.g. "\\.\DISPLAY1"
// Get the monitor name (E.g. "Generic Non-PnP Monitor")
DISPLAY_DEVICE ddm = {sizeof(DISPLAY_DEVICE)};
DWORD dwMon = 0;
while (EnumDisplayDevices(info.szDevice, dwMon++, &ddm, 0))
{
if (ddm.StateFlags & DISPLAY_DEVICE_ACTIVE && ddm.StateFlags & DISPLAY_DEVICE_ATTACHED)
{
2011-12-09 19:49:06 +00:00
monitor.monitorName.assign(ddm.DeviceString, wcsnlen(ddm.DeviceString, _countof(ddm.DeviceString)));
break;
}
}
m->monitors.push_back(monitor);
if (info.dwFlags & MONITORINFOF_PRIMARY)
{
// It's primary monitor!
m->primary = (int)m->monitors.size();
}
}
return TRUE;
}
2011-11-19 11:32:23 +00:00
/*
** Returns the number of monitors.
**
*/
2013-05-31 14:18:52 +00:00
size_t System::GetMonitorCount()
{
if (c_Monitors.monitors.empty())
{
SetMultiMonitorInfo();
}
return c_Monitors.monitors.size();
}
2011-11-19 11:32:23 +00:00
/*
** Sets the multi-monitor information.
**
*/
2013-05-31 14:18:52 +00:00
void System::SetMultiMonitorInfo()
{
2012-06-01 13:13:01 +00:00
std::vector<MonitorInfo>& monitors = c_Monitors.monitors;
2013-05-31 14:18:52 +00:00
bool logging = g_Rainmeter->GetDebug();
c_Monitors.vsT = GetSystemMetrics(SM_YVIRTUALSCREEN);
c_Monitors.vsL = GetSystemMetrics(SM_XVIRTUALSCREEN);
c_Monitors.vsH = GetSystemMetrics(SM_CYVIRTUALSCREEN);
c_Monitors.vsW = GetSystemMetrics(SM_CXVIRTUALSCREEN);
c_Monitors.primary = 1; // If primary screen is not found, 1st screen is assumed as primary screen.
c_Monitors.useEnumDisplayDevices = true;
c_Monitors.useEnumDisplayMonitors = false;
if (logging)
{
2013-05-30 14:19:42 +00:00
LogDebug(L"------------------------------");
LogDebug(L"* EnumDisplayDevices / EnumDisplaySettings API");
}
DISPLAY_DEVICE dd = {sizeof(DISPLAY_DEVICE)};
2013-05-31 14:28:39 +00:00
if (EnumDisplayDevices(nullptr, 0, &dd, 0))
{
DWORD dwDevice = 0;
do
{
std::wstring msg;
2011-12-09 19:49:06 +00:00
std::wstring deviceName(dd.DeviceName, wcsnlen(dd.DeviceName, _countof(dd.DeviceName)));
std::wstring deviceString;
if (logging)
{
2011-12-09 19:49:06 +00:00
deviceString.assign(dd.DeviceString, wcsnlen(dd.DeviceString, _countof(dd.DeviceString)));
2013-05-30 14:19:42 +00:00
LogDebug(deviceName.c_str());
if (dd.StateFlags & DISPLAY_DEVICE_ACTIVE)
{
msg += L"ACTIVE ";
}
if (dd.StateFlags & DISPLAY_DEVICE_MULTI_DRIVER)
{
msg += L"MULTI ";
}
if (dd.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE)
{
msg += L"PRIMARY ";
}
if (dd.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER)
{
msg += L"MIRROR ";
}
if (dd.StateFlags & DISPLAY_DEVICE_VGA_COMPATIBLE)
{
msg += L"VGA ";
}
if (dd.StateFlags & DISPLAY_DEVICE_REMOVABLE)
{
msg += L"REMOVABLE ";
}
if (dd.StateFlags & DISPLAY_DEVICE_MODESPRUNED)
{
msg += L"PRUNED ";
}
if (dd.StateFlags & DISPLAY_DEVICE_REMOTE)
{
msg += L"REMOTE ";
}
if (dd.StateFlags & DISPLAY_DEVICE_DISCONNECT)
{
msg += L"DISCONNECT ";
}
}
if ((dd.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER) == 0)
{
2012-06-01 13:13:01 +00:00
MonitorInfo monitor = {0};
2013-05-31 14:28:39 +00:00
monitor.handle = nullptr;
2011-12-09 19:49:06 +00:00
monitor.deviceName = deviceName; // E.g. "\\.\DISPLAY1"
// Get the monitor name (E.g. "Generic Non-PnP Monitor")
DISPLAY_DEVICE ddm = {sizeof(DISPLAY_DEVICE)};
DWORD dwMon = 0;
2011-12-09 19:49:06 +00:00
while (EnumDisplayDevices(deviceName.c_str(), dwMon++, &ddm, 0))
{
if (ddm.StateFlags & DISPLAY_DEVICE_ACTIVE && ddm.StateFlags & DISPLAY_DEVICE_ATTACHED)
{
2011-12-09 19:49:06 +00:00
monitor.monitorName.assign(ddm.DeviceString, wcsnlen(ddm.DeviceString, _countof(ddm.DeviceString)));
if (logging)
{
2013-05-30 14:19:42 +00:00
LogDebugF(L" Name : %s", monitor.monitorName.c_str());
}
break;
}
}
if (logging)
{
2013-05-30 14:19:42 +00:00
LogDebugF(L" Adapter : %s", deviceString.c_str());
LogDebugF(L" Flags : %s(0x%08X)", msg.c_str(), dd.StateFlags);
}
if (dd.StateFlags & DISPLAY_DEVICE_ACTIVE)
{
monitor.active = true;
DEVMODE dm = {0};
dm.dmSize = sizeof(DEVMODE);
2011-12-09 19:49:06 +00:00
if (EnumDisplaySettings(deviceName.c_str(), ENUM_CURRENT_SETTINGS, &dm))
{
POINT pos = {dm.dmPosition.x, dm.dmPosition.y};
monitor.handle = MonitorFromPoint(pos, MONITOR_DEFAULTTONULL);
if (logging)
{
2013-05-30 14:19:42 +00:00
LogDebugF(L" Handle : 0x%p", monitor.handle);
}
}
2013-05-31 14:28:39 +00:00
if (monitor.handle != nullptr)
{
MONITORINFO info = {sizeof(MONITORINFO)};
GetMonitorInfo(monitor.handle, &info);
monitor.screen = info.rcMonitor;
monitor.work = info.rcWork;
if (logging)
{
2013-05-30 14:19:42 +00:00
LogDebugF(L" ScrArea : L=%i, T=%i, R=%i, B=%i (W=%i, H=%i)",
info.rcMonitor.left, info.rcMonitor.top, info.rcMonitor.right, info.rcMonitor.bottom,
info.rcMonitor.right - info.rcMonitor.left, info.rcMonitor.bottom - info.rcMonitor.top);
2013-05-30 14:19:42 +00:00
LogDebugF(L" WorkArea : L=%i, T=%i, R=%i, B=%i (W=%i, H=%i)",
info.rcWork.left, info.rcWork.top, info.rcWork.right, info.rcWork.bottom,
info.rcWork.right - info.rcWork.left, info.rcWork.bottom - info.rcWork.top);
}
}
else // monitor not found
{
c_Monitors.useEnumDisplayMonitors = true;
}
}
else
{
monitor.active = false;
}
monitors.push_back(monitor);
if (dd.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE)
{
// It's primary monitor!
c_Monitors.primary = (int)monitors.size();
}
}
else
{
if (logging)
{
2013-05-30 14:19:42 +00:00
LogDebugF(L" Adapter : %s", deviceString.c_str());
LogDebugF(L" Flags : %s(0x%08X)", msg.c_str(), dd.StateFlags);
}
}
2010-03-30 22:37:05 +00:00
++dwDevice;
}
2013-05-31 14:28:39 +00:00
while (EnumDisplayDevices(nullptr, dwDevice, &dd, 0));
}
if (monitors.empty()) // Failed to enumerate the non-mirroring monitors
{
2013-05-30 14:19:42 +00:00
LogWarning(L"Failed to enumerate the non-mirroring monitors. Only EnumDisplayMonitors is used instead.");
c_Monitors.useEnumDisplayDevices = false;
c_Monitors.useEnumDisplayMonitors = true;
}
if (logging)
{
2013-05-30 14:19:42 +00:00
LogDebug(L"------------------------------");
LogDebug(L"* EnumDisplayMonitors API");
}
if (c_Monitors.useEnumDisplayMonitors)
{
2013-05-31 14:28:39 +00:00
EnumDisplayMonitors(nullptr, nullptr, MyInfoEnumProc, (LPARAM)(&c_Monitors));
if (monitors.empty()) // Failed to enumerate the monitors
{
2013-05-30 14:19:42 +00:00
LogWarning(L"Failed to enumerate monitors. Using dummy monitor info.");
c_Monitors.useEnumDisplayMonitors = false;
2012-06-01 13:13:01 +00:00
MonitorInfo monitor;
2011-12-09 19:49:06 +00:00
monitor.active = true;
POINT pos = {0, 0};
monitor.handle = MonitorFromPoint(pos, MONITOR_DEFAULTTOPRIMARY);
monitor.screen.left = 0;
monitor.screen.top = 0;
monitor.screen.right = GetSystemMetrics(SM_CXSCREEN);
monitor.screen.bottom = GetSystemMetrics(SM_CYSCREEN);
2011-12-09 19:49:06 +00:00
if (SystemParametersInfo(SPI_GETWORKAREA, 0, &(monitor.work), 0) == 0) // failed
{
monitor.work = monitor.screen;
}
monitor.deviceName = L"DUMMY";
monitors.push_back(monitor);
c_Monitors.primary = 1;
}
}
else
{
if (logging)
{
2013-05-31 14:28:39 +00:00
EnumDisplayMonitors(nullptr, nullptr, MyInfoEnumProc, (LPARAM)nullptr); // Only logging
}
}
if (logging)
{
2013-05-30 14:19:42 +00:00
LogDebug(L"------------------------------");
std::wstring method = L"* METHOD: ";
if (c_Monitors.useEnumDisplayDevices)
{
method += L"EnumDisplayDevices + ";
method += c_Monitors.useEnumDisplayMonitors ? L"EnumDisplayMonitors Mode" : L"EnumDisplaySettings Mode";
}
else
{
method += c_Monitors.useEnumDisplayMonitors ? L"EnumDisplayMonitors Mode" : L"Dummy Mode";
}
2013-05-30 14:19:42 +00:00
LogDebug(method.c_str());
2013-05-30 14:19:42 +00:00
LogDebugF(L"* MONITORS: Count=%i, Primary=@%i", (int)monitors.size(), c_Monitors.primary);
LogDebug(L"@0: Virtual screen");
LogDebugF(L" L=%i, T=%i, R=%i, B=%i (W=%i, H=%i)",
c_Monitors.vsL, c_Monitors.vsT, c_Monitors.vsL + c_Monitors.vsW, c_Monitors.vsT + c_Monitors.vsH,
c_Monitors.vsW, c_Monitors.vsH);
int i = 1;
for (auto iter = monitors.cbegin(); iter != monitors.cend(); ++iter, ++i)
{
if ((*iter).active)
{
2013-05-30 14:19:42 +00:00
LogDebugF(L"@%i: %s (active), MonitorName: %s", i, (*iter).deviceName.c_str(), (*iter).monitorName.c_str());
LogDebugF(L" L=%i, T=%i, R=%i, B=%i (W=%i, H=%i)",
(*iter).screen.left, (*iter).screen.top, (*iter).screen.right, (*iter).screen.bottom,
(*iter).screen.right - (*iter).screen.left, (*iter).screen.bottom - (*iter).screen.top);
}
else
{
2013-05-30 14:19:42 +00:00
LogDebugF(L"@%i: %s (inactive), MonitorName: %s", i, (*iter).deviceName.c_str(), (*iter).monitorName.c_str());
}
}
2013-05-30 14:19:42 +00:00
LogDebug(L"------------------------------");
}
}
2011-11-19 11:32:23 +00:00
/*
** Updates the workarea information.
**
*/
2013-05-31 14:18:52 +00:00
void System::UpdateWorkareaInfo()
{
2012-06-01 13:13:01 +00:00
std::vector<MonitorInfo>& monitors = c_Monitors.monitors;
if (monitors.empty())
{
SetMultiMonitorInfo();
return;
}
int i = 1;
for (auto iter = monitors.begin(); iter != monitors.end(); ++iter, ++i)
{
2013-05-31 14:28:39 +00:00
if ((*iter).active && (*iter).handle != nullptr)
{
MONITORINFO info = {sizeof(MONITORINFO)};
GetMonitorInfo((*iter).handle, &info);
(*iter).work = info.rcWork;
2013-05-31 14:18:52 +00:00
if (g_Rainmeter->GetDebug())
{
2013-05-30 14:19:42 +00:00
LogDebugF(L"WorkArea@%i : L=%i, T=%i, R=%i, B=%i (W=%i, H=%i)",
i,
info.rcWork.left, info.rcWork.top, info.rcWork.right, info.rcWork.bottom,
info.rcWork.right - info.rcWork.left, info.rcWork.bottom - info.rcWork.top);
}
}
}
}
/*
** Finds the Default Shell's window.
**
*/
2013-05-31 14:18:52 +00:00
HWND System::GetDefaultShellWindow()
{
2013-05-31 14:28:39 +00:00
static HWND c_ShellW = nullptr; // cache
HWND ShellW = GetShellWindow();
if (ShellW)
{
if (ShellW == c_ShellW)
{
2011-04-19 01:20:17 +00:00
return ShellW;
}
else
{
2013-01-25 17:08:41 +00:00
const int classLen = _countof(L"Progman") + 1;
2011-11-18 07:33:41 +00:00
WCHAR className[classLen];
if (!(GetClassName(ShellW, className, classLen) > 0 &&
2011-08-13 10:03:16 +00:00
wcscmp(className, L"Progman") == 0))
{
2013-05-31 14:28:39 +00:00
ShellW = nullptr;
}
}
}
2011-08-13 10:03:16 +00:00
c_ShellW = ShellW;
return ShellW;
}
/*
2011-04-26 09:58:06 +00:00
** Finds the WorkerW window.
2013-05-31 14:28:39 +00:00
** If the WorkerW window is not active, returns nullptr.
**
*/
2013-05-31 14:18:52 +00:00
HWND System::GetWorkerW()
{
2013-05-31 14:28:39 +00:00
static HWND c_DefView = nullptr; // cache
HWND ShellW = GetDefaultShellWindow();
2013-05-31 14:28:39 +00:00
if (!ShellW) return nullptr; // Default Shell (Explorer) not running
2011-08-13 10:03:16 +00:00
if (c_DefView && IsWindow(c_DefView))
{
HWND parent = GetAncestor(c_DefView, GA_PARENT);
if (parent)
{
if (parent == ShellW)
{
2013-05-31 14:28:39 +00:00
return nullptr;
2011-08-13 10:03:16 +00:00
}
else
{
2013-01-25 17:08:41 +00:00
const int classLen = _countof(L"WorkerW") + 1;
2011-11-18 07:33:41 +00:00
WCHAR className[classLen];
if (GetClassName(parent, className, classLen) > 0 &&
2011-08-13 10:03:16 +00:00
wcscmp(className, L"WorkerW") == 0)
{
return parent;
}
}
}
}
2013-05-31 14:28:39 +00:00
HWND WorkerW = nullptr, DefView = FindWindowEx(ShellW, nullptr, L"SHELLDLL_DefView", L"");
if (DefView == nullptr)
{
2013-05-31 14:28:39 +00:00
while (WorkerW = FindWindowEx(nullptr, WorkerW, L"WorkerW", L""))
{
2011-08-13 10:03:16 +00:00
if (IsWindowVisible(WorkerW) &&
BelongToSameProcess(ShellW, WorkerW) &&
2013-05-31 14:28:39 +00:00
(DefView = FindWindowEx(WorkerW, nullptr, L"SHELLDLL_DefView", L"")))
{
2011-08-13 10:03:16 +00:00
break;
}
}
}
2011-08-13 10:03:16 +00:00
c_DefView = DefView;
return WorkerW;
}
/*
** Returns the first window whose position is not ZPOSITION_ONDESKTOP,
** ZPOSITION_BOTTOM, or ZPOSITION_NORMAL.
**
*/
2013-05-31 14:18:52 +00:00
HWND System::GetBackmostTopWindow()
{
HWND winPos = c_HelperWindow;
// Skip all ZPOSITION_ONDESKTOP, ZPOSITION_BOTTOM, and ZPOSITION_NORMAL windows
while (winPos = ::GetNextWindow(winPos, GW_HWNDPREV))
{
2013-05-31 14:18:52 +00:00
MeterWindow* wnd = g_Rainmeter->GetMeterWindow(winPos);
if (!wnd ||
(wnd->GetWindowZPosition() != ZPOSITION_NORMAL &&
wnd->GetWindowZPosition() != ZPOSITION_ONDESKTOP &&
wnd->GetWindowZPosition() != ZPOSITION_ONBOTTOM))
{
break;
}
}
return winPos;
}
/*
** Checks whether the given windows belong to the same process.
**
*/
2013-05-31 14:18:52 +00:00
bool System::BelongToSameProcess(HWND hwndA, HWND hwndB)
{
DWORD procAId = 0, procBId = 0;
GetWindowThreadProcessId(hwndA, &procAId);
GetWindowThreadProcessId(hwndB, &procBId);
return (procAId == procBId);
}
/*
** Retrieves the Rainmeter's meter windows in Z-order.
**
*/
BOOL CALLBACK MyEnumWindowsProc(HWND hwnd, LPARAM lParam)
{
2013-05-31 14:18:52 +00:00
bool logging = g_Rainmeter->GetDebug() && DEBUG_VERBOSE;
2013-01-25 17:08:41 +00:00
const int classLen = _countof(METERWINDOW_CLASS_NAME) + (DEBUG_VERBOSE ? 32 : 1);
2011-11-18 07:33:41 +00:00
WCHAR className[classLen];
2013-05-31 14:18:52 +00:00
MeterWindow* Window;
2011-09-03 21:51:25 +00:00
WCHAR flag;
2011-11-18 07:33:41 +00:00
if (GetClassName(hwnd, className, classLen) > 0 &&
2010-09-04 08:04:13 +00:00
wcscmp(className, METERWINDOW_CLASS_NAME) == 0 &&
2013-05-31 14:18:52 +00:00
(Window = g_Rainmeter->GetMeterWindow(hwnd)))
{
ZPOSITION zPos = Window->GetWindowZPosition();
if (zPos == ZPOSITION_ONDESKTOP ||
2013-05-31 14:18:52 +00:00
(zPos == ZPOSITION_NORMAL && g_Rainmeter->IsNormalStayDesktop()) ||
zPos == ZPOSITION_ONBOTTOM)
{
if (lParam)
{
2013-05-31 14:18:52 +00:00
((std::vector<MeterWindow*>*)lParam)->push_back(Window);
}
2011-09-03 21:51:25 +00:00
if (logging) flag = L'+';
}
else
{
2011-09-03 21:51:25 +00:00
if (logging) flag = L'-';
}
if (logging)
{
2013-05-30 14:19:42 +00:00
LogDebugF(L"%c [%c] 0x%p : %s (Name: \"%s\", zPos=%i)",
flag, IsWindowVisible(hwnd) ? L'V' : L'H', hwnd, className, Window->GetFolderPath().c_str(), (int)zPos);
}
}
else
{
2011-09-03 21:51:25 +00:00
if (logging)
{
2013-05-31 14:18:52 +00:00
flag = (hwnd == System::GetHelperWindow()) ? L'o' : ' ';
2013-05-30 14:19:42 +00:00
LogDebugF(L"%c [%c] 0x%p : %s", flag, IsWindowVisible(hwnd) ? L'V' : L'H', hwnd, className);
2011-09-03 21:51:25 +00:00
}
}
return TRUE;
}
/*
** Arranges the meter window in Z-order.
**
*/
2013-05-31 14:18:52 +00:00
void System::ChangeZPosInOrder()
{
2013-05-31 14:18:52 +00:00
bool logging = g_Rainmeter->GetDebug() && DEBUG_VERBOSE;
std::vector<MeterWindow*> windowsInZOrder;
2013-05-30 14:19:42 +00:00
if (logging) LogDebug(L"1: ----- BEFORE -----");
// Retrieve the Rainmeter's meter windows in Z-order
EnumWindows(MyEnumWindowsProc, (LPARAM)(&windowsInZOrder));
2011-11-18 07:33:41 +00:00
auto resetZPos = [&](ZPOSITION zpos)
{
// Reset ZPos in Z-order (Bottom)
2013-05-31 14:18:52 +00:00
std::vector<MeterWindow*>::const_iterator iter = windowsInZOrder.begin();
2012-02-07 08:32:37 +00:00
for ( ; iter != windowsInZOrder.end(); ++iter)
{
if ((*iter)->GetWindowZPosition() == zpos)
{
(*iter)->ChangeZPos(zpos); // reset
}
}
};
2013-05-31 14:18:52 +00:00
if (g_Rainmeter->IsNormalStayDesktop())
{
resetZPos(ZPOSITION_NORMAL);
}
if (!c_ShowDesktop)
{
resetZPos(ZPOSITION_ONBOTTOM);
}
resetZPos(ZPOSITION_ONDESKTOP);
if (logging)
{
2013-05-30 14:19:42 +00:00
LogDebug(L"2: ----- AFTER -----");
// Log all windows in Z-order
2013-05-31 14:28:39 +00:00
EnumWindows(MyEnumWindowsProc, (LPARAM)nullptr);
}
}
/*
** Moves the helper window to the reference position.
**
*/
2013-05-31 14:18:52 +00:00
void System::PrepareHelperWindow(HWND WorkerW)
{
2013-05-31 14:18:52 +00:00
bool logging = g_Rainmeter->GetDebug() && DEBUG_VERBOSE;
2011-09-03 21:51:25 +00:00
SetWindowPos(c_Window, HWND_BOTTOM, 0, 0, 0, 0, ZPOS_FLAGS); // always on bottom
2010-12-21 04:49:01 +00:00
if (c_ShowDesktop && WorkerW)
{
// Set WS_EX_TOPMOST flag
2011-09-03 21:51:25 +00:00
SetWindowPos(c_HelperWindow, HWND_TOPMOST, 0, 0, 0, 0, ZPOS_FLAGS);
// Find the "backmost" topmost window
HWND hwnd = WorkerW;
while (hwnd = ::GetNextWindow(hwnd, GW_HWNDPREV))
{
if (GetWindowLongPtr(hwnd, GWL_EXSTYLE) & WS_EX_TOPMOST)
{
2011-04-19 01:20:17 +00:00
WCHAR className[64], windowText[64];
if (logging)
{
2011-04-19 01:20:17 +00:00
GetClassName(hwnd, className, 64);
GetWindowText(hwnd, windowText, 64);
2011-09-03 21:51:25 +00:00
2011-09-06 08:41:42 +00:00
SetLastError(ERROR_SUCCESS);
}
// Insert the helper window after the found window
2011-09-03 21:51:25 +00:00
if (0 != SetWindowPos(c_HelperWindow, hwnd, 0, 0, 0, 0, ZPOS_FLAGS))
{
if (logging)
{
2013-05-30 14:19:42 +00:00
LogDebugF(L"System: HelperWindow: hwnd=0x%p (WorkerW=0x%p), hwndInsertAfter=0x%p (\"%s\" %s) - %s",
c_HelperWindow, WorkerW, hwnd, windowText, className, (GetWindowLongPtr(c_HelperWindow, GWL_EXSTYLE) & WS_EX_TOPMOST) ? L"TOPMOST" : L"NORMAL");
}
return;
}
if (logging)
{
2011-09-03 21:51:25 +00:00
DWORD err = GetLastError();
2013-05-30 14:19:42 +00:00
LogDebugF(L"System: HelperWindow: hwnd=0x%p (WorkerW=0x%p), hwndInsertAfter=0x%p (\"%s\" %s) - FAILED (ErrorCode=0x%08X)",
2011-09-03 21:51:25 +00:00
c_HelperWindow, WorkerW, hwnd, windowText, className, err);
}
}
}
if (logging)
{
2013-05-30 14:19:42 +00:00
LogDebugF(L"System: HelperWindow: hwnd=0x%p (WorkerW=0x%p), hwndInsertAfter=HWND_TOPMOST - %s",
c_HelperWindow, WorkerW, (GetWindowLongPtr(c_HelperWindow, GWL_EXSTYLE) & WS_EX_TOPMOST) ? L"TOPMOST" : L"NORMAL");
}
}
else
{
// Insert the helper window to the bottom
2011-09-03 21:51:25 +00:00
SetWindowPos(c_HelperWindow, HWND_BOTTOM, 0, 0, 0, 0, ZPOS_FLAGS);
if (logging)
{
2013-05-30 14:19:42 +00:00
LogDebugF(L"System: HelperWindow: hwnd=0x%p (WorkerW=0x%p), hwndInsertAfter=HWND_BOTTOM - %s",
c_HelperWindow, WorkerW, (GetWindowLongPtr(c_HelperWindow, GWL_EXSTYLE) & WS_EX_TOPMOST) ? L"TOPMOST" : L"NORMAL");
}
}
}
/*
** Changes the "Show Desktop" state.
**
*/
2013-05-31 14:18:52 +00:00
bool System::CheckDesktopState(HWND WorkerW)
{
2013-05-31 14:28:39 +00:00
HWND hwnd = nullptr;
if (WorkerW && IsWindowVisible(WorkerW))
{
2013-05-31 14:28:39 +00:00
hwnd = FindWindowEx(nullptr, WorkerW, L"RainmeterSystem", L"System");
}
bool stateChanged = (hwnd && !c_ShowDesktop) || (!hwnd && c_ShowDesktop);
if (stateChanged)
{
c_ShowDesktop = !c_ShowDesktop;
2013-05-31 14:18:52 +00:00
if (g_Rainmeter->GetDebug())
{
2013-05-30 14:19:42 +00:00
LogDebugF(L"System: \"Show %s\" has been detected.",
c_ShowDesktop ? L"desktop" : L"open windows");
}
PrepareHelperWindow(WorkerW);
ChangeZPosInOrder();
if (c_ShowDesktop)
{
2013-05-31 14:28:39 +00:00
SetTimer(c_Window, TIMER_SHOWDESKTOP, INTERVAL_RESTOREWINDOWS, nullptr);
}
else
{
2013-05-31 14:28:39 +00:00
SetTimer(c_Window, TIMER_SHOWDESKTOP, INTERVAL_SHOWDESKTOP, nullptr);
}
}
return stateChanged;
}
/*
** The event hook procedure
**
*/
2013-05-31 14:18:52 +00:00
void CALLBACK System::MyWinEventProc(HWINEVENTHOOK hWinEventHook, DWORD event, HWND hwnd, LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime)
{
if (event == EVENT_SYSTEM_FOREGROUND)
{
if (!c_ShowDesktop)
{
2013-01-25 17:08:41 +00:00
const int classLen = _countof(L"WorkerW") + 1;
2011-11-18 07:33:41 +00:00
WCHAR className[classLen];
if (GetClassName(hwnd, className, classLen) > 0 &&
wcscmp(className, L"WorkerW") == 0 &&
BelongToSameProcess(GetDefaultShellWindow(), hwnd))
{
const int max = 5;
int loop = 0;
2013-05-31 14:28:39 +00:00
while (loop < max && FindWindowEx(hwnd, nullptr, L"SHELLDLL_DefView", L"") == nullptr)
{
Sleep(2); // Wait for 2-16 ms before retrying
++loop;
}
if (loop < max)
{
loop = 0;
while (loop < max && !CheckDesktopState(hwnd))
{
Sleep(2); // Wait for 2-16 ms before retrying
++loop;
}
}
}
}
}
}
/*
** The window procedure
**
*/
2013-05-31 14:18:52 +00:00
LRESULT CALLBACK System::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
2010-12-21 04:49:01 +00:00
if (hWnd != c_Window)
{
2011-09-06 08:41:42 +00:00
if (uMsg == WM_WINDOWPOSCHANGING)
{
((LPWINDOWPOS)lParam)->flags |= SWP_NOZORDER;
return 0;
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
switch (uMsg)
{
case WM_WINDOWPOSCHANGING:
((LPWINDOWPOS)lParam)->flags |= SWP_NOZORDER;
break;
case WM_TIMER:
switch (wParam)
{
case TIMER_SHOWDESKTOP:
if (wParam == TIMER_SHOWDESKTOP)
{
CheckDesktopState(GetWorkerW());
}
break;
case TIMER_RESUME:
KillTimer(hWnd, TIMER_RESUME);
2013-05-31 14:18:52 +00:00
if (g_Rainmeter->IsRedrawable())
{
2013-05-31 14:18:52 +00:00
std::map<std::wstring, MeterWindow*>::const_iterator iter = g_Rainmeter->GetAllMeterWindows().begin();
for ( ; iter != g_Rainmeter->GetAllMeterWindows().end(); ++iter)
{
(*iter).second->RedrawWindow();
}
}
break;
}
break;
case WM_DISPLAYCHANGE:
2013-05-30 14:19:42 +00:00
LogNotice(L"System: Display settings changed");
ClearMultiMonitorInfo();
2013-05-31 14:18:52 +00:00
ConfigParser::ClearMultiMonitorVariables();
case WM_SETTINGCHANGE:
if (uMsg == WM_DISPLAYCHANGE || (/*uMsg == WM_SETTINGCHANGE &&*/ wParam == SPI_SETWORKAREA))
{
if (uMsg == WM_SETTINGCHANGE) // SPI_SETWORKAREA
{
2013-05-30 14:19:42 +00:00
LogNotice(L"System: Work area changed");
UpdateWorkareaInfo();
2013-05-31 14:18:52 +00:00
ConfigParser::UpdateWorkareaVariables();
}
// Deliver WM_DISPLAYCHANGE / WM_SETTINGCHANGE message to all meter windows
2013-05-31 14:18:52 +00:00
std::map<std::wstring, MeterWindow*>::const_iterator iter = g_Rainmeter->GetAllMeterWindows().begin();
for ( ; iter != g_Rainmeter->GetAllMeterWindows().end(); ++iter)
{
PostMessage((*iter).second->GetWindow(), WM_METERWINDOW_DELAYED_MOVE, (WPARAM)uMsg, (LPARAM)0);
}
}
break;
case WM_POWERBROADCAST:
if (wParam == PBT_APMRESUMESUSPEND)
{
// Deliver PBT_APMRESUMESUSPEND event to all meter windows
2013-05-31 14:28:39 +00:00
SetTimer(hWnd, TIMER_RESUME, INTERVAL_RESUME, nullptr);
}
return TRUE;
default:
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
return 0;
}
/*
** Retrieves the number of milliseconds that have elapsed since the system was started.
** In XP, returns the predictive value due to the 32bit limitation.
**
*/
2013-05-31 14:18:52 +00:00
ULONGLONG System::GetTickCount64()
{
typedef ULONGLONG (WINAPI * FPGETTICKCOUNT64)();
static FPGETTICKCOUNT64 c_GetTickCount64 = (FPGETTICKCOUNT64)GetProcAddress(GetModuleHandle(L"kernel32"), "GetTickCount64");
if (c_GetTickCount64)
{
return c_GetTickCount64();
}
else
{
static ULONGLONG lastTicks = 0;
ULONGLONG ticks = GetTickCount();
while (ticks < lastTicks) ticks += 0x100000000;
lastTicks = ticks;
return ticks;
}
}
/*
** Gets the cursor position in last message retrieved by GetMessage().
**
*/
2013-05-31 14:18:52 +00:00
POINT System::GetCursorPosition()
{
DWORD pos = GetMessagePos();
POINT pt = { GET_X_LPARAM(pos), GET_Y_LPARAM(pos) };
return pt;
}
2011-11-08 19:02:31 +00:00
/*
** Checks if file is writable.
**
*/
2013-05-31 14:18:52 +00:00
bool System::IsFileWritable(LPCWSTR file)
2011-11-08 19:02:31 +00:00
{
2013-05-31 14:28:39 +00:00
HANDLE hFile = CreateFile(file, GENERIC_WRITE, FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);
2011-11-08 19:02:31 +00:00
if (hFile == INVALID_HANDLE_VALUE)
{
return false;
}
CloseHandle(hFile);
return true;
}
/*
** This function is a wrapper function for LoadLibrary().
**
2011-09-29 17:14:51 +00:00
** Avoids loading a DLL from current directory.
**
*/
2013-05-31 14:18:52 +00:00
HMODULE System::RmLoadLibrary(LPCWSTR lpLibFileName, DWORD* dwError)
{
2011-09-29 17:14:51 +00:00
// Remove current directory from DLL search path
SetDllDirectory(L"");
SetLastError(ERROR_SUCCESS);
HMODULE hLib = LoadLibrary(lpLibFileName);
if (dwError)
{
*dwError = GetLastError();
}
return hLib;
}
/*
** Resets working directory to default.
**
*/
2013-05-31 14:18:52 +00:00
void System::ResetWorkingDirectory()
{
WCHAR directory[MAX_PATH] = {0};
GetCurrentDirectory(MAX_PATH, directory);
2012-03-23 16:45:35 +00:00
const WCHAR* workDir = c_WorkingDirectory.c_str();
if (_wcsicmp(directory, workDir) != 0)
{
2012-03-23 16:45:35 +00:00
SetCurrentDirectory(workDir);
}
}
/*
** Initializes a critical section object by using InitializeCriticalSectionEx function with CRITICAL_SECTION_NO_DEBUG_INFO flag.
** For more details: http://stackoverflow.com/questions/804848/critical-sections-leaking-memory-on-vista-win2008/
**
*/
2013-05-31 14:18:52 +00:00
void System::InitializeCriticalSection(LPCRITICAL_SECTION lpCriticalSection)
{
typedef BOOL (WINAPI * FPINITCRITEX)(LPCRITICAL_SECTION lpCriticalSection, DWORD dwSpinCount, DWORD Flags);
static FPINITCRITEX InitializeCriticalSectionEx = Platform::IsAtLeastWinVista() ?
(FPINITCRITEX)GetProcAddress(GetModuleHandle(L"Kernel32"), "InitializeCriticalSectionEx") : nullptr;
if (InitializeCriticalSectionEx)
{
if (InitializeCriticalSectionEx(lpCriticalSection, 0, CRITICAL_SECTION_NO_DEBUG_INFO))
{
return;
}
}
::InitializeCriticalSectionAndSpinCount(lpCriticalSection, 0);
}
/*
** Sets clipboard text to given string.
**
*/
2013-05-31 14:18:52 +00:00
void System::SetClipboardText(const std::wstring& text)
{
2013-05-31 14:28:39 +00:00
if (OpenClipboard(nullptr))
{
// Include terminating null char
size_t len = text.length() + 1;
HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE, len * sizeof(WCHAR));
if (hMem)
{
LPVOID data = GlobalLock(hMem);
2011-12-09 08:40:19 +00:00
memcpy(data, text.c_str(), len * sizeof(WCHAR));
GlobalUnlock(hMem);
2011-12-09 08:40:19 +00:00
EmptyClipboard();
if (!SetClipboardData(CF_UNICODETEXT, hMem))
{
GlobalFree(hMem);
}
}
CloseClipboard();
}
}
/*
** Sets the system wallpapar.
**
*/
2013-05-31 14:18:52 +00:00
void System::SetWallpaper(const std::wstring& wallpaper, const std::wstring& style)
{
if (!wallpaper.empty())
{
2012-02-04 16:51:14 +00:00
if (_waccess(wallpaper.c_str(), 0) == -1)
{
2013-05-30 14:19:42 +00:00
LogErrorF(L"!SetWallpaper: Unable to read file: %s", wallpaper.c_str());
2012-02-04 16:51:14 +00:00
return;
}
Bitmap* bitmap = Bitmap::FromFile(wallpaper.c_str());
if (bitmap && bitmap->GetLastStatus() == Ok)
{
2013-05-31 14:18:52 +00:00
std::wstring file = g_Rainmeter->GetSettingsPath() + L"Wallpaper.bmp";
const CLSID bmpClsid = { 0x557cf400, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } };
if (bitmap->Save(file.c_str(), &bmpClsid) == Ok)
{
if (!style.empty())
{
HKEY hKey;
if (RegOpenKeyEx(HKEY_CURRENT_USER, L"Control Panel\\Desktop", 0, KEY_SET_VALUE, &hKey) == ERROR_SUCCESS)
{
2013-05-31 14:28:39 +00:00
const WCHAR* wallStyle = nullptr;
const WCHAR* wallTile = L"0";
const WCHAR* option = style.c_str();
if (_wcsicmp(option, L"CENTER") == 0)
{
wallStyle = L"0";
}
else if (_wcsicmp(option, L"TILE") == 0)
{
wallStyle = L"0";
wallTile = L"1";
}
else if (_wcsicmp(option, L"STRETCH") == 0)
{
wallStyle = L"2";
}
else if (Platform::IsAtLeastWin7())
{
if (_wcsicmp(option, L"FIT") == 0)
{
wallStyle = L"6";
}
else if (_wcsicmp(option, L"FILL") == 0)
{
wallStyle = L"10";
}
}
if (wallStyle)
{
RegSetValueEx(hKey, L"WallpaperStyle", 0, REG_SZ, (const BYTE*)wallStyle, sizeof(WCHAR) * 2);
RegSetValueEx(hKey, L"TileWallpaper", 0, REG_SZ, (const BYTE*)wallTile, sizeof(WCHAR) * 2);
}
else
{
2013-05-30 14:19:42 +00:00
LogError(L"!SetWallpaper: Invalid style");
}
RegCloseKey(hKey);
}
}
SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, (void*)file.c_str(), SPIF_UPDATEINIFILE);
}
}
}
}
2011-03-29 19:21:57 +00:00
/*
** Copies files and folders from one location to another.
**
*/
2013-05-31 14:18:52 +00:00
bool System::CopyFiles(std::wstring from, std::wstring to, bool bMove)
{
// If given "from" path ends with path separator, remove it (Workaround for XP: error code 1026)
size_t len;
while (len = from.size(), len > 0 && PathUtil::IsSeparator(from[len - 1]))
{
from.resize(len - 1);
}
2012-05-30 05:10:12 +00:00
// The strings must end with double \0
from.append(1, L'\0');
to.append(1, L'\0');
2011-11-14 14:32:11 +00:00
SHFILEOPSTRUCT fo =
{
2013-05-31 14:28:39 +00:00
nullptr,
2011-11-14 14:32:11 +00:00
bMove ? FO_MOVE : FO_COPY,
2012-05-30 05:10:12 +00:00
from.c_str(),
to.c_str(),
2011-11-14 14:32:11 +00:00
FOF_NO_UI | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
};
int result = SHFileOperation(&fo);
if (result != 0)
{
2013-05-30 14:19:42 +00:00
LogErrorF(L"Copy error: From %s to %s (%i)", from.c_str(), to.c_str(), result);
return false;
}
return true;
}
2011-03-29 19:21:57 +00:00
/*
** Removes a file even if a file is read-only.
**
*/
2013-05-31 14:18:52 +00:00
bool System::RemoveFile(const std::wstring& file)
{
DWORD attr = GetFileAttributes(file.c_str());
if (attr == -1 || (attr & FILE_ATTRIBUTE_READONLY))
{
// Unset read-only
SetFileAttributes(file.c_str(), (attr == -1) ? FILE_ATTRIBUTE_NORMAL : attr - FILE_ATTRIBUTE_READONLY);
}
return (DeleteFile(file.c_str()) != 0);
}
/*
** Recursively removes folder.
**
*/
2013-05-31 14:18:52 +00:00
bool System::RemoveFolder(std::wstring folder)
{
// The strings must end with double nul
2012-06-10 10:14:49 +00:00
folder.append(1, L'\0');
2011-11-14 14:32:11 +00:00
SHFILEOPSTRUCT fo =
{
2013-05-31 14:28:39 +00:00
nullptr,
2011-11-14 14:32:11 +00:00
FO_DELETE,
2012-06-10 10:14:49 +00:00
folder.c_str(),
2013-05-31 14:28:39 +00:00
nullptr,
2011-11-14 14:32:11 +00:00
FOF_NO_UI | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
};
int result = SHFileOperation(&fo);
if (result != 0)
{
2013-05-30 14:19:42 +00:00
LogErrorF(L"Unable to delete folder %s (%i)", folder.c_str(), result);
return false;
}
return true;
}
2011-03-29 19:21:57 +00:00
/*
** Retrieves the "IniFileMapping" entries from Registry.
**
*/
2013-05-31 14:18:52 +00:00
void System::UpdateIniFileMappingList()
{
static ULONGLONG s_LastWriteTime = 0;
2011-11-10 13:44:19 +00:00
HKEY hKey;
LONG ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\IniFileMapping", 0, KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS, &hKey);
if (ret == ERROR_SUCCESS)
{
2011-11-10 13:44:19 +00:00
DWORD numSubKeys;
ULONGLONG ftLastWriteTime;
2011-11-10 13:44:19 +00:00
bool changed = false;
2013-05-31 14:28:39 +00:00
ret = RegQueryInfoKey(hKey, nullptr, nullptr, nullptr, &numSubKeys, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, (LPFILETIME)&ftLastWriteTime);
2011-11-10 13:44:19 +00:00
if (ret == ERROR_SUCCESS)
{
2013-05-30 14:19:42 +00:00
//LogDebugF(L"IniFileMapping: numSubKeys=%u, ftLastWriteTime=%llu", numSubKeys, ftLastWriteTime);
2011-11-10 13:44:19 +00:00
if (ftLastWriteTime != s_LastWriteTime ||
2011-11-10 13:44:19 +00:00
numSubKeys != c_IniFileMappings.size())
{
s_LastWriteTime = ftLastWriteTime;
2011-11-10 13:44:19 +00:00
if (numSubKeys > c_IniFileMappings.capacity())
{
c_IniFileMappings.reserve(numSubKeys);
}
changed = true;
}
}
2011-11-10 13:44:19 +00:00
else
{
s_LastWriteTime = 0;
2011-11-10 13:44:19 +00:00
changed = true;
}
if (changed)
{
if (!c_IniFileMappings.empty())
{
c_IniFileMappings.clear();
}
2011-11-14 14:32:11 +00:00
WCHAR* buffer = new WCHAR[MAX_PATH];
2011-11-10 13:44:19 +00:00
DWORD index = 0, cch = MAX_PATH;
2013-05-31 14:28:39 +00:00
while ((ret = RegEnumKeyEx(hKey, index++, buffer, &cch, nullptr, nullptr, nullptr, nullptr)) != ERROR_NO_MORE_ITEMS)
2011-11-10 13:44:19 +00:00
{
if (ret == ERROR_SUCCESS)
{
c_IniFileMappings.push_back(buffer);
}
cch = MAX_PATH;
}
2011-11-14 14:32:11 +00:00
delete [] buffer;
2011-11-10 13:44:19 +00:00
}
RegCloseKey(hKey);
}
}
2011-03-29 19:21:57 +00:00
/*
** Prepares a temporary file if iniFile is included in the "IniFileMapping" entries.
** If iniFile is not included, returns a empty string. If error occurred, returns "?".
** Note that a temporary file must be deleted by caller.
**
*/
2013-05-31 14:18:52 +00:00
std::wstring System::GetTemporaryFile(const std::wstring& iniFile)
{
std::wstring temporary;
2011-11-10 13:44:19 +00:00
if (!c_IniFileMappings.empty())
{
std::wstring::size_type pos = iniFile.find_last_of(L"\\/");
2011-11-10 13:44:19 +00:00
const WCHAR* filename = iniFile.c_str() + ((pos != std::wstring::npos) ? pos + 1 : 0);
2011-11-10 13:44:19 +00:00
std::vector<std::wstring>::const_iterator iter = c_IniFileMappings.begin();
for ( ; iter != c_IniFileMappings.end(); ++iter)
{
2011-11-10 13:44:19 +00:00
if (_wcsicmp((*iter).c_str(), filename) == 0)
{
2011-11-14 14:32:11 +00:00
WCHAR* buffer = new WCHAR[MAX_PATH];
2011-11-14 14:32:11 +00:00
if (GetTempPath(MAX_PATH, buffer) != 0 &&
GetTempFileName(buffer, L"cfg", 0, buffer) != 0)
{
temporary = buffer;
2011-11-10 13:44:19 +00:00
std::wstring tmp = GetTemporaryFile(temporary);
2011-11-14 14:32:11 +00:00
if (!tmp.empty() || !CopyFiles(iniFile, temporary)) // temporary is reserved or failed
{
RemoveFile(temporary);
2011-11-14 14:32:11 +00:00
if (tmp.empty())
{
temporary = L"?";
}
else
{
temporary.swap(tmp);
}
}
}
else // failed
{
2013-05-30 14:19:42 +00:00
LogErrorF(L"Unable to create temporary file to: %s", temporary.c_str());
2011-11-14 14:32:11 +00:00
temporary = L"?";
}
2011-11-14 14:32:11 +00:00
delete [] buffer;
break;
}
}
}
return temporary;
}