Files
PowerToys/tools/BugReportTool/BugReportTool/Main.cpp

404 lines
10 KiB
C++
Raw Normal View History

#include <filesystem>
#include <fstream>
#include <string>
#include <vector>
#include <Shlobj.h>
#include <winrt/Windows.Data.Json.h>
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.System.UserProfile.h>
#include <winrt/Windows.Globalization.h>
#include "ZipTools/ZipFolder.h"
#include <common/SettingsAPI/settings_helpers.h>
#include <common/utils/json.h>
#include <common/utils/timeutil.h>
#include <common/utils/exec.h>
#include "Package.h"
#include "ReportMonitorInfo.h"
#include "RegistryUtils.h"
#include "EventViewer.h"
#include "InstallationFolder.h"
2022-10-26 14:02:31 +01:00
#include "ReportGPOValues.h"
using namespace std;
using namespace std::filesystem;
using namespace winrt::Windows::Data::Json;
map<wstring, vector<wstring>> escapeInfo = {
{ L"FancyZones\\app-zone-history.json", { L"app-zone-history/app-path" } },
{ L"FancyZones\\settings.json", { L"properties/fancyzones_excluded_apps" } },
{ L"MouseWithoutBorders\\settings.json", { L"properties/SecurityKey" } }, // avoid leaking connection key
[KBM]Launch apps / URI with keyboard shortcuts, support chords (#30121) * Working UI update with just runProgram Path and isRunProgram * First working, basic. no args or path, or setting change detections. * Revert and fixed. * Some clean up, working with config file monitor * Args and Start-in should be working. * File monitor, quotes, xaml screens one * Fixed enable/disable toogle from XAML * Code cleanup. * Betting logging. * Cleanup, start of RunProgramDescriptor and usage of run_non_elevated/run_elevated * Code moved to KeyboardEventHandlers, but not enabled since it won't build as is, needs elevation.h. Other testing.. * Key chords working, pretty much * Added gui for elevation level, need to refresh on change... * f: include shellapi.h and reference wil in KBMEL * run_elevated/run_non_elevated sorted out. Working! * Removed lots of old temp code. * Fix some speling errors. * Cleanup before trying to add a UI for the chord * Added "DifferentUser" option * Closer on UI for chords. * Better UI, lots working. * Clean up * Text for “Allow chords” – needs to look better… * Bugs and clean-up * Cleanup * Refactor and clean up. * More clean up * Some localization. * Don’t show “Allow chords“ to the “to” shortcut * Maybe better foreground after opening new app * Better chord matching. * Runprogram fix for stealing existing shortcut. * Better runProgram stuff * Temp commit * Working well * Toast test * More toast * Added File and Folder picker UI * Pre-check on run program file exists. * Refactor to SetupRunProgramControls * Open URI UI is going. * Open URI working well * Open URI stuff working well * Allowed AppSpecific shortcut and fixed backup/restore shortcut dups * Fixed settings screen * Start of code to find by name... * UI fixed * Small fixes * Some single edit code working. * UI getting better. * Fixes * Fixed and merge from main * UI updates * UI updates. * UI stuff * Fixed crash from move ui item locations. * Fixed crash from move ui item locations. * Added delete confirm * Basic sound working. * Localized some stuff * Added sounds * Better experiance when shortcut is in use. * UI tweaks * Fixed KBM ui for unicode shortcut not having "," * Some clean up * Cleanup * Cleanup * Fixed applyXamlStyling * Added back stuff lost in merge * applyXamlStyling, again * Fixed crash on change from non shortcut to shortcut * Update src/modules/keyboardmanager/KeyboardManagerEngineTest/KeyboardManagerEngineTest.vcxproj * Fixed some spelling type issues. * ImplementationLibrary 231216 * Comment bump to see if the Microsoft.Windows.ImplementationLibrary version thing gets picked up * Correct, Microsoft.Windows.ImplementationLibrary, finally? * Fixed two test that failed because we now allow key-chords. * Removed shortcut sounds. * use original behavior when "allow chords" is off in shortcut window * fix crash when editing a shortcut that has apps specified for it * split KBM chords with comma on dashboard page * Fix some spelling items. * More "spelling" * Fix XAML styling * align TextBlock and ToggleSwitch * fix cutoff issue at the top * increase ComboBox width * Added *Unsupported* for backwards compat on config of KBM * fix spellcheck * Fix crash on Remap key screen * Fixed Remap Keys ComboBox width too short. * Removed KBM Single Edit mode, fixed crash. * Fix Xaml with xaml cops * Fix crash on setting "target app" for some types of shortcuts. * Space to toggle chord, combobox back * fix spellcheck * fix some code nits * Code review updates. * Add exclusions to the bug report tool * Code review and kill CloseAndEndTask * Fix alignment / 3 comboboxes per row * Fix daily telemetry events to exclude start app and open URI * Add chords and remove app start and open uri from config telemetry * comma instead of plus in human readable shortcut telemetry data * Code review, restore default-old state when new row added in KBM * Code review, restore default-old state when new row added in KBM, part 2 * Still show target app on Settings * Only allow enabling chords for origin shortcuts --------- Co-authored-by: Andrey Nekrasov <yuyoyuppe@users.noreply.github.com> Co-authored-by: Jaime Bernardo <jaime@janeasystems.com>
2024-02-27 18:12:05 -05:00
{ L"Keyboard Manager\\default.json", {
L"remapKeysToText",
L"remapShortcutsToText",
L"remapShortcuts/global/runProgramFilePath",
L"remapShortcuts/global/runProgramArgs",
L"remapShortcuts/global/runProgramStartInDir",
L"remapShortcuts/global/openUri",
L"remapShortcuts/appSpecific/runProgramFilePath",
L"remapShortcuts/appSpecific/runProgramArgs",
L"remapShortcuts/appSpecific/runProgramStartInDir",
L"remapShortcuts/appSpecific/openUri",
} }, // avoid leaking personal information from text, URI or application mappings
[New Module] Workspaces (#34324) * spell checker * Adding OOBE Projects page * changed the default hotkey * module interface * rename projects editor * bug report tool * installer * gpo * exit event constant * extend search for projects by search over the containing apps' names * [Projects] fix grammatical issue #43 (1 app - many apps) * [Projects] Editor: Main page: fix layout if there are many apps, launch button not disappearing on the right side * dsc * github * pipeline * guid prefix * [Projects] fixing general settings gpo handling in runner + minor changes * arm build fix * Do not allow saving project if name or applist is empty. Also minor UI changes * version * editor version * spellcheck * editor dll signing * update projects names to filter them out * shortcut saving fix * [Projects] Editor: brining the highlighted app's icon into the foreground. + minor UI fixes * spell checker * spellcheck * [Projects] re-implementing icon size calculation to have similar sized icons for every app. * [projects] Adding info message for cases: there are no projects or no results for the search * [Projects] Adding Edit button to the popup. + minor changes * [Projects] Making popup having rounded corners * changed "no projects" text color and position * remove opening the first proj * fix placing windows of the same app in the project * [Projects] bringing back the breadcrumb on the editor page. Make it clickable. * [Projects] optimizing click handlers * [Projects] Removing not selected apps on save * moved on thread executor to common * moved display utils * added convert rect * unsigned monitor number * set awareness * app placement * [Projects] Re-implementing preview drawing - one common image * [Projects] fix boundary calculation, use DPI aware values * fix launching with command line args * Fix ARM64 CI build * launch packaged apps using names when possible * spell-check * update packaged apps path * projects editor single instance * [Projects] Add Select all checkbox, Delete selected button * Add Checkbox for per monitor selection * modifying highlight in preview * spell checker * logs * exclude help windows https://github.com/JaneaSystems/PowerToys-DevProjects/issues/49 * Add intermediate step to project creation * minor bugfix * mutex fix * modifying highlight for minimized apps * Fixing bug: re-draw the preview on app deletion in the editor * Adding helper class for getting the right bounds for screens * spell checker * spell checker * Minor fixes in the capture dialog * get dpi unaware screen bounds * refactoring: added utils * changed window filter https://github.com/JaneaSystems/PowerToys-DevProjects/issues/2 * clean up * refactoring * projects common lib * localizable default project prefix * launcher resources * clean up * change snapshot project saving https://github.com/JaneaSystems/PowerToys-DevProjects/issues/14 * changed project data https://github.com/JaneaSystems/PowerToys-DevProjects/issues/14 * changed project creation save-cancel handles https://github.com/JaneaSystems/PowerToys-DevProjects/issues/14 * spell-check * Remove checkboxes, delete feature * remove unused from the project * get command line args in the snapshot * minimized settings snap fix * set window property after launching * FZ: ignore projects launched windows * Implementing major new features: remove button, position manipulation, arguments, admin, minimized, maximized * modifying colors * launcher project filters * clean up * Hide Admin checkbox * hide WIP * spell-check * Revert "Hide Admin checkbox" This reverts commit 3036df9d7fe48de6418b0ebeff6422d535cb25e2. * get app elevated property * Implementing Launch and Edit feature * fixing: update of listed projects on the main page after hitting save in editor * Fix for packaged app's icons * fixing scroll speed issue * change scroll speed to 15 * launch elevated apps * minor fixes * minor fix * enhancing shortcut handling * can-launch-elevated check * projects module interface telemetry * Implementing store of setting "order by". * minor string correction * moved projects data parsing * telemetry * add move apps checkbox * notification about elevated apps * restart unelevated * move existing windows * keep opened windows at the same positions * handle powertoys settings * use common theme * fix corrupted data: project id and monitor id * project launch on "launch and edit" * clean up * show screen numbers instead of monitor names * launcher error messages * fix default shortcut * Adding launch button to projects settings, dashboard and flyout * Adding new app which is launched when launching a project. It shows the status of the launch process * spell checker * Renaming Projects to App Layouts. Replacing only string values, not the variable names * Re-ordering modules after Renaming Projects + spell checker * setting window size according to the screen (making it bigger) * commenting out feature "move apps if exist" * spell checker * Add ProjectsLauncherUI to signing * opening apps in minimized state which are placed on a monitor, which is not found at the moment of launching * consistent file name * removed unused sln * telemetry: create event * WindowPosition comparison * telemetry: edit event * fix muted Launch as admin checkbox * telemetry: delete event * updated Edit telemetry event * added invoke point to launcher args * added utils * parse invoke point * replaced tuple with struct * telemetry: launch event * MonitorRect comparison * resources * rename: folders * remove outdated * rename: window property * rename: files and folders * rename: common data structures * rename: telemetry namespace * rename: workspaces data * rename ProjectsLib -> WorkspacesLib * rename: gpo * rename: settings * rename: launcher UI * rename: other * rename: pt run * rename: fz * rename: module interface * rename: icon * rename: snapshot tool * rename: editor * rename: common files * rename: launcher * rename: editor resources * fix empty file crash * rename: json * rename: module interface * fix custom actions build * added launch editor event constant * xaml formatting * Add missing method defition to interop::Constants idl Remove Any CPU config * more .sln cleanup * [Run][PowerToys] Fix Workspaces utility (#34336) polished workspaces utility * build fix - align CppWinRT version * address PR comment: fix isdigit * indentation * address PR comment: rename function * address PR comment: changed version for workspaces and revision * added supported version definition * addressPR comment: use BringToForeground * address PR comments: updated projects * address PR comment: uncomment gpo in settings * address PR comment: rename oobe view * update OOBE image with current module name * moved AppUtils * launching with AppUserModel.ID * fixed module order in settings * fix xaml formatting * [Workspaces] Close launcher if there are failed launches. Plus adding new spinner gif * fix topmost LauncherUI * clean up * UI closing * BugReportTool - omit cmd arg data * Delete icon on workspace removal * Adding cancellation to launcher UI. * reordered launching * fix terminating UI * Removing old shortcut on workspace renaming * Sentence case labels * get process path without waiting * comment out unused * remove unused argument * logs * New icon * fix launch and edit for the new project * fix launch and edit: save new project * Update exe icons --------- Co-authored-by: donlaci <laszlo@janeasystems.com> Co-authored-by: Jaime Bernardo <jaime@janeasystems.com> Co-authored-by: Stefan Markovic <stefan@janeasystems.com> Co-authored-by: Davide Giacometti <davide.giacometti@outlook.it> Co-authored-by: Niels Laute <niels.laute@live.nl>
2024-08-23 09:28:13 +02:00
{ L"Workspaces/workspaces.json", { L"workspaces/applications/command-line-arguments" } },
{ L"AdvancedPaste/settings.json", {
L"properties/custom-actions/value/name",
L"properties/custom-actions/value/prompt"
} },
};
vector<wstring> filesToDelete = {
L"AdvancedPaste\\lastQuery.json",
L"AdvancedPaste\\kernelQueryCache.json",
2020-12-24 17:05:32 +01:00
L"PowerToys Run\\Cache",
L"PowerRename\\replace-mru.json",
L"PowerRename\\search-mru.json",
L"PowerToys Run\\Settings\\UserSelectedRecord.json",
L"PowerToys Run\\Settings\\QueryHistory.json",
L"NewPlus\\Templates",
[General]Add an option for telemetry opt-in and visualization(#34078) * Data diagnostics opt-in * [c++] Drop DROP_PII flag * Bump telemtry package to 2.0.2 * Drop DropPii from custom actions * Cleanup * Do not start manually C# EtwTrace. FZ engine exit event. * ImageResizer, PowerRename, FileLocksmith prev handlers * Revert C# handlers exe logging * Revert "Revert C# handlers exe logging" This reverts commit 4c75a3953b085aeffaefe8e9e20c39cebb899ea1. * Do not recreate EtwTrace * consume package * xaml formatting * Fix deps.json audit * Update telem package paths * Address PR comments * Fix AdvancedPaste close on PT close * Override etl file name for explorer loaded dlls Start/stop tracer when needed for explorer loaded dlls to prevent explorer overload * Fix setting desc * Fix missing events * Add infobar to restart when enable data viewing * Flush on timer every 30s * [Settings] Update View Data diagnostic description text [New+] Add tracer * Show Restart info bar for both enable/disable data viewer * Fix newplus * Fix stuck on restart and terminate AdvPaste exe on destroy() * [Installer] Add tracer * Address PR comment * Add missing tracers * Exclude etw dir from BugReport * Fix bad merge * [Hosts] Proper exit on initial dialog * [OOBE] Make Data diagnostic setting visible without scroll * [OOBE] Add hiperlynk to open general settings * Disable data view on disabling data diagnostics * Don't disable View data button * Fix disabling data viewing * Add missing dot * Revert formatting
2024-10-24 22:04:32 +02:00
L"etw",
};
vector<wstring> GetXpathArray(wstring xpath)
{
vector<wstring> result;
wstring cur = L"";
for (auto ch : xpath)
{
if (ch == L'/')
{
result.push_back(cur);
cur = L"";
continue;
}
cur += ch;
}
if (!cur.empty())
{
result.push_back(cur);
}
return result;
}
void HideByXPath(IJsonValue& val, vector<wstring>& xpathArray, int p)
{
if (val.ValueType() == JsonValueType::Array)
{
for (auto it : val.GetArray())
{
HideByXPath(it, xpathArray, p);
}
return;
}
if (p == xpathArray.size() - 1)
{
if (val.ValueType() == JsonValueType::Object)
{
auto obj = val.GetObjectW();
if (obj.HasKey(xpathArray[p]))
{
auto privateDatavalue = JsonValue::CreateStringValue(L"<private_data>");
obj.SetNamedValue(xpathArray[p], privateDatavalue);
}
}
return;
}
if (val.ValueType() == JsonValueType::Object)
{
IJsonValue newVal;
try
{
newVal = val.GetObjectW().GetNamedValue(xpathArray[p]);
}
catch (...)
{
return;
}
HideByXPath(newVal, xpathArray, p + 1);
}
}
void HideForFile(const path& dir, const wstring& relativePath)
{
path jsonPath = dir;
jsonPath.append(relativePath);
auto jObject = json::from_file(jsonPath.wstring());
if (!jObject.has_value())
{
wprintf(L"Failed to parse file %s\n", jsonPath.c_str());
return;
}
JsonValue jValue = json::value(jObject.value());
for (auto xpath : escapeInfo[relativePath])
{
vector<wstring> xpathArray = GetXpathArray(xpath);
HideByXPath(jValue, xpathArray, 0);
}
json::to_file(jsonPath.wstring(), jObject.value());
}
bool DeleteFolder(wstring path)
{
error_code err;
remove_all(path, err);
if (err.value() != 0)
{
wprintf_s(L"Failed to delete %s. Error code: %d\n", path.c_str(), err.value());
return false;
}
return true;
}
void HideUserPrivateInfo(const filesystem::path& dir)
{
// Replace data in json files
for (auto& it : escapeInfo)
{
HideForFile(dir, it.first);
}
[Auto-update] Auto-update improvements (#11356) * [Updating] Refactor autoupdate mechanism to use Settings window buttons * [Updating] Don't use underscores in update_state (#11029) * [Updating] Rename action_runner to be consisent with accepted format * [Updating] Make UpdateState values explicit * [Setup] Set default bootstrapper log severity to debug * [BugReport] Include all found bootstrapper logs * [Setup] Use capital letter for ActionRunner * [Updating] Simple UI to test UpdateState * [Action Runner] cleanup and coding style * [BugReportTool] fix coding convension * [Auto-update][PT Settings] Updated general page in the Settings (#11227) * [Auto-update][PT Settings] File watcher monitoring UpdateState.json (#11282) * Handle button clicks (#11288) * [Updating] Document ActionRunner cmd flags * [Auto-update][PT Settings] Updated UI (#11335) * [Updating] Do not reset update state when msi cancellation detected * [Updating] Directly launch update_now PT action instead of using custom URI scheme * Checking for updates UI (#11354) * [Updating] Fix cannotDownload state in action runner * [Updating] Reset update state to CannotDownload if action runner encountered an error * [Updating][PT Settings] downloading label, disable button in error state * Changed error message * [Updating rename CannotDownload to ErrorDownloading * [Updating] Add trace logging for Check for updates callback * [Updating][PT Settings] simplify downloading checks * [Updating][PT Settings] Updated text labels * [Updating][PT Settings] Retry to load settings if failed * [Updating][PT Settings] Text fix * [Updating][PT Settings] Installed version links removed * [Updating][PT Settings] Error text updated * [Updating][PT Settings] Show label after version checked * [Updating][PT Settings] Text foreground fix * [Updating][PT Settings] Clean up * [Updating] Do not reset releasePageUrl in case of error/cancellation * [Updating][PT Settings] fixed missing string * [Updating][PT Settings] checked for updates state fix Co-authored-by: yuyoyuppe <a.yuyoyuppe@gmail.com> Co-authored-by: Andrey Nekrasov <yuyoyuppe@users.noreply.github.com> Co-authored-by: Enrico Giordani <enrico.giordani@gmail.com>
2021-05-21 13:32:34 +03:00
// Delete files
for (auto it : filesToDelete)
{
auto path = dir;
path = path.append(it);
DeleteFolder(path);
}
}
void ReportWindowsVersion(const filesystem::path& tmpDir)
{
auto versionReportPath = tmpDir;
versionReportPath = versionReportPath.append("windows-version.txt");
OSVERSIONINFOEXW osInfo{};
try
{
NTSTATUS(WINAPI * RtlGetVersion)
(LPOSVERSIONINFOEXW) = nullptr;
*reinterpret_cast<FARPROC*>(& RtlGetVersion) = GetProcAddress(GetModuleHandleA("ntdll"), "RtlGetVersion");
if (RtlGetVersion)
{
osInfo.dwOSVersionInfoSize = sizeof(osInfo);
RtlGetVersion(&osInfo);
}
}
catch (...)
{
printf("Failed to get windows version info\n");
return;
}
try
{
wofstream versionReport(versionReportPath);
versionReport << "MajorVersion: " << osInfo.dwMajorVersion << endl;
versionReport << "MinorVersion: " << osInfo.dwMinorVersion << endl;
versionReport << "BuildNumber: " << osInfo.dwBuildNumber << endl;
}
catch (...)
{
printf("Failed to write to %s\n", versionReportPath.string().c_str());
}
}
void ReportWindowsSettings(const filesystem::path& tmpDir)
{
std::wstring userLanguage;
std::wstring userLocale;
try
{
const auto lang = winrt::Windows::System::UserProfile::GlobalizationPreferences::Languages().GetAt(0);
userLanguage = winrt::Windows::Globalization::Language{ lang }.DisplayName().c_str();
wchar_t localeName[LOCALE_NAME_MAX_LENGTH]{};
if (!LCIDToLocaleName(GetThreadLocale(), localeName, LOCALE_NAME_MAX_LENGTH, 0))
{
throw -1;
}
userLocale = localeName;
}
catch (...)
{
printf("Failed to get windows settings\n");
return;
}
try
{
wofstream settingsReport(tmpDir / "windows-settings.txt");
settingsReport << "Preferred user language: " << userLanguage << endl;
settingsReport << "User locale: " << userLocale << endl;
}
catch (...)
{
printf("Failed to write windows settings\n");
}
}
void ReportDotNetInstallationInfo(const filesystem::path& tmpDir)
{
auto dotnetInfoPath = tmpDir;
dotnetInfoPath.append("dotnet-installation-info.txt");
try
{
wofstream dotnetReport(dotnetInfoPath);
auto dotnetInfo = exec_and_read_output(LR"(dotnet --list-runtimes)");
if (!dotnetInfo.has_value())
{
printf("Failed to get dotnet installation information\n");
return;
}
dotnetReport << dotnetInfo.value().c_str();
}
catch (...)
{
printf("Failed to report dotnet installation information");
}
}
void ReportInstallerLogs(const filesystem::path& tmpDir, const filesystem::path& reportDir)
{
const char* bootstrapperLogFilePrefix = "powertoys-bootstrapper-msi-";
const char* PTLogFilePrefix = "PowerToysMSIInstaller_";
for (auto& entry : directory_iterator{ tmpDir })
{
std::error_code ec;
if (entry.is_directory(ec) || !entry.path().has_filename())
{
continue;
}
const auto fileName = entry.path().filename().string();
if (!fileName.starts_with(bootstrapperLogFilePrefix) && !fileName.starts_with(PTLogFilePrefix))
{
continue;
}
copy(entry.path(), reportDir / fileName, ec);
}
}
int wmain(int argc, wchar_t* argv[], wchar_t*)
{
// Get path to save zip
wstring saveZipPath;
if (argc > 1)
{
saveZipPath = argv[1];
}
else
{
wchar_t buffer[MAX_PATH];
if (SHGetSpecialFolderPath(HWND_DESKTOP, buffer, CSIDL_DESKTOP, FALSE))
{
saveZipPath = buffer;
}
else
{
printf("Failed to retrieve the desktop path. Error code: %d\n", GetLastError());
return 1;
}
}
auto settingsRootPath = PTSettingsHelper::get_root_save_folder_location();
settingsRootPath += L"\\";
auto localLowPath = PTSettingsHelper::get_local_low_folder_location();
localLowPath += L"\\logs\\";
const auto tempDir = temp_directory_path();
auto reportDir = temp_directory_path() / "PowerToys\\";
if (!DeleteFolder(reportDir))
{
printf("Failed to delete temp folder\n");
}
try
{
copy(settingsRootPath, reportDir, copy_options::recursive);
// Remove updates folder contents
DeleteFolder(reportDir / "Updates");
}
catch (...)
{
printf("Failed to copy PowerToys folder\n");
return 1;
}
try
{
copy(localLowPath, reportDir, copy_options::recursive);
}
catch (...)
{
printf("Failed to copy logs saved in LocalLow\n");
}
#ifndef _DEBUG
InstallationFolder::ReportStructure(reportDir);
#endif
// Hide sensitive information
HideUserPrivateInfo(reportDir);
// Write windows settings to the temporary folder
ReportWindowsSettings(reportDir);
// Write monitors info to the temporary folder
ReportMonitorInfo(reportDir);
// Write windows version info to the temporary folder
ReportWindowsVersion(reportDir);
// Write dotnet installation info to the temporary folder
ReportDotNetInstallationInfo(reportDir);
// Write registry to the temporary folder
ReportRegistry(reportDir);
2022-10-26 14:02:31 +01:00
// Write gpo policies to the temporary folder
ReportGPOValues(reportDir);
// Write compatibility tab info to the temporary folder
ReportCompatibilityTab(reportDir);
// Write event viewer logs info to the temporary folder
EventViewer::ReportEventViewerInfo(reportDir);
ReportInstallerLogs(tempDir, reportDir);
ReportInstalledContextMenuPackages(reportDir);
// Zip folder
auto zipPath = path::path(saveZipPath);
try
{
ZipFolder(zipPath, reportDir);
}
catch (...)
{
printf("Failed to zip folder\n");
return 1;
}
DeleteFolder(reportDir);
return 0;
}