//! A builder for Windows application manifest XML files. //! //! This module allows the construction of application manifests from code with the //! [`ManifestBuilder`], for use from a Cargo build script. Once configured, the builder //! should be passed to [`embed_manifest()`][crate::embed_manifest] to generate the //! correct instructions for Cargo. For any other use, the builder will output the XML //! when formatted for [`Display`], or with [`to_string()`][ToString]. For more //! information about the different elements of an application manifest, see //! [Application Manifests][1] in the Microsoft Windows App Development documentation. //! //! [1]: https://docs.microsoft.com/en-us/windows/win32/sbscs/application-manifests //! //! To generate the manifest XML separately, the XML can be output with `write!` or //! copied to a string with [`to_string()`][ToString]. To produce the manifest XML with //! extra whitespace for formatting, format it with the ‘alternate’ flag: //! //! ``` //! # use embed_manifest::new_manifest; //! let builder = new_manifest("Company.OrgUnit.Program"); //! assert_eq!(format!("{:#}", builder), r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?> //! <assembly xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3" manifestVersion="1.0"> //! <assemblyIdentity name="Company.OrgUnit.Program" type="win32" version="1.4.0.0"/> //! <dependency> //! <dependentAssembly> //! <assemblyIdentity language="*" name="Microsoft.Windows.Common-Controls" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" type="win32" version="6.0.0.0"/> //! </dependentAssembly> //! </dependency> //! <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1"> //! <application> //! <maxversiontested Id="10.0.18362.1"/> //! <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/> //! <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/> //! <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/> //! <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/> //! </application> //! </compatibility> //! <asmv3:application> //! <asmv3:windowsSettings> //! <activeCodePage xmlns="http://schemas.microsoft.com/SMI/2019/WindowsSettings">UTF-8</activeCodePage> //! <dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">permonitorv2</dpiAwareness> //! <longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware> //! <printerDriverIsolation xmlns="http://schemas.microsoft.com/SMI/2011/WindowsSettings">true</printerDriverIsolation> //! </asmv3:windowsSettings> //! </asmv3:application> //! <asmv3:trustInfo> //! <asmv3:security> //! <asmv3:requestedPrivileges> //! <asmv3:requestedExecutionLevel level="asInvoker" uiAccess="false"/> //! </asmv3:requestedPrivileges> //! </asmv3:security> //! </asmv3:trustInfo> //! </assembly>"#.replace("\n", "\r\n")) //! ```
use std::fmt::{Display, Formatter}; use std::ops::RangeBounds; use std::{env, fmt};
usecrate::manifest::xml::XmlFormatter;
mod xml;
#[cfg(test)] mod test;
/// An opaque container to describe the Windows application manifest for the /// executable. A new instance with reasonable defaults is created with /// [`new_manifest()`][crate::new_manifest]. #[derive(Debug)] pubstruct ManifestBuilder {
identity: Option<AssemblyIdentity>,
dependent_assemblies: Vec<AssemblyIdentity>,
compatibility: ApplicationCompatibility,
windows_settings: WindowsSettings,
requested_execution_level: Option<RequestedExecutionLevel>,
}
// Set the dot-separated [application name][identity] in the manifest. // // [identity]: https://learn.microsoft.com/en-us/windows/win32/sbscs/application-manifests#assemblyIdentity pubfn name(mutself, name: &str) -> Self { matchself.identity {
Some(refmut identity) => identity.name = name.to_string(),
None => self.identity = Some(AssemblyIdentity::application_version(name, 0, 0, 0, 0)),
} self
}
/// Set the four-part application version number in the manifest. pubfn version(mutself, major: u16, minor: u16, build: u16, revision: u16) -> Self { matchself.identity {
Some(refmut identity) => identity.version = Version(major, minor, build, revision),
None => { self.identity = Some(AssemblyIdentity::application_version("", major, minor, build, revision));
}
} self
}
/// Add a dependency on a specific version of a side-by-side assembly /// to the application manifest. For more information on side-by-side /// assemblies, see [Using Side-by-side Assemblies][sxs]. /// /// [sxs]: https://docs.microsoft.com/en-us/windows/win32/sbscs/using-side-by-side-assemblies pubfn dependency(mutself, identity: AssemblyIdentity) -> Self { self.dependent_assemblies.push(identity); self
}
/// Remove a dependency on a side-by-side assembly. This can be used to /// remove the default dependency on Common Controls version 6: /// /// ``` /// # use embed_manifest::new_manifest; /// new_manifest("Company.OrgUnit.Program") /// .remove_dependency("Microsoft.Windows.Common-Controls") /// # ; /// ``` pubfn remove_dependency(mutself, name: &str) -> Self { self.dependent_assemblies.retain(|d| d.name != name); self
}
/// Set the “maximum version tested” based on a Windows SDK version. /// This compatibility setting enables the use of XAML Islands, as described in /// [Host a standard WinRT XAML control in a C++ desktop (Win32) app][xaml]. /// /// [xaml]: https://docs.microsoft.com/en-us/windows/apps/desktop/modernize/host-standard-control-with-xaml-islands-cpp pubfn max_version_tested(mutself, version: MaxVersionTested) -> Self { self.compatibility.max_version_tested = Some(version); self
}
/// Remove the “maximum version tested” from the application compatibility. pubfn remove_max_version_tested(mutself) -> Self { self.compatibility.max_version_tested = None; self
}
/// Set the range of supported versions of Windows for application compatibility. /// The default value declares compatibility with every version from /// [Windows 7][SupportedOS::Windows7] to [Windows 10 and 11][SupportedOS::Windows10]. pubfn supported_os<R: RangeBounds<SupportedOS>>(mutself, os_range: R) -> Self { use SupportedOS::*;
self.compatibility.supported_os.clear(); for os in [WindowsVista, Windows7, Windows8, Windows81, Windows10] { if os_range.contains(&os) { self.compatibility.supported_os.push(os);
}
} self
}
/// Set the code page used for single-byte Windows API, starting from Windows 10 /// version 1903. The default setting of [UTF-8][`ActiveCodePage::Utf8`] makes Rust /// strings work directly with APIs like `MessageBoxA`. pubfn active_code_page(mutself, code_page: ActiveCodePage) -> Self { self.windows_settings.active_code_page = code_page; self
}
/// Configures how Windows should display this program on monitors where the /// graphics need scaling, whether by the application drawing its user /// interface at different sizes or by the Windows system rendering the graphics /// to a bitmap then resizing that for display. pubfn dpi_awareness(mutself, setting: DpiAwareness) -> Self { self.windows_settings.dpi_awareness = setting; self
}
/// Attempts to scale GDI primitives by the per-monitor scaling values, /// from Windows 10 version 1703. It seems to be best to leave this disabled. pubfn gdi_scaling(mutself, setting: Setting) -> Self { self.windows_settings.gdi_scaling = setting.enabled(); self
}
/// Select the memory allocator use by the standard heap allocation APIs, /// including the default Rust allocator. Selecting a different algorithm /// may make performance and memory use better or worse, so any changes /// should be carefully tested. pubfn heap_type(mutself, setting: HeapType) -> Self { self.windows_settings.heap_type = setting; self
}
/// Enable paths longer than 260 characters with some wide-character Win32 APIs, /// when also enabled in the Windows registry. For more details, see /// [Maximum Path Length Limitation][1] in the Windows App Development /// documentation. /// /// As of Rust 1.58, the [Rust standard library bypasses this limitation][2] itself /// by using Unicode paths beginning with `\\?\`. /// /// [1]: https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation /// [2]: https://github.com/rust-lang/rust/pull/89174 pubfn long_path_aware(mutself, setting: Setting) -> Self { self.windows_settings.long_path_aware = setting.enabled(); self
}
/// Enable printer driver isolation for the application, improving security and /// stability when printing by loading the printer driver in a separate /// application. This is poorly documented, but is described in a blog post, /// “[Application-level Printer Driver Isolation][post]”. /// /// [post]: https://peteronprogramming.wordpress.com/2018/01/22/application-level-printer-driver-isolation/ pubfn printer_driver_isolation(mutself, setting: Setting) -> Self { self.windows_settings.printer_driver_isolation = setting.enabled(); self
}
/// Configure whether the application should receive mouse wheel scroll events /// with a minimum delta of 1, 40 or 120, as described in /// [Windows precision touchpad devices][touchpad]. /// /// [touchpad]: https://docs.microsoft.com/en-us/windows/win32/w8cookbook/windows-precision-touchpad-devices pubfn scrolling_awareness(mutself, setting: ScrollingAwareness) -> Self { self.windows_settings.scrolling_awareness = setting; self
}
/// Allows the application to disable the filtering that normally /// removes UWP windows from the results of the `EnumWindows` API. pubfn window_filtering(mutself, setting: Setting) -> Self { self.windows_settings.disable_window_filtering = setting.disabled(); self
}
/// Selects the authorities to execute the program with, rather than /// [guessing based on a filename][installer] like `setup.exe`, /// `update.exe` or `patch.exe`. /// /// [installer]: https://docs.microsoft.com/en-us/windows/security/identity-protection/user-account-control/how-user-account-control-works#installer-detection-technology pubfn requested_execution_level(mutself, level: ExecutionLevel) -> Self { matchself.requested_execution_level {
Some(refmut requested_execution_level) => requested_execution_level.level = level,
None => self.requested_execution_level = Some(RequestedExecutionLevel { level, ui_access: false }),
} self
}
/// Allows the application to access the user interface of applications /// running with elevated permissions when this program does not, typically /// for accessibility. The program must additionally be correctly signed /// and installed in a trusted location like the Program Files directory. pubfn ui_access(mutself, access: bool) -> Self { matchself.requested_execution_level {
Some(refmut requested_execution_level) => requested_execution_level.ui_access = access,
None => { self.requested_execution_level = Some(RequestedExecutionLevel {
level: ExecutionLevel::AsInvoker,
ui_access: access,
})
}
} self
}
}
/// Creates a new value for a [manifest dependency][ManifestBuilder::dependency], /// with the `version` as an array of numbers like `[1, 0, 0, 0]` for 1.0.0.0, /// and the public key token as a 64-bit number like `0x6595b64144ccf1df`. pubfn new(name: &str, version: [u16; 4], public_key_token: u64) -> AssemblyIdentity {
AssemblyIdentity {
r#type: AssemblyType::Win32,
name: name.to_string(),
language: Some("*".to_string()),
processor_architecture: Some(AssemblyProcessorArchitecture::All),
version: Version(version[0], version[1], version[2], version[3]),
public_key_token: Some(PublicKeyToken(public_key_token)),
}
}
/// Change the language from `"*"` to the language code in `language`. pubfn language(mutself, language: &str) -> Self { self.language = Some(language.to_string()); self
}
/// Change the processor architecture from `"*"` to the architecture in `arch`. pubfn processor_architecture(mutself, arch: AssemblyProcessorArchitecture) -> Self { self.processor_architecture = Some(arch); self
}
fn xml_to(&self, w: &mut XmlFormatter) -> fmt::Result { let version = self.version.to_string(); let public_key_token = self.public_key_token.as_ref().map(|token| token.to_string());
/// Processor architecture for an assembly identity. #[derive(Debug)] #[non_exhaustive] pubenum AssemblyProcessorArchitecture { /// Any processor architecture, as `"*"`.
All, /// 32-bit x86 processors, as `"x86"`.
X86, /// 64-bit x64 processors, as `"x64"`.
Amd64, /// 32-bit ARM processors, as `"arm"`.
Arm, /// 64-bit ARM processors, as `"arm64"`.
Arm64,
}
/// Windows build versions for [`max_version_tested()`][ManifestBuilder::max_version_tested] /// from the [Windows SDK archive](https://developer.microsoft.com/en-us/windows/downloads/sdk-archive/). #[derive(Debug)] #[non_exhaustive] pubenum MaxVersionTested { /// Windows 10 version 1903, with build version 10.0.18362.0.
Windows10Version1903, /// Windows 10 version 2004, with build version 10.0.19041.0.
Windows10Version2004, /// Windows 10 version 2104, with build version 10.0.20348.0.
Windows10Version2104, /// Windows 11, with build version 10.0.22000.194.
Windows11, /// Windows 11 version 22H2, with build version 10.0.22621.1.
Windows11Version22H2,
}
impl MaxVersionTested { /// Return the Windows version as a string. pubfn as_str(&self) -> &'static str { matchself { Self::Windows10Version1903 => "10.0.18362.1", Self::Windows10Version2004 => "10.0.19041.0", Self::Windows10Version2104 => "10.0.20348.0", Self::Windows11 => "10.0.22000.194", Self::Windows11Version22H2 => "10.0.22621.1",
}
}
}
/// Operating system versions for Windows compatibility. #[derive(Debug, Ord, PartialOrd, Eq, PartialEq)] #[non_exhaustive] pubenum SupportedOS { /// Windows Vista and Windows Server 2008.
WindowsVista, /// Windows 7 and Windows Server 2008 R2.
Windows7, /// Windows 8 and Windows Server 2012.
Windows8, /// Windows 8.1 and Windows Server 2012 R2.
Windows81, /// Windows 10 and 11, and Windows Server 2016, 2019 and 2022.
Windows10,
}
impl SupportedOS { /// Returns the GUID string for the Windows version. pubfn as_str(&self) -> &'static str { matchself { Self::WindowsVista => "{e2011457-1546-43c5-a5fe-008deee3d3f0}", Self::Windows7 => "{35138b9a-5d96-4fbd-8e2d-a2440225f93a}", Self::Windows8 => "{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}", Self::Windows81 => "{1f676c76-80e1-4239-95bb-83d0f6d0da78}", Self::Windows10 => "{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}",
}
}
}
/// Configure whether a Windows setting is enabled or disabled, avoiding confusion /// over which of these options `true` and `false` represent. #[derive(Debug)] pubenum Setting {
Disabled = 0,
Enabled = 1,
}
impl Setting { /// Returns `true` if the setting should be disabled. fn disabled(&self) -> bool {
matches!(self, Setting::Disabled)
}
/// Returns `true` if the setting should be enabled. fn enabled(&self) -> bool {
matches!(self, Setting::Enabled)
}
}
/// The code page used by single-byte APIs in the program. #[derive(Debug)] #[non_exhaustive] pubenum ActiveCodePage { /// Use the code page from the configured system locale, or UTF-8 if “Use Unicode UTF-8 /// for worldwide language support” is configured.
System, /// Use UTF-8 from Windows 10 version 1903 and on Windows 11.
Utf8, /// Use the code page from the configured system locale, even when “Use Unicode UTF-8 /// for worldwide language support” is configured.
Legacy, /// Use the code page from the configured system locale on Windows 10, or from this /// locale on Windows 11.
Locale(String),
}
/// Options for how Windows will handle drawing on monitors when the graphics /// need scaling to display at the correct size. /// /// See [High DPI Desktop Application Development on Windows][dpi] for more details /// about the impact of these options. /// /// [dpi]: https://docs.microsoft.com/en-us/windows/win32/hidpi/high-dpi-desktop-application-development-on-windows #[derive(Debug)] #[non_exhaustive] pubenum DpiAwareness { /// DPI awareness is not configured, so Windows will scale the application unless /// changed via the `SetProcessDpiAware` or `SetProcessDpiAwareness` API.
UnawareByDefault, /// DPI awareness is not configured, with Windows 8.1, 10 and 11 not able /// to change the setting via API.
Unaware, /// The program uses the system DPI, or the DPI of the monitor they start on if /// “Fix scaling for apps” is enabled. If the DPI does not match the current /// monitor then Windows will scale the application.
System, /// The program uses the system DPI on Windows Vista, 7 and 8, and version 1 of /// per-monitor DPI awareness on Windows 8.1, 10 and 11. Using version 1 of the /// API is not recommended.
PerMonitor, /// The program uses the system DPI on Windows Vista, 7 and 8, version 1 of /// per-monitor DPI awareness on Windows 8.1 and Windows 10 version 1507 and 1511, /// and version 2 of per-monitor DPI awareness from Windows 10 version 1607.
PerMonitorV2, /// The program uses the system DPI on Windows Vista, 7, 8, 8.1 and Windows 10 /// version 1507 and 1511, and version 2 of per-monitor DPI awareness from /// Windows 10 version 1607.
PerMonitorV2Only,
}
/// The heap type for the default memory allocator. #[derive(Debug)] #[non_exhaustive] pubenum HeapType { /// The default heap type since Windows Vista.
LowFragmentationHeap, /// The modern segment heap, which may reduce total memory allocation in some programs. /// This is supported since Windows 10 version 2004. See /// [Improving Memory Usage in Microsoft Edge][edge]. /// /// [edge]: https://blogs.windows.com/msedgedev/2020/06/17/improving-memory-usage/
SegmentHeap,
}
/// Whether the application supports scroll wheel events with a minimum delta /// of 1, 40 or 120. #[derive(Debug)] #[non_exhaustive] pubenum ScrollingAwareness { /// The application can only handle scroll wheel events with the original delta of 120.
LowResolution, /// The application can handle high precision scroll wheel events with a delta of 40.
HighResolution, /// The application can handle ultra high precision scroll wheel events with a delta as low as 1.
UltraHighResolution,
}
/// The requested execution level for the application when started. /// /// The behaviour of each option is described in /// [Designing UAC Applications for Windows Vista Step 6: Create and Embed an Application Manifest][step6]. /// /// [step6]: https://msdn.microsoft.com/en-us/library/bb756929.aspx #[derive(Debug)] pubenum ExecutionLevel { /// The application will always run with the same authorities as the program invoking it.
AsInvoker, /// The program will run without special authorities for a standard user, but will try to /// run with administrator authority if the user is an administrator. This is rarely used.
HighestAvailable, /// The application will run as an administrator, prompting for elevation if necessary.
RequireAdministrator,
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.