[DevDocs] More content and restructure (#40165)
Some checks failed
Spell checking / Check Spelling (push) Has been cancelled
Spell checking / Report (Push) (push) Has been cancelled
Spell checking / Report (PR) (push) Has been cancelled
Spell checking / Update PR (push) Has been cancelled

## Summary of the Pull Request
Accumulated information from internal transition about the modules
development, and reworked it to be added in dev docs. Also the dev docs
intself was restructured to be more organized. New pages was
verified by transition team.

## PR Checklist
- [x] **Dev docs:** Added/updated

---------

Co-authored-by: Zhaopeng Wang (from Dev Box) <zhaopengwang@microsoft.com>
Co-authored-by: Hao Liu <liuhao3418@gmail.com>
Co-authored-by: Peiyao Zhao <105847726+zhaopy536@users.noreply.github.com>
Co-authored-by: Mengyuan <162882040+chenmy77@users.noreply.github.com>
Co-authored-by: zhaopeng wang <33367956+wang563681252@users.noreply.github.com>
Co-authored-by: Jaylyn Barbee <51131738+Jaylyn-Barbee@users.noreply.github.com>
This commit is contained in:
Gleb Khmyznikov
2025-07-01 14:27:34 +02:00
committed by GitHub
parent 9c2e83d6eb
commit 725535b760
102 changed files with 5361 additions and 325 deletions

View File

@@ -0,0 +1,98 @@
# Debugging PowerToys
This document covers techniques and tools for debugging PowerToys.
## Pre-Debugging Setup
Before you can start debugging PowerToys, you need to set up your development environment:
1. Fork the repository and clone it to your machine
2. Navigate to the repository root directory
3. Run `git submodule update --init --recursive` to initialize all submodules
4. Change directory to `.config` and run `winget configure .\configuration.vsEnterprise.winget` (pick the configuration file that matches your Visual Studio distribution)
### Optional: Building Outside Visual Studio
You can build the entire solution from the command line, which is sometimes faster than building within Visual Studio:
1. Open Developer Command Prompt for VS 2022
2. Navigate to the repository root directory
3. Run the following command(don't forget to set the correct platform):
```
msbuild -restore -p:RestorePackagesConfig=true -p:Platform=ARM64 -m PowerToys.sln
```
4. This process should complete in approximately 13-14 minutes for a full build
## Debugging Techniques
### Visual Studio Debugging
To debug the PowerToys application in Visual Studio, set the `runner` project as your start-up project, then start the debugger.
Some PowerToys modules must be run with the highest permission level if the current user is a member of the Administrators group. The highest permission level is required to be able to perform some actions when an elevated application (e.g. Task Manager) is in the foreground or is the target of an action. Without elevated privileges some PowerToys modules will still work but with some limitations:
- The `FancyZones` module will not be able to move an elevated window to a zone.
- The `Shortcut Guide` module will not appear if the foreground window belongs to an elevated application.
Therefore, it is recommended to run Visual Studio with elevated privileges when debugging these scenarios. If you want to avoid running Visual Studio with elevated privileges and don't mind the limitations described above, you can do the following: open the `runner` project properties and navigate to the `Linker -> Manifest File` settings, edit the `UAC Execution Level` property and change it from `highestAvailable (level='highestAvailable')` to `asInvoker (/level='asInvoker').
### Shell Process Debugging Tool
The Shell Process Debugging Tool is a Visual Studio extension that helps debug multiple processes, which is especially useful for PowerToys modules started by the runner.
#### Debugging Setup Process
1. Install ["Debug Child Processes"](https://marketplace.visualstudio.com/items?itemName=vsdbgplat.MicrosoftChildProcessDebuggingPowerTool2022) Visual Studio extension
2. Configure which processes to debug and what debugger to use for each
3. Start PowerToys from Visual Studio
4. The extension will automatically attach to specified child processes when launched
#### Debugging Color Picker Example
1. Set breakpoints in both ColorPicker and its module interface
2. Use Shell Process Debugging to attach to ColorPickerUI.exe
3. Debug .NET and native code together
4. Runner needs to be running to properly test activation
#### Debugging DLL Main/Module Interface
- Breakpoints in DLL code will be hit when loaded by runner
- No special setup needed as DLL is loaded into runner process
#### Debugging Short-Lived Processes
- For processes with short lifetimes (like in Workspaces)
- List all processes explicitly in debugging configuration
- Set correct debugger type (.NET debugger for C# code)
### Finding Registered Events
1. Run WinObj tool from SysInternals as administrator
2. Search for event name
3. Shows handles to the event (typically runner and module)
### Common Debugging Usage Patterns
#### Debugging with Bug Report
1. Check module-specific logs for exceptions/crashes
2. Copy user's settings to your AppData to reproduce their configuration
3. Check Event Viewer XML files if logs don't show crashes
4. Compare installation_folder_structure.txt to detect corrupted installations
5. Check installer logs for installation-related issues
6. Look at Windows version and language settings for patterns across users
#### Installer Debugging
- Can only build installer in Release mode
- Typically debug using logs and message boxes
- Logs located in:
- `%LOCALAPPDATA%\Temp\PowerToys_bootstrapper_*.log` - MSI tool logs
- `%LOCALAPPDATA%\Temp\PowerToys_*.log` - Custom installer logs
- Logs in Bug Reports are useful for troubleshooting installation issues
#### Settings UI Debugging
- Use shell process debugging to connect to newly created processes
- Debug the `PowerToys.Settings.exe` process
- Add breakpoints as needed for troubleshooting
- Logs are stored in the local app directory: `%LOCALAPPDATA%\Microsoft\PowerToys`
- Check Event Viewer for application crashes related to `PowerToys.Settings.exe`
- Crash dumps can be obtained from Event Viewer

View File

@@ -0,0 +1,146 @@
# PowerToys Development Guidelines
## Using Open Source Packages and Libraries
### License Considerations
- MIT license is generally acceptable for inclusion in the project
- For any license other than MIT, double check with the PM team
- All external packages or projects must be mentioned in the `notice.md` file
- Even if a license permits free use, it's better to verify with the team
### Safety and Quality Considerations
- Ensure the code being included is safe to use
- Avoid repositories or packages that are not widely used
- Check for packages with significant downloads/usage and good ratings
- Important because our pipeline signs external DLLs with Microsoft certificate
- Unsafe code signed with Microsoft certificate can cause serious issues
## Code Signing
### Signing JSON File
- Modifications to the signing JSON file are typically done manually
- When adding new DLLs (internal PowerToys modules or external libraries)
- When the release pipeline fails with a list of unsigned DLLs/executables:
- For PowerToys DLLs, manually add them to the list
- For external DLLs, verify they're safe to sign before including
### File Signing Requirements
- All DLLs and executables must be signed
- New files need to be added to the signing configuration
- CI checks if all files are signed
- Even Microsoft-sourced dependencies are signed if they aren't already
## Performance Measurement
- Currently no built-in timers to measure PowerToys startup time
- Startup measurement could be added in the runner:
- At the start of the main method
- After all module interface DLLs are loaded
- Alternative: use profilers or Visual Studio profiler
- Startup currently takes some time due to:
- Approximately 20 module interface DLLs that need to be loaded
- Modules that are started during loading
- No dashboards or dedicated tools for performance measurement
- Uses System.Diagnostics.Stopwatch in code
- Performance data is logged to default PowerToys logs
- Can search logs for stopwatch-related messages to diagnose performance issues
- Some telemetry events contain performance information
## Dependency Management
### WinRT SDK and CS/WinRT
- Updates to WinRT SDK and CS/WinRT are done periodically
- WinRT SDK often requires higher versions of CS/WinRT or vice versa
- Check for new versions in NuGet.org or Visual Studio's NuGet Package Explorer
- Prefer stable versions over preview versions
- Best practice: Update early in the release cycle to catch potential regressions
### WebView2
- Used for components like monotone file preview
- WebView2 version is related to the WebView runtime in Windows
- Previous issues with Windows Update installing new WebView runtime versions
- WebView team now includes PowerToys testing in their release cycle
- When updating WebView2:
- Update the version
- Open a PR
- Perform sanity checks on components that use WebView2
### General Dependency Update Process
- When updating via Visual Studio, it will automatically update dependencies
- After updates, perform:
- Clean build
- Sanity check that all modules still work
- Open PR with changes
## Testing Requirements
### Multiple Computers
- **Mouse Without Borders**: Requires multiple physical computers for proper testing
- Testing with VMs is not recommended as it may cause confusion between host and guest mouse input
- At least 2 computers are needed, sometimes testing with 3 is done
- Testing is usually assigned to team members known to have multiple computers
### Multiple Monitors
- Some utilities require multiple monitors for testing
- At least 2 monitors are recommended
- One monitor should be able to use different DPI settings
### Fuzzing Testing
- Security team requires fuzzing testing for modules that handle file I/O or user input
- Helps identify vulnerabilities and bugs by feeding random, invalid, or unexpected data
- PowerToys integrates with Microsoft's OneFuzz service for automated testing
- Both .NET (C#) and C++ modules have different fuzzing implementation approaches
- New modules handling file I/O or user input should implement fuzzing tests
- For detailed setup instructions, see [Fuzzing Testing in PowerToys](../tools/fuzzingtesting.md)
### Testing Process
- For reporting bugs during the release candidate testing:
1. Discuss in team chat
2. Determine if it's a regression (check if bug exists in previous version)
3. Check if an issue is already open
4. Open a new issue if needed
5. Decide on criticality for the release (if regression)
### Release Testing
- Team follows a release checklist
- Includes testing for WinGet configuration
- Sign-off process:
- Teams sign off on modules independently
- Regressions found in first release candidates lead to PRs
- Second release candidate verified fixes
- Command Palette needs separate sign-off
- Final verification ensures modules don't crash with Command Palette integration
## PR Management and Release Process
### PR Review Process
- PM team typically tags PRs with "need review"
- Small fixes from community that don't change much are usually accepted
- PM team adds tags like "need review" to highlight PRs
- PMs set priorities (sometimes using "info.90" tags)
- PMs decide which PRs to prioritize
- Team members can help get PRs merged when there's flexibility
### PR Approval Requirements
- PRs need approval from code owners before merging
- New team members can approve PRs but final approval comes from code owners
### PR Priority Handling
- Old PRs sometimes "slip through the cracks" if not high priority
- PMs tag important PRs with "priority one" to indicate they should be included in release
- Draft PRs are generally not prioritized
### Specific PR Types
- CI-related PRs need review and code owner approval
- Feature additions (like GPO support) need PM decision on whether the feature is wanted
- Bug fixes related to Watson errors sometimes don't have corresponding issue links
- Command Palette is considered high priority for the upcoming release
## Project Management Notes
- Be careful about not merging incomplete features into main
- Feature branches should be used for work in progress
- PRs touching installer files should be carefully reviewed
- Incomplete features should not be merged into main
- Use feature branches (feature/name-of-feature) for work-in-progress features
- Only merge to main when complete or behind experimentation flags

View File

@@ -0,0 +1,223 @@
# Localization
## Table of Contents
1. [Localization on the pipeline (CDPX)](#localization-on-the-pipeline-cdpx)
1. [UWP Special case](#uwp-special-case)
2. [Enabling localization on a new project](#enabling-localization-on-a-new-project)
1. [C++](#c)
2. [C#](#c-1)
3. [UWP](#uwp)
3. [Lcl Files](#lcl-files)
4. [Possible Issues in localization PRs (LEGO)](#possible-issues-in-localization-prs-lego)
5. [Enabling localized MSI for a new project](#enabling-localized-msi-for-a-new-project)
## Localization on the pipeline (CDPX)
[The localization step](https://github.com/microsoft/PowerToys/blob/86d77103e9c69686c297490acb04775d43ef8b76/.pipelines/pipeline.user.windows.yml#L45-L52) is run on the pipeline before the solution is built. This step runs the [build-localization](https://github.com/microsoft/PowerToys/blob/main/.pipelines/build-localization.cmd) script, which generates resx files for all the projects with localization enabled using the `Localization.XLoc` package.
The [`Localization.XLoc`](https://github.com/microsoft/PowerToys/blob/86d77103e9c69686c297490acb04775d43ef8b76/.pipelines/build-localization.cmd#L24-L25) tool is run on the repo root, and it checks for all occurrences of `LocProject.json`. Each localized project has a `LocProject.json` file in the project root, which contains the location of the English resx file, list of languages for localization, and the output path where the localized resx files are to be copied to. In addition to this, some other parameters can be set, such as whether the language ID should be added as a folder in the file path or in the file name. When the CDPX pipeline is run, the localization team is notified of changes in the English resx files. For each project with localization enabled, a `loc` folder (see [this](https://github.com/microsoft/PowerToys/tree/main/src/modules/launcher/Microsoft.Launcher/loc) for example) is created in the same directory as the `LocProject.json` file. The folder contains language specific folders which in turn have a nested folder path equivalent to `OutputPath` in the `LocProject.json`. Each of these folders contain one `lcl` file. The `lcl` files contain the English resources along with their translation for that language. These are described in more detail in the [Lcl files section](#lcl-files). Once the `.resx` files are generated, they will be used during the `Build PowerToys` step for localized versions of the modules.
Since the localization script requires certain nuget packages, the [`restore-localization`](https://github.com/microsoft/PowerToys/blob/main/.pipelines/restore-localization.cmd) script is run before running `build-localization` to install all the required packages. This script must [run in the `restore` step](https://github.com/microsoft/PowerToys/blob/86d77103e9c69686c297490acb04775d43ef8b76/.pipelines/pipeline.user.windows.yml#L37-L39) of pipeline because [the host is network isolated](https://onebranch.visualstudio.com/Pipeline/_wiki/wikis/Pipeline.wiki/2066/Consuming-Packages-in-a-CDPx-Pipeline?anchor=overview) at the `build` step. The [Toolset package source](https://github.com/microsoft/PowerToys/blob/86d77103e9c69686c297490acb04775d43ef8b76/.pipelines/pipeline.user.windows.yml#L23) is used for this.
The process and variables that can be tweaked on the pipeline are described in more detail on [onebranch (account required) under Localization](https://onebranch.visualstudio.com/Pipeline/_wiki/wikis/Pipeline.wiki/290/Localization).
The localized resource dlls for C# projects are added to the MSI only for build on the pipeline. This is done by checking if the [`IsPipeline` variable is defined](https://github.com/microsoft/PowerToys/blob/f92bd6ffd38014c228544bb8d68d0937ce4c2b6d/installer/PowerToysSetup/Product.wxs#L804-L805), which gets defined before [building the installer on the pipeline](https://github.com/microsoft/PowerToys/blob/f92bd6ffd38014c228544bb8d68d0937ce4c2b6d/.pipelines/build-installer.cmd#L4). This is done because the localized resx files are only present on the pipeline, and not having this check would result in the installer project failing to build locally.
## Enabling localization on a new project
To enable localization on a new project, the first step is to create a file `LocProject.json` in the project root.
For example, for a project in the folder `src\path` where the resx file is present in `resources\Resources.resx`, the LocProject.json file will contain the following:
```
{
"Projects": [
{
"LanguageSet": "Azure_Languages",
"LocItems": [
{
"SourceFile": "src\\path\\resources\\Resources.resx",
"CopyOption": "LangIDOnName",
"OutputPath": "src\\path\\resources"
}
]
}
]
}
```
The rest of the steps depend on the project type and are covered in the sections below. The steps to add the localized files to the MSI can be found in [Enabling localized MSI for a new project](#Enabling-localized-MSI-for-a-new-project).
### C++
C++ projects do not support `resx` files, and instead use `rc` files along with `resource.h` files. The CDPX pipeline however doesn't support localizing `rc` files and the other alternative they support is directly translating the resources from the binary which makes it harder to maintain resources. To avoid this, a custom script has been added which expects a resx file and converts the entries to an rc file with a string table and adds resource declarations to a resource.h file so that the resources can be compiled with the C++ project.
If you already have a .rc file, copy the string table to a separate txt file and run the [convert-stringtable-to-resx.ps1](https://github.com/microsoft/PowerToys/blob/main/tools/build/convert-stringtable-to-resx.ps1) script on it. This script is not very robust to input, and requires the data in a specific format, where `IDS_ResName L"ResourceValue"` and any number of spaces can be present in between. The script converts this file to the format expected by [`resgen`](https://learn.microsoft.com/dotnet/framework/tools/resgen-exe-resource-file-generator#Convert), which will convert it to resx. The resource names are changed from all uppercase to title case, and the `IDS_` prefix is removed. Escape characters might have to be manually replaced, for example .rc files would have escaped double quotes as `""`, so this should be replaced with just `"` before converting to the resx files.
After generating the resx file, rename the existing rc and h files to ProjName.base.rc and resource.base.h. In the rc file remove the string table which is to be localized and in the .h file remove all `#define`s corresponding to localized resources. In the vcxproj of the C++ project, add the following build event:
```
<Target Name="GenerateResourceFiles" BeforeTargets="PrepareForBuild">
<Exec Command="powershell -NonInteractive -executionpolicy Unrestricted $(SolutionDir)tools\build\convert-resx-to-rc.ps1 $(MSBuildThisFileDirectory) resource.base.h resource.h ProjName.base.rc ProjName.rc" />
</Target>
```
This event runs a script which generates a resource.h and ProjName.rc in the `Generated Files` folder using the strings in all the resx files along with the existing information in resource.base.h and ProjName.base.rc. The script is [convert-resx-to-rc.ps1](https://github.com/microsoft/PowerToys/blob/main/tools/build/convert-resx-to-rc.ps1). The script uses [`resgen`](https://learn.microsoft.com/dotnet/framework/tools/resgen-exe-resource-file-generator#Convert) to convert the resx file to a string table expected in the .rc file format. When the resources are added to the rc file the `IDS_` prefix is added and resource names are in upper case (as it was originally). Any occurrences of `"` in the string resource is escaped as `""` to prevent build errors. The string tables are added to the rc file in the following format:
```
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
STRINGTABLE
BEGIN
strings
END
#endif
```
Since there is no API to identify the `AFX_TARG_*`, `LANG_*` or `SUBLANG_*` values from each langId from the pipeline, these are hardcoded in the script (for each language) as done in [lines 50-77 of `convert-resx-to-rc.ps1`](https://github.com/microsoft/PowerToys/blob/f92bd6ffd38014c228544bb8d68d0937ce4c2b6d/tools/build/convert-resx-to-rc.ps1#L50-L77). **If any other languages are added in the future, this script will have to be updated.** In order to determine what are the language codes, you can open the rc file in Resource View, right click the string table and press `Insert Copy` and choose the corresponding language. This autogenerates the required code and can be used to figure out the language codes. The files also add the resource declarations to a resource.h file, starting from 101 by default(this can be changed by an optional argument). Since the output files will be generated in `Generated Files`, any includes in these two files will require an additional `..\` and wherever resource.h is used, it will have to be included as `Generated Files\resource.h`. While adding `resource.base.h` and `ProjName.base.rc` to the vcxproj, these should be modified to not participate in the build to avoid build errors:
```
<None Include="Resources.resx" />
```
Some rc/resource.h files might be used in multiple projects (for example, KBM). To ensure the projects build for these cases, the build event can be added to the entire directory so that the rc files are generated before any project is built. See [Directory.Build.targets](https://github.com/microsoft/PowerToys/blob/main/src/modules/keyboardmanager/Directory.Build.targets) for an example.
Check [this PR](https://github.com/microsoft/PowerToys/pull/6104) for an example for making these changes for a C++ project.
### C#
Since C# projects natively support `resx` files, the only step required here is to include all the resx files in the build. For .NET Core projects this is done automatically and the .csproj does not need to be modified. For other projects, the following line needs to be added:
```
<EmbeddedResource Include="Properties\Resources.*.resx" />
```
**Note:** Building with localized resources may cause a build warning `Referenced assembly 'mscorlib.dll' targets a different processor` which is a VS bug. More details can be found in [PowerToys issue #7269](https://github.com/microsoft/PowerToys/issues/7269).
**Note:** If a project needs to be migrated from XAML resources to resx, the easiest way to convert the resources would be to change to format to `=` separates resources by either manually (by Ctrl+H on a text editor), or by a script, and then running [`resgen`](https://learn.microsoft.com/dotnet/framework/tools/resgen-exe-resource-file-generator#Convert) on `Developer Command Prompt for VS` to convert it to resx format.
```
<system:String x:Key="wox_plugin_calculator_plugin_name">Calculator</system:String>
<system:String x:Key="wox_plugin_calculator_plugin_description">Allows to do mathematical calculations.(Try 5*3-2 in Wox)</system:String>
<system:String x:Key="wox_plugin_calculator_not_a_number">Not a number (NaN)</system:String>
```
to
```
wox_plugin_calculator_plugin_name=Calculator
wox_plugin_calculator_plugin_description=Allows to do mathematical calculations.(Try 5*3-2 in Wox)
wox_plugin_calculator_not_a_number=Not a number (NaN)
```
After adding the resx file to the project along with the resource generator, references to the strings will have to be replaced with `Properties.Resources.resName` rather than the custom APIs. Check [this PR](https://github.com/microsoft/PowerToys/pull/6165) for an example of the changes required.
### UWP
UWP projects expect `resw` files rather than `resx` (the format is almost the same). Unlike other C# projects, the files are expected in the format `fullLangId\Resources.resw`. To include these files in the build, replace the following line in the csproj:
```
<PRIResource Include="Strings\en-us\Resources.resw" />
```
to
```
<PRIResource Include="Strings\*\Resources.resw" />
```
## Lcl Files
Lcl files contain all the resources that are present in the English resx file, along with a translation if it has been added.
For example, an entry for a resource in the lcl file looks like this:
```
<Item ItemId=";EditKeyboard_WindowName" ItemType="0;.resx" PsrId="211" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Remap keys]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Remapper des touches]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
</Item>
```
The `<Tgt>` element would not be present in the initial commits of the lcl files, as only the English version of the string would be present.
**Note:** The CDPX Localization system has a fail-safe check on the lcl files, where if the English string value which is present inside `<Val><![CDATA[*]]></Val>` does not match the value present in the English Resources.resx file then the translated value will not be copied to the localized resx file. This is present so that obsolete translations would not be loaded when the English resource has changed, and the English string will be used rather than the obsolete translation.
## Possible Issues in localization PRs (LEGO)
Since the LEGO PRs update some of the strings in LCL files at a time, there can be multiple PRs which modify the same files, leading to merge conflicts. In most cases this would show up on GitHub as a merge conflict, but sometimes a bad git merge may occur, and the file could end up with incorrect formatting, such as two `<Tgt>` elements for a single resource. These can be fixed by ensuring the elements follow the format described in [this section](#lcl-files). To catch such errors, the build farm should be run for every LEGO PR and if any error occurs in the localization step, we should check the corresponding resx/lcl files for conflicts.
## Enabling localized MSI for a new project
For C++ and UWP projects no additional files are generated with localization that need to be added to the MSI. For C++ projects all the resources are added to the dll/exe, while for UWP projects they are added to the `resources.pri` file (which is present even for an unlocalized project). To verify if the localized resources are added to the `resources.pri` file the following steps can be done:
- Open `Developer Command Prompt for VS`
- After navigating to the folder containing the pri file, run the following command:
makepri.exe dump /if .\resources.pri
- Check the contents of the `resources.pri.xml` file that is generated from the command. The last section of the file will contain the resources with the strings in all the languages:
```
<NamedResource name="GeneralSettings_RunningAsAdminText" uri="ms-resource://f4f787a5-f0ae-47a9-be89-5408b1dd2b47/Resources/GeneralSettings_RunningAsAdminText">
<Candidate qualifiers="Language-FR" type="String">
<Value>Running as administrator</Value>
</Candidate>
<Candidate qualifiers="Language-EN-US" isDefault="true" type="String">
<Value>Running as administrator</Value>
</Candidate>
</NamedResource>
```
For C# projects, satellite dlls are generated when the project is built. For a project named `ProjName`, files are created in the format `langId\ProjName.resources.dll` where `langId` is in the same format as the lcl files. The satellite dlls need to be included with the MSI, but they must be added only if the solution is built from the build farm, as the localized resx files will not be present on local machines (and that could cause local builds of the installer to fail).
This can be done by adding the directory name of the project to [Product.wxs near line 806](https://github.com/microsoft/PowerToys/blob/f92bd6ffd38014c228544bb8d68d0937ce4c2b6d/installer/PowerToysSetup/Product.wxs#L806) and a resource component for the project can be created in [Product.wxs near lines 845-847](https://github.com/microsoft/PowerToys/blob/f92bd6ffd38014c228544bb8d68d0937ce4c2b6d/installer/PowerToysSetup/Product.wxs#L845-L847) in this format:
```
<Component Id="ProjName_$(var.IdSafeLanguage)_Component" Directory="Resource$(var.IdSafeLanguage)ProjNameInstallFolder">
<File Id="ProjName_$(var.IdSafeLanguage)_File" Source="$(var.BinX64Dir)modules\ProjName\$(var.Language)\ProjName.resources.dll" />
</Component>
```
We should also ensure the new dlls are signed by the pipeline. Currently all dlls of the form [`*.resources.dll` are signed](https://github.com/microsoft/PowerToys/blob/f92bd6ffd38014c228544bb8d68d0937ce4c2b6d/.pipelines/pipeline.user.windows.yml#L68).
**Note:** The resource dlls should be added to the MSI project only after the initial commit with the lcl files has been done by the Localization team. Otherwise the pipeline will fail as there wouldn't be any resx files to generate the dlls.
## Working With Strings
In order to support localization **YOU SHOULD NOT** have hardcoded UI display strings in your code. Instead, use resource files to consume strings.
### For CPP
Use [`StringTable` resource][String Table] to store the strings and resource header file(`resource.h`) to store Id's linked to the UI display string. Add the strings with Id's referenced from the header file to the resource-definition script file. You can use [Visual Studio Resource Editor][VS Resource Editor] to create and manage resource files.
- `resource.h`:
XXX must be a unique int in the list (mostly the int ID of the last string id plus one):
```cpp
#define IDS_MODULE_DISPLAYNAME XXX
```
- `StringTable` in resource-definition script file `validmodulename.rc`:
```
STRINGTABLE
BEGIN
IDS_MODULE_DISPLAYNAME L"Module Name"
END
```
- Use the `GET_RESOURCE_STRING(UINT resource_id)` method to consume strings in your code.
```cpp
#include <common.h>
std::wstring GET_RESOURCE_STRING(IDS_MODULE_DISPLAYNAME)
```
### For C#
Use [XML resource file(.resx)][Resx Files] to store the UI display strings and [`Resource Manager`][Resource Manager] to consume those strings in the code. You can use [Visual Studio][Resx Files VS] to create and manage XML resources files.
- `Resources.resx`
```xml
<data name="ValidUIDisplayString" xml:space="preserve">
<value>Description to be displayed on UI.</value>
<comment>This text is displayed when XYZ button clicked.</comment>
</data>
```
- Use [`Resource Manager`][Resource Manager] to consume strings in code.
```csharp
System.Resources.ResourceManager manager = new System.Resources.ResourceManager(baseName, assembly);
string validUIDisplayString = manager.GetString("ValidUIDisplayString", resourceCulture);
```
In case of Visual Studio is used to create the resource file. Simply use the `Resources` class in auto-generated `Resources.Designer.cs` file to access the strings which encapsulate the [`Resource Manager`][Resource Manager] logic.
```csharp
string validUIDisplayString = Resources.ValidUIDisplayString;
```
[VS Resource Editor]: https://learn.microsoft.com/cpp/windows/resource-editors?view=vs-2019
[String Table]: https://learn.microsoft.com/windows/win32/menurc/stringtable-resource
[Resx Files VS]: https://learn.microsoft.com/dotnet/framework/resources/creating-resource-files-for-desktop-apps#resource-files-in-visual-studio
[Resx Files]: https://learn.microsoft.com/dotnet/framework/resources/creating-resource-files-for-desktop-apps#resources-in-resx-files
[Resource Manager]: https://learn.microsoft.com/dotnet/api/system.resources.resourcemanager?view=netframework-4.8

View File

@@ -0,0 +1,147 @@
# Logging and Telemetry in PowerToys
## Logging Types in PowerToys
PowerToys has several types of logging mechanisms:
1. Text file logs (application writes logs to files)
2. Telemetry/diagnostic data (sent to Microsoft servers)
3. Event Viewer logs (used by some utilities like Mouse Without Borders)
4. Watson reports (crash reports sent to Microsoft)
## Log File Locations
### Regular Logs
- Located at: `%LOCALAPPDATA%\Microsoft\PowerToys\Logs`
- Organized by utility and sometimes by version
- Examples: PowerToys Run logs, module interface logs
- C# and C++ components both write logs to these locations
### Low-Privilege Logs
- Some components (like preview handlers and thumbnail providers) are started by Explorer and have low privileges
- These components write logs to: `%USERPROFILE%/AppData/LocalLow/Microsoft/PowerToys`
- Example: Monaco preview handler logs
### Module Logs
- Logs always stored in user's AppData regardless of installation type
- Each module creates its own log
- Even with machine-wide installation, logs are per-user
- Different users can have different logs even with a machine-wide installation
## Log Implementation
### C++ Logging
In C++ projects we use the awesome [spdlog](https://github.com/gabime/spdlog) library for logging as a git submodule under the `deps` directory. To use it in your project, just include [spdlog.props](/deps/spdlog.props) in a .vcxproj like this:
```xml
<Import Project="..\..\..\deps\spdlog.props" />
```
It'll add the required include dirs and link the library binary itself.
- Projects need to include the logging project as a dependency
- Uses a git submodule for the actual logging library
- Logs are initialized in the main file:
```cpp
init_logger();
```
- After initialization, any file can use the logger
- Logger settings contain constants like log file locations
### C# Logging
For C# projects there is a static logger class in Managed Common called `Logger`.
To use it, add a project reference to `ManagedCommon` and add the following line of code to all the files using the logger:
```Csharp
using ManagedCommon;
```
In the `Main` function (or a function with a similar meaning (like `App` in a `App.xaml.cs` file)) you have to call `InitializeLogger` and specify the location where the logs will be saved (always use a path scheme similar to this example):
```Csharp
Logger.InitializeLogger("\\FancyZones\\Editor\\Logs");
```
For a low-privilege process you have to set the optional second parameter to `true`:
```Csharp
Logger.InitializeLogger("\\FileExplorer\\Monaco\\Logs", true);
```
The `Logger` class contains the following logging functions:
```Csharp
// Logs an error that the utility encountered
Logger.LogError(string message);
Logger.LogError(string message, Exception ex);
// Logs an error that isn't that grave
Logger.LogWarning(string message);
// Logs what the app is doing at the moment
Logger.LogInfo(string message);
// Like LogInfo just with infos important for debugging
Logger.LogDebug(string message);
// Logs the current state of the utility.
Logger.LogTrace();
```
## Log File Management
- Currently, most logs are not automatically cleaned up
- Some modules have community contributions to clean old logs, but not universally implemented
- By default, all info-level logs are written
- Debug and trace logs may not be written by default
- Log settings can be found in settings.json, but not all APIs honor these settings
## Telemetry
### Implementation
- Uses Event Tracing for Windows (ETW) for telemetry
- Different from the text file logging system
- Keys required to send telemetry to the right server
- Keys are not stored in the repository
- Obfuscated in public code
- Replaced during the release process
- Stored in private NuGet packages for release builds
### C++ Telemetry
- Managed through trace_base.h which:
- Registers the provider
- Checks if user has disabled diagnostics
- Defines events
- Example from Always On Top:
```cpp
Trace::AlwaysOnTop::Enable(true);
```
### C# Telemetry
- Uses PowerToysTelemetry class
- WriteEvent method sends telemetry
- Projects add a reference to the PowerToys.Telemetry project
- Example:
```csharp
PowerToysTelemetry.Log.WriteEvent(new LauncherShowEvent(hotKey));
```
### User Controls
- Settings page allows users to:
- Turn off/on sending telemetry
- Enable viewing of telemetry data
### Viewing Telemetry Data
- When "Enable viewing" is turned on, PowerToys starts ETW tracing
- Saves ETL files for 28 days
- Located at: `%LOCALAPPDATA%\Microsoft\PowerToys\ETL` (for most utilities)
- Low-privilege components save to a different location
- Button in settings converts ETL to XML for user readability
- XML format chosen to follow approved compliance pattern from Windows Subsystem for Android
- Files older than 28 days are automatically deleted
## Bug Report Tool
The [BugReportTool](/tools/BugReportTool) can be triggered via:
- Right-click on PowerToys tray icon → Report Bug
- Left-click on tray icon → Open Settings → Bug Report Tool
It creates a zip file on desktop named "PowerToys_Report_[date]_[time].zip" containing logs and system information.
See [Bug Report Tool](../tools/bug-report-tool.md) for more detailed information about the tool.