File: wutil.cpp

package info (click to toggle)
0ad 0.28.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 182,352 kB
  • sloc: cpp: 201,989; javascript: 19,730; ansic: 15,057; python: 6,597; sh: 2,046; perl: 1,232; xml: 543; java: 533; makefile: 105
file content (317 lines) | stat: -rw-r--r-- 8,058 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
/* Copyright (C) 2023 Wildfire Games.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "precompiled.h"
#include "lib/sysdep/os/win/wutil.h"

#include <stdio.h>
#include <stdlib.h>	// __argc

#include "lib/file/file.h"
#include "lib/posix/posix.h"
#include "lib/sysdep/sysdep.h"
#include "lib/sysdep/os/win/win.h"
#include "lib/sysdep/os/win/wdbg.h"	// wdbg_assert

#include <shlobj.h>	// SHGetFolderPath

#include <SDL_loadso.h>
#include <SDL_syswm.h>


//-----------------------------------------------------------------------------
// safe allocator

// may be used independently of libc malloc
// (in particular, before _cinit and while calling static dtors).
// used by wpthread critical section code.

void* wutil_Allocate(size_t size)
{
	const DWORD flags = HEAP_ZERO_MEMORY;
	return HeapAlloc(GetProcessHeap(), flags, size);
}

void wutil_Free(void* p)
{
	const DWORD flags = 0;
	HeapFree(GetProcessHeap(), flags, p);
}


//-----------------------------------------------------------------------------
// locks

// several init functions are before called before _cinit.
// POSIX static mutex init may not have been done by then,
// so we need our own lightweight functions.

static CRITICAL_SECTION cs[NUM_CS];
static bool cs_valid;

void wutil_Lock(WinLockId id)
{
	if(!cs_valid)
		return;
	EnterCriticalSection(&cs[id]);
}

void wutil_Unlock(WinLockId id)
{
	if(!cs_valid)
		return;
	LeaveCriticalSection(&cs[id]);
}

bool wutil_IsLocked(WinLockId id)
{
	if(!cs_valid)
		return false;
	const BOOL successfullyEntered = TryEnterCriticalSection(&cs[id]);
	if(!successfullyEntered)
		return true;	// still locked
	LeaveCriticalSection(&cs[id]);
	return false;	// probably not locked
}


static void InitLocks()
{
	for(int i = 0; i < NUM_CS; i++)
		InitializeCriticalSection(&cs[i]);

	cs_valid = true;
}

static void ShutdownLocks()
{
	cs_valid = false;

	for(int i = 0; i < NUM_CS; i++)
		DeleteCriticalSection(&cs[i]);
	memset(cs, 0, sizeof(cs));
}


//-----------------------------------------------------------------------------
// error codes

// only call after a Win32 function indicates failure.
Status StatusFromWin()
{
	switch(GetLastError())
	{
	case ERROR_BUSY:
	case WAIT_TIMEOUT:
		return ERR::AGAIN;
	case ERROR_OPERATION_ABORTED:
		return ERR::ABORTED;

	case ERROR_INVALID_HANDLE:
		return ERR::INVALID_HANDLE;
	case ERROR_INSUFFICIENT_BUFFER:
		return ERR::INVALID_SIZE;
	case ERROR_INVALID_PARAMETER:
	case ERROR_BAD_ARGUMENTS:
		return ERR::INVALID_PARAM;

	case ERROR_OUTOFMEMORY:
	case ERROR_NOT_ENOUGH_MEMORY:
		return ERR::NO_MEM;
	case ERROR_NOT_SUPPORTED:
	case ERROR_CALL_NOT_IMPLEMENTED:
	case ERROR_PROC_NOT_FOUND:
		return ERR::NOT_SUPPORTED;

	case ERROR_FILE_NOT_FOUND:
	case ERROR_PATH_NOT_FOUND:
		return ERR::FILE_NOT_FOUND;
	case ERROR_ACCESS_DENIED:
		return ERR::FILE_ACCESS;

	default:
		return ERR::FAIL;
	}
}

//-----------------------------------------------------------------------------
// directories

// Helper to avoid duplicating this setup
static OsPath GetFolderPath(int csidl)
{
	WinScopedPreserveLastError s;
	HWND hwnd = 0;	// ignored unless a dial-up connection is needed to access the folder
	HANDLE token = 0;
	wchar_t path[MAX_PATH];	// mandated by SHGetFolderPathW
	const HRESULT ret = SHGetFolderPathW(hwnd, csidl, token, 0, path);
	if (!SUCCEEDED(ret))
	{
		debug_printf("SHGetFolderPathW failed with HRESULT = 0x%08lx for csidl = 0x%04x\n", ret, csidl);
		debug_warn("SHGetFolderPathW failed (see debug output)");
	}
	if (GetLastError() == ERROR_NO_TOKEN)	// avoid polluting last error
		SetLastError(0);
	return OsPath(path);
}

OsPath wutil_LocalAppdataPath()
{
	// Local application data.
	return GetFolderPath(CSIDL_LOCAL_APPDATA);
}

OsPath wutil_RoamingAppdataPath()
{
	// Roaming application data.
	return GetFolderPath(CSIDL_APPDATA);
}

OsPath wutil_PersonalPath()
{
	// My documents.
	return GetFolderPath(CSIDL_PERSONAL);
}

//-----------------------------------------------------------------------------

Status wutil_SetPrivilege(const wchar_t* privilege, bool enable)
{
	WinScopedPreserveLastError s;

	HANDLE hToken;
	if(!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &hToken))
		return ERR::_1;

	TOKEN_PRIVILEGES tp;
	if (!LookupPrivilegeValueW(NULL, privilege, &tp.Privileges[0].Luid))
		return ERR::_2;
	tp.PrivilegeCount = 1;
	tp.Privileges[0].Attributes = enable? SE_PRIVILEGE_ENABLED : 0;

	SetLastError(0);
	const BOOL ok = AdjustTokenPrivileges(hToken, FALSE, &tp, 0, 0, 0);
	if(!ok || GetLastError() != 0)
		return ERR::_3;

	WARN_IF_FALSE(CloseHandle(hToken));
	return INFO::OK;
}


//-----------------------------------------------------------------------------
// module handle

HMODULE wutil_LibModuleHandle()
{
	return GetModuleHandle(0);
}

//-----------------------------------------------------------------------------
// find main window

// this is required by the error dialog and clipboard code.
// note that calling from wutil_Init won't work, because the app will not
// have created its window by then.

static HWND hAppWindow;

void wutil_SetAppWindow(SDL_Window* window)
{
	SDL_SysWMinfo wmInfo;
	SDL_VERSION(&wmInfo.version);
	if (SDL_GetWindowWMInfo(window, &wmInfo) && wmInfo.subsystem == SDL_SYSWM_WINDOWS)
		hAppWindow = wmInfo.info.win.window;
}

void* wutil_GetAppHDC()
{
	return GetDC(hAppWindow);
}

void wutil_SetAppWindow(void* hwnd)
{
	hAppWindow = reinterpret_cast<HWND>(hwnd);
}

HWND wutil_AppWindow()
{
	if (hAppWindow)
	{
		// In case of an assertion we might not receive a notification about the
		// closed window. So check it in-place.
		if (IsWindow(hAppWindow))
		{
			// There is a chance that a new window might be opened with the
			// same handle.
			DWORD pid;
			GetWindowThreadProcessId(hAppWindow, &pid);
			if (pid != GetCurrentProcessId())
				hAppWindow = 0;
		}
		else
			hAppWindow = 0;
	}
	return hAppWindow;
}

void wutil_EnableHiDPIOnWindows()
{
	// We build with VS using XP toolkit which doesn't support DPI awareness.
	// It was introduced in 8.1.
	// https://docs.microsoft.com/en-us/windows/win32/api/shellscalingapi/ne-shellscalingapi-process_dpi_awareness
	typedef enum PROCESS_DPI_AWARENESS {
		PROCESS_DPI_UNAWARE,
		PROCESS_SYSTEM_DPI_AWARE,
		PROCESS_PER_MONITOR_DPI_AWARE
	};

	// https://docs.microsoft.com/en-us/windows/win32/api/shellscalingapi/nf-shellscalingapi-setprocessdpiawareness
	using SetProcessDpiAwarenessFunc = HRESULT(WINAPI *)(PROCESS_DPI_AWARENESS);
	void* shcoreDLL = SDL_LoadObject("SHCORE.DLL");
	if (!shcoreDLL)
		return;

	SetProcessDpiAwarenessFunc SetProcessDpiAwareness =
		reinterpret_cast<SetProcessDpiAwarenessFunc>(SDL_LoadFunction(shcoreDLL, "SetProcessDpiAwareness"));
	if (SetProcessDpiAwareness)
		SetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE);

	SDL_UnloadObject(shcoreDLL);
}

//-----------------------------------------------------------------------------

Status wutil_Init()
{
	InitLocks();

	return INFO::OK;
}


Status wutil_Shutdown()
{
	ShutdownLocks();

	return INFO::OK;
}