platform-windows.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. /******************************************************************************
  2. Copyright (C) 2013 by Hugh Bailey <[email protected]>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ******************************************************************************/
  14. #include <algorithm>
  15. #include <sstream>
  16. #include "obs-config.h"
  17. #include "obs-app.hpp"
  18. #include "qt-wrappers.hpp"
  19. #include "platform.hpp"
  20. #include <util/windows/win-version.h>
  21. #include <util/platform.h>
  22. #define WIN32_LEAN_AND_MEAN
  23. #include <windows.h>
  24. #include <shellapi.h>
  25. #include <shlobj.h>
  26. #include <Dwmapi.h>
  27. #include <mmdeviceapi.h>
  28. #include <audiopolicy.h>
  29. #include <util/windows/WinHandle.hpp>
  30. #include <util/windows/HRError.hpp>
  31. #include <util/windows/ComPtr.hpp>
  32. #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
  33. #include <QWinTaskbarButton>
  34. #include <QMainWindow>
  35. #endif
  36. using namespace std;
  37. static inline bool check_path(const char *data, const char *path,
  38. string &output)
  39. {
  40. ostringstream str;
  41. str << path << data;
  42. output = str.str();
  43. printf("Attempted path: %s\n", output.c_str());
  44. return os_file_exists(output.c_str());
  45. }
  46. bool GetDataFilePath(const char *data, string &output)
  47. {
  48. if (check_path(data, "data/obs-studio/", output))
  49. return true;
  50. return check_path(data, OBS_DATA_PATH "/obs-studio/", output);
  51. }
  52. string GetDefaultVideoSavePath()
  53. {
  54. wchar_t path_utf16[MAX_PATH];
  55. char path_utf8[MAX_PATH] = {};
  56. SHGetFolderPathW(NULL, CSIDL_MYVIDEO, NULL, SHGFP_TYPE_CURRENT,
  57. path_utf16);
  58. os_wcs_to_utf8(path_utf16, wcslen(path_utf16), path_utf8, MAX_PATH);
  59. return string(path_utf8);
  60. }
  61. static vector<string> GetUserPreferredLocales()
  62. {
  63. vector<string> result;
  64. ULONG num, length = 0;
  65. if (!GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, &num, nullptr,
  66. &length))
  67. return result;
  68. vector<wchar_t> buffer(length);
  69. if (!GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, &num,
  70. &buffer.front(), &length))
  71. return result;
  72. result.reserve(num);
  73. auto start = begin(buffer);
  74. auto end_ = end(buffer);
  75. decltype(start) separator;
  76. while ((separator = find(start, end_, 0)) != end_) {
  77. if (result.size() == num)
  78. break;
  79. char conv[MAX_PATH] = {};
  80. os_wcs_to_utf8(&*start, separator - start, conv, MAX_PATH);
  81. result.emplace_back(conv);
  82. start = separator + 1;
  83. }
  84. return result;
  85. }
  86. vector<string> GetPreferredLocales()
  87. {
  88. vector<string> windows_locales = GetUserPreferredLocales();
  89. auto obs_locales = GetLocaleNames();
  90. auto windows_to_obs = [&obs_locales](string windows) {
  91. string lang_match;
  92. for (auto &locale_pair : obs_locales) {
  93. auto &locale = locale_pair.first;
  94. if (locale == windows.substr(0, locale.size()))
  95. return locale;
  96. if (lang_match.size())
  97. continue;
  98. if (locale.substr(0, 2) == windows.substr(0, 2))
  99. lang_match = locale;
  100. }
  101. return lang_match;
  102. };
  103. vector<string> result;
  104. result.reserve(obs_locales.size());
  105. for (const string &locale : windows_locales) {
  106. string match = windows_to_obs(locale);
  107. if (!match.size())
  108. continue;
  109. if (find(begin(result), end(result), match) != end(result))
  110. continue;
  111. result.emplace_back(match);
  112. }
  113. return result;
  114. }
  115. uint32_t GetWindowsVersion()
  116. {
  117. static uint32_t ver = 0;
  118. if (ver == 0) {
  119. struct win_version_info ver_info;
  120. get_win_ver(&ver_info);
  121. ver = (ver_info.major << 8) | ver_info.minor;
  122. }
  123. return ver;
  124. }
  125. uint32_t GetWindowsBuild()
  126. {
  127. static uint32_t build = 0;
  128. if (build == 0) {
  129. struct win_version_info ver_info;
  130. get_win_ver(&ver_info);
  131. build = ver_info.build;
  132. }
  133. return build;
  134. }
  135. void SetAeroEnabled(bool enable)
  136. {
  137. static HRESULT(WINAPI * func)(UINT) = nullptr;
  138. static bool failed = false;
  139. if (!func) {
  140. if (failed) {
  141. return;
  142. }
  143. HMODULE dwm = LoadLibraryW(L"dwmapi");
  144. if (!dwm) {
  145. failed = true;
  146. return;
  147. }
  148. func = reinterpret_cast<decltype(func)>(
  149. GetProcAddress(dwm, "DwmEnableComposition"));
  150. if (!func) {
  151. failed = true;
  152. return;
  153. }
  154. }
  155. func(enable ? DWM_EC_ENABLECOMPOSITION : DWM_EC_DISABLECOMPOSITION);
  156. }
  157. bool IsAlwaysOnTop(QWidget *window)
  158. {
  159. DWORD exStyle = GetWindowLong((HWND)window->winId(), GWL_EXSTYLE);
  160. return (exStyle & WS_EX_TOPMOST) != 0;
  161. }
  162. void SetAlwaysOnTop(QWidget *window, bool enable)
  163. {
  164. HWND hwnd = (HWND)window->winId();
  165. SetWindowPos(hwnd, enable ? HWND_TOPMOST : HWND_NOTOPMOST, 0, 0, 0, 0,
  166. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
  167. }
  168. void SetProcessPriority(const char *priority)
  169. {
  170. if (!priority)
  171. return;
  172. if (strcmp(priority, "High") == 0)
  173. SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
  174. else if (strcmp(priority, "AboveNormal") == 0)
  175. SetPriorityClass(GetCurrentProcess(),
  176. ABOVE_NORMAL_PRIORITY_CLASS);
  177. else if (strcmp(priority, "Normal") == 0)
  178. SetPriorityClass(GetCurrentProcess(), NORMAL_PRIORITY_CLASS);
  179. else if (strcmp(priority, "BelowNormal") == 0)
  180. SetPriorityClass(GetCurrentProcess(),
  181. BELOW_NORMAL_PRIORITY_CLASS);
  182. else if (strcmp(priority, "Idle") == 0)
  183. SetPriorityClass(GetCurrentProcess(), IDLE_PRIORITY_CLASS);
  184. }
  185. void SetWin32DropStyle(QWidget *window)
  186. {
  187. HWND hwnd = (HWND)window->winId();
  188. LONG_PTR ex_style = GetWindowLongPtr(hwnd, GWL_EXSTYLE);
  189. ex_style |= WS_EX_ACCEPTFILES;
  190. SetWindowLongPtr(hwnd, GWL_EXSTYLE, ex_style);
  191. }
  192. bool SetDisplayAffinitySupported(void)
  193. {
  194. static bool checked = false;
  195. static bool supported;
  196. /* this has to be version gated as setting WDA_EXCLUDEFROMCAPTURE on
  197. older Windows builds behaves like WDA_MONITOR (black box) */
  198. if (!checked) {
  199. if (GetWindowsVersion() > 0x0A00 ||
  200. GetWindowsVersion() == 0x0A00 && GetWindowsBuild() >= 19041)
  201. supported = true;
  202. else
  203. supported = false;
  204. checked = true;
  205. }
  206. return supported;
  207. }
  208. bool DisableAudioDucking(bool disable)
  209. {
  210. ComPtr<IMMDeviceEnumerator> devEmum;
  211. ComPtr<IMMDevice> device;
  212. ComPtr<IAudioSessionManager2> sessionManager2;
  213. ComPtr<IAudioSessionControl> sessionControl;
  214. ComPtr<IAudioSessionControl2> sessionControl2;
  215. HRESULT result = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr,
  216. CLSCTX_INPROC_SERVER,
  217. __uuidof(IMMDeviceEnumerator),
  218. (void **)&devEmum);
  219. if (FAILED(result))
  220. return false;
  221. result = devEmum->GetDefaultAudioEndpoint(eRender, eConsole, &device);
  222. if (FAILED(result))
  223. return false;
  224. result = device->Activate(__uuidof(IAudioSessionManager2),
  225. CLSCTX_INPROC_SERVER, nullptr,
  226. (void **)&sessionManager2);
  227. if (FAILED(result))
  228. return false;
  229. result = sessionManager2->GetAudioSessionControl(nullptr, 0,
  230. &sessionControl);
  231. if (FAILED(result))
  232. return false;
  233. result = sessionControl->QueryInterface(&sessionControl2);
  234. if (FAILED(result))
  235. return false;
  236. result = sessionControl2->SetDuckingPreference(disable);
  237. return SUCCEEDED(result);
  238. }
  239. struct RunOnceMutexData {
  240. WinHandle handle;
  241. inline RunOnceMutexData(HANDLE h) : handle(h) {}
  242. };
  243. RunOnceMutex::RunOnceMutex(RunOnceMutex &&rom)
  244. {
  245. delete data;
  246. data = rom.data;
  247. rom.data = nullptr;
  248. }
  249. RunOnceMutex::~RunOnceMutex()
  250. {
  251. delete data;
  252. }
  253. RunOnceMutex &RunOnceMutex::operator=(RunOnceMutex &&rom)
  254. {
  255. delete data;
  256. data = rom.data;
  257. rom.data = nullptr;
  258. return *this;
  259. }
  260. RunOnceMutex CheckIfAlreadyRunning(bool &already_running)
  261. {
  262. string name;
  263. if (!portable_mode) {
  264. name = "OBSStudioCore";
  265. } else {
  266. char path[500];
  267. char absPath[512];
  268. *path = 0;
  269. *absPath = 0;
  270. GetConfigPath(path, sizeof(path), "");
  271. os_get_abs_path(path, absPath, sizeof(absPath));
  272. name = "OBSStudioPortable";
  273. name += absPath;
  274. }
  275. BPtr<wchar_t> wname;
  276. os_utf8_to_wcs_ptr(name.c_str(), name.size(), &wname);
  277. if (wname) {
  278. wchar_t *temp = wname;
  279. while (*temp) {
  280. if (!iswalnum(*temp))
  281. *temp = L'_';
  282. temp++;
  283. }
  284. }
  285. HANDLE h = OpenMutexW(SYNCHRONIZE, false, wname.Get());
  286. already_running = !!h;
  287. if (!already_running)
  288. h = CreateMutexW(nullptr, false, wname.Get());
  289. RunOnceMutex rom(h ? new RunOnceMutexData(h) : nullptr);
  290. return rom;
  291. }
  292. struct MonitorData {
  293. const wchar_t *id;
  294. MONITORINFOEX info;
  295. bool found;
  296. };
  297. static BOOL CALLBACK GetMonitorCallback(HMONITOR monitor, HDC, LPRECT,
  298. LPARAM param)
  299. {
  300. MonitorData *data = (MonitorData *)param;
  301. if (GetMonitorInfoW(monitor, &data->info)) {
  302. if (wcscmp(data->info.szDevice, data->id) == 0) {
  303. data->found = true;
  304. return false;
  305. }
  306. }
  307. return true;
  308. }
  309. #define GENERIC_MONITOR_NAME QStringLiteral("Generic PnP Monitor")
  310. QString GetMonitorName(const QString &id)
  311. {
  312. MonitorData data = {};
  313. data.id = (const wchar_t *)id.utf16();
  314. data.info.cbSize = sizeof(data.info);
  315. EnumDisplayMonitors(nullptr, nullptr, GetMonitorCallback,
  316. (LPARAM)&data);
  317. if (!data.found) {
  318. return GENERIC_MONITOR_NAME;
  319. }
  320. UINT32 numPath, numMode;
  321. if (GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &numPath,
  322. &numMode) != ERROR_SUCCESS) {
  323. return GENERIC_MONITOR_NAME;
  324. }
  325. std::vector<DISPLAYCONFIG_PATH_INFO> paths(numPath);
  326. std::vector<DISPLAYCONFIG_MODE_INFO> modes(numMode);
  327. if (QueryDisplayConfig(QDC_ONLY_ACTIVE_PATHS, &numPath, paths.data(),
  328. &numMode, modes.data(),
  329. nullptr) != ERROR_SUCCESS) {
  330. return GENERIC_MONITOR_NAME;
  331. }
  332. DISPLAYCONFIG_TARGET_DEVICE_NAME target;
  333. bool found = false;
  334. paths.resize(numPath);
  335. for (size_t i = 0; i < numPath; ++i) {
  336. const DISPLAYCONFIG_PATH_INFO &path = paths[i];
  337. DISPLAYCONFIG_SOURCE_DEVICE_NAME s;
  338. s.header.type = DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME;
  339. s.header.size = sizeof(s);
  340. s.header.adapterId = path.sourceInfo.adapterId;
  341. s.header.id = path.sourceInfo.id;
  342. if (DisplayConfigGetDeviceInfo(&s.header) == ERROR_SUCCESS &&
  343. wcscmp(data.info.szDevice, s.viewGdiDeviceName) == 0) {
  344. target.header.type =
  345. DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_NAME;
  346. target.header.size = sizeof(target);
  347. target.header.adapterId = path.sourceInfo.adapterId;
  348. target.header.id = path.targetInfo.id;
  349. found = DisplayConfigGetDeviceInfo(&target.header) ==
  350. ERROR_SUCCESS;
  351. break;
  352. }
  353. }
  354. if (!found) {
  355. return GENERIC_MONITOR_NAME;
  356. }
  357. return QString::fromWCharArray(target.monitorFriendlyDeviceName);
  358. }
  359. /* Based on https://www.winehq.org/pipermail/wine-devel/2008-September/069387.html */
  360. typedef const char *(CDECL *WINEGETVERSION)(void);
  361. bool IsRunningOnWine()
  362. {
  363. WINEGETVERSION func;
  364. HMODULE nt;
  365. nt = GetModuleHandleW(L"ntdll");
  366. if (!nt)
  367. return false;
  368. func = (WINEGETVERSION)GetProcAddress(nt, "wine_get_version");
  369. if (func) {
  370. blog(LOG_WARNING, "Running on Wine version \"%s\"", func());
  371. return true;
  372. }
  373. return false;
  374. }
  375. #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
  376. QWinTaskbarButton *taskBtn;
  377. void TaskbarOverlayInit()
  378. {
  379. QMainWindow *main = App()->GetMainWindow();
  380. taskBtn = new QWinTaskbarButton(main);
  381. taskBtn->setWindow(main->windowHandle());
  382. }
  383. void TaskbarOverlaySetStatus(TaskbarOverlayStatus status)
  384. {
  385. if (status == TaskbarOverlayStatusInactive) {
  386. taskBtn->clearOverlayIcon();
  387. return;
  388. }
  389. QIcon icon;
  390. if (status == TaskbarOverlayStatusActive) {
  391. icon = QIcon::fromTheme("obs-active",
  392. QIcon(":/res/images/active.png"));
  393. } else {
  394. icon = QIcon::fromTheme("obs-paused",
  395. QIcon(":/res/images/paused.png"));
  396. }
  397. taskBtn->setOverlayIcon(icon);
  398. }
  399. #else
  400. HWND hwnd;
  401. void TaskbarOverlayInit()
  402. {
  403. hwnd = (HWND)App()->GetMainWindow()->winId();
  404. }
  405. void TaskbarOverlaySetStatus(TaskbarOverlayStatus status)
  406. {
  407. ITaskbarList4 *taskbarIcon;
  408. auto hr = CoCreateInstance(CLSID_TaskbarList, NULL,
  409. CLSCTX_INPROC_SERVER,
  410. IID_PPV_ARGS(&taskbarIcon));
  411. if (FAILED(hr)) {
  412. taskbarIcon->Release();
  413. return;
  414. }
  415. hr = taskbarIcon->HrInit();
  416. if (FAILED(hr)) {
  417. taskbarIcon->Release();
  418. return;
  419. }
  420. if (status != TaskbarOverlayStatusInactive) {
  421. QIcon qicon;
  422. switch (status) {
  423. case TaskbarOverlayStatusActive:
  424. qicon = QIcon::fromTheme(
  425. "obs-active", QIcon(":/res/images/active.png"));
  426. break;
  427. case TaskbarOverlayStatusPaused:
  428. qicon = QIcon::fromTheme(
  429. "obs-paused", QIcon(":/res/images/paused.png"));
  430. break;
  431. }
  432. HICON hicon = nullptr;
  433. if (!qicon.isNull()) {
  434. Q_GUI_EXPORT HICON qt_pixmapToWinHICON(
  435. const QPixmap &p);
  436. hicon = qt_pixmapToWinHICON(
  437. qicon.pixmap(GetSystemMetrics(SM_CXSMICON)));
  438. if (!hicon)
  439. return;
  440. }
  441. taskbarIcon->SetOverlayIcon(hwnd, hicon, nullptr);
  442. DestroyIcon(hicon);
  443. } else {
  444. taskbarIcon->SetOverlayIcon(hwnd, nullptr, nullptr);
  445. }
  446. taskbarIcon->Release();
  447. }
  448. #endif