You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2751 lines
97 KiB

  1. //-------------------------------------------------------------------------------------------------
  2. // <copyright file="WixStandardBootstrapperApplication.cpp" company="Outercurve Foundation">
  3. // Copyright (c) 2004, Outercurve Foundation.
  4. // This software is released under Microsoft Reciprocal License (MS-RL).
  5. // The license and further copyright text can be found in the file
  6. // LICENSE.TXT at the root directory of the distribution.
  7. // </copyright>
  8. //-------------------------------------------------------------------------------------------------
  9. #include "pch.h"
  10. static const LPCWSTR PYBA_WINDOW_CLASS = L"PythonBA";
  11. static const LPCWSTR PYBA_VARIABLE_LAUNCH_TARGET_PATH = L"LaunchTarget";
  12. static const LPCWSTR PYBA_VARIABLE_LAUNCH_TARGET_ELEVATED_ID = L"LaunchTargetElevatedId";
  13. static const LPCWSTR PYBA_VARIABLE_LAUNCH_ARGUMENTS = L"LaunchArguments";
  14. static const LPCWSTR PYBA_VARIABLE_LAUNCH_HIDDEN = L"LaunchHidden";
  15. static const DWORD PYBA_ACQUIRE_PERCENTAGE = 30;
  16. static const LPCWSTR PYBA_VARIABLE_BUNDLE_FILE_VERSION = L"WixBundleFileVersion";
  17. enum PYBA_STATE {
  18. PYBA_STATE_INITIALIZING,
  19. PYBA_STATE_INITIALIZED,
  20. PYBA_STATE_HELP,
  21. PYBA_STATE_DETECTING,
  22. PYBA_STATE_DETECTED,
  23. PYBA_STATE_PLANNING,
  24. PYBA_STATE_PLANNED,
  25. PYBA_STATE_APPLYING,
  26. PYBA_STATE_CACHING,
  27. PYBA_STATE_CACHED,
  28. PYBA_STATE_EXECUTING,
  29. PYBA_STATE_EXECUTED,
  30. PYBA_STATE_APPLIED,
  31. PYBA_STATE_FAILED,
  32. };
  33. static const int WM_PYBA_SHOW_HELP = WM_APP + 100;
  34. static const int WM_PYBA_DETECT_PACKAGES = WM_APP + 101;
  35. static const int WM_PYBA_PLAN_PACKAGES = WM_APP + 102;
  36. static const int WM_PYBA_APPLY_PACKAGES = WM_APP + 103;
  37. static const int WM_PYBA_CHANGE_STATE = WM_APP + 104;
  38. static const int WM_PYBA_SHOW_FAILURE = WM_APP + 105;
  39. // This enum must be kept in the same order as the PAGE_NAMES array.
  40. enum PAGE {
  41. PAGE_LOADING,
  42. PAGE_HELP,
  43. PAGE_INSTALL,
  44. PAGE_SIMPLE_INSTALL,
  45. PAGE_CUSTOM1,
  46. PAGE_CUSTOM2,
  47. PAGE_MODIFY,
  48. PAGE_PROGRESS,
  49. PAGE_PROGRESS_PASSIVE,
  50. PAGE_SUCCESS,
  51. PAGE_FAILURE,
  52. COUNT_PAGE,
  53. };
  54. // This array must be kept in the same order as the PAGE enum.
  55. static LPCWSTR PAGE_NAMES[] = {
  56. L"Loading",
  57. L"Help",
  58. L"Install",
  59. L"SimpleInstall",
  60. L"Custom1",
  61. L"Custom2",
  62. L"Modify",
  63. L"Progress",
  64. L"ProgressPassive",
  65. L"Success",
  66. L"Failure",
  67. };
  68. enum CONTROL_ID {
  69. // Non-paged controls
  70. ID_CLOSE_BUTTON = THEME_FIRST_ASSIGN_CONTROL_ID,
  71. ID_MINIMIZE_BUTTON,
  72. // Welcome page
  73. ID_INSTALL_ALL_USERS_BUTTON,
  74. ID_INSTALL_JUST_FOR_ME_BUTTON,
  75. ID_INSTALL_CUSTOM_BUTTON,
  76. ID_INSTALL_SIMPLE_BUTTON,
  77. ID_INSTALL_CANCEL_BUTTON,
  78. // Customize Page
  79. ID_TARGETDIR_EDITBOX,
  80. ID_CUSTOM_ASSOCIATE_FILES_CHECKBOX,
  81. ID_CUSTOM_INSTALL_ALL_USERS_CHECKBOX,
  82. ID_CUSTOM_BROWSE_BUTTON,
  83. ID_CUSTOM_BROWSE_BUTTON_LABEL,
  84. ID_CUSTOM_INSTALL_BUTTON,
  85. ID_CUSTOM_NEXT_BUTTON,
  86. ID_CUSTOM1_BACK_BUTTON,
  87. ID_CUSTOM2_BACK_BUTTON,
  88. ID_CUSTOM1_CANCEL_BUTTON,
  89. ID_CUSTOM2_CANCEL_BUTTON,
  90. // Modify page
  91. ID_MODIFY_BUTTON,
  92. ID_REPAIR_BUTTON,
  93. ID_UNINSTALL_BUTTON,
  94. ID_MODIFY_CANCEL_BUTTON,
  95. // Progress page
  96. ID_CACHE_PROGRESS_PACKAGE_TEXT,
  97. ID_CACHE_PROGRESS_BAR,
  98. ID_CACHE_PROGRESS_TEXT,
  99. ID_EXECUTE_PROGRESS_PACKAGE_TEXT,
  100. ID_EXECUTE_PROGRESS_BAR,
  101. ID_EXECUTE_PROGRESS_TEXT,
  102. ID_EXECUTE_PROGRESS_ACTIONDATA_TEXT,
  103. ID_OVERALL_PROGRESS_PACKAGE_TEXT,
  104. ID_OVERALL_PROGRESS_BAR,
  105. ID_OVERALL_CALCULATED_PROGRESS_BAR,
  106. ID_OVERALL_PROGRESS_TEXT,
  107. ID_PROGRESS_CANCEL_BUTTON,
  108. // Success page
  109. ID_LAUNCH_BUTTON,
  110. ID_SUCCESS_TEXT,
  111. ID_SUCCESS_RESTART_TEXT,
  112. ID_SUCCESS_RESTART_BUTTON,
  113. ID_SUCCESS_CANCEL_BUTTON,
  114. // Failure page
  115. ID_FAILURE_LOGFILE_LINK,
  116. ID_FAILURE_MESSAGE_TEXT,
  117. ID_FAILURE_RESTART_TEXT,
  118. ID_FAILURE_RESTART_BUTTON,
  119. ID_FAILURE_CANCEL_BUTTON
  120. };
  121. static THEME_ASSIGN_CONTROL_ID CONTROL_ID_NAMES[] = {
  122. { ID_CLOSE_BUTTON, L"CloseButton" },
  123. { ID_MINIMIZE_BUTTON, L"MinimizeButton" },
  124. { ID_INSTALL_ALL_USERS_BUTTON, L"InstallAllUsersButton" },
  125. { ID_INSTALL_JUST_FOR_ME_BUTTON, L"InstallJustForMeButton" },
  126. { ID_INSTALL_CUSTOM_BUTTON, L"InstallCustomButton" },
  127. { ID_INSTALL_SIMPLE_BUTTON, L"InstallSimpleButton" },
  128. { ID_INSTALL_CANCEL_BUTTON, L"InstallCancelButton" },
  129. { ID_TARGETDIR_EDITBOX, L"TargetDir" },
  130. { ID_CUSTOM_ASSOCIATE_FILES_CHECKBOX, L"AssociateFiles" },
  131. { ID_CUSTOM_INSTALL_ALL_USERS_CHECKBOX, L"InstallAllUsers" },
  132. { ID_CUSTOM_BROWSE_BUTTON, L"CustomBrowseButton" },
  133. { ID_CUSTOM_BROWSE_BUTTON_LABEL, L"CustomBrowseButtonLabel" },
  134. { ID_CUSTOM_INSTALL_BUTTON, L"CustomInstallButton" },
  135. { ID_CUSTOM_NEXT_BUTTON, L"CustomNextButton" },
  136. { ID_CUSTOM1_BACK_BUTTON, L"Custom1BackButton" },
  137. { ID_CUSTOM2_BACK_BUTTON, L"Custom2BackButton" },
  138. { ID_CUSTOM1_CANCEL_BUTTON, L"Custom1CancelButton" },
  139. { ID_CUSTOM2_CANCEL_BUTTON, L"Custom2CancelButton" },
  140. { ID_MODIFY_BUTTON, L"ModifyButton" },
  141. { ID_REPAIR_BUTTON, L"RepairButton" },
  142. { ID_UNINSTALL_BUTTON, L"UninstallButton" },
  143. { ID_MODIFY_CANCEL_BUTTON, L"ModifyCancelButton" },
  144. { ID_CACHE_PROGRESS_PACKAGE_TEXT, L"CacheProgressPackageText" },
  145. { ID_CACHE_PROGRESS_BAR, L"CacheProgressbar" },
  146. { ID_CACHE_PROGRESS_TEXT, L"CacheProgressText" },
  147. { ID_EXECUTE_PROGRESS_PACKAGE_TEXT, L"ExecuteProgressPackageText" },
  148. { ID_EXECUTE_PROGRESS_BAR, L"ExecuteProgressbar" },
  149. { ID_EXECUTE_PROGRESS_TEXT, L"ExecuteProgressText" },
  150. { ID_EXECUTE_PROGRESS_ACTIONDATA_TEXT, L"ExecuteProgressActionDataText" },
  151. { ID_OVERALL_PROGRESS_PACKAGE_TEXT, L"OverallProgressPackageText" },
  152. { ID_OVERALL_PROGRESS_BAR, L"OverallProgressbar" },
  153. { ID_OVERALL_CALCULATED_PROGRESS_BAR, L"OverallCalculatedProgressbar" },
  154. { ID_OVERALL_PROGRESS_TEXT, L"OverallProgressText" },
  155. { ID_PROGRESS_CANCEL_BUTTON, L"ProgressCancelButton" },
  156. { ID_LAUNCH_BUTTON, L"LaunchButton" },
  157. { ID_SUCCESS_TEXT, L"SuccessText" },
  158. { ID_SUCCESS_RESTART_TEXT, L"SuccessRestartText" },
  159. { ID_SUCCESS_RESTART_BUTTON, L"SuccessRestartButton" },
  160. { ID_SUCCESS_CANCEL_BUTTON, L"SuccessCancelButton" },
  161. { ID_FAILURE_LOGFILE_LINK, L"FailureLogFileLink" },
  162. { ID_FAILURE_MESSAGE_TEXT, L"FailureMessageText" },
  163. { ID_FAILURE_RESTART_TEXT, L"FailureRestartText" },
  164. { ID_FAILURE_RESTART_BUTTON, L"FailureRestartButton" },
  165. { ID_FAILURE_CANCEL_BUTTON, L"FailureCancelButton" },
  166. };
  167. class PythonBootstrapperApplication : public CBalBaseBootstrapperApplication {
  168. void ShowPage(DWORD newPageId) {
  169. // Process each control for special handling in the new page.
  170. ProcessPageControls(ThemeGetPage(_theme, newPageId));
  171. // Enable disable controls per-page.
  172. if (_pageIds[PAGE_INSTALL] == newPageId || _pageIds[PAGE_SIMPLE_INSTALL] == newPageId) {
  173. InstallPage_Show();
  174. } else if (_pageIds[PAGE_CUSTOM1] == newPageId) {
  175. Custom1Page_Show();
  176. } else if (_pageIds[PAGE_CUSTOM2] == newPageId) {
  177. Custom2Page_Show();
  178. } else if (_pageIds[PAGE_MODIFY] == newPageId) {
  179. ModifyPage_Show();
  180. } else if (_pageIds[PAGE_SUCCESS] == newPageId) {
  181. SuccessPage_Show();
  182. } else if (_pageIds[PAGE_FAILURE] == newPageId) {
  183. FailurePage_Show();
  184. }
  185. // Prevent repainting while switching page to avoid ugly flickering
  186. _suppressPaint = TRUE;
  187. ThemeShowPage(_theme, newPageId, SW_SHOW);
  188. ThemeShowPage(_theme, _visiblePageId, SW_HIDE);
  189. _suppressPaint = FALSE;
  190. InvalidateRect(_theme->hwndParent, nullptr, TRUE);
  191. _visiblePageId = newPageId;
  192. // On the install page set the focus to the install button or
  193. // the next enabled control if install is disabled
  194. if (_pageIds[PAGE_INSTALL] == newPageId) {
  195. ThemeSetFocus(_theme, ID_INSTALL_ALL_USERS_BUTTON);
  196. } else if (_pageIds[PAGE_SIMPLE_INSTALL] == newPageId) {
  197. ThemeSetFocus(_theme, ID_INSTALL_SIMPLE_BUTTON);
  198. }
  199. }
  200. //
  201. // Handles control clicks
  202. //
  203. void OnCommand(CONTROL_ID id) {
  204. LPWSTR defaultDir = nullptr;
  205. LPWSTR targetDir = nullptr;
  206. LONGLONG elevated, crtInstalled;
  207. BOOL checked;
  208. WCHAR wzPath[MAX_PATH] = { };
  209. BROWSEINFOW browseInfo = { };
  210. PIDLIST_ABSOLUTE pidl = nullptr;
  211. HRESULT hr = S_OK;
  212. switch(id) {
  213. case ID_CLOSE_BUTTON:
  214. OnClickCloseButton();
  215. break;
  216. // Install commands
  217. case ID_INSTALL_SIMPLE_BUTTON:
  218. hr = BalGetStringVariable(L"TargetDir", &targetDir);
  219. if (FAILED(hr) || !targetDir || !*targetDir) {
  220. LONGLONG installAll;
  221. if (SUCCEEDED(BalGetNumericVariable(L"InstallAllUsers", &installAll)) && installAll) {
  222. hr = BalGetStringVariable(L"DefaultAllUsersTargetDir", &defaultDir);
  223. BalExitOnFailure(hr, "Failed to get the default all users install directory");
  224. } else {
  225. hr = BalGetStringVariable(L"DefaultJustForMeTargetDir", &defaultDir);
  226. BalExitOnFailure(hr, "Failed to get the default per-user install directory");
  227. }
  228. if (!defaultDir || !*defaultDir) {
  229. BalLogError(E_INVALIDARG, "Default install directory is blank");
  230. }
  231. hr = BalFormatString(defaultDir, &targetDir);
  232. BalExitOnFailure1(hr, "Failed to format '%ls'", defaultDir);
  233. hr = _engine->SetVariableString(L"TargetDir", targetDir);
  234. ReleaseStr(targetDir);
  235. BalExitOnFailure(hr, "Failed to set install target directory");
  236. } else {
  237. ReleaseStr(targetDir);
  238. }
  239. OnPlan(BOOTSTRAPPER_ACTION_INSTALL);
  240. break;
  241. case ID_INSTALL_ALL_USERS_BUTTON:
  242. SavePageSettings();
  243. hr = _engine->SetVariableNumeric(L"InstallAllUsers", 1);
  244. ExitOnFailure(hr, L"Failed to set install scope");
  245. hr = _engine->SetVariableNumeric(L"CompileAll", 1);
  246. ExitOnFailure(hr, L"Failed to set compile all setting");
  247. hr = BalGetStringVariable(L"DefaultAllUsersTargetDir", &defaultDir);
  248. BalExitOnFailure(hr, "Failed to get the default all users install directory");
  249. if (!defaultDir || !*defaultDir) {
  250. BalLogError(E_INVALIDARG, "Default install directory is blank");
  251. }
  252. hr = BalFormatString(defaultDir, &targetDir);
  253. BalExitOnFailure1(hr, "Failed to format '%ls'", defaultDir);
  254. hr = _engine->SetVariableString(L"TargetDir", targetDir);
  255. ReleaseStr(targetDir);
  256. BalExitOnFailure(hr, "Failed to set install target directory");
  257. OnPlan(BOOTSTRAPPER_ACTION_INSTALL);
  258. break;
  259. case ID_INSTALL_JUST_FOR_ME_BUTTON:
  260. SavePageSettings();
  261. hr = _engine->SetVariableNumeric(L"InstallAllUsers", 0);
  262. ExitOnFailure(hr, L"Failed to set install scope");
  263. hr = BalGetStringVariable(L"DefaultJustForMeTargetDir", &defaultDir);
  264. BalExitOnFailure(hr, "Failed to get the default per-user install directory");
  265. if (!defaultDir || !*defaultDir) {
  266. BalLogError(E_INVALIDARG, "Default install directory is blank");
  267. }
  268. hr = BalFormatString(defaultDir, &targetDir);
  269. BalExitOnFailure1(hr, "Failed to format '%ls'", defaultDir);
  270. hr = _engine->SetVariableString(L"TargetDir", targetDir);
  271. ReleaseStr(targetDir);
  272. BalExitOnFailure(hr, "Failed to set install target directory");
  273. if (!QueryElevateForCrtInstall()) {
  274. break;
  275. }
  276. OnPlan(BOOTSTRAPPER_ACTION_INSTALL);
  277. break;
  278. case ID_CUSTOM1_BACK_BUTTON:
  279. SavePageSettings();
  280. if (_modifying) {
  281. GoToPage(PAGE_MODIFY);
  282. } else {
  283. GoToPage(PAGE_INSTALL);
  284. }
  285. break;
  286. case ID_INSTALL_CUSTOM_BUTTON: __fallthrough;
  287. case ID_CUSTOM2_BACK_BUTTON:
  288. SavePageSettings();
  289. GoToPage(PAGE_CUSTOM1);
  290. break;
  291. case ID_CUSTOM_NEXT_BUTTON:
  292. SavePageSettings();
  293. GoToPage(PAGE_CUSTOM2);
  294. break;
  295. case ID_CUSTOM_INSTALL_BUTTON:
  296. SavePageSettings();
  297. hr = BalGetStringVariable(L"TargetDir", &targetDir);
  298. if (SUCCEEDED(hr)) {
  299. // TODO: Check whether directory exists and contains another installation
  300. ReleaseStr(targetDir);
  301. }
  302. checked = ThemeIsControlChecked(_theme, ID_CUSTOM_INSTALL_ALL_USERS_CHECKBOX);
  303. if (!checked && !QueryElevateForCrtInstall()) {
  304. break;
  305. }
  306. OnPlan(_command.action);
  307. break;
  308. case ID_CUSTOM_INSTALL_ALL_USERS_CHECKBOX:
  309. hr = BalGetNumericVariable(L"WixBundleElevated", &elevated);
  310. checked = ThemeIsControlChecked(_theme, ID_CUSTOM_INSTALL_ALL_USERS_CHECKBOX);
  311. ThemeControlElevates(_theme, ID_CUSTOM_INSTALL_BUTTON, checked && (FAILED(hr) || !elevated));
  312. ThemeShowControl(_theme, ID_CUSTOM_BROWSE_BUTTON_LABEL, checked ? SW_HIDE : SW_SHOW);
  313. ThemeGetTextControl(_theme, ID_TARGETDIR_EDITBOX, &targetDir);
  314. if (targetDir) {
  315. // Check the current value against the default to see
  316. // if we should switch it automatically.
  317. hr = BalGetStringVariable(
  318. checked ? L"DefaultJustForMeTargetDir" : L"DefaultAllUsersTargetDir",
  319. &defaultDir
  320. );
  321. if (SUCCEEDED(hr) && defaultDir) {
  322. LPWSTR formatted = nullptr;
  323. if (defaultDir[0] && SUCCEEDED(BalFormatString(defaultDir, &formatted))) {
  324. if (wcscmp(formatted, targetDir) == 0) {
  325. ReleaseStr(defaultDir);
  326. defaultDir = nullptr;
  327. ReleaseStr(formatted);
  328. formatted = nullptr;
  329. hr = BalGetStringVariable(
  330. checked ? L"DefaultAllUsersTargetDir" : L"DefaultJustForMeTargetDir",
  331. &defaultDir
  332. );
  333. if (SUCCEEDED(hr) && defaultDir && defaultDir[0] && SUCCEEDED(BalFormatString(defaultDir, &formatted))) {
  334. ThemeSetTextControl(_theme, ID_TARGETDIR_EDITBOX, formatted);
  335. ReleaseStr(formatted);
  336. }
  337. } else {
  338. ReleaseStr(formatted);
  339. }
  340. }
  341. ReleaseStr(defaultDir);
  342. }
  343. }
  344. break;
  345. case ID_CUSTOM_BROWSE_BUTTON:
  346. browseInfo.hwndOwner = _hWnd;
  347. browseInfo.pszDisplayName = wzPath;
  348. browseInfo.lpszTitle = _theme->sczCaption;
  349. browseInfo.ulFlags = BIF_RETURNONLYFSDIRS | BIF_USENEWUI;
  350. pidl = ::SHBrowseForFolderW(&browseInfo);
  351. if (pidl && ::SHGetPathFromIDListW(pidl, wzPath)) {
  352. ThemeSetTextControl(_theme, ID_TARGETDIR_EDITBOX, wzPath);
  353. }
  354. if (pidl) {
  355. ::CoTaskMemFree(pidl);
  356. }
  357. break;
  358. // Modify commands
  359. case ID_MODIFY_BUTTON:
  360. // Some variables cannot be modified
  361. _engine->SetVariableString(L"InstallAllUsersState", L"disable");
  362. _engine->SetVariableString(L"TargetDirState", L"disable");
  363. _engine->SetVariableString(L"CustomBrowseButtonState", L"disable");
  364. _modifying = TRUE;
  365. GoToPage(PAGE_CUSTOM1);
  366. break;
  367. case ID_REPAIR_BUTTON:
  368. OnPlan(BOOTSTRAPPER_ACTION_REPAIR);
  369. break;
  370. case ID_UNINSTALL_BUTTON:
  371. OnPlan(BOOTSTRAPPER_ACTION_UNINSTALL);
  372. break;
  373. }
  374. LExit:
  375. return;
  376. }
  377. void InstallPage_Show() {
  378. // Ensure the All Users install button has a UAC shield
  379. LONGLONG elevated, installAll;
  380. if (FAILED(BalGetNumericVariable(L"WixBundleElevated", &elevated))) {
  381. elevated = 0;
  382. }
  383. ThemeControlElevates(_theme, ID_INSTALL_ALL_USERS_BUTTON, !elevated);
  384. if (SUCCEEDED(BalGetNumericVariable(L"InstallAllUsers", &installAll)) && installAll) {
  385. ThemeControlElevates(_theme, ID_INSTALL_SIMPLE_BUTTON, !elevated);
  386. }
  387. }
  388. void Custom1Page_Show() {
  389. }
  390. void Custom2Page_Show() {
  391. HRESULT hr;
  392. LONGLONG installAll, elevated, includeLauncher;
  393. if (FAILED(BalGetNumericVariable(L"WixBundleElevated", &elevated))) {
  394. elevated = 0;
  395. }
  396. if (SUCCEEDED(BalGetNumericVariable(L"InstallAllUsers", &installAll))) {
  397. ThemeControlElevates(_theme, ID_CUSTOM_INSTALL_BUTTON, installAll && !elevated);
  398. ThemeShowControl(_theme, ID_CUSTOM_BROWSE_BUTTON_LABEL, SW_HIDE);
  399. } else {
  400. installAll = 0;
  401. ThemeShowControl(_theme, ID_CUSTOM_BROWSE_BUTTON_LABEL, SW_SHOW);
  402. }
  403. if (SUCCEEDED(BalGetNumericVariable(L"Include_launcher", &includeLauncher)) && includeLauncher) {
  404. ThemeControlEnable(_theme, ID_CUSTOM_ASSOCIATE_FILES_CHECKBOX, TRUE);
  405. } else {
  406. ThemeSendControlMessage(_theme, ID_CUSTOM_ASSOCIATE_FILES_CHECKBOX, BM_SETCHECK, BST_UNCHECKED, 0);
  407. ThemeControlEnable(_theme, ID_CUSTOM_ASSOCIATE_FILES_CHECKBOX, FALSE);
  408. }
  409. LPWSTR targetDir = nullptr;
  410. hr = BalGetStringVariable(L"TargetDir", &targetDir);
  411. if (SUCCEEDED(hr) && targetDir && targetDir[0]) {
  412. ThemeSetTextControl(_theme, ID_TARGETDIR_EDITBOX, targetDir);
  413. StrFree(targetDir);
  414. } else if (SUCCEEDED(hr)) {
  415. StrFree(targetDir);
  416. targetDir = nullptr;
  417. LPWSTR defaultTargetDir = nullptr;
  418. hr = BalGetStringVariable(L"DefaultCustomTargetDir", &defaultTargetDir);
  419. if (SUCCEEDED(hr) && defaultTargetDir && !defaultTargetDir[0]) {
  420. StrFree(defaultTargetDir);
  421. defaultTargetDir = nullptr;
  422. hr = BalGetStringVariable(
  423. installAll ? L"DefaultAllUsersTargetDir" : L"DefaultJustForMeTargetDir",
  424. &defaultTargetDir
  425. );
  426. }
  427. if (SUCCEEDED(hr) && defaultTargetDir) {
  428. if (defaultTargetDir[0] && SUCCEEDED(BalFormatString(defaultTargetDir, &targetDir))) {
  429. ThemeSetTextControl(_theme, ID_TARGETDIR_EDITBOX, targetDir);
  430. StrFree(targetDir);
  431. }
  432. StrFree(defaultTargetDir);
  433. }
  434. }
  435. }
  436. void ModifyPage_Show() {
  437. ThemeControlEnable(_theme, ID_REPAIR_BUTTON, !_suppressRepair);
  438. }
  439. void SuccessPage_Show() {
  440. // on the "Success" page, check if the restart or launch button should be enabled.
  441. BOOL showRestartButton = FALSE;
  442. BOOL launchTargetExists = FALSE;
  443. LOC_STRING *successText = nullptr;
  444. HRESULT hr = S_OK;
  445. if (_restartRequired) {
  446. if (BOOTSTRAPPER_RESTART_PROMPT == _command.restart) {
  447. showRestartButton = TRUE;
  448. }
  449. } else if (ThemeControlExists(_theme, ID_LAUNCH_BUTTON)) {
  450. launchTargetExists = BalStringVariableExists(PYBA_VARIABLE_LAUNCH_TARGET_PATH);
  451. }
  452. switch (_plannedAction) {
  453. case BOOTSTRAPPER_ACTION_INSTALL:
  454. hr = LocGetString(_wixLoc, L"#(loc.SuccessInstallMessage)", &successText);
  455. break;
  456. case BOOTSTRAPPER_ACTION_MODIFY:
  457. hr = LocGetString(_wixLoc, L"#(loc.SuccessModifyMessage)", &successText);
  458. break;
  459. case BOOTSTRAPPER_ACTION_REPAIR:
  460. hr = LocGetString(_wixLoc, L"#(loc.SuccessRepairMessage)", &successText);
  461. break;
  462. case BOOTSTRAPPER_ACTION_UNINSTALL:
  463. hr = LocGetString(_wixLoc, L"#(loc.SuccessRemoveMessage)", &successText);
  464. break;
  465. }
  466. if (successText) {
  467. LPWSTR formattedString = nullptr;
  468. BalFormatString(successText->wzText, &formattedString);
  469. if (formattedString) {
  470. ThemeSetTextControl(_theme, ID_SUCCESS_TEXT, formattedString);
  471. StrFree(formattedString);
  472. }
  473. }
  474. ThemeControlEnable(_theme, ID_LAUNCH_BUTTON, launchTargetExists && BOOTSTRAPPER_ACTION_UNINSTALL < _plannedAction);
  475. ThemeControlEnable(_theme, ID_SUCCESS_RESTART_TEXT, showRestartButton);
  476. ThemeControlEnable(_theme, ID_SUCCESS_RESTART_BUTTON, showRestartButton);
  477. }
  478. void FailurePage_Show() {
  479. // on the "Failure" page, show error message and check if the restart button should be enabled.
  480. // if there is a log file variable then we'll assume the log file exists.
  481. BOOL showLogLink = (_bundle.sczLogVariable && *_bundle.sczLogVariable);
  482. BOOL showErrorMessage = FALSE;
  483. BOOL showRestartButton = FALSE;
  484. if (FAILED(_hrFinal)) {
  485. LPWSTR unformattedText = nullptr;
  486. LPWSTR text = nullptr;
  487. // If we know the failure message, use that.
  488. if (_failedMessage && *_failedMessage) {
  489. StrAllocString(&unformattedText, _failedMessage, 0);
  490. } else {
  491. // try to get the error message from the error code.
  492. StrAllocFromError(&unformattedText, _hrFinal, nullptr);
  493. if (!unformattedText || !*unformattedText) {
  494. StrAllocFromError(&unformattedText, E_FAIL, nullptr);
  495. }
  496. }
  497. if (E_WIXSTDBA_CONDITION_FAILED == _hrFinal) {
  498. if (unformattedText) {
  499. StrAllocString(&text, unformattedText, 0);
  500. }
  501. } else {
  502. StrAllocFormatted(&text, L"0x%08x - %ls", _hrFinal, unformattedText);
  503. }
  504. if (text) {
  505. ThemeSetTextControl(_theme, ID_FAILURE_MESSAGE_TEXT, text);
  506. showErrorMessage = TRUE;
  507. }
  508. ReleaseStr(text);
  509. ReleaseStr(unformattedText);
  510. }
  511. if (_restartRequired && BOOTSTRAPPER_RESTART_PROMPT == _command.restart) {
  512. showRestartButton = TRUE;
  513. }
  514. ThemeControlEnable(_theme, ID_FAILURE_LOGFILE_LINK, showLogLink);
  515. ThemeControlEnable(_theme, ID_FAILURE_MESSAGE_TEXT, showErrorMessage);
  516. ThemeControlEnable(_theme, ID_FAILURE_RESTART_TEXT, showRestartButton);
  517. ThemeControlEnable(_theme, ID_FAILURE_RESTART_BUTTON, showRestartButton);
  518. }
  519. public: // IBootstrapperApplication
  520. virtual STDMETHODIMP OnStartup() {
  521. HRESULT hr = S_OK;
  522. DWORD dwUIThreadId = 0;
  523. // create UI thread
  524. _hUiThread = ::CreateThread(nullptr, 0, UiThreadProc, this, 0, &dwUIThreadId);
  525. if (!_hUiThread) {
  526. ExitWithLastError(hr, "Failed to create UI thread.");
  527. }
  528. LExit:
  529. return hr;
  530. }
  531. virtual STDMETHODIMP_(int) OnShutdown() {
  532. int nResult = IDNOACTION;
  533. // wait for UI thread to terminate
  534. if (_hUiThread) {
  535. ::WaitForSingleObject(_hUiThread, INFINITE);
  536. ReleaseHandle(_hUiThread);
  537. }
  538. // If a restart was required.
  539. if (_restartRequired && _allowRestart) {
  540. nResult = IDRESTART;
  541. }
  542. return nResult;
  543. }
  544. virtual STDMETHODIMP_(int) OnDetectRelatedBundle(
  545. __in LPCWSTR wzBundleId,
  546. __in BOOTSTRAPPER_RELATION_TYPE relationType,
  547. __in LPCWSTR /*wzBundleTag*/,
  548. __in BOOL fPerMachine,
  549. __in DWORD64 /*dw64Version*/,
  550. __in BOOTSTRAPPER_RELATED_OPERATION operation
  551. ) {
  552. BalInfoAddRelatedBundleAsPackage(&_bundle.packages, wzBundleId, relationType, fPerMachine);
  553. // Remember when our bundle would cause a downgrade.
  554. if (BOOTSTRAPPER_RELATED_OPERATION_DOWNGRADE == operation) {
  555. _downgrading = TRUE;
  556. }
  557. return CheckCanceled() ? IDCANCEL : IDOK;
  558. }
  559. virtual STDMETHODIMP_(void) OnDetectPackageComplete(
  560. __in LPCWSTR wzPackageId,
  561. __in HRESULT /*hrStatus*/,
  562. __in BOOTSTRAPPER_PACKAGE_STATE state
  563. ) { }
  564. virtual STDMETHODIMP_(void) OnDetectComplete(__in HRESULT hrStatus) {
  565. if (SUCCEEDED(hrStatus) && _baFunction) {
  566. BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "Running detect complete BA function");
  567. _baFunction->OnDetectComplete();
  568. }
  569. if (SUCCEEDED(hrStatus)) {
  570. hrStatus = EvaluateConditions();
  571. }
  572. SetState(PYBA_STATE_DETECTED, hrStatus);
  573. // If we're not interacting with the user or we're doing a layout or we're just after a force restart
  574. // then automatically start planning.
  575. if (BOOTSTRAPPER_DISPLAY_FULL > _command.display ||
  576. BOOTSTRAPPER_ACTION_LAYOUT == _command.action ||
  577. BOOTSTRAPPER_ACTION_UNINSTALL == _command.action ||
  578. BOOTSTRAPPER_RESUME_TYPE_REBOOT == _command.resumeType) {
  579. if (SUCCEEDED(hrStatus)) {
  580. ::PostMessageW(_hWnd, WM_PYBA_PLAN_PACKAGES, 0, _command.action);
  581. }
  582. }
  583. }
  584. virtual STDMETHODIMP_(int) OnPlanRelatedBundle(
  585. __in_z LPCWSTR /*wzBundleId*/,
  586. __inout_z BOOTSTRAPPER_REQUEST_STATE* pRequestedState
  587. ) {
  588. return CheckCanceled() ? IDCANCEL : IDOK;
  589. }
  590. virtual STDMETHODIMP_(int) OnPlanPackageBegin(
  591. __in_z LPCWSTR wzPackageId,
  592. __inout BOOTSTRAPPER_REQUEST_STATE *pRequestState
  593. ) {
  594. HRESULT hr = S_OK;
  595. BAL_INFO_PACKAGE* pPackage = nullptr;
  596. if (_nextPackageAfterRestart) {
  597. // After restart we need to finish the dependency registration for our package so allow the package
  598. // to go present.
  599. if (CSTR_EQUAL == ::CompareStringW(LOCALE_NEUTRAL, 0, wzPackageId, -1, _nextPackageAfterRestart, -1)) {
  600. // Do not allow a repair because that could put us in a perpetual restart loop.
  601. if (BOOTSTRAPPER_REQUEST_STATE_REPAIR == *pRequestState) {
  602. *pRequestState = BOOTSTRAPPER_REQUEST_STATE_PRESENT;
  603. }
  604. ReleaseNullStr(_nextPackageAfterRestart); // no more skipping now.
  605. } else {
  606. // not the matching package, so skip it.
  607. BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "Skipping package: %ls, after restart because it was applied before the restart.", wzPackageId);
  608. *pRequestState = BOOTSTRAPPER_REQUEST_STATE_NONE;
  609. }
  610. } else if ((_plannedAction == BOOTSTRAPPER_ACTION_INSTALL || _plannedAction == BOOTSTRAPPER_ACTION_MODIFY) &&
  611. SUCCEEDED(BalInfoFindPackageById(&_bundle.packages, wzPackageId, &pPackage))) {
  612. BOOL f = FALSE;
  613. if (SUCCEEDED(_engine->EvaluateCondition(pPackage->sczInstallCondition, &f)) && f) {
  614. *pRequestState = BOOTSTRAPPER_REQUEST_STATE_PRESENT;
  615. }
  616. }
  617. return CheckCanceled() ? IDCANCEL : IDOK;
  618. }
  619. virtual STDMETHODIMP_(int) OnPlanMsiFeature(
  620. __in_z LPCWSTR wzPackageId,
  621. __in_z LPCWSTR wzFeatureId,
  622. __inout BOOTSTRAPPER_FEATURE_STATE* pRequestedState
  623. ) {
  624. LONGLONG install;
  625. if (wcscmp(wzFeatureId, L"AssociateFiles") == 0) {
  626. if (SUCCEEDED(_engine->GetVariableNumeric(L"AssociateFiles", &install)) && install) {
  627. *pRequestedState = BOOTSTRAPPER_FEATURE_STATE_LOCAL;
  628. } else {
  629. *pRequestedState = BOOTSTRAPPER_FEATURE_STATE_ABSENT;
  630. }
  631. } else {
  632. *pRequestedState = BOOTSTRAPPER_FEATURE_STATE_LOCAL;
  633. }
  634. return CheckCanceled() ? IDCANCEL : IDNOACTION;
  635. }
  636. virtual STDMETHODIMP_(void) OnPlanComplete(__in HRESULT hrStatus) {
  637. if (SUCCEEDED(hrStatus) && _baFunction) {
  638. BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "Running plan complete BA function");
  639. _baFunction->OnPlanComplete();
  640. }
  641. SetState(PYBA_STATE_PLANNED, hrStatus);
  642. if (SUCCEEDED(hrStatus)) {
  643. ::PostMessageW(_hWnd, WM_PYBA_APPLY_PACKAGES, 0, 0);
  644. }
  645. _startedExecution = FALSE;
  646. _calculatedCacheProgress = 0;
  647. _calculatedExecuteProgress = 0;
  648. }
  649. virtual STDMETHODIMP_(int) OnCachePackageBegin(
  650. __in_z LPCWSTR wzPackageId,
  651. __in DWORD cCachePayloads,
  652. __in DWORD64 dw64PackageCacheSize
  653. ) {
  654. if (wzPackageId && *wzPackageId) {
  655. BAL_INFO_PACKAGE* pPackage = nullptr;
  656. HRESULT hr = BalInfoFindPackageById(&_bundle.packages, wzPackageId, &pPackage);
  657. LPCWSTR wz = (SUCCEEDED(hr) && pPackage->sczDisplayName) ? pPackage->sczDisplayName : wzPackageId;
  658. ThemeSetTextControl(_theme, ID_CACHE_PROGRESS_PACKAGE_TEXT, wz);
  659. // If something started executing, leave it in the overall progress text.
  660. if (!_startedExecution) {
  661. ThemeSetTextControl(_theme, ID_OVERALL_PROGRESS_PACKAGE_TEXT, wz);
  662. }
  663. }
  664. return __super::OnCachePackageBegin(wzPackageId, cCachePayloads, dw64PackageCacheSize);
  665. }
  666. virtual STDMETHODIMP_(int) OnCacheAcquireProgress(
  667. __in_z LPCWSTR wzPackageOrContainerId,
  668. __in_z_opt LPCWSTR wzPayloadId,
  669. __in DWORD64 dw64Progress,
  670. __in DWORD64 dw64Total,
  671. __in DWORD dwOverallPercentage
  672. ) {
  673. WCHAR wzProgress[5] = { };
  674. #ifdef DEBUG
  675. BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "PYBA: OnCacheAcquireProgress() - container/package: %ls, payload: %ls, progress: %I64u, total: %I64u, overall progress: %u%%", wzPackageOrContainerId, wzPayloadId, dw64Progress, dw64Total, dwOverallPercentage);
  676. #endif
  677. ::StringCchPrintfW(wzProgress, countof(wzProgress), L"%u%%", dwOverallPercentage);
  678. ThemeSetTextControl(_theme, ID_CACHE_PROGRESS_TEXT, wzProgress);
  679. ThemeSetProgressControl(_theme, ID_CACHE_PROGRESS_BAR, dwOverallPercentage);
  680. _calculatedCacheProgress = dwOverallPercentage * PYBA_ACQUIRE_PERCENTAGE / 100;
  681. ThemeSetProgressControl(_theme, ID_OVERALL_CALCULATED_PROGRESS_BAR, _calculatedCacheProgress + _calculatedExecuteProgress);
  682. SetTaskbarButtonProgress(_calculatedCacheProgress + _calculatedExecuteProgress);
  683. return __super::OnCacheAcquireProgress(wzPackageOrContainerId, wzPayloadId, dw64Progress, dw64Total, dwOverallPercentage);
  684. }
  685. virtual STDMETHODIMP_(int) OnCacheAcquireComplete(
  686. __in_z LPCWSTR wzPackageOrContainerId,
  687. __in_z_opt LPCWSTR wzPayloadId,
  688. __in HRESULT hrStatus,
  689. __in int nRecommendation
  690. ) {
  691. SetProgressState(hrStatus);
  692. return __super::OnCacheAcquireComplete(wzPackageOrContainerId, wzPayloadId, hrStatus, nRecommendation);
  693. }
  694. virtual STDMETHODIMP_(int) OnCacheVerifyComplete(
  695. __in_z LPCWSTR wzPackageId,
  696. __in_z LPCWSTR wzPayloadId,
  697. __in HRESULT hrStatus,
  698. __in int nRecommendation
  699. ) {
  700. SetProgressState(hrStatus);
  701. return __super::OnCacheVerifyComplete(wzPackageId, wzPayloadId, hrStatus, nRecommendation);
  702. }
  703. virtual STDMETHODIMP_(void) OnCacheComplete(__in HRESULT /*hrStatus*/) {
  704. ThemeSetTextControl(_theme, ID_CACHE_PROGRESS_PACKAGE_TEXT, L"");
  705. SetState(PYBA_STATE_CACHED, S_OK); // we always return success here and let OnApplyComplete() deal with the error.
  706. }
  707. virtual STDMETHODIMP_(int) OnError(
  708. __in BOOTSTRAPPER_ERROR_TYPE errorType,
  709. __in LPCWSTR wzPackageId,
  710. __in DWORD dwCode,
  711. __in_z LPCWSTR wzError,
  712. __in DWORD dwUIHint,
  713. __in DWORD /*cData*/,
  714. __in_ecount_z_opt(cData) LPCWSTR* /*rgwzData*/,
  715. __in int nRecommendation
  716. ) {
  717. int nResult = nRecommendation;
  718. LPWSTR sczError = nullptr;
  719. if (BOOTSTRAPPER_DISPLAY_EMBEDDED == _command.display) {
  720. HRESULT hr = _engine->SendEmbeddedError(dwCode, wzError, dwUIHint, &nResult);
  721. if (FAILED(hr)) {
  722. nResult = IDERROR;
  723. }
  724. } else if (BOOTSTRAPPER_DISPLAY_FULL == _command.display) {
  725. // If this is an authentication failure, let the engine try to handle it for us.
  726. if (BOOTSTRAPPER_ERROR_TYPE_HTTP_AUTH_SERVER == errorType || BOOTSTRAPPER_ERROR_TYPE_HTTP_AUTH_PROXY == errorType) {
  727. nResult = IDTRYAGAIN;
  728. } else // show a generic error message box.
  729. {
  730. BalRetryErrorOccurred(wzPackageId, dwCode);
  731. if (!_showingInternalUIThisPackage) {
  732. // If no error message was provided, use the error code to try and get an error message.
  733. if (!wzError || !*wzError || BOOTSTRAPPER_ERROR_TYPE_WINDOWS_INSTALLER != errorType) {
  734. HRESULT hr = StrAllocFromError(&sczError, dwCode, nullptr);
  735. if (FAILED(hr) || !sczError || !*sczError) {
  736. StrAllocFormatted(&sczError, L"0x%x", dwCode);
  737. }
  738. }
  739. nResult = ::MessageBoxW(_hWnd, sczError ? sczError : wzError, _theme->sczCaption, dwUIHint);
  740. }
  741. }
  742. SetProgressState(HRESULT_FROM_WIN32(dwCode));
  743. } else {
  744. // just take note of the error code and let things continue.
  745. BalRetryErrorOccurred(wzPackageId, dwCode);
  746. }
  747. ReleaseStr(sczError);
  748. return nResult;
  749. }
  750. virtual STDMETHODIMP_(int) OnExecuteMsiMessage(
  751. __in_z LPCWSTR wzPackageId,
  752. __in INSTALLMESSAGE mt,
  753. __in UINT uiFlags,
  754. __in_z LPCWSTR wzMessage,
  755. __in DWORD cData,
  756. __in_ecount_z_opt(cData) LPCWSTR* rgwzData,
  757. __in int nRecommendation
  758. ) {
  759. #ifdef DEBUG
  760. BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "PYBA: OnExecuteMsiMessage() - package: %ls, message: %ls", wzPackageId, wzMessage);
  761. #endif
  762. if (BOOTSTRAPPER_DISPLAY_FULL == _command.display && (INSTALLMESSAGE_WARNING == mt || INSTALLMESSAGE_USER == mt)) {
  763. int nResult = ::MessageBoxW(_hWnd, wzMessage, _theme->sczCaption, uiFlags);
  764. return nResult;
  765. }
  766. if (INSTALLMESSAGE_ACTIONSTART == mt) {
  767. ThemeSetTextControl(_theme, ID_EXECUTE_PROGRESS_ACTIONDATA_TEXT, wzMessage);
  768. }
  769. return __super::OnExecuteMsiMessage(wzPackageId, mt, uiFlags, wzMessage, cData, rgwzData, nRecommendation);
  770. }
  771. virtual STDMETHODIMP_(int) OnProgress(__in DWORD dwProgressPercentage, __in DWORD dwOverallProgressPercentage) {
  772. WCHAR wzProgress[5] = { };
  773. #ifdef DEBUG
  774. BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "PYBA: OnProgress() - progress: %u%%, overall progress: %u%%", dwProgressPercentage, dwOverallProgressPercentage);
  775. #endif
  776. ::StringCchPrintfW(wzProgress, countof(wzProgress), L"%u%%", dwOverallProgressPercentage);
  777. ThemeSetTextControl(_theme, ID_OVERALL_PROGRESS_TEXT, wzProgress);
  778. ThemeSetProgressControl(_theme, ID_OVERALL_PROGRESS_BAR, dwOverallProgressPercentage);
  779. SetTaskbarButtonProgress(dwOverallProgressPercentage);
  780. return __super::OnProgress(dwProgressPercentage, dwOverallProgressPercentage);
  781. }
  782. virtual STDMETHODIMP_(int) OnExecutePackageBegin(__in_z LPCWSTR wzPackageId, __in BOOL fExecute) {
  783. LPWSTR sczFormattedString = nullptr;
  784. _startedExecution = TRUE;
  785. if (wzPackageId && *wzPackageId) {
  786. BAL_INFO_PACKAGE* pPackage = nullptr;
  787. BalInfoFindPackageById(&_bundle.packages, wzPackageId, &pPackage);
  788. LPCWSTR wz = wzPackageId;
  789. if (pPackage) {
  790. LOC_STRING* pLocString = nullptr;
  791. switch (pPackage->type) {
  792. case BAL_INFO_PACKAGE_TYPE_BUNDLE_ADDON:
  793. LocGetString(_wixLoc, L"#(loc.ExecuteAddonRelatedBundleMessage)", &pLocString);
  794. break;
  795. case BAL_INFO_PACKAGE_TYPE_BUNDLE_PATCH:
  796. LocGetString(_wixLoc, L"#(loc.ExecutePatchRelatedBundleMessage)", &pLocString);
  797. break;
  798. case BAL_INFO_PACKAGE_TYPE_BUNDLE_UPGRADE:
  799. LocGetString(_wixLoc, L"#(loc.ExecuteUpgradeRelatedBundleMessage)", &pLocString);
  800. break;
  801. }
  802. if (pLocString) {
  803. // If the wix developer is showing a hidden variable in the UI, then obviously they don't care about keeping it safe
  804. // so don't go down the rabbit hole of making sure that this is securely freed.
  805. BalFormatString(pLocString->wzText, &sczFormattedString);
  806. }
  807. wz = sczFormattedString ? sczFormattedString : pPackage->sczDisplayName ? pPackage->sczDisplayName : wzPackageId;
  808. }
  809. _showingInternalUIThisPackage = pPackage && pPackage->fDisplayInternalUI;
  810. ThemeSetTextControl(_theme, ID_EXECUTE_PROGRESS_PACKAGE_TEXT, wz);
  811. ThemeSetTextControl(_theme, ID_OVERALL_PROGRESS_PACKAGE_TEXT, wz);
  812. } else {
  813. _showingInternalUIThisPackage = FALSE;
  814. }
  815. ReleaseStr(sczFormattedString);
  816. return __super::OnExecutePackageBegin(wzPackageId, fExecute);
  817. }
  818. virtual int __stdcall OnExecuteProgress(
  819. __in_z LPCWSTR wzPackageId,
  820. __in DWORD dwProgressPercentage,
  821. __in DWORD dwOverallProgressPercentage
  822. ) {
  823. WCHAR wzProgress[8] = { };
  824. #ifdef DEBUG
  825. BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "PYBA: OnExecuteProgress() - package: %ls, progress: %u%%, overall progress: %u%%", wzPackageId, dwProgressPercentage, dwOverallProgressPercentage);
  826. #endif
  827. ::StringCchPrintfW(wzProgress, countof(wzProgress), L"%u%%", dwOverallProgressPercentage);
  828. ThemeSetTextControl(_theme, ID_EXECUTE_PROGRESS_TEXT, wzProgress);
  829. ThemeSetProgressControl(_theme, ID_EXECUTE_PROGRESS_BAR, dwOverallProgressPercentage);
  830. _calculatedExecuteProgress = dwOverallProgressPercentage * (100 - PYBA_ACQUIRE_PERCENTAGE) / 100;
  831. ThemeSetProgressControl(_theme, ID_OVERALL_CALCULATED_PROGRESS_BAR, _calculatedCacheProgress + _calculatedExecuteProgress);
  832. SetTaskbarButtonProgress(_calculatedCacheProgress + _calculatedExecuteProgress);
  833. return __super::OnExecuteProgress(wzPackageId, dwProgressPercentage, dwOverallProgressPercentage);
  834. }
  835. virtual STDMETHODIMP_(int) OnExecutePackageComplete(
  836. __in_z LPCWSTR wzPackageId,
  837. __in HRESULT hrExitCode,
  838. __in BOOTSTRAPPER_APPLY_RESTART restart,
  839. __in int nRecommendation
  840. ) {
  841. SetProgressState(hrExitCode);
  842. if (_wcsnicmp(wzPackageId, L"path_", 5) == 0 && SUCCEEDED(hrExitCode)) {
  843. SendMessageTimeoutW(
  844. HWND_BROADCAST,
  845. WM_SETTINGCHANGE,
  846. 0,
  847. reinterpret_cast<LPARAM>(L"Environment"),
  848. SMTO_ABORTIFHUNG,
  849. 1000,
  850. nullptr
  851. );
  852. }
  853. int nResult = __super::OnExecutePackageComplete(wzPackageId, hrExitCode, restart, nRecommendation);
  854. return nResult;
  855. }
  856. virtual STDMETHODIMP_(void) OnExecuteComplete(__in HRESULT hrStatus) {
  857. ThemeSetTextControl(_theme, ID_EXECUTE_PROGRESS_PACKAGE_TEXT, L"");
  858. ThemeSetTextControl(_theme, ID_EXECUTE_PROGRESS_ACTIONDATA_TEXT, L"");
  859. ThemeSetTextControl(_theme, ID_OVERALL_PROGRESS_PACKAGE_TEXT, L"");
  860. ThemeControlEnable(_theme, ID_PROGRESS_CANCEL_BUTTON, FALSE); // no more cancel.
  861. SetState(PYBA_STATE_EXECUTED, S_OK); // we always return success here and let OnApplyComplete() deal with the error.
  862. SetProgressState(hrStatus);
  863. }
  864. virtual STDMETHODIMP_(int) OnResolveSource(
  865. __in_z LPCWSTR wzPackageOrContainerId,
  866. __in_z_opt LPCWSTR wzPayloadId,
  867. __in_z LPCWSTR wzLocalSource,
  868. __in_z_opt LPCWSTR wzDownloadSource
  869. ) {
  870. int nResult = IDERROR; // assume we won't resolve source and that is unexpected.
  871. if (BOOTSTRAPPER_DISPLAY_FULL == _command.display) {
  872. if (wzDownloadSource) {
  873. nResult = IDDOWNLOAD;
  874. } else {
  875. // prompt to change the source location.
  876. OPENFILENAMEW ofn = { };
  877. WCHAR wzFile[MAX_PATH] = { };
  878. ::StringCchCopyW(wzFile, countof(wzFile), wzLocalSource);
  879. ofn.lStructSize = sizeof(ofn);
  880. ofn.hwndOwner = _hWnd;
  881. ofn.lpstrFile = wzFile;
  882. ofn.nMaxFile = countof(wzFile);
  883. ofn.lpstrFilter = L"All Files\0*.*\0";
  884. ofn.nFilterIndex = 1;
  885. ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
  886. ofn.lpstrTitle = _theme->sczCaption;
  887. if (::GetOpenFileNameW(&ofn)) {
  888. HRESULT hr = _engine->SetLocalSource(wzPackageOrContainerId, wzPayloadId, ofn.lpstrFile);
  889. nResult = SUCCEEDED(hr) ? IDRETRY : IDERROR;
  890. } else {
  891. nResult = IDCANCEL;
  892. }
  893. }
  894. } else if (wzDownloadSource) {
  895. // If doing a non-interactive install and download source is available, let's try downloading the package silently
  896. nResult = IDDOWNLOAD;
  897. }
  898. // else there's nothing more we can do in non-interactive mode
  899. return CheckCanceled() ? IDCANCEL : nResult;
  900. }
  901. virtual STDMETHODIMP_(int) OnApplyComplete(__in HRESULT hrStatus, __in BOOTSTRAPPER_APPLY_RESTART restart) {
  902. _restartResult = restart; // remember the restart result so we return the correct error code no matter what the user chooses to do in the UI.
  903. // If a restart was encountered and we are not suppressing restarts, then restart is required.
  904. _restartRequired = (BOOTSTRAPPER_APPLY_RESTART_NONE != restart && BOOTSTRAPPER_RESTART_NEVER < _command.restart);
  905. // If a restart is required and we're not displaying a UI or we are not supposed to prompt for restart then allow the restart.
  906. _allowRestart = _restartRequired && (BOOTSTRAPPER_DISPLAY_FULL > _command.display || BOOTSTRAPPER_RESTART_PROMPT < _command.restart);
  907. // If we are showing UI, wait a beat before moving to the final screen.
  908. if (BOOTSTRAPPER_DISPLAY_NONE < _command.display) {
  909. ::Sleep(250);
  910. }
  911. SetState(PYBA_STATE_APPLIED, hrStatus);
  912. SetTaskbarButtonProgress(100); // show full progress bar, green, yellow, or red
  913. return IDNOACTION;
  914. }
  915. virtual STDMETHODIMP_(void) OnLaunchApprovedExeComplete(__in HRESULT hrStatus, __in DWORD /*processId*/) {
  916. if (HRESULT_FROM_WIN32(ERROR_ACCESS_DENIED) == hrStatus) {
  917. //try with ShelExec next time
  918. OnClickLaunchButton();
  919. } else {
  920. ::PostMessageW(_hWnd, WM_CLOSE, 0, 0);
  921. }
  922. }
  923. private:
  924. //
  925. // UiThreadProc - entrypoint for UI thread.
  926. //
  927. static DWORD WINAPI UiThreadProc(__in LPVOID pvContext) {
  928. HRESULT hr = S_OK;
  929. PythonBootstrapperApplication* pThis = (PythonBootstrapperApplication*)pvContext;
  930. BOOL comInitialized = FALSE;
  931. BOOL ret = FALSE;
  932. MSG msg = { };
  933. // Initialize COM and theme.
  934. hr = ::CoInitialize(nullptr);
  935. BalExitOnFailure(hr, "Failed to initialize COM.");
  936. comInitialized = TRUE;
  937. hr = ThemeInitialize(pThis->_hModule);
  938. BalExitOnFailure(hr, "Failed to initialize theme manager.");
  939. hr = pThis->InitializeData();
  940. BalExitOnFailure(hr, "Failed to initialize data in bootstrapper application.");
  941. // Create main window.
  942. pThis->InitializeTaskbarButton();
  943. hr = pThis->CreateMainWindow();
  944. BalExitOnFailure(hr, "Failed to create main window.");
  945. if (FAILED(pThis->_hrFinal)) {
  946. pThis->SetState(PYBA_STATE_FAILED, hr);
  947. ::PostMessageW(pThis->_hWnd, WM_PYBA_SHOW_FAILURE, 0, 0);
  948. } else {
  949. // Okay, we're ready for packages now.
  950. pThis->SetState(PYBA_STATE_INITIALIZED, hr);
  951. ::PostMessageW(pThis->_hWnd, BOOTSTRAPPER_ACTION_HELP == pThis->_command.action ? WM_PYBA_SHOW_HELP : WM_PYBA_DETECT_PACKAGES, 0, 0);
  952. }
  953. // message pump
  954. while (0 != (ret = ::GetMessageW(&msg, nullptr, 0, 0))) {
  955. if (-1 == ret) {
  956. hr = E_UNEXPECTED;
  957. BalExitOnFailure(hr, "Unexpected return value from message pump.");
  958. } else if (!ThemeHandleKeyboardMessage(pThis->_theme, msg.hwnd, &msg)) {
  959. ::TranslateMessage(&msg);
  960. ::DispatchMessageW(&msg);
  961. }
  962. }
  963. // Succeeded thus far, check to see if anything went wrong while actually
  964. // executing changes.
  965. if (FAILED(pThis->_hrFinal)) {
  966. hr = pThis->_hrFinal;
  967. } else if (pThis->CheckCanceled()) {
  968. hr = HRESULT_FROM_WIN32(ERROR_INSTALL_USEREXIT);
  969. }
  970. LExit:
  971. // destroy main window
  972. pThis->DestroyMainWindow();
  973. // initiate engine shutdown
  974. DWORD dwQuit = HRESULT_CODE(hr);
  975. if (BOOTSTRAPPER_APPLY_RESTART_INITIATED == pThis->_restartResult) {
  976. dwQuit = ERROR_SUCCESS_REBOOT_INITIATED;
  977. } else if (BOOTSTRAPPER_APPLY_RESTART_REQUIRED == pThis->_restartResult) {
  978. dwQuit = ERROR_SUCCESS_REBOOT_REQUIRED;
  979. }
  980. pThis->_engine->Quit(dwQuit);
  981. ReleaseTheme(pThis->_theme);
  982. ThemeUninitialize();
  983. // uninitialize COM
  984. if (comInitialized) {
  985. ::CoUninitialize();
  986. }
  987. return hr;
  988. }
  989. //
  990. // InitializeData - initializes all the package information.
  991. //
  992. HRESULT InitializeData() {
  993. HRESULT hr = S_OK;
  994. LPWSTR sczModulePath = nullptr;
  995. IXMLDOMDocument *pixdManifest = nullptr;
  996. hr = BalManifestLoad(_hModule, &pixdManifest);
  997. BalExitOnFailure(hr, "Failed to load bootstrapper application manifest.");
  998. hr = ParseOverridableVariablesFromXml(pixdManifest);
  999. BalExitOnFailure(hr, "Failed to read overridable variables.");
  1000. hr = ProcessCommandLine(&_language);
  1001. ExitOnFailure(hr, "Unknown commandline parameters.");
  1002. hr = PathRelativeToModule(&sczModulePath, nullptr, _hModule);
  1003. BalExitOnFailure(hr, "Failed to get module path.");
  1004. hr = LoadLocalization(sczModulePath, _language);
  1005. ExitOnFailure(hr, "Failed to load localization.");
  1006. hr = LoadTheme(sczModulePath, _language);
  1007. ExitOnFailure(hr, "Failed to load theme.");
  1008. hr = BalInfoParseFromXml(&_bundle, pixdManifest);
  1009. BalExitOnFailure(hr, "Failed to load bundle information.");
  1010. hr = BalConditionsParseFromXml(&_conditions, pixdManifest, _wixLoc);
  1011. BalExitOnFailure(hr, "Failed to load conditions from XML.");
  1012. hr = LoadBootstrapperBAFunctions();
  1013. BalExitOnFailure(hr, "Failed to load bootstrapper functions.");
  1014. hr = UpdateUIStrings(_command.action);
  1015. BalExitOnFailure(hr, "Failed to load UI strings.");
  1016. GetBundleFileVersion();
  1017. // don't fail if we couldn't get the version info; best-effort only
  1018. LExit:
  1019. ReleaseObject(pixdManifest);
  1020. ReleaseStr(sczModulePath);
  1021. return hr;
  1022. }
  1023. //
  1024. // ProcessCommandLine - process the provided command line arguments.
  1025. //
  1026. HRESULT ProcessCommandLine(__inout LPWSTR* psczLanguage) {
  1027. HRESULT hr = S_OK;
  1028. int argc = 0;
  1029. LPWSTR* argv = nullptr;
  1030. LPWSTR sczVariableName = nullptr;
  1031. LPWSTR sczVariableValue = nullptr;
  1032. if (_command.wzCommandLine && *_command.wzCommandLine) {
  1033. argv = ::CommandLineToArgvW(_command.wzCommandLine, &argc);
  1034. ExitOnNullWithLastError(argv, hr, "Failed to get command line.");
  1035. for (int i = 0; i < argc; ++i) {
  1036. if (argv[i][0] == L'-' || argv[i][0] == L'/') {
  1037. if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, NORM_IGNORECASE, &argv[i][1], -1, L"lang", -1)) {
  1038. if (i + 1 >= argc) {
  1039. hr = E_INVALIDARG;
  1040. BalExitOnFailure(hr, "Must specify a language.");
  1041. }
  1042. ++i;
  1043. hr = StrAllocString(psczLanguage, &argv[i][0], 0);
  1044. BalExitOnFailure(hr, "Failed to copy language.");
  1045. }
  1046. } else if (_overridableVariables) {
  1047. int value;
  1048. const wchar_t* pwc = wcschr(argv[i], L'=');
  1049. if (pwc) {
  1050. hr = StrAllocString(&sczVariableName, argv[i], pwc - argv[i]);
  1051. BalExitOnFailure(hr, "Failed to copy variable name.");
  1052. hr = DictKeyExists(_overridableVariables, sczVariableName);
  1053. if (E_NOTFOUND == hr) {
  1054. BalLog(BOOTSTRAPPER_LOG_LEVEL_ERROR, "Ignoring attempt to set non-overridable variable: '%ls'.", sczVariableName);
  1055. hr = S_OK;
  1056. continue;
  1057. }
  1058. ExitOnFailure(hr, "Failed to check the dictionary of overridable variables.");
  1059. hr = StrAllocString(&sczVariableValue, ++pwc, 0);
  1060. BalExitOnFailure(hr, "Failed to copy variable value.");
  1061. if (::StrToIntEx(sczVariableValue, STIF_DEFAULT, &value)) {
  1062. hr = _engine->SetVariableNumeric(sczVariableName, value);
  1063. } else {
  1064. hr = _engine->SetVariableString(sczVariableName, sczVariableValue);
  1065. }
  1066. BalExitOnFailure(hr, "Failed to set variable.");
  1067. } else {
  1068. BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "Ignoring unknown argument: %ls", argv[i]);
  1069. }
  1070. }
  1071. }
  1072. }
  1073. LExit:
  1074. if (argv) {
  1075. ::LocalFree(argv);
  1076. }
  1077. ReleaseStr(sczVariableName);
  1078. ReleaseStr(sczVariableValue);
  1079. return hr;
  1080. }
  1081. HRESULT LoadLocalization(__in_z LPCWSTR wzModulePath, __in_z_opt LPCWSTR wzLanguage) {
  1082. HRESULT hr = S_OK;
  1083. LPWSTR sczLocPath = nullptr;
  1084. LPCWSTR wzLocFileName = L"Default.wxl";
  1085. hr = LocProbeForFile(wzModulePath, wzLocFileName, wzLanguage, &sczLocPath);
  1086. BalExitOnFailure2(hr, "Failed to probe for loc file: %ls in path: %ls", wzLocFileName, wzModulePath);
  1087. hr = LocLoadFromFile(sczLocPath, &_wixLoc);
  1088. BalExitOnFailure1(hr, "Failed to load loc file from path: %ls", sczLocPath);
  1089. if (WIX_LOCALIZATION_LANGUAGE_NOT_SET != _wixLoc->dwLangId) {
  1090. ::SetThreadLocale(_wixLoc->dwLangId);
  1091. }
  1092. hr = StrAllocString(&_confirmCloseMessage, L"#(loc.ConfirmCancelMessage)", 0);
  1093. ExitOnFailure(hr, "Failed to initialize confirm message loc identifier.");
  1094. hr = LocLocalizeString(_wixLoc, &_confirmCloseMessage);
  1095. BalExitOnFailure1(hr, "Failed to localize confirm close message: %ls", _confirmCloseMessage);
  1096. LExit:
  1097. ReleaseStr(sczLocPath);
  1098. return hr;
  1099. }
  1100. HRESULT LoadTheme(__in_z LPCWSTR wzModulePath, __in_z_opt LPCWSTR wzLanguage) {
  1101. HRESULT hr = S_OK;
  1102. LPWSTR sczThemePath = nullptr;
  1103. LPCWSTR wzThemeFileName = L"Default.thm";
  1104. LPWSTR sczCaption = nullptr;
  1105. hr = LocProbeForFile(wzModulePath, wzThemeFileName, wzLanguage, &sczThemePath);
  1106. BalExitOnFailure2(hr, "Failed to probe for theme file: %ls in path: %ls", wzThemeFileName, wzModulePath);
  1107. hr = ThemeLoadFromFile(sczThemePath, &_theme);
  1108. BalExitOnFailure1(hr, "Failed to load theme from path: %ls", sczThemePath);
  1109. hr = ThemeLocalize(_theme, _wixLoc);
  1110. BalExitOnFailure1(hr, "Failed to localize theme: %ls", sczThemePath);
  1111. // Update the caption if there are any formatted strings in it.
  1112. // If the wix developer is showing a hidden variable in the UI, then
  1113. // obviously they don't care about keeping it safe so don't go down the
  1114. // rabbit hole of making sure that this is securely freed.
  1115. hr = BalFormatString(_theme->sczCaption, &sczCaption);
  1116. if (SUCCEEDED(hr)) {
  1117. ThemeUpdateCaption(_theme, sczCaption);
  1118. }
  1119. LExit:
  1120. ReleaseStr(sczCaption);
  1121. ReleaseStr(sczThemePath);
  1122. return hr;
  1123. }
  1124. HRESULT ParseOverridableVariablesFromXml(__in IXMLDOMDocument* pixdManifest) {
  1125. HRESULT hr = S_OK;
  1126. IXMLDOMNode* pNode = nullptr;
  1127. IXMLDOMNodeList* pNodes = nullptr;
  1128. DWORD cNodes = 0;
  1129. LPWSTR scz = nullptr;
  1130. BOOL hidden = FALSE;
  1131. // get the list of variables users can override on the command line
  1132. hr = XmlSelectNodes(pixdManifest, L"/BootstrapperApplicationData/WixStdbaOverridableVariable", &pNodes);
  1133. if (S_FALSE == hr) {
  1134. ExitFunction1(hr = S_OK);
  1135. }
  1136. ExitOnFailure(hr, "Failed to select overridable variable nodes.");
  1137. hr = pNodes->get_length((long*)&cNodes);
  1138. ExitOnFailure(hr, "Failed to get overridable variable node count.");
  1139. if (cNodes) {
  1140. hr = DictCreateStringList(&_overridableVariables, 32, DICT_FLAG_NONE);
  1141. ExitOnFailure(hr, "Failed to create the string dictionary.");
  1142. for (DWORD i = 0; i < cNodes; ++i) {
  1143. hr = XmlNextElement(pNodes, &pNode, nullptr);
  1144. ExitOnFailure(hr, "Failed to get next node.");
  1145. // @Name
  1146. hr = XmlGetAttributeEx(pNode, L"Name", &scz);
  1147. ExitOnFailure(hr, "Failed to get @Name.");
  1148. hr = XmlGetYesNoAttribute(pNode, L"Hidden", &hidden);
  1149. if (!hidden) {
  1150. hr = DictAddKey(_overridableVariables, scz);
  1151. ExitOnFailure1(hr, "Failed to add \"%ls\" to the string dictionary.", scz);
  1152. }
  1153. // prepare next iteration
  1154. ReleaseNullObject(pNode);
  1155. }
  1156. }
  1157. LExit:
  1158. ReleaseObject(pNode);
  1159. ReleaseObject(pNodes);
  1160. ReleaseStr(scz);
  1161. return hr;
  1162. }
  1163. //
  1164. // Get the file version of the bootstrapper and record in bootstrapper log file
  1165. //
  1166. HRESULT GetBundleFileVersion() {
  1167. HRESULT hr = S_OK;
  1168. ULARGE_INTEGER uliVersion = { };
  1169. LPWSTR sczCurrentPath = nullptr;
  1170. hr = PathForCurrentProcess(&sczCurrentPath, nullptr);
  1171. BalExitOnFailure(hr, "Failed to get bundle path.");
  1172. hr = FileVersion(sczCurrentPath, &uliVersion.HighPart, &uliVersion.LowPart);
  1173. BalExitOnFailure(hr, "Failed to get bundle file version.");
  1174. hr = _engine->SetVariableVersion(PYBA_VARIABLE_BUNDLE_FILE_VERSION, uliVersion.QuadPart);
  1175. BalExitOnFailure(hr, "Failed to set WixBundleFileVersion variable.");
  1176. LExit:
  1177. ReleaseStr(sczCurrentPath);
  1178. return hr;
  1179. }
  1180. //
  1181. // CreateMainWindow - creates the main install window.
  1182. //
  1183. HRESULT CreateMainWindow() {
  1184. HRESULT hr = S_OK;
  1185. HICON hIcon = reinterpret_cast<HICON>(_theme->hIcon);
  1186. WNDCLASSW wc = { };
  1187. DWORD dwWindowStyle = 0;
  1188. int x = CW_USEDEFAULT;
  1189. int y = CW_USEDEFAULT;
  1190. POINT ptCursor = { };
  1191. HMONITOR hMonitor = nullptr;
  1192. MONITORINFO mi = { };
  1193. // If the theme did not provide an icon, try using the icon from the bundle engine.
  1194. if (!hIcon) {
  1195. HMODULE hBootstrapperEngine = ::GetModuleHandleW(nullptr);
  1196. if (hBootstrapperEngine) {
  1197. hIcon = ::LoadIconW(hBootstrapperEngine, MAKEINTRESOURCEW(1));
  1198. }
  1199. }
  1200. // Register the window class and create the window.
  1201. wc.lpfnWndProc = PythonBootstrapperApplication::WndProc;
  1202. wc.hInstance = _hModule;
  1203. wc.hIcon = hIcon;
  1204. wc.hCursor = ::LoadCursorW(nullptr, (LPCWSTR)IDC_ARROW);
  1205. wc.hbrBackground = _theme->rgFonts[_theme->dwFontId].hBackground;
  1206. wc.lpszMenuName = nullptr;
  1207. wc.lpszClassName = PYBA_WINDOW_CLASS;
  1208. if (!::RegisterClassW(&wc)) {
  1209. ExitWithLastError(hr, "Failed to register window.");
  1210. }
  1211. _registered = TRUE;
  1212. // Calculate the window style based on the theme style and command display value.
  1213. dwWindowStyle = _theme->dwStyle;
  1214. if (BOOTSTRAPPER_DISPLAY_NONE >= _command.display) {
  1215. dwWindowStyle &= ~WS_VISIBLE;
  1216. }
  1217. // Don't show the window if there is a splash screen (it will be made visible when the splash screen is hidden)
  1218. if (::IsWindow(_command.hwndSplashScreen)) {
  1219. dwWindowStyle &= ~WS_VISIBLE;
  1220. }
  1221. // Center the window on the monitor with the mouse.
  1222. if (::GetCursorPos(&ptCursor)) {
  1223. hMonitor = ::MonitorFromPoint(ptCursor, MONITOR_DEFAULTTONEAREST);
  1224. if (hMonitor) {
  1225. mi.cbSize = sizeof(mi);
  1226. if (::GetMonitorInfoW(hMonitor, &mi)) {
  1227. x = mi.rcWork.left + (mi.rcWork.right - mi.rcWork.left - _theme->nWidth) / 2;
  1228. y = mi.rcWork.top + (mi.rcWork.bottom - mi.rcWork.top - _theme->nHeight) / 2;
  1229. }
  1230. }
  1231. }
  1232. _hWnd = ::CreateWindowExW(
  1233. 0,
  1234. wc.lpszClassName,
  1235. _theme->sczCaption,
  1236. dwWindowStyle,
  1237. x,
  1238. y,
  1239. _theme->nWidth,
  1240. _theme->nHeight,
  1241. HWND_DESKTOP,
  1242. nullptr,
  1243. _hModule,
  1244. this
  1245. );
  1246. ExitOnNullWithLastError(_hWnd, hr, "Failed to create window.");
  1247. hr = S_OK;
  1248. LExit:
  1249. return hr;
  1250. }
  1251. //
  1252. // InitializeTaskbarButton - initializes taskbar button for progress.
  1253. //
  1254. void InitializeTaskbarButton() {
  1255. HRESULT hr = S_OK;
  1256. hr = ::CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_ALL, __uuidof(ITaskbarList3), reinterpret_cast<LPVOID*>(&_taskbarList));
  1257. if (REGDB_E_CLASSNOTREG == hr) {
  1258. // not supported before Windows 7
  1259. ExitFunction1(hr = S_OK);
  1260. }
  1261. BalExitOnFailure(hr, "Failed to create ITaskbarList3. Continuing.");
  1262. _taskbarButtonCreatedMessage = ::RegisterWindowMessageW(L"TaskbarButtonCreated");
  1263. BalExitOnNullWithLastError(_taskbarButtonCreatedMessage, hr, "Failed to get TaskbarButtonCreated message. Continuing.");
  1264. LExit:
  1265. return;
  1266. }
  1267. //
  1268. // DestroyMainWindow - clean up all the window registration.
  1269. //
  1270. void DestroyMainWindow() {
  1271. if (::IsWindow(_hWnd)) {
  1272. ::DestroyWindow(_hWnd);
  1273. _hWnd = nullptr;
  1274. _taskbarButtonOK = FALSE;
  1275. }
  1276. if (_registered) {
  1277. ::UnregisterClassW(PYBA_WINDOW_CLASS, _hModule);
  1278. _registered = FALSE;
  1279. }
  1280. }
  1281. //
  1282. // WndProc - standard windows message handler.
  1283. //
  1284. static LRESULT CALLBACK WndProc(
  1285. __in HWND hWnd,
  1286. __in UINT uMsg,
  1287. __in WPARAM wParam,
  1288. __in LPARAM lParam
  1289. ) {
  1290. #pragma warning(suppress:4312)
  1291. auto pBA = reinterpret_cast<PythonBootstrapperApplication*>(::GetWindowLongPtrW(hWnd, GWLP_USERDATA));
  1292. switch (uMsg) {
  1293. case WM_NCCREATE: {
  1294. LPCREATESTRUCT lpcs = reinterpret_cast<LPCREATESTRUCT>(lParam);
  1295. pBA = reinterpret_cast<PythonBootstrapperApplication*>(lpcs->lpCreateParams);
  1296. #pragma warning(suppress:4244)
  1297. ::SetWindowLongPtrW(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(pBA));
  1298. break;
  1299. }
  1300. case WM_NCDESTROY: {
  1301. LRESULT lres = ThemeDefWindowProc(pBA ? pBA->_theme : nullptr, hWnd, uMsg, wParam, lParam);
  1302. ::SetWindowLongPtrW(hWnd, GWLP_USERDATA, 0);
  1303. return lres;
  1304. }
  1305. case WM_CREATE:
  1306. if (!pBA->OnCreate(hWnd)) {
  1307. return -1;
  1308. }
  1309. break;
  1310. case WM_QUERYENDSESSION:
  1311. return IDCANCEL != pBA->OnSystemShutdown(static_cast<DWORD>(lParam), IDCANCEL);
  1312. case WM_CLOSE:
  1313. // If the user chose not to close, do *not* let the default window proc handle the message.
  1314. if (!pBA->OnClose()) {
  1315. return 0;
  1316. }
  1317. break;
  1318. case WM_DESTROY:
  1319. ::PostQuitMessage(0);
  1320. break;
  1321. case WM_PAINT: __fallthrough;
  1322. case WM_ERASEBKGND:
  1323. if (pBA && pBA->_suppressPaint) {
  1324. return TRUE;
  1325. }
  1326. break;
  1327. case WM_PYBA_SHOW_HELP:
  1328. pBA->OnShowHelp();
  1329. return 0;
  1330. case WM_PYBA_DETECT_PACKAGES:
  1331. pBA->OnDetect();
  1332. return 0;
  1333. case WM_PYBA_PLAN_PACKAGES:
  1334. pBA->OnPlan(static_cast<BOOTSTRAPPER_ACTION>(lParam));
  1335. return 0;
  1336. case WM_PYBA_APPLY_PACKAGES:
  1337. pBA->OnApply();
  1338. return 0;
  1339. case WM_PYBA_CHANGE_STATE:
  1340. pBA->OnChangeState(static_cast<PYBA_STATE>(lParam));
  1341. return 0;
  1342. case WM_PYBA_SHOW_FAILURE:
  1343. pBA->OnShowFailure();
  1344. return 0;
  1345. case WM_COMMAND:
  1346. switch (LOWORD(wParam)) {
  1347. // Customize commands
  1348. // Success/failure commands
  1349. case ID_LAUNCH_BUTTON:
  1350. pBA->OnClickLaunchButton();
  1351. return 0;
  1352. case ID_SUCCESS_RESTART_BUTTON: __fallthrough;
  1353. case ID_FAILURE_RESTART_BUTTON:
  1354. pBA->OnClickRestartButton();
  1355. return 0;
  1356. case IDCANCEL: __fallthrough;
  1357. case ID_INSTALL_CANCEL_BUTTON: __fallthrough;
  1358. case ID_CUSTOM1_CANCEL_BUTTON: __fallthrough;
  1359. case ID_CUSTOM2_CANCEL_BUTTON: __fallthrough;
  1360. case ID_MODIFY_CANCEL_BUTTON: __fallthrough;
  1361. case ID_PROGRESS_CANCEL_BUTTON: __fallthrough;
  1362. case ID_SUCCESS_CANCEL_BUTTON: __fallthrough;
  1363. case ID_FAILURE_CANCEL_BUTTON: __fallthrough;
  1364. case ID_CLOSE_BUTTON:
  1365. pBA->OnCommand(ID_CLOSE_BUTTON);
  1366. return 0;
  1367. default:
  1368. pBA->OnCommand((CONTROL_ID)LOWORD(wParam));
  1369. }
  1370. break;
  1371. case WM_NOTIFY:
  1372. if (lParam) {
  1373. LPNMHDR pnmhdr = reinterpret_cast<LPNMHDR>(lParam);
  1374. switch (pnmhdr->code) {
  1375. case NM_CLICK: __fallthrough;
  1376. case NM_RETURN:
  1377. switch (static_cast<DWORD>(pnmhdr->idFrom)) {
  1378. case ID_FAILURE_LOGFILE_LINK:
  1379. pBA->OnClickLogFileLink();
  1380. return 1;
  1381. }
  1382. }
  1383. }
  1384. break;
  1385. case WM_CTLCOLORBTN:
  1386. if (pBA) {
  1387. HWND button = (HWND)lParam;
  1388. DWORD style = GetWindowLong(button, GWL_STYLE) & BS_TYPEMASK;
  1389. if (style == BS_COMMANDLINK || style == BS_DEFCOMMANDLINK) {
  1390. return (LRESULT)pBA->_theme->rgFonts[pBA->_theme->dwFontId].hBackground;
  1391. }
  1392. }
  1393. break;
  1394. }
  1395. if (pBA && pBA->_taskbarList && uMsg == pBA->_taskbarButtonCreatedMessage) {
  1396. pBA->_taskbarButtonOK = TRUE;
  1397. return 0;
  1398. }
  1399. return ThemeDefWindowProc(pBA ? pBA->_theme : nullptr, hWnd, uMsg, wParam, lParam);
  1400. }
  1401. //
  1402. // OnCreate - finishes loading the theme.
  1403. //
  1404. BOOL OnCreate(__in HWND hWnd) {
  1405. HRESULT hr = S_OK;
  1406. hr = ThemeLoadControls(_theme, hWnd, CONTROL_ID_NAMES, countof(CONTROL_ID_NAMES));
  1407. BalExitOnFailure(hr, "Failed to load theme controls.");
  1408. C_ASSERT(COUNT_PAGE == countof(PAGE_NAMES));
  1409. C_ASSERT(countof(_pageIds) == countof(PAGE_NAMES));
  1410. ThemeGetPageIds(_theme, PAGE_NAMES, _pageIds, countof(_pageIds));
  1411. // Initialize the text on all "application" (non-page) controls.
  1412. for (DWORD i = 0; i < _theme->cControls; ++i) {
  1413. THEME_CONTROL* pControl = _theme->rgControls + i;
  1414. LPWSTR text = nullptr;
  1415. LPWSTR name = nullptr;
  1416. LOC_STRING *locText = nullptr;
  1417. // If a command link has a note, then add it.
  1418. if ((pControl->dwStyle & BS_TYPEMASK) == BS_COMMANDLINK ||
  1419. (pControl->dwStyle & BS_TYPEMASK) == BS_DEFCOMMANDLINK) {
  1420. hr = StrAllocFormatted(&name, L"#(loc.%lsNote)", pControl->sczName);
  1421. if (SUCCEEDED(hr)) {
  1422. hr = LocGetString(_wixLoc, name, &locText);
  1423. ReleaseStr(name);
  1424. if (SUCCEEDED(hr) && locText && locText->wzText && locText->wzText[0]) {
  1425. hr = BalFormatString(locText->wzText, &text);
  1426. if (SUCCEEDED(hr) && text && text[0]) {
  1427. ThemeSendControlMessage(_theme, pControl->wId, BCM_SETNOTE, 0, (LPARAM)text);
  1428. ReleaseStr(text);
  1429. text = nullptr;
  1430. }
  1431. }
  1432. }
  1433. hr = S_OK;
  1434. }
  1435. if (!pControl->wPageId && pControl->sczText && *pControl->sczText) {
  1436. HRESULT hrFormat;
  1437. // If the wix developer is showing a hidden variable in the UI,
  1438. // then obviously they don't care about keeping it safe so don't
  1439. // go down the rabbit hole of making sure that this is securely
  1440. // freed.
  1441. hrFormat = BalFormatString(pControl->sczText, &text);
  1442. if (SUCCEEDED(hrFormat)) {
  1443. ThemeSetTextControl(_theme, pControl->wId, text);
  1444. ReleaseStr(text);
  1445. }
  1446. }
  1447. }
  1448. LExit:
  1449. return SUCCEEDED(hr);
  1450. }
  1451. //
  1452. // OnShowFailure - display the failure page.
  1453. //
  1454. void OnShowFailure() {
  1455. SetState(PYBA_STATE_FAILED, S_OK);
  1456. // If the UI should be visible, display it now and hide the splash screen
  1457. if (BOOTSTRAPPER_DISPLAY_NONE < _command.display) {
  1458. ::ShowWindow(_theme->hwndParent, SW_SHOW);
  1459. }
  1460. _engine->CloseSplashScreen();
  1461. return;
  1462. }
  1463. //
  1464. // OnShowHelp - display the help page.
  1465. //
  1466. void OnShowHelp() {
  1467. SetState(PYBA_STATE_HELP, S_OK);
  1468. // If the UI should be visible, display it now and hide the splash screen
  1469. if (BOOTSTRAPPER_DISPLAY_NONE < _command.display) {
  1470. ::ShowWindow(_theme->hwndParent, SW_SHOW);
  1471. }
  1472. _engine->CloseSplashScreen();
  1473. return;
  1474. }
  1475. //
  1476. // OnDetect - start the processing of packages.
  1477. //
  1478. void OnDetect() {
  1479. HRESULT hr = S_OK;
  1480. if (_baFunction) {
  1481. BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "Running detect BA function");
  1482. hr = _baFunction->OnDetect();
  1483. BalExitOnFailure(hr, "Failed calling detect BA function.");
  1484. }
  1485. SetState(PYBA_STATE_DETECTING, hr);
  1486. // If the UI should be visible, display it now and hide the splash screen
  1487. if (BOOTSTRAPPER_DISPLAY_NONE < _command.display) {
  1488. ::ShowWindow(_theme->hwndParent, SW_SHOW);
  1489. }
  1490. _engine->CloseSplashScreen();
  1491. // Tell the core we're ready for the packages to be processed now.
  1492. hr = _engine->Detect();
  1493. BalExitOnFailure(hr, "Failed to start detecting chain.");
  1494. LExit:
  1495. if (FAILED(hr)) {
  1496. SetState(PYBA_STATE_DETECTING, hr);
  1497. }
  1498. return;
  1499. }
  1500. HRESULT UpdateUIStrings(__in BOOTSTRAPPER_ACTION action) {
  1501. HRESULT hr = S_OK;
  1502. LPCWSTR likeInstalling = nullptr;
  1503. LPCWSTR likeInstallation = nullptr;
  1504. switch (action) {
  1505. case BOOTSTRAPPER_ACTION_INSTALL:
  1506. likeInstalling = L"Installing";
  1507. likeInstallation = L"Installation";
  1508. break;
  1509. case BOOTSTRAPPER_ACTION_MODIFY:
  1510. // For modify, we actually want to pass INSTALL
  1511. action = BOOTSTRAPPER_ACTION_INSTALL;
  1512. likeInstalling = L"Modifying";
  1513. likeInstallation = L"Modification";
  1514. break;
  1515. case BOOTSTRAPPER_ACTION_REPAIR:
  1516. likeInstalling = L"Repairing";
  1517. likeInstallation = L"Repair";
  1518. break;
  1519. case BOOTSTRAPPER_ACTION_UNINSTALL:
  1520. likeInstalling = L"Uninstalling";
  1521. likeInstallation = L"Uninstallation";
  1522. break;
  1523. }
  1524. if (likeInstalling) {
  1525. LPWSTR locName = nullptr;
  1526. LOC_STRING *locText = nullptr;
  1527. hr = StrAllocFormatted(&locName, L"#(loc.%ls)", likeInstalling);
  1528. if (SUCCEEDED(hr)) {
  1529. hr = LocGetString(_wixLoc, locName, &locText);
  1530. ReleaseStr(locName);
  1531. }
  1532. _engine->SetVariableString(
  1533. L"ActionLikeInstalling",
  1534. SUCCEEDED(hr) && locText ? locText->wzText : likeInstalling
  1535. );
  1536. }
  1537. if (likeInstallation) {
  1538. LPWSTR locName = nullptr;
  1539. LOC_STRING *locText = nullptr;
  1540. hr = StrAllocFormatted(&locName, L"#(loc.%ls)", likeInstallation);
  1541. if (SUCCEEDED(hr)) {
  1542. hr = LocGetString(_wixLoc, locName, &locText);
  1543. ReleaseStr(locName);
  1544. }
  1545. _engine->SetVariableString(
  1546. L"ActionLikeInstallation",
  1547. SUCCEEDED(hr) && locText ? locText->wzText : likeInstallation
  1548. );
  1549. }
  1550. return hr;
  1551. }
  1552. //
  1553. // OnPlan - plan the detected changes.
  1554. //
  1555. void OnPlan(__in BOOTSTRAPPER_ACTION action) {
  1556. HRESULT hr = S_OK;
  1557. _plannedAction = action;
  1558. hr = UpdateUIStrings(action);
  1559. BalExitOnFailure(hr, "Failed to update strings");
  1560. // If we are going to apply a downgrade, bail.
  1561. if (_downgrading && BOOTSTRAPPER_ACTION_UNINSTALL < action) {
  1562. if (_suppressDowngradeFailure) {
  1563. BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "A newer version of this product is installed but downgrade failure has been suppressed; continuing...");
  1564. } else {
  1565. hr = HRESULT_FROM_WIN32(ERROR_PRODUCT_VERSION);
  1566. BalExitOnFailure(hr, "Cannot install a product when a newer version is installed.");
  1567. }
  1568. }
  1569. SetState(PYBA_STATE_PLANNING, hr);
  1570. if (_baFunction) {
  1571. BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "Running plan BA function");
  1572. _baFunction->OnPlan();
  1573. }
  1574. hr = _engine->Plan(action);
  1575. BalExitOnFailure(hr, "Failed to start planning packages.");
  1576. LExit:
  1577. if (FAILED(hr)) {
  1578. SetState(PYBA_STATE_PLANNING, hr);
  1579. }
  1580. return;
  1581. }
  1582. //
  1583. // OnApply - apply the packages.
  1584. //
  1585. void OnApply() {
  1586. HRESULT hr = S_OK;
  1587. SetState(PYBA_STATE_APPLYING, hr);
  1588. SetProgressState(hr);
  1589. SetTaskbarButtonProgress(0);
  1590. hr = _engine->Apply(_hWnd);
  1591. BalExitOnFailure(hr, "Failed to start applying packages.");
  1592. ThemeControlEnable(_theme, ID_PROGRESS_CANCEL_BUTTON, TRUE); // ensure the cancel button is enabled before starting.
  1593. LExit:
  1594. if (FAILED(hr)) {
  1595. SetState(PYBA_STATE_APPLYING, hr);
  1596. }
  1597. return;
  1598. }
  1599. //
  1600. // OnChangeState - change state.
  1601. //
  1602. void OnChangeState(__in PYBA_STATE state) {
  1603. LPWSTR unformattedText = nullptr;
  1604. _state = state;
  1605. // If our install is at the end (success or failure) and we're not showing full UI
  1606. // then exit (prompt for restart if required).
  1607. if ((PYBA_STATE_APPLIED <= _state && BOOTSTRAPPER_DISPLAY_FULL > _command.display)) {
  1608. // If a restart was required but we were not automatically allowed to
  1609. // accept the reboot then do the prompt.
  1610. if (_restartRequired && !_allowRestart) {
  1611. StrAllocFromError(&unformattedText, HRESULT_FROM_WIN32(ERROR_SUCCESS_REBOOT_REQUIRED), nullptr);
  1612. _allowRestart = IDOK == ::MessageBoxW(
  1613. _hWnd,
  1614. unformattedText ? unformattedText : L"The requested operation is successful. Changes will not be effective until the system is rebooted.",
  1615. _theme->sczCaption,
  1616. MB_ICONEXCLAMATION | MB_OKCANCEL
  1617. );
  1618. }
  1619. // Quietly exit.
  1620. ::PostMessageW(_hWnd, WM_CLOSE, 0, 0);
  1621. } else { // try to change the pages.
  1622. DWORD newPageId = 0;
  1623. DeterminePageId(_state, &newPageId);
  1624. if (_visiblePageId != newPageId) {
  1625. ShowPage(newPageId);
  1626. }
  1627. }
  1628. ReleaseStr(unformattedText);
  1629. }
  1630. //
  1631. // Called before showing a page to handle all controls.
  1632. //
  1633. void ProcessPageControls(THEME_PAGE *pPage) {
  1634. if (!pPage) {
  1635. return;
  1636. }
  1637. for (DWORD i = 0; i < pPage->cControlIndices; ++i) {
  1638. THEME_CONTROL* pControl = _theme->rgControls + pPage->rgdwControlIndices[i];
  1639. // If this is a named control, try to set its default state.
  1640. if (pControl->sczName && *pControl->sczName) {
  1641. // If this is a checkable control, try to set its default state
  1642. // to the state of a matching named Burn variable.
  1643. if (IsCheckable(pControl)) {
  1644. LONGLONG llValue = 0;
  1645. HRESULT hr = BalGetNumericVariable(pControl->sczName, &llValue);
  1646. // If the control value isn't set then disable it.
  1647. if (!SUCCEEDED(hr)) {
  1648. ThemeControlEnable(_theme, pControl->wId, FALSE);
  1649. } else {
  1650. ThemeSendControlMessage(
  1651. _theme,
  1652. pControl->wId,
  1653. BM_SETCHECK,
  1654. SUCCEEDED(hr) && llValue ? BST_CHECKED : BST_UNCHECKED,
  1655. 0
  1656. );
  1657. }
  1658. }
  1659. // Hide or disable controls based on the control name with 'State' appended
  1660. LPWSTR controlName = nullptr;
  1661. HRESULT hr = StrAllocFormatted(&controlName, L"%lsState", pControl->sczName);
  1662. if (SUCCEEDED(hr)) {
  1663. LPWSTR controlState = nullptr;
  1664. hr = BalGetStringVariable(controlName, &controlState);
  1665. if (SUCCEEDED(hr) && controlState && *controlState) {
  1666. if (CSTR_EQUAL == ::CompareStringW(LOCALE_NEUTRAL, 0, controlState, -1, L"disable", -1)) {
  1667. BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "Disable control %ls", pControl->sczName);
  1668. ThemeControlEnable(_theme, pControl->wId, FALSE);
  1669. } else if (CSTR_EQUAL == ::CompareStringW(LOCALE_NEUTRAL, 0, controlState, -1, L"hide", -1)) {
  1670. BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "Hide control %ls", pControl->sczName);
  1671. // TODO: This doesn't work
  1672. ThemeShowControl(_theme, pControl->wId, SW_HIDE);
  1673. }
  1674. }
  1675. StrFree(controlState);
  1676. }
  1677. StrFree(controlName);
  1678. }
  1679. // Format the text in each of the new page's controls
  1680. if (pControl->sczText && *pControl->sczText) {
  1681. // If the wix developer is showing a hidden variable
  1682. // in the UI, then obviously they don't care about
  1683. // keeping it safe so don't go down the rabbit hole
  1684. // of making sure that this is securely freed.
  1685. LPWSTR text = nullptr;
  1686. HRESULT hr = BalFormatString(pControl->sczText, &text);
  1687. if (SUCCEEDED(hr)) {
  1688. ThemeSetTextControl(_theme, pControl->wId, text);
  1689. }
  1690. }
  1691. }
  1692. }
  1693. //
  1694. // OnClose - called when the window is trying to be closed.
  1695. //
  1696. BOOL OnClose() {
  1697. BOOL close = FALSE;
  1698. // If we've already succeeded or failed or showing the help page, just close (prompts are annoying if the bootstrapper is done).
  1699. if (PYBA_STATE_APPLIED <= _state || PYBA_STATE_HELP == _state) {
  1700. close = TRUE;
  1701. } else {
  1702. // prompt the user or force the cancel if there is no UI.
  1703. close = PromptCancel(
  1704. _hWnd,
  1705. BOOTSTRAPPER_DISPLAY_FULL != _command.display,
  1706. _confirmCloseMessage ? _confirmCloseMessage : L"Are you sure you want to cancel?",
  1707. _theme->sczCaption
  1708. );
  1709. }
  1710. // If we're doing progress then we never close, we just cancel to let rollback occur.
  1711. if (PYBA_STATE_APPLYING <= _state && PYBA_STATE_APPLIED > _state) {
  1712. // If we canceled disable cancel button since clicking it again is silly.
  1713. if (close) {
  1714. ThemeControlEnable(_theme, ID_PROGRESS_CANCEL_BUTTON, FALSE);
  1715. }
  1716. close = FALSE;
  1717. }
  1718. return close;
  1719. }
  1720. //
  1721. // OnClickCloseButton - close the application.
  1722. //
  1723. void OnClickCloseButton() {
  1724. ::SendMessageW(_hWnd, WM_CLOSE, 0, 0);
  1725. }
  1726. //
  1727. // OnClickLaunchButton - launch the app from the success page.
  1728. //
  1729. void OnClickLaunchButton() {
  1730. HRESULT hr = S_OK;
  1731. LPWSTR sczUnformattedLaunchTarget = nullptr;
  1732. LPWSTR sczLaunchTarget = nullptr;
  1733. LPWSTR sczLaunchTargetElevatedId = nullptr;
  1734. LPWSTR sczUnformattedArguments = nullptr;
  1735. LPWSTR sczArguments = nullptr;
  1736. int nCmdShow = SW_SHOWNORMAL;
  1737. hr = BalGetStringVariable(PYBA_VARIABLE_LAUNCH_TARGET_PATH, &sczUnformattedLaunchTarget);
  1738. BalExitOnFailure1(hr, "Failed to get launch target variable '%ls'.", PYBA_VARIABLE_LAUNCH_TARGET_PATH);
  1739. hr = BalFormatString(sczUnformattedLaunchTarget, &sczLaunchTarget);
  1740. BalExitOnFailure1(hr, "Failed to format launch target variable: %ls", sczUnformattedLaunchTarget);
  1741. if (BalStringVariableExists(PYBA_VARIABLE_LAUNCH_TARGET_ELEVATED_ID)) {
  1742. hr = BalGetStringVariable(PYBA_VARIABLE_LAUNCH_TARGET_ELEVATED_ID, &sczLaunchTargetElevatedId);
  1743. BalExitOnFailure1(hr, "Failed to get launch target elevated id '%ls'.", PYBA_VARIABLE_LAUNCH_TARGET_ELEVATED_ID);
  1744. }
  1745. if (BalStringVariableExists(PYBA_VARIABLE_LAUNCH_ARGUMENTS)) {
  1746. hr = BalGetStringVariable(PYBA_VARIABLE_LAUNCH_ARGUMENTS, &sczUnformattedArguments);
  1747. BalExitOnFailure1(hr, "Failed to get launch arguments '%ls'.", PYBA_VARIABLE_LAUNCH_ARGUMENTS);
  1748. }
  1749. if (BalStringVariableExists(PYBA_VARIABLE_LAUNCH_HIDDEN)) {
  1750. nCmdShow = SW_HIDE;
  1751. }
  1752. if (sczLaunchTargetElevatedId && !_triedToLaunchElevated) {
  1753. _triedToLaunchElevated = TRUE;
  1754. hr = _engine->LaunchApprovedExe(_hWnd, sczLaunchTargetElevatedId, sczUnformattedArguments, 0);
  1755. if (FAILED(hr)) {
  1756. BalLogError(hr, "Failed to launch elevated target: %ls", sczLaunchTargetElevatedId);
  1757. //try with ShelExec next time
  1758. OnClickLaunchButton();
  1759. }
  1760. } else {
  1761. if (sczUnformattedArguments) {
  1762. hr = BalFormatString(sczUnformattedArguments, &sczArguments);
  1763. BalExitOnFailure1(hr, "Failed to format launch arguments variable: %ls", sczUnformattedArguments);
  1764. }
  1765. hr = ShelExec(sczLaunchTarget, sczArguments, L"open", nullptr, nCmdShow, _hWnd, nullptr);
  1766. BalExitOnFailure1(hr, "Failed to launch target: %ls", sczLaunchTarget);
  1767. ::PostMessageW(_hWnd, WM_CLOSE, 0, 0);
  1768. }
  1769. LExit:
  1770. StrSecureZeroFreeString(sczArguments);
  1771. ReleaseStr(sczUnformattedArguments);
  1772. ReleaseStr(sczLaunchTargetElevatedId);
  1773. StrSecureZeroFreeString(sczLaunchTarget);
  1774. ReleaseStr(sczUnformattedLaunchTarget);
  1775. return;
  1776. }
  1777. //
  1778. // OnClickRestartButton - allows the restart and closes the app.
  1779. //
  1780. void OnClickRestartButton() {
  1781. AssertSz(_restartRequired, "Restart must be requested to be able to click on the restart button.");
  1782. _allowRestart = TRUE;
  1783. ::SendMessageW(_hWnd, WM_CLOSE, 0, 0);
  1784. return;
  1785. }
  1786. //
  1787. // OnClickLogFileLink - show the log file.
  1788. //
  1789. void OnClickLogFileLink() {
  1790. HRESULT hr = S_OK;
  1791. LPWSTR sczLogFile = nullptr;
  1792. hr = BalGetStringVariable(_bundle.sczLogVariable, &sczLogFile);
  1793. BalExitOnFailure1(hr, "Failed to get log file variable '%ls'.", _bundle.sczLogVariable);
  1794. hr = ShelExec(L"notepad.exe", sczLogFile, L"open", nullptr, SW_SHOWDEFAULT, _hWnd, nullptr);
  1795. BalExitOnFailure1(hr, "Failed to open log file target: %ls", sczLogFile);
  1796. LExit:
  1797. ReleaseStr(sczLogFile);
  1798. return;
  1799. }
  1800. //
  1801. // SetState
  1802. //
  1803. void SetState(__in PYBA_STATE state, __in HRESULT hrStatus) {
  1804. if (FAILED(hrStatus)) {
  1805. _hrFinal = hrStatus;
  1806. }
  1807. if (FAILED(_hrFinal)) {
  1808. state = PYBA_STATE_FAILED;
  1809. }
  1810. if (_state != state) {
  1811. ::PostMessageW(_hWnd, WM_PYBA_CHANGE_STATE, 0, state);
  1812. }
  1813. }
  1814. //
  1815. // GoToPage
  1816. //
  1817. void GoToPage(__in PAGE page) {
  1818. _installPage = page;
  1819. ::PostMessageW(_hWnd, WM_PYBA_CHANGE_STATE, 0, _state);
  1820. }
  1821. void DeterminePageId(__in PYBA_STATE state, __out DWORD* pdwPageId) {
  1822. LONGLONG simple;
  1823. if (BOOTSTRAPPER_DISPLAY_PASSIVE == _command.display) {
  1824. switch (state) {
  1825. case PYBA_STATE_INITIALIZED:
  1826. *pdwPageId = BOOTSTRAPPER_ACTION_HELP == _command.action
  1827. ? _pageIds[PAGE_HELP]
  1828. : _pageIds[PAGE_LOADING];
  1829. break;
  1830. case PYBA_STATE_HELP:
  1831. *pdwPageId = _pageIds[PAGE_HELP];
  1832. break;
  1833. case PYBA_STATE_DETECTING:
  1834. *pdwPageId = _pageIds[PAGE_LOADING]
  1835. ? _pageIds[PAGE_LOADING]
  1836. : _pageIds[PAGE_PROGRESS_PASSIVE]
  1837. ? _pageIds[PAGE_PROGRESS_PASSIVE]
  1838. : _pageIds[PAGE_PROGRESS];
  1839. break;
  1840. case PYBA_STATE_DETECTED: __fallthrough;
  1841. case PYBA_STATE_PLANNING: __fallthrough;
  1842. case PYBA_STATE_PLANNED: __fallthrough;
  1843. case PYBA_STATE_APPLYING: __fallthrough;
  1844. case PYBA_STATE_CACHING: __fallthrough;
  1845. case PYBA_STATE_CACHED: __fallthrough;
  1846. case PYBA_STATE_EXECUTING: __fallthrough;
  1847. case PYBA_STATE_EXECUTED:
  1848. *pdwPageId = _pageIds[PAGE_PROGRESS_PASSIVE]
  1849. ? _pageIds[PAGE_PROGRESS_PASSIVE]
  1850. : _pageIds[PAGE_PROGRESS];
  1851. break;
  1852. default:
  1853. *pdwPageId = 0;
  1854. break;
  1855. }
  1856. } else if (BOOTSTRAPPER_DISPLAY_FULL == _command.display) {
  1857. switch (state) {
  1858. case PYBA_STATE_INITIALIZING:
  1859. *pdwPageId = 0;
  1860. break;
  1861. case PYBA_STATE_INITIALIZED:
  1862. *pdwPageId = BOOTSTRAPPER_ACTION_HELP == _command.action
  1863. ? _pageIds[PAGE_HELP]
  1864. : _pageIds[PAGE_LOADING];
  1865. break;
  1866. case PYBA_STATE_HELP:
  1867. *pdwPageId = _pageIds[PAGE_HELP];
  1868. break;
  1869. case PYBA_STATE_DETECTING:
  1870. *pdwPageId = _pageIds[PAGE_LOADING];
  1871. break;
  1872. case PYBA_STATE_DETECTED:
  1873. if (_installPage == PAGE_LOADING) {
  1874. switch (_command.action) {
  1875. case BOOTSTRAPPER_ACTION_INSTALL:
  1876. if (SUCCEEDED(BalGetNumericVariable(L"SimpleInstall", &simple)) && simple) {
  1877. _installPage = PAGE_SIMPLE_INSTALL;
  1878. } else {
  1879. _installPage = PAGE_INSTALL;
  1880. }
  1881. break;
  1882. case BOOTSTRAPPER_ACTION_MODIFY: __fallthrough;
  1883. case BOOTSTRAPPER_ACTION_REPAIR: __fallthrough;
  1884. case BOOTSTRAPPER_ACTION_UNINSTALL:
  1885. _installPage = PAGE_MODIFY;
  1886. break;
  1887. }
  1888. }
  1889. *pdwPageId = _pageIds[_installPage];
  1890. break;
  1891. case PYBA_STATE_PLANNING: __fallthrough;
  1892. case PYBA_STATE_PLANNED: __fallthrough;
  1893. case PYBA_STATE_APPLYING: __fallthrough;
  1894. case PYBA_STATE_CACHING: __fallthrough;
  1895. case PYBA_STATE_CACHED: __fallthrough;
  1896. case PYBA_STATE_EXECUTING: __fallthrough;
  1897. case PYBA_STATE_EXECUTED:
  1898. *pdwPageId = _pageIds[PAGE_PROGRESS];
  1899. break;
  1900. case PYBA_STATE_APPLIED:
  1901. *pdwPageId = _pageIds[PAGE_SUCCESS];
  1902. break;
  1903. case PYBA_STATE_FAILED:
  1904. *pdwPageId = _pageIds[PAGE_FAILURE];
  1905. break;
  1906. }
  1907. }
  1908. }
  1909. BOOL IsCrtInstalled() {
  1910. if (_crtInstalledToken > 0) {
  1911. return TRUE;
  1912. } else if (_crtInstalledToken == 0) {
  1913. return FALSE;
  1914. }
  1915. // Check whether at least CRT v10.0.9920.0 is available.
  1916. // It should only be installed as a Windows Update package, which means
  1917. // we don't need to worry about 32-bit/64-bit.
  1918. // However, since the WU package does not include vcruntime140.dll, we
  1919. // still install that ourselves.
  1920. LPCWSTR crtFile = L"api-ms-win-crt-runtime-l1-1-0.dll";
  1921. DWORD cbVer = GetFileVersionInfoSizeW(crtFile, nullptr);
  1922. if (!cbVer) {
  1923. _crtInstalledToken = 0;
  1924. return FALSE;
  1925. }
  1926. void *pData = malloc(cbVer);
  1927. if (!pData) {
  1928. _crtInstalledToken = 0;
  1929. return FALSE;
  1930. }
  1931. if (!GetFileVersionInfoW(crtFile, 0, cbVer, pData)) {
  1932. free(pData);
  1933. _crtInstalledToken = 0;
  1934. return FALSE;
  1935. }
  1936. VS_FIXEDFILEINFO *ffi;
  1937. UINT cb;
  1938. BOOL result = FALSE;
  1939. if (VerQueryValueW(pData, L"\\", (LPVOID*)&ffi, &cb) &&
  1940. ffi->dwFileVersionMS == 0x000A0000 && ffi->dwFileVersionLS >= 0x26C00000) {
  1941. result = TRUE;
  1942. }
  1943. free(pData);
  1944. _crtInstalledToken = result ? 1 : 0;
  1945. return result;
  1946. }
  1947. BOOL QueryElevateForCrtInstall() {
  1948. // Called to prompt the user that even though they think they won't need
  1949. // to elevate, they actually will because of the CRT install.
  1950. if (IsCrtInstalled()) {
  1951. // CRT is already installed - no need to prompt
  1952. return TRUE;
  1953. }
  1954. LONGLONG elevated;
  1955. HRESULT hr = BalGetNumericVariable(L"WixBundleElevated", &elevated);
  1956. if (SUCCEEDED(hr) && elevated) {
  1957. // Already elevated - no need to prompt
  1958. return TRUE;
  1959. }
  1960. LOC_STRING *locStr;
  1961. hr = LocGetString(_wixLoc, L"#(loc.ElevateForCRTInstall)", &locStr);
  1962. if (FAILED(hr)) {
  1963. BalLogError(hr, "Failed to get ElevateForCRTInstall string");
  1964. return FALSE;
  1965. }
  1966. return ::MessageBoxW(_hWnd, locStr->wzText, _theme->sczCaption, MB_YESNO) != IDNO;
  1967. }
  1968. HRESULT EvaluateConditions() {
  1969. HRESULT hr = S_OK;
  1970. BOOL result = FALSE;
  1971. for (DWORD i = 0; i < _conditions.cConditions; ++i) {
  1972. BAL_CONDITION* pCondition = _conditions.rgConditions + i;
  1973. hr = BalConditionEvaluate(pCondition, _engine, &result, &_failedMessage);
  1974. BalExitOnFailure(hr, "Failed to evaluate condition.");
  1975. if (!result) {
  1976. // Hope they didn't have hidden variables in their message, because it's going in the log in plaintext.
  1977. BalLog(BOOTSTRAPPER_LOG_LEVEL_ERROR, "%ls", _failedMessage);
  1978. hr = E_WIXSTDBA_CONDITION_FAILED;
  1979. // todo: remove in WiX v4, in case people are relying on v3.x logging behavior
  1980. BalExitOnFailure1(hr, "Bundle condition evaluated to false: %ls", pCondition->sczCondition);
  1981. }
  1982. }
  1983. ReleaseNullStrSecure(_failedMessage);
  1984. LExit:
  1985. return hr;
  1986. }
  1987. void SetTaskbarButtonProgress(__in DWORD dwOverallPercentage) {
  1988. HRESULT hr = S_OK;
  1989. if (_taskbarButtonOK) {
  1990. hr = _taskbarList->SetProgressValue(_hWnd, dwOverallPercentage, 100UL);
  1991. BalExitOnFailure1(hr, "Failed to set taskbar button progress to: %d%%.", dwOverallPercentage);
  1992. }
  1993. LExit:
  1994. return;
  1995. }
  1996. void SetTaskbarButtonState(__in TBPFLAG tbpFlags) {
  1997. HRESULT hr = S_OK;
  1998. if (_taskbarButtonOK) {
  1999. hr = _taskbarList->SetProgressState(_hWnd, tbpFlags);
  2000. BalExitOnFailure1(hr, "Failed to set taskbar button state.", tbpFlags);
  2001. }
  2002. LExit:
  2003. return;
  2004. }
  2005. void SetProgressState(__in HRESULT hrStatus) {
  2006. TBPFLAG flag = TBPF_NORMAL;
  2007. if (IsCanceled() || HRESULT_FROM_WIN32(ERROR_INSTALL_USEREXIT) == hrStatus) {
  2008. flag = TBPF_PAUSED;
  2009. } else if (IsRollingBack() || FAILED(hrStatus)) {
  2010. flag = TBPF_ERROR;
  2011. }
  2012. SetTaskbarButtonState(flag);
  2013. }
  2014. HRESULT LoadBootstrapperBAFunctions() {
  2015. HRESULT hr = S_OK;
  2016. LPWSTR sczBafPath = nullptr;
  2017. hr = PathRelativeToModule(&sczBafPath, L"bafunctions.dll", _hModule);
  2018. BalExitOnFailure(hr, "Failed to get path to BA function DLL.");
  2019. #ifdef DEBUG
  2020. BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "PYBA: LoadBootstrapperBAFunctions() - BA function DLL %ls", sczBafPath);
  2021. #endif
  2022. _hBAFModule = ::LoadLibraryW(sczBafPath);
  2023. if (_hBAFModule) {
  2024. auto pfnBAFunctionCreate = reinterpret_cast<PFN_BOOTSTRAPPER_BA_FUNCTION_CREATE>(::GetProcAddress(_hBAFModule, "CreateBootstrapperBAFunction"));
  2025. BalExitOnNullWithLastError1(pfnBAFunctionCreate, hr, "Failed to get CreateBootstrapperBAFunction entry-point from: %ls", sczBafPath);
  2026. hr = pfnBAFunctionCreate(_engine, _hBAFModule, &_baFunction);
  2027. BalExitOnFailure(hr, "Failed to create BA function.");
  2028. }
  2029. #ifdef DEBUG
  2030. else {
  2031. BalLogError(HRESULT_FROM_WIN32(::GetLastError()), "PYBA: LoadBootstrapperBAFunctions() - Failed to load DLL %ls", sczBafPath);
  2032. }
  2033. #endif
  2034. LExit:
  2035. if (_hBAFModule && !_baFunction) {
  2036. ::FreeLibrary(_hBAFModule);
  2037. _hBAFModule = nullptr;
  2038. }
  2039. ReleaseStr(sczBafPath);
  2040. return hr;
  2041. }
  2042. BOOL IsCheckable(THEME_CONTROL* pControl) {
  2043. if (!pControl->sczName || !pControl->sczName[0]) {
  2044. return FALSE;
  2045. }
  2046. if (pControl->type == THEME_CONTROL_TYPE_CHECKBOX) {
  2047. return TRUE;
  2048. }
  2049. if (pControl->type == THEME_CONTROL_TYPE_BUTTON) {
  2050. if ((pControl->dwStyle & BS_TYPEMASK) == BS_AUTORADIOBUTTON) {
  2051. return TRUE;
  2052. }
  2053. }
  2054. return FALSE;
  2055. }
  2056. void SavePageSettings() {
  2057. DWORD pageId = 0;
  2058. THEME_PAGE* pPage = nullptr;
  2059. DeterminePageId(_state, &pageId);
  2060. pPage = ThemeGetPage(_theme, pageId);
  2061. if (!pPage) {
  2062. return;
  2063. }
  2064. for (DWORD i = 0; i < pPage->cControlIndices; ++i) {
  2065. // Loop through all the checkable controls and set a Burn variable
  2066. // with that name to true or false.
  2067. THEME_CONTROL* pControl = _theme->rgControls + pPage->rgdwControlIndices[i];
  2068. if (IsCheckable(pControl) && ThemeControlEnabled(_theme, pControl->wId)) {
  2069. BOOL checked = ThemeIsControlChecked(_theme, pControl->wId);
  2070. _engine->SetVariableNumeric(pControl->sczName, checked ? 1 : 0);
  2071. }
  2072. // Loop through all the editbox controls with names and set a
  2073. // Burn variable with that name to the contents.
  2074. if (THEME_CONTROL_TYPE_EDITBOX == pControl->type && pControl->sczName && *pControl->sczName) {
  2075. LPWSTR sczValue = nullptr;
  2076. ThemeGetTextControl(_theme, pControl->wId, &sczValue);
  2077. _engine->SetVariableString(pControl->sczName, sczValue);
  2078. }
  2079. }
  2080. }
  2081. public:
  2082. //
  2083. // Constructor - initialize member variables.
  2084. //
  2085. PythonBootstrapperApplication(
  2086. __in HMODULE hModule,
  2087. __in BOOL fPrereq,
  2088. __in HRESULT hrHostInitialization,
  2089. __in IBootstrapperEngine* pEngine,
  2090. __in const BOOTSTRAPPER_COMMAND* pCommand
  2091. ) : CBalBaseBootstrapperApplication(pEngine, pCommand, 3, 3000) {
  2092. _hModule = hModule;
  2093. memcpy_s(&_command, sizeof(_command), pCommand, sizeof(BOOTSTRAPPER_COMMAND));
  2094. LONGLONG llInstalled = 0;
  2095. HRESULT hr = BalGetNumericVariable(L"WixBundleInstalled", &llInstalled);
  2096. if (SUCCEEDED(hr) && BOOTSTRAPPER_RESUME_TYPE_REBOOT != _command.resumeType && 0 < llInstalled && BOOTSTRAPPER_ACTION_INSTALL == _command.action) {
  2097. _command.action = BOOTSTRAPPER_ACTION_MODIFY;
  2098. } else if (0 == llInstalled && (BOOTSTRAPPER_ACTION_MODIFY == _command.action || BOOTSTRAPPER_ACTION_REPAIR == _command.action)) {
  2099. _command.action = BOOTSTRAPPER_ACTION_INSTALL;
  2100. }
  2101. _plannedAction = BOOTSTRAPPER_ACTION_UNKNOWN;
  2102. // When resuming from restart doing some install-like operation, try to find the package that forced the
  2103. // restart. We'll use this information during planning.
  2104. _nextPackageAfterRestart = nullptr;
  2105. if (BOOTSTRAPPER_RESUME_TYPE_REBOOT == _command.resumeType && BOOTSTRAPPER_ACTION_UNINSTALL < _command.action) {
  2106. // Ensure the forced restart package variable is null when it is an empty string.
  2107. HRESULT hr = BalGetStringVariable(L"WixBundleForcedRestartPackage", &_nextPackageAfterRestart);
  2108. if (FAILED(hr) || !_nextPackageAfterRestart || !*_nextPackageAfterRestart) {
  2109. ReleaseNullStr(_nextPackageAfterRestart);
  2110. }
  2111. }
  2112. _crtInstalledToken = -1;
  2113. pEngine->SetVariableNumeric(L"CRTInstalled", IsCrtInstalled() ? 1 : 0);
  2114. _wixLoc = nullptr;
  2115. memset(&_bundle, 0, sizeof(_bundle));
  2116. memset(&_conditions, 0, sizeof(_conditions));
  2117. _confirmCloseMessage = nullptr;
  2118. _failedMessage = nullptr;
  2119. _language = nullptr;
  2120. _theme = nullptr;
  2121. memset(_pageIds, 0, sizeof(_pageIds));
  2122. _hUiThread = nullptr;
  2123. _registered = FALSE;
  2124. _hWnd = nullptr;
  2125. _state = PYBA_STATE_INITIALIZING;
  2126. _visiblePageId = 0;
  2127. _installPage = PAGE_LOADING;
  2128. _hrFinal = hrHostInitialization;
  2129. _downgrading = FALSE;
  2130. _restartResult = BOOTSTRAPPER_APPLY_RESTART_NONE;
  2131. _restartRequired = FALSE;
  2132. _allowRestart = FALSE;
  2133. _suppressDowngradeFailure = FALSE;
  2134. _suppressRepair = FALSE;
  2135. _modifying = FALSE;
  2136. _overridableVariables = nullptr;
  2137. _taskbarList = nullptr;
  2138. _taskbarButtonCreatedMessage = UINT_MAX;
  2139. _taskbarButtonOK = FALSE;
  2140. _showingInternalUIThisPackage = FALSE;
  2141. _triedToLaunchElevated = FALSE;
  2142. _suppressPaint = FALSE;
  2143. pEngine->AddRef();
  2144. _engine = pEngine;
  2145. _hBAFModule = nullptr;
  2146. _baFunction = nullptr;
  2147. }
  2148. //
  2149. // Destructor - release member variables.
  2150. //
  2151. ~PythonBootstrapperApplication() {
  2152. AssertSz(!::IsWindow(_hWnd), "Window should have been destroyed before destructor.");
  2153. AssertSz(!_theme, "Theme should have been released before destructor.");
  2154. ReleaseObject(_taskbarList);
  2155. ReleaseDict(_overridableVariables);
  2156. ReleaseStr(_failedMessage);
  2157. ReleaseStr(_confirmCloseMessage);
  2158. BalConditionsUninitialize(&_conditions);
  2159. BalInfoUninitialize(&_bundle);
  2160. LocFree(_wixLoc);
  2161. ReleaseStr(_language);
  2162. ReleaseStr(_nextPackageAfterRestart);
  2163. ReleaseNullObject(_engine);
  2164. if (_hBAFModule) {
  2165. ::FreeLibrary(_hBAFModule);
  2166. _hBAFModule = nullptr;
  2167. }
  2168. }
  2169. private:
  2170. HMODULE _hModule;
  2171. BOOTSTRAPPER_COMMAND _command;
  2172. IBootstrapperEngine* _engine;
  2173. BOOTSTRAPPER_ACTION _plannedAction;
  2174. LPWSTR _nextPackageAfterRestart;
  2175. WIX_LOCALIZATION* _wixLoc;
  2176. BAL_INFO_BUNDLE _bundle;
  2177. BAL_CONDITIONS _conditions;
  2178. LPWSTR _failedMessage;
  2179. LPWSTR _confirmCloseMessage;
  2180. LPWSTR _language;
  2181. THEME* _theme;
  2182. DWORD _pageIds[countof(PAGE_NAMES)];
  2183. HANDLE _hUiThread;
  2184. BOOL _registered;
  2185. HWND _hWnd;
  2186. PYBA_STATE _state;
  2187. HRESULT _hrFinal;
  2188. DWORD _visiblePageId;
  2189. PAGE _installPage;
  2190. BOOL _startedExecution;
  2191. DWORD _calculatedCacheProgress;
  2192. DWORD _calculatedExecuteProgress;
  2193. BOOL _downgrading;
  2194. BOOTSTRAPPER_APPLY_RESTART _restartResult;
  2195. BOOL _restartRequired;
  2196. BOOL _allowRestart;
  2197. BOOL _suppressDowngradeFailure;
  2198. BOOL _suppressRepair;
  2199. BOOL _modifying;
  2200. int _crtInstalledToken;
  2201. STRINGDICT_HANDLE _overridableVariables;
  2202. ITaskbarList3* _taskbarList;
  2203. UINT _taskbarButtonCreatedMessage;
  2204. BOOL _taskbarButtonOK;
  2205. BOOL _showingInternalUIThisPackage;
  2206. BOOL _triedToLaunchElevated;
  2207. BOOL _suppressPaint;
  2208. HMODULE _hBAFModule;
  2209. IBootstrapperBAFunction* _baFunction;
  2210. };
  2211. //
  2212. // CreateBootstrapperApplication - creates a new IBootstrapperApplication object.
  2213. //
  2214. HRESULT CreateBootstrapperApplication(
  2215. __in HMODULE hModule,
  2216. __in BOOL fPrereq,
  2217. __in HRESULT hrHostInitialization,
  2218. __in IBootstrapperEngine* pEngine,
  2219. __in const BOOTSTRAPPER_COMMAND* pCommand,
  2220. __out IBootstrapperApplication** ppApplication
  2221. ) {
  2222. HRESULT hr = S_OK;
  2223. if (fPrereq) {
  2224. hr = E_INVALIDARG;
  2225. ExitWithLastError(hr, "Failed to create UI thread.");
  2226. }
  2227. PythonBootstrapperApplication* pApplication = nullptr;
  2228. pApplication = new PythonBootstrapperApplication(hModule, fPrereq, hrHostInitialization, pEngine, pCommand);
  2229. ExitOnNull(pApplication, hr, E_OUTOFMEMORY, "Failed to create new standard bootstrapper application object.");
  2230. *ppApplication = pApplication;
  2231. pApplication = nullptr;
  2232. LExit:
  2233. ReleaseObject(pApplication);
  2234. return hr;
  2235. }