Skip to content

Free, open-source Windows optimization tool for performance, privacy, and simplicity.

Initialize project structure

itsfatduck58761e516acb
diff --git a/.editorconfig b/.editorconfig
new file mode 100644
index 0000000..7aa7585
--- /dev/null
+++ b/.editorconfig
@@ -0,0 +1,6 @@
+[*.cs]
+
+
+# bro ts solve so many warnings!!
+# CA1416: Validate platform compatibility
+dotnet_diagnostic.CA1416.severity = silent
diff --git a/.github/assets/app_restorepoint.png b/.github/assets/app_restorepoint.png
new file mode 100644
index 0000000..579dbd9
Binary files /dev/null and b/.github/assets/app_restorepoint.png differ
diff --git a/.github/assets/app_screenshot.png b/.github/assets/app_screenshot.png
new file mode 100644
index 0000000..a91cda7
Binary files /dev/null and b/.github/assets/app_screenshot.png differ
diff --git a/.github/assets/app_tweaks.png b/.github/assets/app_tweaks.png
new file mode 100644
index 0000000..ce33c6a
Binary files /dev/null and b/.github/assets/app_tweaks.png differ
diff --git a/.github/assets/cc_by_nc_sa_4_0.png b/.github/assets/cc_by_nc_sa_4_0.png
new file mode 100644
index 0000000..2b8e6c4
Binary files /dev/null and b/.github/assets/cc_by_nc_sa_4_0.png differ
diff --git a/.github/assets/optimizerDuck.png b/.github/assets/optimizerDuck.png
new file mode 100644
index 0000000..dd11e18
Binary files /dev/null and b/.github/assets/optimizerDuck.png differ
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..69218d8
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,684 @@
+# Created by https://www.toptal.com/developers/gitignore/api/csharp,rider,visualstudio,windows
+# Edit at https://www.toptal.com/developers/gitignore?templates=csharp,rider,visualstudio,windows
+
+### Csharp ###
+## Ignore Visual Studio temporary files, build results, and
+## files generated by popular Visual Studio add-ons.
+##
+## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
+
+# User-specific files
+.vscode/
+*.rsuser
+*.suo
+*.user
+*.userosscache
+*.sln.docstates
+
+# User-specific files (MonoDevelop/Xamarin Studio)
+*.userprefs
+
+# Mono auto generated files
+mono_crash.*
+
+# Build results
+[Dd]ebug/
+[Dd]ebugPublic/
+[Rr]elease/
+[Rr]eleases/
+x64/
+x86/
+[Ww][Ii][Nn]32/
+[Aa][Rr][Mm]/
+[Aa][Rr][Mm]64/
+bld/
+[Bb]in/
+[Oo]bj/
+[Ll]og/
+[Ll]ogs/
+
+# Visual Studio 2015/2017 cache/options directory
+.vs/
+# Uncomment if you have tasks that create the project's static files in wwwroot
+#wwwroot/
+
+# Visual Studio 2017 auto generated files
+Generated\ Files/
+
+# MSTest test Results
+[Tt]est[Rr]esult*/
+[Bb]uild[Ll]og.*
+
+# NUnit
+*.VisualState.xml
+TestResult.xml
+nunit-*.xml
+
+# Build Results of an ATL Project
+[Dd]ebugPS/
+[Rr]eleasePS/
+dlldata.c
+
+# Benchmark Results
+BenchmarkDotNet.Artifacts/
+
+# .NET Core
+project.lock.json
+project.fragment.lock.json
+artifacts/
+
+# ASP.NET Scaffolding
+ScaffoldingReadMe.txt
+
+# StyleCop
+StyleCopReport.xml
+
+# Files built by Visual Studio
+*_i.c
+*_p.c
+*_h.h
+*.ilk
+*.meta
+*.obj
+*.iobj
+*.pch
+*.pdb
+*.ipdb
+*.pgc
+*.pgd
+*.rsp
+*.sbr
+*.tlb
+*.tli
+*.tlh
+*.tmp
+*.tmp_proj
+*_wpftmp.csproj
+*.log
+*.tlog
+*.vspscc
+*.vssscc
+.builds
+*.pidb
+*.svclog
+*.scc
+
+# Chutzpah Test files
+_Chutzpah*
+
+# Visual C++ cache files
+ipch/
+*.aps
+*.ncb
+*.opendb
+*.opensdf
+*.sdf
+*.cachefile
+*.VC.db
+*.VC.VC.opendb
+
+# Visual Studio profiler
+*.psess
+*.vsp
+*.vspx
+*.sap
+
+# Visual Studio Trace Files
+*.e2e
+
+# TFS 2012 Local Workspace
+$tf/
+
+# Guidance Automation Toolkit
+*.gpState
+
+# ReSharper is a .NET coding add-in
+_ReSharper*/
+*.[Rr]e[Ss]harper
+*.DotSettings.user
+
+# TeamCity is a build add-in
+_TeamCity*
+
+# DotCover is a Code Coverage Tool
+*.dotCover
+
+# AxoCover is a Code Coverage Tool
+.axoCover/*
+!.axoCover/settings.json
+
+# Coverlet is a free, cross platform Code Coverage Tool
+coverage*.json
+coverage*.xml
+coverage*.info
+
+# Visual Studio code coverage results
+*.coverage
+*.coveragexml
+
+# NCrunch
+_NCrunch_*
+.*crunch*.local.xml
+nCrunchTemp_*
+
+# MightyMoose
+*.mm.*
+AutoTest.Net/
+
+# Web workbench (sass)
+.sass-cache/
+
+# Installshield output folder
+[Ee]xpress/
+
+# DocProject is a documentation generator add-in
+DocProject/buildhelp/
+DocProject/Help/*.HxT
+DocProject/Help/*.HxC
+DocProject/Help/*.hhc
+DocProject/Help/*.hhk
+DocProject/Help/*.hhp
+DocProject/Help/Html2
+DocProject/Help/html
+
+# Click-Once directory
+publish/
+
+# Publish Web Output
+*.[Pp]ublish.xml
+*.azurePubxml
+# Note: Comment the next line if you want to checkin your web deploy settings,
+# but database connection strings (with potential passwords) will be unencrypted
+*.pubxml
+*.publishproj
+
+# Microsoft Azure Web App publish settings. Comment the next line if you want to
+# checkin your Azure Web App publish settings, but sensitive information contained
+# in these scripts will be unencrypted
+PublishScripts/
+
+# NuGet Packages
+*.nupkg
+# NuGet Symbol Packages
+*.snupkg
+# The packages folder can be ignored because of Package Restore
+**/[Pp]ackages/*
+# except build/, which is used as an MSBuild target.
+!**/[Pp]ackages/build/
+# Uncomment if necessary however generally it will be regenerated when needed
+#!**/[Pp]ackages/repositories.config
+# NuGet v3's project.json files produces more ignorable files
+*.nuget.props
+*.nuget.targets
+
+# Microsoft Azure Build Output
+csx/
+*.build.csdef
+
+# Microsoft Azure Emulator
+ecf/
+rcf/
+
+# Windows Store app package directories and files
+AppPackages/
+BundleArtifacts/
+Package.StoreAssociation.xml
+_pkginfo.txt
+*.appx
+*.appxbundle
+*.appxupload
+
+# Visual Studio cache files
+# files ending in .cache can be ignored
+*.[Cc]ache
+# but keep track of directories ending in .cache
+!?*.[Cc]ache/
+
+# Others
+ClientBin/
+~$*
+*~
+*.dbmdl
+*.dbproj.schemaview
+*.jfm
+*.pfx
+*.publishsettings
+orleans.codegen.cs
+
+# Including strong name files can present a security risk
+# (https://github.com/github/gitignore/pull/2483#issue-259490424)
+#*.snk
+
+# Since there are multiple workflows, uncomment next line to ignore bower_components
+# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
+#bower_components/
+
+# RIA/Silverlight projects
+Generated_Code/
+
+# Backup & report files from converting an old project file
+# to a newer Visual Studio version. Backup files are not needed,
+# because we have git ;-)
+_UpgradeReport_Files/
+Backup*/
+UpgradeLog*.XML
+UpgradeLog*.htm
+ServiceFabricBackup/
+*.rptproj.bak
+
+# SQL Server files
+*.mdf
+*.ldf
+*.ndf
+
+# Business Intelligence projects
+*.rdl.data
+*.bim.layout
+*.bim_*.settings
+*.rptproj.rsuser
+*- [Bb]ackup.rdl
+*- [Bb]ackup ([0-9]).rdl
+*- [Bb]ackup ([0-9][0-9]).rdl
+
+# Microsoft Fakes
+FakesAssemblies/
+
+# GhostDoc plugin setting file
+*.GhostDoc.xml
+
+# Node.js Tools for Visual Studio
+.ntvs_analysis.dat
+node_modules/
+
+# Visual Studio 6 build log
+*.plg
+
+# Visual Studio 6 workspace options file
+*.opt
+
+# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
+*.vbw
+
+# Visual Studio 6 auto-generated project file (contains which files were open etc.)
+*.vbp
+
+# Visual Studio 6 workspace and project file (working project files containing files to include in project)
+*.dsw
+*.dsp
+
+# Visual Studio 6 technical files
+
+# Visual Studio LightSwitch build output
+**/*.HTMLClient/GeneratedArtifacts
+**/*.DesktopClient/GeneratedArtifacts
+**/*.DesktopClient/ModelManifest.xml
+**/*.Server/GeneratedArtifacts
+**/*.Server/ModelManifest.xml
+_Pvt_Extensions
+
+# Paket dependency manager
+.paket/paket.exe
+paket-files/
+
+# FAKE - F# Make
+.fake/
+
+# CodeRush personal settings
+.cr/personal
+
+# Python Tools for Visual Studio (PTVS)
+__pycache__/
+*.pyc
+
+# Cake - Uncomment if you are using it
+# tools/**
+# !tools/packages.config
+
+# Tabs Studio
+*.tss
+
+# Telerik's JustMock configuration file
+*.jmconfig
+
+# BizTalk build output
+*.btp.cs
+*.btm.cs
+*.odx.cs
+*.xsd.cs
+
+# OpenCover UI analysis results
+OpenCover/
+
+# Azure Stream Analytics local run output
+ASALocalRun/
+
+# MSBuild Binary and Structured Log
+*.binlog
+
+# NVidia Nsight GPU debugger configuration file
+*.nvuser
+
+# MFractors (Xamarin productivity tool) working folder
+.mfractor/
+
+# Local History for Visual Studio
+.localhistory/
+
+# Visual Studio History (VSHistory) files
+.vshistory/
+
+# BeatPulse healthcheck temp database
+healthchecksdb
+
+# Backup folder for Package Reference Convert tool in Visual Studio 2017
+MigrationBackup/
+
+# Ionide (cross platform F# VS Code tools) working folder
+.ionide/
+
+# Fody - auto-generated XML schema
+FodyWeavers.xsd
+
+# VS Code files for those working on multiple tools
+.vscode/*
+!.vscode/settings.json
+!.vscode/tasks.json
+!.vscode/launch.json
+!.vscode/extensions.json
+*.code-workspace
+
+# Local History for Visual Studio Code
+.history/
+
+# Windows Installer files from build outputs
+*.cab
+*.msi
+*.msix
+*.msm
+*.msp
+
+# JetBrains Rider
+*.sln.iml
+
+### Rider ###
+# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
+# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
+
+# User-specific stuff
+.idea/**/workspace.xml
+.idea/**/tasks.xml
+.idea/**/usage.statistics.xml
+.idea/**/dictionaries
+.idea/**/shelf
+
+# AWS User-specific
+.idea/**/aws.xml
+
+# Generated files
+.idea/**/contentModel.xml
+
+# Sensitive or high-churn files
+.idea/**/dataSources/
+.idea/**/dataSources.ids
+.idea/**/dataSources.local.xml
+.idea/**/sqlDataSources.xml
+.idea/**/dynamic.xml
+.idea/**/uiDesigner.xml
+.idea/**/dbnavigator.xml
+
+# Gradle
+.idea/**/gradle.xml
+.idea/**/libraries
+
+# Gradle and Maven with auto-import
+# When using Gradle or Maven with auto-import, you should exclude module files,
+# since they will be recreated, and may cause churn. Uncomment if using
+# auto-import.
+# .idea/artifacts
+# .idea/compiler.xml
+# .idea/jarRepositories.xml
+# .idea/modules.xml
+# .idea/*.iml
+# .idea/modules
+# *.iml
+# *.ipr
+
+# CMake
+cmake-build-*/
+
+# Mongo Explorer plugin
+.idea/**/mongoSettings.xml
+
+# File-based project format
+*.iws
+
+# IntelliJ
+out/
+
+# mpeltonen/sbt-idea plugin
+.idea_modules/
+
+# JIRA plugin
+atlassian-ide-plugin.xml
+
+# Cursive Clojure plugin
+.idea/replstate.xml
+
+# SonarLint plugin
+.idea/sonarlint/
+
+# Crashlytics plugin (for Android Studio and IntelliJ)
+com_crashlytics_export_strings.xml
+crashlytics.properties
+crashlytics-build.properties
+fabric.properties
+
+# Editor-based Rest Client
+.idea/httpRequests
+
+# Android studio 3.1+ serialized cache file
+.idea/caches/build_file_checksums.ser
+
+### Windows ###
+# Windows thumbnail cache files
+Thumbs.db
+Thumbs.db:encryptable
+ehthumbs.db
+ehthumbs_vista.db
+
+# Dump file
+*.stackdump
+
+# Folder config file
+[Dd]esktop.ini
+
+# Recycle Bin used on file shares
+$RECYCLE.BIN/
+
+# Windows Installer files
+
+# Windows shortcuts
+*.lnk
+
+### VisualStudio ###
+
+# User-specific files
+
+# User-specific files (MonoDevelop/Xamarin Studio)
+
+# Mono auto generated files
+
+# Build results
+
+# Visual Studio 2015/2017 cache/options directory
+# Uncomment if you have tasks that create the project's static files in wwwroot
+
+# Visual Studio 2017 auto generated files
+
+# MSTest test Results
+
+# NUnit
+
+# Build Results of an ATL Project
+
+# Benchmark Results
+
+# .NET Core
+
+# ASP.NET Scaffolding
+
+# StyleCop
+
+# Files built by Visual Studio
+
+# Chutzpah Test files
+
+# Visual C++ cache files
+
+# Visual Studio profiler
+
+# Visual Studio Trace Files
+
+# TFS 2012 Local Workspace
+
+# Guidance Automation Toolkit
+
+# ReSharper is a .NET coding add-in
+
+# TeamCity is a build add-in
+
+# DotCover is a Code Coverage Tool
+
+# AxoCover is a Code Coverage Tool
+
+# Coverlet is a free, cross platform Code Coverage Tool
+
+# Visual Studio code coverage results
+
+# NCrunch
+
+# MightyMoose
+
+# Web workbench (sass)
+
+# Installshield output folder
+
+# DocProject is a documentation generator add-in
+
+# Click-Once directory
+
+# Publish Web Output
+# Note: Comment the next line if you want to checkin your web deploy settings,
+# but database connection strings (with potential passwords) will be unencrypted
+
+# Microsoft Azure Web App publish settings. Comment the next line if you want to
+# checkin your Azure Web App publish settings, but sensitive information contained
+# in these scripts will be unencrypted
+
+# NuGet Packages
+# NuGet Symbol Packages
+# The packages folder can be ignored because of Package Restore
+# except build/, which is used as an MSBuild target.
+# Uncomment if necessary however generally it will be regenerated when needed
+# NuGet v3's project.json files produces more ignorable files
+
+# Microsoft Azure Build Output
+
+# Microsoft Azure Emulator
+
+# Windows Store app package directories and files
+
+# Visual Studio cache files
+# files ending in .cache can be ignored
+# but keep track of directories ending in .cache
+
+# Others
+
+# Including strong name files can present a security risk
+# (https://github.com/github/gitignore/pull/2483#issue-259490424)
+
+# Since there are multiple workflows, uncomment next line to ignore bower_components
+# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
+
+# RIA/Silverlight projects
+
+# Backup & report files from converting an old project file
+# to a newer Visual Studio version. Backup files are not needed,
+# because we have git ;-)
+
+# SQL Server files
+
+# Business Intelligence projects
+
+# Microsoft Fakes
+
+# GhostDoc plugin setting file
+
+# Node.js Tools for Visual Studio
+
+# Visual Studio 6 build log
+
+# Visual Studio 6 workspace options file
+
+# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
+
+# Visual Studio 6 auto-generated project file (contains which files were open etc.)
+
+# Visual Studio 6 workspace and project file (working project files containing files to include in project)
+
+# Visual Studio 6 technical files
+
+# Visual Studio LightSwitch build output
+
+# Paket dependency manager
+
+# FAKE - F# Make
+
+# CodeRush personal settings
+
+# Python Tools for Visual Studio (PTVS)
+
+# Cake - Uncomment if you are using it
+# tools/**
+# !tools/packages.config
+
+# Tabs Studio
+
+# Telerik's JustMock configuration file
+
+# BizTalk build output
+
+# OpenCover UI analysis results
+
+# Azure Stream Analytics local run output
+
+# MSBuild Binary and Structured Log
+
+# NVidia Nsight GPU debugger configuration file
+
+# MFractors (Xamarin productivity tool) working folder
+
+# Local History for Visual Studio
+
+# Visual Studio History (VSHistory) files
+
+# BeatPulse healthcheck temp database
+
+# Backup folder for Package Reference Convert tool in Visual Studio 2017
+
+# Ionide (cross platform F# VS Code tools) working folder
+
+# Fody - auto-generated XML schema
+
+# VS Code files for those working on multiple tools
+
+# Local History for Visual Studio Code
+
+# Windows Installer files from build outputs
+
+# JetBrains Rider
+
+### VisualStudio Patch ###
+# Additional files built by Visual Studio
+
+# End of https://www.toptal.com/developers/gitignore/api/csharp,rider,visualstudio,windows
\ No newline at end of file
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..cbe5ad1
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,437 @@
+Attribution-NonCommercial-ShareAlike 4.0 International
+
+=======================================================================
+
+Creative Commons Corporation ("Creative Commons") is not a law firm and
+does not provide legal services or legal advice. Distribution of
+Creative Commons public licenses does not create a lawyer-client or
+other relationship. Creative Commons makes its licenses and related
+information available on an "as-is" basis. Creative Commons gives no
+warranties regarding its licenses, any material licensed under their
+terms and conditions, or any related information. Creative Commons
+disclaims all liability for damages resulting from their use to the
+fullest extent possible.
+
+Using Creative Commons Public Licenses
+
+Creative Commons public licenses provide a standard set of terms and
+conditions that creators and other rights holders may use to share
+original works of authorship and other material subject to copyright
+and certain other rights specified in the public license below. The
+following considerations are for informational purposes only, are not
+exhaustive, and do not form part of our licenses.
+
+ Considerations for licensors: Our public licenses are
+ intended for use by those authorized to give the public
+ permission to use material in ways otherwise restricted by
+ copyright and certain other rights. Our licenses are
+ irrevocable. Licensors should read and understand the terms
+ and conditions of the license they choose before applying it.
+ Licensors should also secure all rights necessary before
+ applying our licenses so that the public can reuse the
+ material as expected. Licensors should clearly mark any
+ material not subject to the license. This includes other CC-
+ licensed material, or material used under an exception or
+ limitation to copyright. More considerations for licensors:
+ wiki.creativecommons.org/Considerations_for_licensors
+
+ Considerations for the public: By using one of our public
+ licenses, a licensor grants the public permission to use the
+ licensed material under specified terms and conditions. If
+ the licensor's permission is not necessary for any reason--for
+ example, because of any applicable exception or limitation to
+ copyright--then that use is not regulated by the license. Our
+ licenses grant only permissions under copyright and certain
+ other rights that a licensor has authority to grant. Use of
+ the licensed material may still be restricted for other
+ reasons, including because others have copyright or other
+ rights in the material. A licensor may make special requests,
+ such as asking that all changes be marked or described.
+ Although not required by our licenses, you are encouraged to
+ respect those requests where reasonable. More considerations
+ for the public:
+ wiki.creativecommons.org/Considerations_for_licensees
+
+=======================================================================
+
+Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
+Public License
+
+By exercising the Licensed Rights (defined below), You accept and agree
+to be bound by the terms and conditions of this Creative Commons
+Attribution-NonCommercial-ShareAlike 4.0 International Public License
+("Public License"). To the extent this Public License may be
+interpreted as a contract, You are granted the Licensed Rights in
+consideration of Your acceptance of these terms and conditions, and the
+Licensor grants You such rights in consideration of benefits the
+Licensor receives from making the Licensed Material available under
+these terms and conditions.
+
+
+Section 1 -- Definitions.
+
+ a. Adapted Material means material subject to Copyright and Similar
+ Rights that is derived from or based upon the Licensed Material
+ and in which the Licensed Material is translated, altered,
+ arranged, transformed, or otherwise modified in a manner requiring
+ permission under the Copyright and Similar Rights held by the
+ Licensor. For purposes of this Public License, where the Licensed
+ Material is a musical work, performance, or sound recording,
+ Adapted Material is always produced where the Licensed Material is
+ synched in timed relation with a moving image.
+
+ b. Adapter's License means the license You apply to Your Copyright
+ and Similar Rights in Your contributions to Adapted Material in
+ accordance with the terms and conditions of this Public License.
+
+ c. BY-NC-SA Compatible License means a license listed at
+ creativecommons.org/compatiblelicenses, approved by Creative
+ Commons as essentially the equivalent of this Public License.
+
+ d. Copyright and Similar Rights means copyright and/or similar rights
+ closely related to copyright including, without limitation,
+ performance, broadcast, sound recording, and Sui Generis Database
+ Rights, without regard to how the rights are labeled or
+ categorized. For purposes of this Public License, the rights
+ specified in Section 2(b)(1)-(2) are not Copyright and Similar
+ Rights.
+
+ e. Effective Technological Measures means those measures that, in the
+ absence of proper authority, may not be circumvented under laws
+ fulfilling obligations under Article 11 of the WIPO Copyright
+ Treaty adopted on December 20, 1996, and/or similar international
+ agreements.
+
+ f. Exceptions and Limitations means fair use, fair dealing, and/or
+ any other exception or limitation to Copyright and Similar Rights
+ that applies to Your use of the Licensed Material.
+
+ g. License Elements means the license attributes listed in the name
+ of a Creative Commons Public License. The License Elements of this
+ Public License are Attribution, NonCommercial, and ShareAlike.
+
+ h. Licensed Material means the artistic or literary work, database,
+ or other material to which the Licensor applied this Public
+ License.
+
+ i. Licensed Rights means the rights granted to You subject to the
+ terms and conditions of this Public License, which are limited to
+ all Copyright and Similar Rights that apply to Your use of the
+ Licensed Material and that the Licensor has authority to license.
+
+ j. Licensor means the individual(s) or entity(ies) granting rights
+ under this Public License.
+
+ k. NonCommercial means not primarily intended for or directed towards
+ commercial advantage or monetary compensation. For purposes of
+ this Public License, the exchange of the Licensed Material for
+ other material subject to Copyright and Similar Rights by digital
+ file-sharing or similar means is NonCommercial provided there is
+ no payment of monetary compensation in connection with the
+ exchange.
+
+ l. Share means to provide material to the public by any means or
+ process that requires permission under the Licensed Rights, such
+ as reproduction, public display, public performance, distribution,
+ dissemination, communication, or importation, and to make material
+ available to the public including in ways that members of the
+ public may access the material from a place and at a time
+ individually chosen by them.
+
+ m. Sui Generis Database Rights means rights other than copyright
+ resulting from Directive 96/9/EC of the European Parliament and of
+ the Council of 11 March 1996 on the legal protection of databases,
+ as amended and/or succeeded, as well as other essentially
+ equivalent rights anywhere in the world.
+
+ n. You means the individual or entity exercising the Licensed Rights
+ under this Public License. Your has a corresponding meaning.
+
+
+Section 2 -- Scope.
+
+ a. License grant.
+
+ 1. Subject to the terms and conditions of this Public License,
+ the Licensor hereby grants You a worldwide, royalty-free,
+ non-sublicensable, non-exclusive, irrevocable license to
+ exercise the Licensed Rights in the Licensed Material to:
+
+ a. reproduce and Share the Licensed Material, in whole or
+ in part, for NonCommercial purposes only; and
+
+ b. produce, reproduce, and Share Adapted Material for
+ NonCommercial purposes only.
+
+ 2. Exceptions and Limitations. For the avoidance of doubt, where
+ Exceptions and Limitations apply to Your use, this Public
+ License does not apply, and You do not need to comply with
+ its terms and conditions.
+
+ 3. Term. The term of this Public License is specified in Section
+ 6(a).
+
+ 4. Media and formats; technical modifications allowed. The
+ Licensor authorizes You to exercise the Licensed Rights in
+ all media and formats whether now known or hereafter created,
+ and to make technical modifications necessary to do so. The
+ Licensor waives and/or agrees not to assert any right or
+ authority to forbid You from making technical modifications
+ necessary to exercise the Licensed Rights, including
+ technical modifications necessary to circumvent Effective
+ Technological Measures. For purposes of this Public License,
+ simply making modifications authorized by this Section 2(a)
+ (4) never produces Adapted Material.
+
+ 5. Downstream recipients.
+
+ a. Offer from the Licensor -- Licensed Material. Every
+ recipient of the Licensed Material automatically
+ receives an offer from the Licensor to exercise the
+ Licensed Rights under the terms and conditions of this
+ Public License.
+
+ b. Additional offer from the Licensor -- Adapted Material.
+ Every recipient of Adapted Material from You
+ automatically receives an offer from the Licensor to
+ exercise the Licensed Rights in the Adapted Material
+ under the conditions of the Adapter's License You apply.
+
+ c. No downstream restrictions. You may not offer or impose
+ any additional or different terms or conditions on, or
+ apply any Effective Technological Measures to, the
+ Licensed Material if doing so restricts exercise of the
+ Licensed Rights by any recipient of the Licensed
+ Material.
+
+ 6. No endorsement. Nothing in this Public License constitutes or
+ may be construed as permission to assert or imply that You
+ are, or that Your use of the Licensed Material is, connected
+ with, or sponsored, endorsed, or granted official status by,
+ the Licensor or others designated to receive attribution as
+ provided in Section 3(a)(1)(A)(i).
+
+ b. Other rights.
+
+ 1. Moral rights, such as the right of integrity, are not
+ licensed under this Public License, nor are publicity,
+ privacy, and/or other similar personality rights; however, to
+ the extent possible, the Licensor waives and/or agrees not to
+ assert any such rights held by the Licensor to the limited
+ extent necessary to allow You to exercise the Licensed
+ Rights, but not otherwise.
+
+ 2. Patent and trademark rights are not licensed under this
+ Public License.
+
+ 3. To the extent possible, the Licensor waives any right to
+ collect royalties from You for the exercise of the Licensed
+ Rights, whether directly or through a collecting society
+ under any voluntary or waivable statutory or compulsory
+ licensing scheme. In all other cases the Licensor expressly
+ reserves any right to collect such royalties, including when
+ the Licensed Material is used other than for NonCommercial
+ purposes.
+
+
+Section 3 -- License Conditions.
+
+Your exercise of the Licensed Rights is expressly made subject to the
+following conditions.
+
+ a. Attribution.
+
+ 1. If You Share the Licensed Material (including in modified
+ form), You must:
+
+ a. retain the following if it is supplied by the Licensor
+ with the Licensed Material:
+
+ i. identification of the creator(s) of the Licensed
+ Material and any others designated to receive
+ attribution, in any reasonable manner requested by
+ the Licensor (including by pseudonym if
+ designated);
+
+ ii. a copyright notice;
+
+ iii. a notice that refers to this Public License;
+
+ iv. a notice that refers to the disclaimer of
+ warranties;
+
+ v. a URI or hyperlink to the Licensed Material to the
+ extent reasonably practicable;
+
+ b. indicate if You modified the Licensed Material and
+ retain an indication of any previous modifications; and
+
+ c. indicate the Licensed Material is licensed under this
+ Public License, and include the text of, or the URI or
+ hyperlink to, this Public License.
+
+ 2. You may satisfy the conditions in Section 3(a)(1) in any
+ reasonable manner based on the medium, means, and context in
+ which You Share the Licensed Material. For example, it may be
+ reasonable to satisfy the conditions by providing a URI or
+ hyperlink to a resource that includes the required
+ information.
+ 3. If requested by the Licensor, You must remove any of the
+ information required by Section 3(a)(1)(A) to the extent
+ reasonably practicable.
+
+ b. ShareAlike.
+
+ In addition to the conditions in Section 3(a), if You Share
+ Adapted Material You produce, the following conditions also apply.
+
+ 1. The Adapter's License You apply must be a Creative Commons
+ license with the same License Elements, this version or
+ later, or a BY-NC-SA Compatible License.
+
+ 2. You must include the text of, or the URI or hyperlink to, the
+ Adapter's License You apply. You may satisfy this condition
+ in any reasonable manner based on the medium, means, and
+ context in which You Share Adapted Material.
+
+ 3. You may not offer or impose any additional or different terms
+ or conditions on, or apply any Effective Technological
+ Measures to, Adapted Material that restrict exercise of the
+ rights granted under the Adapter's License You apply.
+
+
+Section 4 -- Sui Generis Database Rights.
+
+Where the Licensed Rights include Sui Generis Database Rights that
+apply to Your use of the Licensed Material:
+
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right
+ to extract, reuse, reproduce, and Share all or a substantial
+ portion of the contents of the database for NonCommercial purposes
+ only;
+
+ b. if You include all or a substantial portion of the database
+ contents in a database in which You have Sui Generis Database
+ Rights, then the database in which You have Sui Generis Database
+ Rights (but not its individual contents) is Adapted Material,
+ including for purposes of Section 3(b); and
+
+ c. You must comply with the conditions in Section 3(a) if You Share
+ all or a substantial portion of the contents of the database.
+
+For the avoidance of doubt, this Section 4 supplements and does not
+replace Your obligations under this Public License where the Licensed
+Rights include other Copyright and Similar Rights.
+
+
+Section 5 -- Disclaimer of Warranties and Limitation of Liability.
+
+ a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
+ EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
+ AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
+ ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
+ IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
+ WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
+ PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
+ ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
+ KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
+ ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
+
+ b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
+ TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
+ NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
+ INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
+ COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
+ USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
+ ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
+ DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
+ IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
+
+ c. The disclaimer of warranties and limitation of liability provided
+ above shall be interpreted in a manner that, to the extent
+ possible, most closely approximates an absolute disclaimer and
+ waiver of all liability.
+
+
+Section 6 -- Term and Termination.
+
+ a. This Public License applies for the term of the Copyright and
+ Similar Rights licensed here. However, if You fail to comply with
+ this Public License, then Your rights under this Public License
+ terminate automatically.
+
+ b. Where Your right to use the Licensed Material has terminated under
+ Section 6(a), it reinstates:
+
+ 1. automatically as of the date the violation is cured, provided
+ it is cured within 30 days of Your discovery of the
+ violation; or
+
+ 2. upon express reinstatement by the Licensor.
+
+ For the avoidance of doubt, this Section 6(b) does not affect any
+ right the Licensor may have to seek remedies for Your violations
+ of this Public License.
+
+ c. For the avoidance of doubt, the Licensor may also offer the
+ Licensed Material under separate terms or conditions or stop
+ distributing the Licensed Material at any time; however, doing so
+ will not terminate this Public License.
+
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
+ License.
+
+
+Section 7 -- Other Terms and Conditions.
+
+ a. The Licensor shall not be bound by any additional or different
+ terms or conditions communicated by You unless expressly agreed.
+
+ b. Any arrangements, understandings, or agreements regarding the
+ Licensed Material not stated herein are separate from and
+ independent of the terms and conditions of this Public License.
+
+
+Section 8 -- Interpretation.
+
+ a. For the avoidance of doubt, this Public License does not, and
+ shall not be interpreted to, reduce, limit, restrict, or impose
+ conditions on any use of the Licensed Material that could lawfully
+ be made without permission under this Public License.
+
+ b. To the extent possible, if any provision of this Public License is
+ deemed unenforceable, it shall be automatically reformed to the
+ minimum extent necessary to make it enforceable. If the provision
+ cannot be reformed, it shall be severed from this Public License
+ without affecting the enforceability of the remaining terms and
+ conditions.
+
+ c. No term or condition of this Public License will be waived and no
+ failure to comply consented to unless expressly agreed to by the
+ Licensor.
+
+ d. Nothing in this Public License constitutes or may be interpreted
+ as a limitation upon, or waiver of, any privileges and immunities
+ that apply to the Licensor or You, including from the legal
+ processes of any jurisdiction or authority.
+
+=======================================================================
+
+Creative Commons is not a party to its public
+licenses. Notwithstanding, Creative Commons may elect to apply one of
+its public licenses to material it publishes and in those instances
+will be considered the “Licensor.” The text of the Creative Commons
+public licenses is dedicated to the public domain under the CC0 Public
+Domain Dedication. Except for the limited purpose of indicating that
+material is shared under a Creative Commons public license or as
+otherwise permitted by the Creative Commons policies published at
+creativecommons.org/policies, Creative Commons does not authorize the
+use of the trademark "Creative Commons" or any other trademark or logo
+of Creative Commons without its prior written consent including,
+without limitation, in connection with any unauthorized modifications
+to any of its public licenses or any other arrangements,
+understandings, or agreements concerning use of licensed material. For
+the avoidance of doubt, this paragraph does not form part of the
+public licenses.
+
+Creative Commons may be contacted at creativecommons.org.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..d7cc76c
--- /dev/null
+++ b/README.md
@@ -0,0 +1,136 @@
+<div align="center">
+
+<img src="./.github/assets/optimizerDuck.png" alt="optimizerDuck Banner" title="optimizerDuck" height="300"/>
+
+# optimizerDuck
+
+**optimizerDuck is a free, open-source Windows optimization tool built for performance, privacy, and simplicity.**
+
+[![Latest Release](https://img.shields.io/github/release/itsfatduck/optimizerDuck?color=f27c13&label=Latest%20Release)](https://github.com/itsfatduck/optimizerDuck/releases/latest)
+[![Downloads](https://img.shields.io/github/downloads/itsfatduck/optimizerDuck/total?color=fed114&label=Downloads)](https://github.com/itsfatduck/optimizerDuck/releases)
+[![License](https://img.shields.io/github/license/itsfatduck/optimizerDuck?color=5cb85c&label=License)](./LICENSE)
+[![Discord](https://img.shields.io/discord/1091675679994675240?color=5865f2&label=Discord)](https://discord.gg/tDUBDCYw9Q)
+<br>
+[![.NET 10.0 RC2](https://img.shields.io/badge/.NET-10.0_RC2-512BD4?logoColor=white)](https://docs.microsoft.com/en-us/dotnet/core/install/windows)
+[![Tested OS](https://img.shields.io/badge/Tested_OS-Windows_10_/_11_x64-0078D6?logoColor=white)](https://www.microsoft.com/en-us/software-download/)
+
+</div>
+
+---
+
+## Download
+
+<img src="./.github/assets/app_screenshot.png" alt="optimizerDuck App Screenshot" title="optimizerDuck App Screenshot" width="1000" />
+
+1. Download the latest release: [Latest Release](https://github.com/itsfatduck/optimizerDuck/releases/latest)
+2. Run the `.exe` file and follow the instructions.
+> **Note:** You may need to restart your PC for some tweaks to take effect.
+---
+
+## What It Actually Does
+
+> **Note:** The list below is a *preview* of what optimizerDuck can do.
+> Features may change, be renamed, or expand over time.
+
+<img src="./.github/assets/app_tweaks.png" alt="optimizerDuck Tweaks" title="optimizerDuck Tweaks (1.0.0)" width="1000" />
+
+* Custom **High Performance** power plan to maintain consistent FPS
+* **GPU process prioritization** and network throttling disabled for real-time apps
+* Disables **USB power saving** to reduce input lag on keyboards and mice
+* Removes **bloatware and background services** you may safely remove
+* Optimizes **visual effects, memory management, and system responsiveness**
+* Disables **telemetry, diagnostics, and advertising data collection**
+* Restores the **classic Windows 10 context menu** for faster access
+* Enables **fast startup, mouse precision, and keyboard response tuning**
+* Disables **annoying pop-ups and notifications** for a distraction-free desktop experience
+* Blocks **Microsoft telemetry and Bing/Cortana integration**
+* Cleans up **Start Menu ads** and configures **Edge browser privacy settings**
+* Provides a **dark, clean, modern terminal interface** built with Spectre.Console
+* Detailed **logging** to track changes and monitor system state
+
+---
+
+## Safety First
+
+<img src="./.github/assets/app_restorepoint.png" alt="optimizerDuck Restore Point" title="optimizerDuck Restore Point" width="1000" />
+
+- **Ask for restore points** before making changes
+- **Modular design** - apply only what you want
+- **Extensive testing** on various hardware configurations
+- **Open source** - you can check every line of code
+- **Manual testing** - All tweaks have been manually tested across multiple hardware configurations
+- **Logging** - Detailed logging file can be found in `%APPDATA%/optimizerDuck/` directory
+
+---
+
+## Mindset Matters
+
+* A powerful PC means little if it's not used efficiently.
+* Real performance isn't just about tweaks or tools — it's about **how you manage your system**.
+
+**Best practices:**
+- Keep your OS lean: avoid unnecessary VPNs, multiple antiviruses, or background apps.
+- When gaming, close what you don't need (browsers, IDEs, chat apps, etc.).
+- Fewer distractions = more resources for what really matters.
+
+---
+
+## Community & Support
+
+- Got questions? Found a bug? Want to suggest a feature?
+
+ - **[Discord Server](https://discord.gg/tDUBDCYw9Q)** - Chat with me and other users
+ - **[GitHub Issues](https://github.com/itsfatduck/optimizerDuck/issues)** - Report bugs or request features
+ - **[GitHub Discussions](https://github.com/itsfatduck/optimizerDuck/discussions)** - Share your optimization results
+
+---
+
+## Contributing
+
+- Found a tweak that should be added? Want to improve the tool?
+
+ - **Fork the repo** and submit a pull request
+ - **Share new optimization ideas** or bug fixes
+ - **Update docs or UI/UX improvements** are always welcome
+
+---
+
+## Acknowledgments
+
+- **[Spectre.Console](https://spectreconsole.net/)** - A modern, cross-platform, and highly customizable terminal interface library for .NET.
+- **[Serilog](https://serilog.net/)** - A flexible logging framework for .NET applications.
+- **[vertical-spectreconsolelogger](https://github.com/verticalsoftware/vertical-spectreconsolelogger/)** - A seriously customizable [Spectre Console](https://spectreconsole.net/) provider for Microsoft.Extensions.Logging.
+- **[WinUtil](https://github.com/ChrisTitusTech/winutil)** - A collection of Windows optimization scripts and tools by Chris Titus Tech.
+- **[Microsoft Docs](https://docs.microsoft.com/en-us/)** - Official documentation for Windows and .NET.
+- And many more open-source contributors who helped make this project possible.
+
+---
+
+## Disclaimer
+
+optimizerDuck is provided "as is", without warranty of any kind.
+By using this tool, you agree that the authors are **not responsible** for any damage, data loss, or issues that may occur.
+Always create a restore point or backup before applying changes.
+
+### DMCA & Attribution Disclaimer
+
+optimizerDuck is an independent open‑source project built from scratch.
+While many tweaks are inspired by community forums and other open‑source projects (such as WinUtil), all code in this repository was written by the author unless otherwise stated.
+
+If you believe any part of this project infringes your copyright, please open an issue or submit a DMCA request via GitHub. We respect intellectual property and will review any valid request promptly.
+
+---
+
+## License
+
+<img src=".github/assets/cc_by_nc_sa_4_0.png" alt="CC BY-NC-SA 4.0 License" title="CC BY-NC-SA 4.0 License" width="400" />
+
+This project is licensed under the [CC BY-NC-SA 4.0 License](https://creativecommons.org/licenses/by-nc-sa/4.0/).<br>see the [LICENSE](./LICENSE) file for details.
+
+---
+
+## Star History
+
+**If optimizerDuck made your PC faster, give it a star! ⭐**<br>It helps more people discover the project and keeps development going.
+
+[![Star History Chart](https://api.star-history.com/svg?repos=itsfatduck/optimizerDuck&type=Date)](https://star-history.com/#itsfatduck/optimizerDuck&Date)
\ No newline at end of file
diff --git a/global.json b/global.json
new file mode 100644
index 0000000..33d0916
--- /dev/null
+++ b/global.json
@@ -0,0 +1,7 @@
+{
+ "sdk": {
+ "version": "10.0.100-rc.2.25502.107",
+ "rollForward": "latestMinor",
+ "allowPrerelease": true
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck.Resources/optimizerDuck.pow b/optimizerDuck.Resources/optimizerDuck.pow
new file mode 100644
index 0000000..f96adc6
Binary files /dev/null and b/optimizerDuck.Resources/optimizerDuck.pow differ
diff --git a/optimizerDuck.Test/PowerShellErrorParserTests.cs b/optimizerDuck.Test/PowerShellErrorParserTests.cs
new file mode 100644
index 0000000..5307491
--- /dev/null
+++ b/optimizerDuck.Test/PowerShellErrorParserTests.cs
@@ -0,0 +1,94 @@
+using optimizerDuck.Core.Extensions;
+
+namespace optimizerDuck.Test;
+
+public class PowerShellErrorParserTests
+{
+ [Fact]
+ public void ParseCliXml_ShouldReturnEmpty_WhenInputIsWhitespace()
+ {
+ var result = " ".ParseCliXml();
+ Assert.Equal(string.Empty, result);
+ }
+
+ [Fact]
+ public void ParseCliXml_ShouldParseSimpleClixml()
+ {
+ var xml = @"#< CLIXML
+<Objs Version='1.1.0.1'>
+ <S>Access is denied</S>
+</Objs>";
+
+ var result = xml.ParseCliXml();
+ Assert.Contains("Access is denied", result);
+ }
+
+ [Fact]
+ public void ParseCliXml_ShouldHandleEncodedNewlines()
+ {
+ var xml = @"#< CLIXML
+<Objs Version='1.1.0.1'>
+ <S>Error_x000D__x000A_Second Line</S>
+</Objs>";
+
+ var result = xml.ParseCliXml();
+ Assert.Contains("Error", result);
+ Assert.Contains("Second Line", result);
+ }
+
+ [Fact]
+ public void ParseCliXml_ShouldHandleListOfObjects()
+ {
+ var xml = @"#< CLIXML
+<Objs Version='1.1.0.1'>
+ <Obj RefId='0'>
+ <TN RefId='0'>
+ <T>System.String</T>
+ </TN>
+ <ToString>First</ToString>
+ </Obj>
+ <Obj RefId='1'>
+ <TN RefId='1'>
+ <T>System.String</T>
+ </TN>
+ <ToString>Second</ToString>
+ </Obj>
+</Objs>";
+
+ var result = xml.ParseCliXml();
+ Assert.Contains("First", result);
+ Assert.Contains("Second", result);
+ }
+
+ [Fact]
+ public void ParseCliXml_ShouldFallback_WhenInvalidXml()
+ {
+ var invalidXml = "<S>Error message missing end tag";
+ var result = invalidXml.ParseCliXml();
+ Assert.Contains("Error message", result);
+ }
+
+ [Fact]
+ public void ParseCliXml_ShouldWrapNonXmlText()
+ {
+ var text = "Access is denied";
+ var result = text.ParseCliXml();
+ Assert.Contains("Access is denied", result);
+ }
+
+ [Fact]
+ public void ParseCliXml_ShouldIgnoreBOM()
+ {
+ var bom = "\uFEFF#< CLIXML<Objs><S>BOM handled</S></Objs>";
+ var result = bom.ParseCliXml();
+ Assert.Contains("BOM handled", result);
+ }
+
+ [Fact]
+ public void ParseCliXml_ShouldReturnEmpty_OnEmptyObjs()
+ {
+ var xml = "#< CLIXML<Objs></Objs>";
+ var result = xml.ParseCliXml();
+ Assert.Equal(string.Empty, result);
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck.Test/RegistryServiceTests.cs b/optimizerDuck.Test/RegistryServiceTests.cs
new file mode 100644
index 0000000..54aada6
--- /dev/null
+++ b/optimizerDuck.Test/RegistryServiceTests.cs
@@ -0,0 +1,132 @@
+using Microsoft.Win32;
+using optimizerDuck.Core.Services;
+using optimizerDuck.Models;
+
+namespace optimizerDuck.Test;
+
+public class RegistryServiceTests
+{
+ [Fact]
+ public void Read()
+ {
+ var pathString =
+ RegistryService.Read<string>(new RegistryItem(
+ @"HKEY_LOCAL_MACHINE\SOFTWARE\dotnet\Setup\InstalledVersions\x64\sharedhost",
+ "Path"));
+ var versionString =
+ RegistryService.Read<string>(new RegistryItem(
+ @"HKEY_LOCAL_MACHINE\SOFTWARE\dotnet\Setup\InstalledVersions\x64\sharedhost",
+ "Version"));
+
+ var binary =
+ RegistryService.Read<byte[]>(new RegistryItem(@"HKEY_LOCAL_MACHINE\SOFTWARE\Logitech\LGHUB\Data",
+ "canary_machine_identifier"));
+
+ Assert.NotNull(pathString);
+ Assert.NotNull(versionString);
+ Assert.NotNull(binary);
+ }
+
+ [Fact]
+ public void Write_And_Read_Back_String_Value()
+ {
+ var testKeyPath = @"HKEY_CURRENT_USER\Software\optimizerDuckTests";
+ var item = new RegistryItem(testKeyPath, "TestString", "hello", RegistryValueKind.String);
+ try
+ {
+ var written = RegistryService.Write(item);
+ Assert.True(written);
+
+ var readBack = RegistryService.Read<string>(new RegistryItem(testKeyPath, "TestString"));
+ Assert.Equal("hello", readBack);
+ }
+ finally
+ {
+ RegistryService.DeleteValue(new RegistryItem(testKeyPath, "TestString"));
+ RegistryService.DeleteSubKey(new RegistryItem(testKeyPath));
+ }
+ }
+
+ [Fact]
+ public void DeleteValue_When_Missing_Is_Treated_As_Success()
+ {
+ var testKeyPath = @"HKEY_CURRENT_USER\Software\optimizerDuckTests_DeleteMissing";
+ try
+ {
+ // Ensure key exists without the value
+ RegistryService.Write(new RegistryItem(testKeyPath, "_bootstrap", 1, RegistryValueKind.DWord));
+ RegistryService.DeleteValue(new RegistryItem(testKeyPath, "_bootstrap"));
+
+ var result = RegistryService.DeleteValue(new RegistryItem(testKeyPath, "DoesNotExist"));
+ Assert.True(result);
+ }
+ finally
+ {
+ RegistryService.DeleteSubKey(new RegistryItem(testKeyPath));
+ }
+ }
+
+ [Fact]
+ public void Write_Creates_SubKey_If_Missing()
+ {
+ var testKeyPath = @"HKEY_CURRENT_USER\Software\optimizerDuckTests_CreateKeyOnWrite\Sub";
+ try
+ {
+ var result = RegistryService.Write(new RegistryItem(testKeyPath, "Flag", 1, RegistryValueKind.DWord));
+ Assert.True(result);
+
+ var readBack = RegistryService.Read<int>(new RegistryItem(testKeyPath, "Flag"));
+ Assert.Equal(1, readBack);
+ }
+ finally
+ {
+ RegistryService.DeleteSubKey(
+ new RegistryItem(@"HKEY_CURRENT_USER\Software\optimizerDuckTests_CreateKeyOnWrite"));
+ }
+ }
+
+ [Fact]
+ public void Read_Converts_Types_When_Possible()
+ {
+ var testKeyPath = @"HKEY_CURRENT_USER\Software\optimizerDuckTests_TypeConversion";
+ try
+ {
+ var writeOk = RegistryService.Write(new RegistryItem(testKeyPath, "Numeric", 123, RegistryValueKind.DWord));
+ Assert.True(writeOk);
+
+ var asString = RegistryService.Read<string>(new RegistryItem(testKeyPath, "Numeric"));
+ Assert.Equal("123", asString);
+
+ var asLong = RegistryService.Read<long>(new RegistryItem(testKeyPath, "Numeric"));
+ Assert.Equal(123L, asLong);
+ }
+ finally
+ {
+ RegistryService.DeleteSubKey(new RegistryItem(testKeyPath));
+ }
+ }
+
+ [Fact]
+ public void DeleteSubKey_Removes_Entire_Tree()
+ {
+ var basePath = @"HKEY_CURRENT_USER\Software\optimizerDuckTests_DeleteTree";
+ var childPath = basePath + "\\Child";
+ try
+ {
+ // Create nested structure
+ Assert.True(RegistryService.Write(new RegistryItem(childPath, "Leaf", "x", RegistryValueKind.String)));
+
+ // Delete base should remove child
+ Assert.True(RegistryService.DeleteSubKey(new RegistryItem(basePath)));
+
+ // Verify
+ var existsAfter = RegistryService.Read<string>(new RegistryItem(childPath, "Leaf"));
+ Assert.Null(existsAfter);
+ }
+ finally
+ {
+ // Ensure cleanup if anything left
+ RegistryService.DeleteSubKey(new RegistryItem(basePath));
+ }
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck.Test/optimizerDuck.Test.csproj b/optimizerDuck.Test/optimizerDuck.Test.csproj
new file mode 100644
index 0000000..941fa17
--- /dev/null
+++ b/optimizerDuck.Test/optimizerDuck.Test.csproj
@@ -0,0 +1,31 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <TargetFramework>net10.0</TargetFramework>
+ <ImplicitUsings>enable</ImplicitUsings>
+ <Nullable>enable</Nullable>
+ <IsPackable>false</IsPackable>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <PackageReference Include="coverlet.collector" Version="6.0.4">
+ <PrivateAssets>all</PrivateAssets>
+ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
+ </PackageReference>
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.0.0"/>
+ <PackageReference Include="xunit" Version="2.9.3"/>
+ <PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
+ <PrivateAssets>all</PrivateAssets>
+ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
+ </PackageReference>
+ </ItemGroup>
+
+ <ItemGroup>
+ <Using Include="Xunit"/>
+ </ItemGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\optimizerDuck\optimizerDuck.csproj"/>
+ </ItemGroup>
+
+</Project>
diff --git a/optimizerDuck.sln b/optimizerDuck.sln
new file mode 100644
index 0000000..5a889d4
--- /dev/null
+++ b/optimizerDuck.sln
@@ -0,0 +1,38 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 18
+VisualStudioVersion = 18.0.11111.16
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "optimizerDuck", "optimizerDuck\optimizerDuck.csproj", "{B4F29678-908B-4259-BB38-CC786052AA65}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "optimizerDuck.Test", "optimizerDuck.Test\optimizerDuck.Test.csproj", "{CF555C17-30D3-4BF0-BA11-D849EF792AA6}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{C3459623-250A-48CB-95E1-8EDFC95BB129}"
+ ProjectSection(SolutionItems) = preProject
+ .editorconfig = .editorconfig
+ EndProjectSection
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug --restart|Any CPU = Debug --restart|Any CPU
+ Debug|Any CPU = Debug|Any CPU
+ Release|Any CPU = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {B4F29678-908B-4259-BB38-CC786052AA65}.Debug --restart|Any CPU.ActiveCfg = Debug --restart|Any CPU
+ {B4F29678-908B-4259-BB38-CC786052AA65}.Debug --restart|Any CPU.Build.0 = Debug --restart|Any CPU
+ {B4F29678-908B-4259-BB38-CC786052AA65}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {B4F29678-908B-4259-BB38-CC786052AA65}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {B4F29678-908B-4259-BB38-CC786052AA65}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {B4F29678-908B-4259-BB38-CC786052AA65}.Release|Any CPU.Build.0 = Release|Any CPU
+ {CF555C17-30D3-4BF0-BA11-D849EF792AA6}.Debug --restart|Any CPU.ActiveCfg = Debug|Any CPU
+ {CF555C17-30D3-4BF0-BA11-D849EF792AA6}.Debug --restart|Any CPU.Build.0 = Debug|Any CPU
+ {CF555C17-30D3-4BF0-BA11-D849EF792AA6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {CF555C17-30D3-4BF0-BA11-D849EF792AA6}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {CF555C17-30D3-4BF0-BA11-D849EF792AA6}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {CF555C17-30D3-4BF0-BA11-D849EF792AA6}.Release|Any CPU.Build.0 = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+EndGlobal
diff --git a/optimizerDuck/Logo.ico b/optimizerDuck/Logo.ico
new file mode 100644
index 0000000..e434f76
Binary files /dev/null and b/optimizerDuck/Logo.ico differ
diff --git a/optimizerDuck/Program.cs b/optimizerDuck/Program.cs
new file mode 100644
index 0000000..ef261a8
--- /dev/null
+++ b/optimizerDuck/Program.cs
@@ -0,0 +1,230 @@
+using System.Text;
+using Microsoft.Extensions.Logging;
+using optimizerDuck.Core;
+using optimizerDuck.Core.Extensions;
+using optimizerDuck.Core.Helpers;
+using optimizerDuck.Core.Managers;
+using optimizerDuck.Core.Services;
+using optimizerDuck.UI;
+using optimizerDuck.UI.Components;
+using optimizerDuck.UI.Logger;
+using Spectre.Console;
+
+namespace optimizerDuck;
+
+/*
+⠀⠀⠀⠀⠀⢀⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
+⠀⠀⠀⠀⠀⣸⣿⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
+⠀⠀⠀⠀⢠⡟⠘⣷⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
+⠀⠀⠀⢰⡟⠀⠀⠈⠻⣷⣤⣤⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
+⠀⠀⣠⡟⠀⠀⠀⠀⠀⠈⢻⡿⣷⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
+⠀⣰⡟⠀⠀⠀⠀⠀⠀⠀⠀⠻⠸⣷⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
+⢰⡏⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢹⣇⠀⣠⣄⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⣀⠀⠀⠀⠀⠀⠀⠀
+⣾⡁⢀⣠⠴⠒⠲⣤⣠⠶⠋⠳⣤⣸⣿⣰⣿⣿⣿⣷⣄⠀⠀⠀⠀⠀⠀⠀⠀⣠⣾⣿⣿⣿⡄⠀⠀⠀⠀⠀⠀
+⣿⠟⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⣽⠏⣿⡿⢿⣿⣿⣿⣷⣄⠀⠀⠀⠀⢠⣾⣿⣿⣿⠋⢹⡇⠀⠀⠀⠀⠀⠀
+⢹⡆⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣰⡟⠀⣿⠁⠀⠙⣿⡛⠛⢿⡶⠶⠶⠶⣿⣄⣀⣰⠃⠀⢸⡇⠀⠀⠀⠀⠀⠀
+⠈⢷⡀⠀⠀⠀⠀⠀⠀⠀⠀⢰⡿⠁⠀⣿⠀⠀⠀⠈⢷⡀⠘⠛⠀⠀⠀⠀⠈⠉⠳⣄⠀⢸⡇⠀⠀⠀⠀⠀⠀
+⠀⠈⢿⣦⡀⠀⠀⠀⠀⠀⢀⣿⣇⣀⠀⢻⠀⠀⠀⠀⢰⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠳⣾⠃⠀⣤⣤⣄⠀⠀
+⠀⠀⠀⠉⠻⢶⣄⣠⣴⠞⠛⠉⠉⠙⠻⢾⣇⠀⢀⣰⠏⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⡄⠀⣿⢩⡿⣿⡆
+⠀⠀⠀⠀⣠⣴⠟⠉⠀⠀⠀⠀⠀⠀⠀⠀⢹⡷⠞⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⡇⠀⣿⣟⣵⡿⠁
+⠀⢀⣠⡾⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣇⠀⠀⠀⣴⣿⠀⠀⠀⠀⠀⠀⢠⣶⠀⠀⣸⡇⠀⠙⠋⠁⠀⠀
+⢸⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⣿⣄⣈⣀⣙⣁⠀⠀⣶⣾⡶⠀⠻⠿⠀⢠⣿⣁⡀⠀⠀⠀⠀⠀
+⠈⠛⠻⠿⠶⠶⠶⡤⣤⣤⣤⣄⣀⣤⣀⣠⣤⣀⣀⣹⣿⣿⣿⣿⣤⣽⣿⣴⣶⣶⡦⢼⣿⣿⣿⣿⠇⠀⠀⠀⠀
+*/
+/// <summary>
+/// I started this project on Oct 16, 2025 btw
+/// </summary>
+internal class Program
+{
+ private static readonly ILogger Log = Logger.CreateLogger<Program>();
+ private OptimizationManager? _optimizer;
+ private SystemSnapshot _systemSnapshot = null!;
+
+ private async Task Init()
+ {
+ RequirementChecker.Restart();
+
+ SystemHelper.Title("Initializing");
+ if (!RequirementChecker.IsAdmin())
+ {
+ Log.LogWarning("Application is not running with administrator privileges.");
+ PromptDialog.Warning(
+ "Administrator Privileges Required",
+ $"""
+ The first initialization to run as admin and maximized seems to have [{Theme.Error}]failed[/].
+ Please restart to grant administrator privileges and ensure the application is maximized.
+ [{Theme.Muted}]You can continue if you have already confirmed your administrator status.[/]
+ """,
+ new PromptOption("Restart", Theme.Warning, () => RequirementChecker.Restart(true)),
+ new PromptOption("Continue anyways", Theme.Success)
+ );
+ }
+
+
+ await AnsiConsole.Status()
+ .Spinner(Spinner.Known.BouncingBar)
+ .SpinnerStyle($"bold {Theme.Primary}")
+ .StartAsyncGlobal("Checking for exclusions...", async ctx =>
+ {
+ Log.LogInformation("Checking for exclusions...");
+ var exclusions = SystemHelper.CheckForExclusions();
+ if (exclusions.Count != 0)
+ PromptDialog.Warning("Missing Anti-Malware Exclusions",
+ $"""
+ Do you want to add [{Theme.Primary}]{string.Join($"[/], [{Theme.Primary}]", exclusions)}[/] to the exclusion list?
+ This will help reduce the chances of errors caused by [{Theme.Error}]antivirus blocking[/].
+ """,
+ new PromptOption("Add", Theme.Success, () =>
+ {
+ ctx.Status("Adding exclusions...");
+ SystemHelper.AddToExclusions(exclusions);
+ }),
+ new PromptOption("Skip", Theme.Error));
+
+ ctx.Status("Fetching system information...");
+ Log.LogInformation("Fetching system information...");
+ _systemSnapshot = await SystemInfoService.RefreshAsync().ConfigureAwait(false);
+
+ Log.LogDebug("=== System Information ===");
+ SystemInfoService.GetSummary(_systemSnapshot, Log);
+ Log.LogDebug("==========================");
+
+ ctx.Status("Checking and creating necessary paths...");
+ Log.LogInformation("Checking and creating necessary paths...");
+ SystemHelper.EnsureDirectoriesExists();
+
+ ctx.Status("Checking system requirements...");
+ Log.LogInformation("Checking system requirements...");
+ RequirementChecker.ValidateSystemRequirements(_systemSnapshot);
+
+ ctx.Status("Initialization completed successfully.");
+ Log.LogInformation($"[{Theme.Success}]Initialization completed successfully.[/]");
+ });
+ }
+
+ private async Task Start()
+ {
+ while (true)
+ {
+ SystemHelper.Title(
+ $"{_systemSnapshot.Os.Name} {_systemSnapshot.Os.Edition} ({_systemSnapshot.Os.Architecture})");
+ AnsiConsole.Clear();
+ AnsiConsole.Write(Defaults.Logo);
+
+ AnsiConsole.WriteLine();
+
+ var start = Align.Center(
+ new PromptPanel('E', "Start Optimization",
+ $"""
+ [bold]Customize your optimization process.[/]
+ Review available tweaks, select what fits your needs,
+ and apply them to fine-tune the system.
+
+ [bold {Theme.Warning}]Some changes may require a restart.[/]
+ [dim white]Network connectivity might be needed for certain tweaks.[/]
+ """,
+ Theme.Primary,
+ CustomBoxBorder.LeftBorder).Build()
+ );
+
+ var middlePanels = Align.Center(
+ new Columns(
+ new PromptPanel('D', "Join our Discord",
+ $"""
+ [bold]{Emoji.Known.SpeechBalloon} Get help, share ideas, and stay updated.[/]
+ Connect with the community and the dev team directly.
+ """,
+ Theme.Info,
+ CustomBoxBorder.UnderlineBorder).Build(),
+ new PromptPanel('G', "GitHub",
+ $"""
+ [bold]{Emoji.Known.Laptop} Explore the source code and releases.[/]
+ Contribute, report issues, or check for the latest updates.
+ """,
+ "white",
+ CustomBoxBorder.UnderlineBorder).Build(),
+ new PromptPanel('I', "System Information",
+ $"""
+ [bold]{Emoji.Known.Gear} View system information.[/]
+ Review detailed system information and diagnostics.
+ """,
+ Theme.Accent,
+ CustomBoxBorder.UnderlineBorder).Build()
+ )
+ { Expand = false }
+ );
+ AnsiConsole.Write(start);
+ AnsiConsole.Write(middlePanels);
+
+ AnsiConsole.WriteLine();
+
+ while (true)
+ {
+ Console.CursorVisible = false;
+ var option = Console.ReadKey(true).KeyChar;
+ Console.CursorVisible = true;
+
+ if (option == 'e')
+ {
+ _optimizer ??= new OptimizationManager(_systemSnapshot);
+ if (await _optimizer.Begin().ConfigureAwait(false))
+ if (await OptimizationManager.RestorePoint().ConfigureAwait(false))
+ await _optimizer.Run().ConfigureAwait(false);
+
+ break;
+ }
+
+ if (option == 'd')
+ {
+ SystemHelper.OpenWebsite(Defaults.DiscordInvite);
+ break;
+ }
+
+ if (option == 'g')
+ {
+ SystemHelper.OpenWebsite(Defaults.GitHubRepo);
+ break;
+ }
+
+ if (option == 'i')
+ {
+ Log.LogInformation("Refreshing System Information...");
+ _systemSnapshot = await SystemInfoService.RefreshAsync().ConfigureAwait(false);
+
+ AnsiConsole.Clear();
+ AnsiConsole.Write(Defaults.Logo);
+ AnsiConsole.Write(SystemInfoService.GetDetailedPanel(_systemSnapshot));
+ AnsiConsole.Write(
+ Align.Center(
+ new Markup("[dim]Press any key to go back to the main menu.[/]"),
+ VerticalAlignment.Middle)
+ );
+ Console.ReadKey();
+ break;
+ }
+ }
+ }
+ }
+
+ private static async Task Main(string[] _)
+ {
+ try
+ {
+ Console.OutputEncoding =
+ Encoding.UTF8; // idk why, but it will fix some ansi issues of spectre console
+
+ AnsiConsole.Clear();
+ AnsiConsole.Write(Defaults.Logo);
+
+ var app = new Program();
+ await app.Init().ConfigureAwait(false);
+ await app.Start().ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ Log.LogCritical(ex, $"[{Theme.Error}]Fatal error![/]");
+ PromptDialog.Exception(ex, "Fatal Error",
+ "An unexpected error occurred while running the application.");
+ }
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck/Properties/launchSettings.json b/optimizerDuck/Properties/launchSettings.json
new file mode 100644
index 0000000..e37d031
--- /dev/null
+++ b/optimizerDuck/Properties/launchSettings.json
@@ -0,0 +1,11 @@
+{
+ "profiles": {
+ "optimizerDuck": {
+ "commandName": "Project"
+ },
+ "WithRestartArgument": {
+ "commandName": "Project",
+ "commandLineArgs": "--restart"
+ }
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck/app.manifest b/optimizerDuck/app.manifest
new file mode 100644
index 0000000..4dd6020
--- /dev/null
+++ b/optimizerDuck/app.manifest
@@ -0,0 +1,79 @@
+<?xml version="1.0" encoding="utf-8"?>
+<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
+ <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
+ <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
+ <security>
+ <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
+ <!-- UAC Manifest Options
+ If you want to change the Windows User Account Control level replace the
+ requestedExecutionLevel node with one of the following.
+
+ <requestedExecutionLevel level="asInvoker" uiAccess="false" />
+ <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
+ <requestedExecutionLevel level="highestAvailable" uiAccess="false" />
+
+ Specifying requestedExecutionLevel element will disable file and registry virtualization.
+ Remove this element if your application requires this virtualization for backwards
+ compatibility.
+ -->
+ <requestedExecutionLevel level="requireAdministrator" uiAccess="false"/>
+ </requestedPrivileges>
+ </security>
+ </trustInfo>
+
+ <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
+ <application>
+ <!-- A list of the Windows versions that this application has been tested on
+ and is designed to work with. Uncomment the appropriate elements
+ and Windows will automatically select the most compatible environment. -->
+
+ <!-- Windows Vista -->
+ <!--<supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />-->
+
+ <!-- Windows 7 -->
+ <!--<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />-->
+
+ <!-- Windows 8 -->
+ <!--<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />-->
+
+ <!-- Windows 8.1 -->
+ <!--<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />-->
+
+ <!-- Windows 10 -->
+ <!--<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />-->
+
+ </application>
+ </compatibility>
+
+ <!-- Indicates that the application is DPI-aware and will not be automatically scaled by Windows at higher
+ DPIs. Windows Presentation Foundation (WPF) applications are automatically DPI-aware and do not need
+ to opt in. Windows Forms applications targeting .NET Framework 4.6 that opt into this setting, should
+ also set the 'EnableWindowsFormsHighDpiAutoResizing' setting to 'true' in their app.config.
+
+ Makes the application long-path aware. See https://docs.microsoft.com/windows/win32/fileio/maximum-file-path-limitation -->
+ <!--
+ <application xmlns="urn:schemas-microsoft-com:asm.v3">
+ <windowsSettings>
+ <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
+ <longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
+ </windowsSettings>
+ </application>
+ -->
+
+ <!-- Enable themes for Windows common controls and dialogs (Windows XP and later) -->
+ <!--
+ <dependency>
+ <dependentAssembly>
+ <assemblyIdentity
+ type="win32"
+ name="Microsoft.Windows.Common-Controls"
+ version="6.0.0.0"
+ processorArchitecture="*"
+ publicKeyToken="6595b64144ccf1df"
+ language="*"
+ />
+ </dependentAssembly>
+ </dependency>
+ -->
+
+</assembly>
diff --git a/optimizerDuck/optimizerDuck.csproj b/optimizerDuck/optimizerDuck.csproj
new file mode 100644
index 0000000..d6f5cf0
--- /dev/null
+++ b/optimizerDuck/optimizerDuck.csproj
@@ -0,0 +1,38 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <OutputType>Exe</OutputType>
+ <TargetFramework>net10.0</TargetFramework>
+ <ImplicitUsings>enable</ImplicitUsings>
+ <Nullable>enable</Nullable>
+ <LangVersion>preview</LangVersion>
+ <ApplicationIcon>Logo.ico</ApplicationIcon>
+ <Configurations>Debug;Release</Configurations>
+ <ApplicationManifest>app.manifest</ApplicationManifest>
+ <FileVersion>1.0.0</FileVersion>
+ <NeutralLanguage>en</NeutralLanguage>
+ </PropertyGroup>
+
+ <PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
+ <PlatformTarget>x64</PlatformTarget>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="9.0.10"/>
+ <PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.10"/>
+ <PackageReference Include="Microsoft.PowerShell.SDK" Version="7.5.4"/>
+ <PackageReference Include="Newtonsoft.Json" Version="13.0.4"/>
+ <PackageReference Include="Serilog" Version="4.3.1-dev-02387"/>
+ <PackageReference Include="Serilog.Extensions.Logging" Version="9.0.2"/>
+ <PackageReference Include="Serilog.Sinks.File" Version="7.0.0"/>
+ <PackageReference Include="Spectre.Console" Version="0.53.0"/>
+ <PackageReference Include="System.Management" Version="9.0.10"/>
+ <PackageReference Include="System.ServiceProcess.ServiceController" Version="9.0.10"/>
+ <PackageReference Include="vertical-spectreconsolelogger" Version="0.10.1-dev.20241201.35"/>
+ </ItemGroup>
+
+ <ItemGroup>
+ <Content Include=".github\.assets\optimizerDuck.png"/>
+ </ItemGroup>
+
+</Project>
diff --git a/optimizerDuck/src/Core/Defaults.cs b/optimizerDuck/src/Core/Defaults.cs
new file mode 100644
index 0000000..394873d
--- /dev/null
+++ b/optimizerDuck/src/Core/Defaults.cs
@@ -0,0 +1,123 @@
+using System.Diagnostics;
+using optimizerDuck.UI;
+using optimizerDuck.UI.Components;
+using Spectre.Console;
+
+namespace optimizerDuck.Core;
+
+public static class Defaults
+{
+ public const string RawLogo = """
+ _ _ _ _____ _
+ | | (_) (_) | __ \ | |
+ ___ _ __ | |_ _ _ __ ___ _ _______ _ __| | | |_ _ ___| | __
+ / _ \| '_ \| __| | '_ ` _ \| |_ / _ \ '__| | | | | | |/ __| |/ /
+ | (_) | |_) | |_| | | | | | | |/ / __/ | | |__| | |_| | (__| <
+ \___/| .__/ \__|_|_| |_| |_|_/___\___|_| |_____/ \__,_|\___|_|\_\
+ | |
+ |_|
+ """;
+
+ public const string
+ EscapeCancellableConsoleMultiSelectionPromptInstructionsText // ok
+ = $"""
+ [grey](Use [{Theme.Primary}]↑ ↓[/] to navigate)[/]
+ [grey](Press [{Theme.Info}]<space>[/] to toggle an option, [{Theme.Success}]<enter>[/] to continue)[/]
+ [grey][[[{Theme.Error}]CTRL + C[/] or [{Theme.Error}]Escape[/] to go back to previous menu]][/]
+ """;
+
+ public const string DiscordInvite = "https://discord.gg/tDUBDCYw9Q";
+ public const string GitHubRepo = "https://github.com/itsfatduck/optimizerDuck";
+
+ public const string ZwtDownloadUrl =
+ "https://github.com/LuSlower/ZwTimerResolution/releases/download/0.0.0.6/ZwTimer.exe";
+
+ public const string PowerPlanUrl = "https://github.com/itsfatduck/optimizerDuck/raw/refs/heads/master/optimizerDuck.Resources/optimizerDuck.pow";
+
+ public const string RestorePointName = "optimizerDuck Restore Point";
+ public const string PowerPlanGUID = "946c0ca5-6ee0-4f2a-9dd7-7addbb8e60f5";
+
+ public static readonly Panel Logo = new(
+ new Align(
+ // @formatter:off
+ new Markup(
+ $"""
+ [{Theme.Secondary}] _ _ _ [/][{Theme.Accent}] _____ _ [/]
+ [{Theme.Secondary}] | | (_) (_) [/][{Theme.Accent}]| __ \ | | [/]
+ [{Theme.Secondary}] ___ _ __ | |_ _ _ __ ___ _ _______ _ __[/][{Theme.Accent}]| | | |_ _ ___| | __[/]
+ [{Theme.Secondary}] / _ \| '_ \| __| | '_ ` _ \| |_ / _ \ '__[/][{Theme.Accent}]| | | | | | |/ __| |/ /[/]
+ [{Theme.Secondary}] | (_) | |_) | |_| | | | | | | |/ / __/ | [/][{Theme.Accent}]| |__| | |_| | (__| < [/]
+ [{Theme.Secondary}] \___/| .__/ \__|_|_| |_| |_|_/___\___|_| [/][{Theme.Accent}]|_____/ \__,_|\___|_|\_\[/]
+ [{Theme.Secondary}] | | [/]
+ [{Theme.Secondary}] |_| [/]
+ """),
+ // @formatter:on
+ HorizontalAlignment.Center
+ ))
+ { Border = CustomBoxBorder.UnderlineBorder, Padding = new Padding(0, 1, 0, 1) };
+
+ private static readonly string ExePath = Environment.ProcessPath!;
+ public static readonly string ExeDir = Path.GetDirectoryName(ExePath)!;
+ public static readonly string FileVersion = FileVersionInfo.GetVersionInfo(ExePath).FileVersion!;
+
+ public static readonly string RootPath =
+ Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "optimizerDuck");
+
+ public static readonly string ResourcesPath =
+ Path.Combine(RootPath, "Resources");
+
+ public static readonly Dictionary<string, string> SAFE_APPS = new()
+ {
+ ["BingWeather"] = "Weather",
+ ["GetHelp"] = "Get Help",
+ ["Getstarted"] = "Get Started / Tips",
+ ["Messaging"] = "Messaging",
+ ["Microsoft3DViewer"] = "3D Viewer",
+ ["MicrosoftSolitaireCollection"] = "Solitaire Collection",
+ ["MicrosoftStickyNotes"] = "Sticky Notes",
+ ["MixedReality.Portal"] = "Mixed Reality Portal",
+ ["OneConnect"] = "OneConnect (Connect App)",
+ ["People"] = "People",
+ ["Print3D"] = "Print 3D",
+ ["SkypeApp"] = "Skype",
+ ["WindowsAlarms"] = "Alarms & Clock",
+ ["WindowsCamera"] = "Camera",
+ ["WindowsMaps"] = "Maps",
+ ["WindowsFeedbackHub"] = "Feedback Hub",
+ ["WindowsSoundRecorder"] = "Voice Recorder",
+ ["YourPhone"] = "Phone Link",
+ ["ZuneMusic"] = "Media Player / Groove",
+ ["Sway"] = "Microsoft Sway",
+ ["3dBuilder"] = "3D Builder (legacy)",
+ ["bing"] = "Microsoft Bing (everything)",
+ ["Drawboard PDF"] = "Drawboard PDF (OEM)",
+ ["WindowsPhone"] = "Windows Phone (old)",
+ ["CommsPhone"] = "Communications Phone (old)",
+ ["Microsoft.Todos"] = "Microsoft To Do",
+ ["windowscommunicationsapps"] = "Mail and Calendar",
+ ["MicrosoftCorporationII.QuickAssist"] = "Quick Assist"
+ };
+
+ public static readonly Dictionary<string, string> CAUTION_APPS = new()
+ {
+ ["WindowsCalculator"] = "Calculator",
+ ["Microsoft.Windows.Photos"] = "Photos",
+ ["Microsoft.MSPaint"] = "Paint",
+ ["Microsoft.Paint3D"] = "Paint 3D",
+ ["Microsoft.ScreenSketch"] = "Snip & Sketch",
+ ["MicrosoftWindows.Client.SnippingTool"] = "Snipping Tool",
+ ["Microsoft.WindowsStore"] = "Microsoft Store",
+ ["Microsoft.XboxIdentityProvider"] = "Xbox Identity Provider",
+ ["Microsoft.WindowsTerminal"] = "Windows Terminal",
+ ["Clipchamp.Clipchamp"] = "Clipchamp (Video Editor)",
+ ["MicrosoftWindows.Notepad"] = "Notepad",
+ // Extensions
+ ["HEIFImageExtension"] = "HEIF Image Extension",
+ ["WebMediaExtensions"] = "Web Media Extensions",
+ ["WebpImageExtension"] = "WebP Image Extension",
+ // Xbox / Game Bar
+ ["Microsoft.XboxGamingOverlay"] = "Xbox Game Bar",
+ ["Microsoft.XboxApp"] = "Xbox App (Console Companion)",
+ ["Microsoft.Xbox.TCUI"] = "Xbox TCUI"
+ };
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/Core/Extensions/StatusExtensions.cs b/optimizerDuck/src/Core/Extensions/StatusExtensions.cs
new file mode 100644
index 0000000..5b370de
--- /dev/null
+++ b/optimizerDuck/src/Core/Extensions/StatusExtensions.cs
@@ -0,0 +1,63 @@
+using optimizerDuck.UI.Logger;
+using Spectre.Console;
+
+namespace optimizerDuck.Core.Extensions;
+
+public static class StatusExtensions
+{
+ public static void StartGlobal(this Status status,
+ string message,
+ Action<StatusContext> action)
+ {
+ var task = status.StartAsync(message, ctx =>
+ {
+ GlobalStatus.Current = ctx;
+ action(ctx);
+ return Task.CompletedTask;
+ });
+
+ task.GetAwaiter().GetResult();
+ }
+
+ public static T StartGlobal<T>(
+ this Status status,
+ string message,
+ Func<StatusContext, T> func)
+ {
+ return status.Start(message, ctx =>
+ {
+ GlobalStatus.Current = ctx;
+ return func(ctx);
+ });
+ }
+
+ public static async Task StartAsyncGlobal(
+ this Status status,
+ string message,
+ Func<StatusContext, Task> action)
+ {
+ ArgumentNullException.ThrowIfNull(status);
+
+ _ = await status.StartAsync<object?>(message, async ctx =>
+ {
+ GlobalStatus.Current = ctx;
+ await action(ctx).ConfigureAwait(false);
+ return null;
+ }).ConfigureAwait(false);
+ }
+
+ public static async Task<T> StartAsyncGlobal<T>(
+ this Status status,
+ string message,
+ Func<StatusContext, Task<T>> func)
+ {
+ ArgumentNullException.ThrowIfNull(status);
+ ArgumentNullException.ThrowIfNull(func);
+
+ return await status.StartAsync<T>(message, async ctx =>
+ {
+ GlobalStatus.Current = ctx;
+ return await func(ctx).ConfigureAwait(false);
+ }).ConfigureAwait(false);
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/Core/Extensions/TextExtensions.cs b/optimizerDuck/src/Core/Extensions/TextExtensions.cs
new file mode 100644
index 0000000..055998f
--- /dev/null
+++ b/optimizerDuck/src/Core/Extensions/TextExtensions.cs
@@ -0,0 +1,108 @@
+using System.Management.Automation;
+using System.Text;
+using System.Xml.Linq;
+
+namespace optimizerDuck.Core.Extensions;
+
+public static class TextExtensions
+{
+ public static string LimitWidth(this string text, int maxWidth, bool wrap = true)
+ {
+ if (string.IsNullOrEmpty(text))
+ return text;
+
+ if (!wrap)
+ return text.Length <= maxWidth ? text : text[..(maxWidth - 1)] + "…";
+
+ var words = text.Split(' ', StringSplitOptions.RemoveEmptyEntries);
+ var sb = new StringBuilder();
+ var line = new StringBuilder();
+
+ foreach (var word in words)
+ {
+ // Check if adding the next word (plus a space if needed) would exceed the max width.
+ // If yes, finalize the current line and start a new one.
+ if (line.Length + word.Length + 1 > maxWidth)
+ if (line.Length > 0)
+ {
+ sb.AppendLine(line.ToString().TrimEnd());
+ line.Clear();
+ }
+
+ line.Append(word).Append(' ');
+ }
+
+ // Trim the trailing space from the last word before appending the line.
+ if (line.Length > 0)
+ sb.Append(line.ToString().TrimEnd());
+
+ return sb.ToString();
+ }
+
+ public static string DecodeBase64(this string value)
+ {
+ if (string.IsNullOrWhiteSpace(value))
+ return value;
+
+ Span<byte> buffer = new byte[value.Length];
+ return Convert.TryFromBase64String(value, buffer, out var bytesWritten)
+ ? Encoding.Unicode.GetString(buffer[..bytesWritten])
+ : string.Empty;
+ }
+
+ public static string ParseCliXml(this string? cliXml)
+ {
+ if (string.IsNullOrWhiteSpace(cliXml))
+ return string.Empty;
+
+ var cleaned = cliXml
+ .Replace("#< CLIXML", string.Empty)
+ .Replace("< CLIXML", string.Empty)
+ .TrimStart('\uFEFF', '\r', '\n', ' ', '\t')
+ .Replace("_x000D__x000A_", "\n");
+
+ if (!cleaned.StartsWith("<Objs", StringComparison.OrdinalIgnoreCase))
+ cleaned = "<Objs>" + cleaned + "</Objs>";
+
+ try
+ {
+ var deserialized = PSSerializer.Deserialize(cleaned);
+
+ return deserialized switch
+ {
+ IEnumerable<object> list => string.Join(Environment.NewLine,
+ list.Where(o => o != null).Select(o => o.ToString()?.Trim() ?? string.Empty)),
+ _ => deserialized?.ToString()?.Trim() ?? string.Empty
+ };
+ }
+ catch
+ {
+ return cleaned.ExtractRawText();
+ }
+ }
+
+ private static string ExtractRawText(this string xml)
+ {
+ try
+ {
+ var doc = XDocument.Parse(xml);
+ var tags = new[] { "S", "E", "L", "ToString" };
+
+ var values = doc.Descendants()
+ .Where(x => tags.Contains(x.Name.LocalName))
+ .Select(x => x.Value.Trim())
+ .ToList();
+
+ if (values.Count == 0)
+ values.Add(doc.Root?.Value?.Trim() ?? string.Empty);
+
+ return string.Join(Environment.NewLine, values)
+ .Replace("_x000D__x000A_", "\n")
+ .Trim();
+ }
+ catch
+ {
+ return xml;
+ }
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/Core/Helpers/ReflectionHelper.cs b/optimizerDuck/src/Core/Helpers/ReflectionHelper.cs
new file mode 100644
index 0000000..7675984
--- /dev/null
+++ b/optimizerDuck/src/Core/Helpers/ReflectionHelper.cs
@@ -0,0 +1,44 @@
+using System.Reflection;
+using optimizerDuck.Core.Managers;
+
+namespace optimizerDuck.Core.Helpers;
+
+public static class ReflectionHelper
+{
+ private static IEnumerable<Type> SafeGetTypes(Assembly asm)
+ {
+ try
+ {
+ return asm.GetTypes();
+ }
+ catch (ReflectionTypeLoadException ex)
+ {
+ // return only the types that were loaded successfully
+ return ex.Types.Where(t => t != null)!;
+ }
+ catch
+ {
+ return [];
+ }
+ }
+
+ public static IEnumerable<Type> FindImplementationsInLoadedAssemblies(Type interfaceType)
+ {
+ if (!interfaceType.IsInterface)
+ throw new ArgumentException("interfaceType must be an interface", nameof(interfaceType));
+
+ return CacheManager.GetOrCreate(interfaceType.FullName!, entry =>
+ {
+ entry.SlidingExpiration = TimeSpan.FromMinutes(5);
+ return AppDomain.CurrentDomain.GetAssemblies()
+ .SelectMany(SafeGetTypes)
+ .Where(t => t != interfaceType && t.IsClass && !t.IsAbstract && interfaceType.IsAssignableFrom(t))
+ .ToList();
+ });
+ }
+
+ public static IEnumerable<Type> FindImplementationsInLoadedAssemblies<TInterface>()
+ {
+ return FindImplementationsInLoadedAssemblies(typeof(TInterface));
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/Core/Helpers/RequirementChecker.cs b/optimizerDuck/src/Core/Helpers/RequirementChecker.cs
new file mode 100644
index 0000000..dacaf97
--- /dev/null
+++ b/optimizerDuck/src/Core/Helpers/RequirementChecker.cs
@@ -0,0 +1,123 @@
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Security.Principal;
+using Microsoft.Extensions.Logging;
+using optimizerDuck.Core.Services;
+using optimizerDuck.UI;
+using optimizerDuck.UI.Components;
+using optimizerDuck.UI.Logger;
+
+namespace optimizerDuck.Core.Helpers;
+
+public static class RequirementChecker
+{
+ private static readonly ILogger Log = Logger.CreateLogger(typeof(RequirementChecker));
+
+ public static bool IsAdmin()
+ {
+ using var identity = WindowsIdentity.GetCurrent();
+ var principal = new WindowsPrincipal(identity);
+ return principal.IsInRole(WindowsBuiltInRole.Administrator);
+ }
+
+ public static void ValidateSystemRequirements(SystemSnapshot s)
+ {
+ if (!OperatingSystem.IsWindows())
+ {
+ Log.LogWarning("Unsupported operating system.");
+
+ PromptDialog.Warning(
+ "Unsupported Operating System",
+ """
+ Currently, this optimizer doesn't support non-Windows operating systems.
+ Please use a supported version of Windows to continue.
+ """,
+ new PromptOption("Exit", Theme.Error, () => Environment.Exit(1))
+ );
+ }
+
+ if (int.TryParse(s.Os.Version, out var version) && version < 10) // only >= Windows 10 supported
+ {
+ Log.LogWarning("Unsupported operating system.");
+
+ PromptDialog.Warning(
+ "Unsupported Operating System",
+ $"""
+ Your operating system version [{Theme.Error}]{s.Os.Version}[/] is not supported.
+ Please upgrade to Windows 10 or later to use this application.
+ [{Theme.WarningMuted}]If you still want to continue, you can choose to do so, but keep in mind that some features may not work as expected.[/]
+ """,
+ new PromptOption("Exit", Theme.Error, () => Environment.Exit(1)),
+ new PromptOption("Continue anyways", Theme.Warning)
+ );
+ }
+
+ if (!Environment.Is64BitOperatingSystem) // only 64-bit supported
+ {
+ Log.LogWarning("Unsupported operating system architecture.");
+ PromptDialog.Warning(
+ "Unsupported Operating System Architecture",
+ $"""
+ Your operating system architecture [{Theme.Error}]{s.Os.Architecture}[/] is not supported.
+ Please upgrade to a 64-bit version of Windows to use this application.
+ [{Theme.WarningMuted}]If you still want to continue, you can choose to do so, but keep in mind that some features may not work as expected.[/]
+ """,
+ new PromptOption("Exit", Theme.Error, () => Environment.Exit(1)),
+ new PromptOption("Continue anyways", Theme.Warning)
+ );
+ }
+ }
+
+ public static void Restart(bool force = false)
+ {
+ var args = Environment.GetCommandLineArgs();
+ if (force || !args.Contains("--restart"))
+ try
+ {
+ SystemHelper.Title("Restarting...");
+ using var process = new Process
+ {
+ StartInfo = new ProcessStartInfo
+ {
+ FileName = Environment.ProcessPath,
+ Arguments = $"--restart {string.Join(" ", args.Skip(1))}",
+ WindowStyle = ProcessWindowStyle.Maximized,
+ WorkingDirectory = Environment.CurrentDirectory,
+ UseShellExecute = true,
+ Verb = "runas"
+ }
+ };
+ Log.LogInformation("Restarting application with administrator privileges and maximized window.");
+ Log.LogWarning(
+ $"Please press [{Theme.Success}]Yes[/] if [{Theme.Primary}]User Account Control[/] (UAC) prompt appears.");
+
+ process.Start();
+ Log.LogInformation("Operation completed successfully! Exiting...");
+ Environment.Exit(0);
+ }
+ catch (Win32Exception ex) when
+ (ex.ErrorCode == -2147467259) // The operation was canceled by the user.
+ {
+ Log.LogError("User [red]declined[/] the elevation prompt.");
+
+ PromptDialog.Warning(
+ "Administrator Privileges Required",
+ $"""
+ To run properly, this application needs administrator rights and should open in full screen.
+ Restart the app and click [{Theme.Success}]Yes[/] if [{Theme.Primary}]User Account Control[/] (UAC) prompt appears.
+ """,
+ new PromptOption("Restart", Theme.Success, () => Restart(true)),
+ new PromptOption("Exit", Theme.Error, () => Environment.Exit(1))
+ );
+ }
+ catch (Exception ex)
+ {
+ Log.LogError(ex, "Failed to restart process");
+
+ PromptDialog.Exception(ex,
+ "Restart Failed",
+ "An error occurred while trying to restart with administrator privileges."
+ );
+ }
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/Core/Helpers/StreamHelper.cs b/optimizerDuck/src/Core/Helpers/StreamHelper.cs
new file mode 100644
index 0000000..a53995b
--- /dev/null
+++ b/optimizerDuck/src/Core/Helpers/StreamHelper.cs
@@ -0,0 +1,34 @@
+using Microsoft.Extensions.Logging;
+using optimizerDuck.UI.Logger;
+
+namespace optimizerDuck.Core.Helpers;
+
+public static class StreamHelper
+{
+ private static readonly ILogger Log = Logger.CreateLogger(typeof(StreamHelper));
+
+ public static async Task<(bool Success, string? FilePath)> TryDownloadAsync(
+ string url,
+ string fileName)
+ {
+ var filePath = Path.Combine(Defaults.ResourcesPath, fileName);
+
+ try
+ {
+ using var client = new HttpClient();
+ using var response = await client.GetAsync(url).ConfigureAwait(false);
+ response.EnsureSuccessStatusCode();
+
+ await using var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
+ await response.Content.CopyToAsync(fs).ConfigureAwait(false);
+
+ Log.LogInformation("Downloaded file from {Url} to {FilePath}", url, filePath);
+ return (true, filePath);
+ }
+ catch (Exception ex)
+ {
+ Log.LogError(ex, "Failed to download file from {Url} to {FilePath}", url, filePath);
+ return (false, null);
+ }
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/Core/Helpers/SystemHelper.cs b/optimizerDuck/src/Core/Helpers/SystemHelper.cs
new file mode 100644
index 0000000..f05e9f8
--- /dev/null
+++ b/optimizerDuck/src/Core/Helpers/SystemHelper.cs
@@ -0,0 +1,89 @@
+using System.Diagnostics;
+using Microsoft.Extensions.Logging;
+using Newtonsoft.Json;
+using optimizerDuck.Core.Services;
+using optimizerDuck.UI;
+using optimizerDuck.UI.Logger;
+
+namespace optimizerDuck.Core.Helpers;
+
+public static class SystemHelper
+{
+ private static readonly ILogger Log = Logger.CreateLogger(typeof(SystemHelper));
+
+ public static void EnsureDirectoriesExists()
+ {
+ if (!Directory.Exists(Defaults.RootPath))
+ {
+ Log.LogInformation(@"AppData\optimizerDuck directory does not exist. Creating directory at: {Path}",
+ Defaults.RootPath);
+ Directory.CreateDirectory(Defaults.RootPath);
+ }
+
+ if (!Directory.Exists(Defaults.ResourcesPath))
+ {
+ Log.LogInformation("Resources directory does not exist. Creating directory at: {Path}",
+ Defaults.ResourcesPath);
+ Directory.CreateDirectory(Defaults.ResourcesPath);
+ }
+ }
+
+ public static void OpenLogFile()
+ {
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = Logger.LogFilePath,
+ UseShellExecute = true
+ });
+ }
+
+ public static void OpenWebsite(string url)
+ {
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = url,
+ UseShellExecute = true
+ });
+ }
+
+ public static void Title(string title)
+ {
+ Console.Title = $"optimizerDuck [{Defaults.FileVersion}] - {title}";
+ }
+
+ public static List<string> CheckForExclusions()
+ {
+ var result = ShellService.PowerShell($$"""
+ @{
+ SelfPath = (Get-MpPreference).ExclusionPath -contains "{{Defaults.ExeDir}}";
+ RootPath = (Get-MpPreference).ExclusionPath -contains "{{Defaults.RootPath}}"
+ } | ConvertTo-Json
+ """);
+ var exclusions = JsonConvert.DeserializeObject<Dictionary<string, bool>>(result.Stdout);
+ var missingPaths = new List<string>();
+ if (exclusions != null && exclusions.TryGetValue("SelfPath", out var selfPathExcluded) && !selfPathExcluded)
+ {
+ Log.LogWarning("Path not excluded: {SelfPath}", Defaults.ExeDir);
+ missingPaths.Add(Defaults.ExeDir);
+ }
+
+ if (exclusions != null && exclusions.TryGetValue("RootPath", out var rootPathExcluded) && !rootPathExcluded)
+ {
+ Log.LogWarning("Path not excluded: {RootPath}", Defaults.RootPath);
+ missingPaths.Add(Defaults.RootPath);
+ }
+
+ // return missing path
+ return missingPaths;
+ }
+
+ public static void AddToExclusions(List<string> paths)
+ {
+ using var tracker = ServiceTracker.Begin();
+ foreach (var path in paths)
+ {
+ var result = ShellService.PowerShell($"Add-MpPreference -ExclusionPath \"{path}\"");
+ if (result.ExitCode != 0) Log.LogWarning($"[{Theme.Error}]Failed to add path to exclusions: {path}[/]");
+ }
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/Core/Helpers/SystemProtectionHelper.cs b/optimizerDuck/src/Core/Helpers/SystemProtectionHelper.cs
new file mode 100644
index 0000000..d396d6b
--- /dev/null
+++ b/optimizerDuck/src/Core/Helpers/SystemProtectionHelper.cs
@@ -0,0 +1,57 @@
+using Microsoft.Extensions.Logging;
+using optimizerDuck.Core.Services;
+using optimizerDuck.UI;
+using optimizerDuck.UI.Components;
+using optimizerDuck.UI.Logger;
+
+namespace optimizerDuck.Core.Helpers;
+
+public static class SystemProtectionHelper
+{
+ private static readonly ILogger Log = Logger.CreateLogger(typeof(SystemProtectionHelper));
+
+ public static bool Enable()
+ {
+ Log.LogInformation("Enabling System Protection...");
+ var result = ShellService.PowerShell("Enable-ComputerRestore -Drive \"$env:SystemDrive\"");
+ if (result.ExitCode != 0)
+ {
+ Log.LogWarning($"[{Theme.Error}]Failed to enable System Protection.[/]");
+ return PromptDialog.Warning("Failed to enable System Protection",
+ $"""
+ We were [{Theme.Error}]unable[/] to enable System Protection.
+ [{Theme.Muted}]For more information, check the log file.[/]
+ """,
+ new PromptOption("Try again", Theme.Warning, Enable), // Enable() trả bool
+ new PromptOption("Skip", Theme.Error, () => false)
+ );
+ }
+
+ Log.LogInformation($"[{Theme.Success}]System Protection enabled successfully.[/]");
+ return true;
+ }
+
+ public static void Create()
+ {
+ Log.LogInformation("Creating a restore point...");
+ var result =
+ ShellService.PowerShell(
+ $"Checkpoint-Computer -Description \"{Defaults.RestorePointName}\" -RestorePointType MODIFY_SETTINGS");
+ if (result.ExitCode != 0)
+ {
+ Log.LogWarning($"[{Theme.Error}]Failed to create restore point.[/]");
+ PromptDialog.Warning("Failed to create Restore Point",
+ $"""
+ We were [{Theme.Error}]unable[/] to create a restore point.
+ [{Theme.Muted}]For more information, check the log file.[/]
+ """,
+ new PromptOption("Try again", Theme.Warning, Create),
+ new PromptOption("Skip", Theme.Error));
+ }
+ else
+ {
+ Log.LogInformation(
+ $"[{Theme.Success}]A restore point [{Theme.Primary}]{Defaults.RestorePointName}[/] created successfully.[/]");
+ }
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/Core/Managers/CacheManager.cs b/optimizerDuck/src/Core/Managers/CacheManager.cs
new file mode 100644
index 0000000..878caac
--- /dev/null
+++ b/optimizerDuck/src/Core/Managers/CacheManager.cs
@@ -0,0 +1,13 @@
+using Microsoft.Extensions.Caching.Memory;
+
+namespace optimizerDuck.Core.Managers;
+
+public static class CacheManager
+{
+ private static readonly MemoryCache _cache = new(new MemoryCacheOptions());
+
+ public static T GetOrCreate<T>(string key, Func<ICacheEntry, T> factory)
+ {
+ return _cache.GetOrCreate(key, factory)!;
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/Core/Managers/OptimizationManager.cs b/optimizerDuck/src/Core/Managers/OptimizationManager.cs
new file mode 100644
index 0000000..3118384
--- /dev/null
+++ b/optimizerDuck/src/Core/Managers/OptimizationManager.cs
@@ -0,0 +1,270 @@
+using System.Diagnostics;
+using System.Reflection;
+using Microsoft.Extensions.Caching.Memory;
+using Microsoft.Extensions.Logging;
+using optimizerDuck.Core.Extensions;
+using optimizerDuck.Core.Helpers;
+using optimizerDuck.Core.Optimizers;
+using optimizerDuck.Core.Services;
+using optimizerDuck.Interfaces;
+using optimizerDuck.Models;
+using optimizerDuck.UI;
+using optimizerDuck.UI.Components;
+using optimizerDuck.UI.Logger;
+using Spectre.Console;
+using ILogger = Microsoft.Extensions.Logging.ILogger;
+
+namespace optimizerDuck.Core.Managers;
+
+public class OptimizationManager(SystemSnapshot systemSnapshot)
+{
+ private static readonly ILogger Log = Logger.CreateLogger<OptimizationManager>();
+ private Queue<OptimizationTweakChoice> _selectedTweaks = new();
+ private SystemSnapshot _systemSnapshot = systemSnapshot;
+
+ public static Queue<string> SelectedBloatware { get; private set; } =
+ new(); // public and static for Remove Bloatware Apps tweak
+
+
+ private static List<OptimizationGroupChoice> GetTweakChoices()
+ {
+ return CacheManager.GetOrCreate("optimization_choices", entry =>
+ {
+ entry.Priority = CacheItemPriority.NeverRemove;
+
+ var groups = new List<OptimizationGroupChoice>();
+ var optimizationGroups = ReflectionHelper.FindImplementationsInLoadedAssemblies(typeof(IOptimizationGroup));
+
+ var enumerable = optimizationGroups as Type[] ?? optimizationGroups.ToArray();
+ var allTweaks = enumerable
+ .SelectMany(og => og.GetNestedTypes(BindingFlags.Public)
+ .Where(t => typeof(IOptimizationTweak).IsAssignableFrom(t))
+ .Select(t => (IOptimizationTweak?)Activator.CreateInstance(t)!))
+ .Where(_ => true)
+ .ToList();
+
+ var globalMaxNameLength = allTweaks.Count != 0
+ ? allTweaks.Max(t => t.Name.Length) + 1
+ : 0;
+
+
+ foreach (var optimizationGroup in enumerable)
+ {
+ var groupInstance = (IOptimizationGroup)Activator.CreateInstance(optimizationGroup)!;
+
+ var tweaks = optimizationGroup
+ .GetNestedTypes(BindingFlags.Public)
+ .Where(t => typeof(IOptimizationTweak).IsAssignableFrom(t))
+ .Select(t => (IOptimizationTweak)Activator.CreateInstance(t)!)
+ .OrderByDescending(t => t.EnabledByDefault)
+ .ToList();
+
+ if (tweaks.Count == 0) // skip groups with no tweaks
+ continue;
+
+ var tweakChoices = tweaks
+ .Select(t =>
+ {
+ var paddedName = t.Name.PadRight(globalMaxNameLength);
+ var description = $"[dim]| {t.Description}[/]";
+
+ return new OptimizationTweakChoice(t, paddedName, description, t.EnabledByDefault);
+ })
+ .ToList();
+
+ groups.Add(new OptimizationGroupChoice(groupInstance.Name, groupInstance.Priority, tweakChoices));
+ }
+
+ var orderedGroups = groups.OrderBy(g => g.Priority).ToList();
+ foreach (var g in orderedGroups)
+ {
+ Log.LogDebug("Loaded group {Group}:", g.Name);
+ foreach (var t in g.Tweaks)
+ if (t.Description != null)
+ Log.LogDebug(" - {TweakName} {TweakDescription}", t.Name, Markup.Remove(t.Description));
+ }
+
+ return orderedGroups;
+ });
+ }
+
+
+ public async Task<bool> Begin()
+ {
+ SystemHelper.Title("Select the tweaks you want to apply");
+ AnsiConsole.Clear();
+ AnsiConsole.Write(Defaults.Logo);
+
+ Log.LogInformation("Loading optimizations...");
+
+ var optimizationGroups = GetTweakChoices();
+ Log.LogInformation("Loaded {GroupAmount} groups with {TweakAmount} tweaks.", optimizationGroups.Count,
+ optimizationGroups.Sum(g => g.Tweaks.Count));
+
+ try
+ {
+ using var escapeCancellableConsole = new EscapeCancellableConsole(AnsiConsole.Console);
+ var promptTweakChoice = new MultiSelectionPrompt<OptimizationTweakChoice>()
+ .Title("Select the tweaks you want to apply")
+ .InstructionsText(Defaults.EscapeCancellableConsoleMultiSelectionPromptInstructionsText)
+ .Required(true)
+ .HighlightStyle(Theme.Primary)
+ .UseConverter(t => $"{t.Name} {t.Description}")
+ .PageSize(24);
+
+ foreach (var g in optimizationGroups)
+ promptTweakChoice.AddChoiceGroup(
+ new OptimizationTweakChoice(null, $"[bold underline]{g.Name}[/]", null,
+ false), // hack to add group title ok vjp pro, and this cant be selected btw
+ g.Tweaks
+ );
+
+ if (_selectedTweaks.Count == 0) // only select enabled by default if no tweaks are selected (first time)
+ foreach (var tweak in optimizationGroups.SelectMany(g => g.Tweaks).Where(t => t.EnabledByDefault))
+ promptTweakChoice.Select(tweak);
+ else
+ foreach (var selectedTweak in _selectedTweaks.ToList())
+ promptTweakChoice.Select(selectedTweak);
+
+ var optimizationTweakChoices =
+ await escapeCancellableConsole.PromptAsync(promptTweakChoice).ConfigureAwait(false);
+
+ _selectedTweaks = new Queue<OptimizationTweakChoice>(optimizationTweakChoices);
+
+ if (_selectedTweaks.Any(t =>
+ t.Instance?.GetType() ==
+ typeof(BloatwareAndServices.RemoveBloatwareApps))) // if Bloatware selection is selected
+ {
+ var promptBloatware = new MultiSelectionPrompt<string>()
+ .Title("Select the bloatware you want to remove")
+ .InstructionsText(Defaults.EscapeCancellableConsoleMultiSelectionPromptInstructionsText)
+ .Required(true)
+ .HighlightStyle(Theme.Primary)
+ .UseConverter(key =>
+ $"{(key.Contains("Safe") || key.Contains("Caution") ? key + " " : "")}{Defaults.SAFE_APPS.GetValueOrDefault(key) ?? Defaults.CAUTION_APPS.GetValueOrDefault(key)}")
+ .AddChoiceGroup("[bold underline lightgreen]Safe Apps[/] - [lightgreen]Recommended[/]",
+ Defaults.SAFE_APPS.Keys)
+ .AddChoiceGroup("[bold underline red]Caution Apps[/] - [red]May cause issues[/]",
+ Defaults.CAUTION_APPS.Keys)
+ .PageSize(24);
+
+ if (SelectedBloatware is { Count: > 0 })
+ foreach (var app in SelectedBloatware)
+ promptBloatware.Select(app);
+ else
+ foreach (var app in Defaults.SAFE_APPS.Keys)
+ promptBloatware.Select(app);
+
+
+ SelectedBloatware =
+ new Queue<string>(await escapeCancellableConsole.PromptAsync(promptBloatware)
+ .ConfigureAwait(false));
+ }
+ }
+ catch (OperationCanceledException)
+ {
+ return false;
+ }
+
+ return true;
+ }
+
+ public static Task<bool> RestorePoint()
+ {
+ AnsiConsole.Clear();
+ AnsiConsole.Write(Defaults.Logo);
+
+ SystemHelper.Title("Setting up");
+
+ return Task.FromResult(PromptDialog.Warning("Restore Point Before Continuing",
+ $"""
+ We [{Theme.Success}]RECOMMEND[/] you to create a Restore Point before continuing.
+ This way, you will be [{Theme.Success}]protected[/] against system-level changes and can always revert them if needed.
+ """,
+ new PromptOption("Yes", Theme.Success, () =>
+ {
+ if (SystemProtectionHelper.Enable()) // if we can enable, create
+ SystemProtectionHelper.Create();
+ }),
+ new PromptOption("Skip", Theme.Error, () => true),
+ new PromptOption("Back", Theme.Warning, () => false)));
+ }
+
+ public async Task Run()
+ {
+ AnsiConsole.Clear();
+ AnsiConsole.Write(Defaults.Logo);
+ SystemHelper.Title("Initializing Optimizer");
+
+ Log.LogInformation("Refreshing system information...");
+ _systemSnapshot = await SystemInfoService.RefreshAsync().ConfigureAwait(false);
+
+ Log.LogDebug("Selected tweaks ({TweakAmount}): {Tweaks}", _selectedTweaks.Count,
+ string.Join(", ", _selectedTweaks.Select(t => t.Name.Trim())));
+ if (SelectedBloatware.Count != 0)
+ Log.LogDebug("Selected bloatware apps ({BloatwareAmount}): {Bloatware}", SelectedBloatware.Count,
+ string.Join(", ", SelectedBloatware));
+
+ Log.LogDebug(new string('=', 60));
+ while (_selectedTweaks.TryDequeue(out var selectedTweak))
+ await AnsiConsole.Status()
+ .Spinner(Spinner.Known.Dots2)
+ .SpinnerStyle($"bold {Theme.Primary}")
+ .StartAsyncGlobal($"Applying [{Theme.Primary}]{selectedTweak.Name.Trim()}[/]...", async ctx =>
+ {
+ var tweakName = selectedTweak.Name.Trim();
+ try
+ {
+ SystemHelper.Title(tweakName);
+ ctx.Status($"Applying [{Theme.Primary}]{tweakName}[/]...");
+
+ using var scope = Log.BeginScope("Tweak: {TweakName}", tweakName);
+
+ Rule($"[bold white] {tweakName} [/]", Theme.Success);
+ Log.LogInformation("Applying {TweakName}...", tweakName);
+
+ var stopwatch = Stopwatch.StartNew();
+
+ await selectedTweak.Instance!.Apply(_systemSnapshot).ConfigureAwait(false);
+
+ stopwatch.Stop();
+
+ Log.LogDebug("Finished tweak in {Elapsed}ms", stopwatch.ElapsedMilliseconds);
+ }
+ catch (Exception e)
+ {
+ Log.LogError(e, "[{Error}]Failed to apply tweak {TweakName}[/], skipped.", Theme.Error,
+ tweakName);
+ }
+ finally
+ {
+ Log.LogDebug(new string('=', 60));
+ }
+ });
+
+ Rule("Optimization completed!", Theme.Success);
+
+ Log.LogInformation($"[{Theme.Success}]Optimization completed![/]");
+
+ PromptDialog.Warning("Restart To Apply Changes",
+ $"""
+ The tweaks have been applied successfully.
+ Please [{Theme.Success}]restart[/] your PC so the changes can work properly.
+ """,
+ new PromptOption("Restart now", Theme.Success, () =>
+ {
+ Log.LogInformation("Restarting...");
+ ShellService.CMD("shutdown /r /t 0");
+ }),
+ new PromptOption("I will restart later", Theme.Warning)
+ );
+ }
+
+ private static void Rule(string title, string ruleColor)
+ {
+ AnsiConsole.WriteLine();
+ AnsiConsole.Write(new Rule(title)
+ .RuleStyle(ruleColor));
+ AnsiConsole.WriteLine();
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/Core/Optimizers/BloatwareAndServices.cs b/optimizerDuck/src/Core/Optimizers/BloatwareAndServices.cs
new file mode 100644
index 0000000..93c7f70
--- /dev/null
+++ b/optimizerDuck/src/Core/Optimizers/BloatwareAndServices.cs
@@ -0,0 +1,367 @@
+using Microsoft.Extensions.Logging;
+using optimizerDuck.Core.Managers;
+using optimizerDuck.Core.Services;
+using optimizerDuck.Interfaces;
+using optimizerDuck.Models;
+using optimizerDuck.UI.Logger;
+
+namespace optimizerDuck.Core.Optimizers;
+
+public class BloatwareAndServices : IOptimizationGroup
+{
+ public string Name { get; } = "Bloatware & Services";
+ public int Priority { get; } = (int)OptimizationGroupPriority.BloatwareAndServices;
+ public static ILogger Log { get; } = Logger.CreateLogger<BloatwareAndServices>();
+
+ public class RemoveBloatwareApps : IOptimizationTweak
+ {
+ public string Name { get; } = "Remove Bloatware Apps";
+
+ public string Description { get; } =
+ "Removes selected bloatware apps (after continue) and bloatware that take up storage space and system resources";
+
+ public bool EnabledByDefault { get; } = true;
+
+ public Task Apply(SystemSnapshot s)
+ {
+ using var tracker = ServiceTracker.Begin();
+
+ while (OptimizationManager.SelectedBloatware.TryDequeue(out var bloatware))
+ {
+ Log.LogInformation("Removing bloatware app: {Bloatware}", bloatware);
+ ShellService.PowerShell($"Get-AppxPackage -AllUsers -Name \"*{bloatware}*\" | Remove-AppxPackage");
+ }
+
+ Log.LogInformation("Bloatware apps have been removed.");
+
+ RegistryService.Write(
+ new RegistryItem(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager",
+ "PreInstalledAppsEnabled", 0),
+ new RegistryItem(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager",
+ "SilentInstalledAppsEnabled", 0),
+ new RegistryItem(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager",
+ "OemPreInstalledAppsEnabled", 0),
+ new RegistryItem(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager",
+ "ContentDeliveryAllowed", 0),
+ new RegistryItem(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager",
+ "SubscribedContentEnabled", 0),
+ new RegistryItem(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager",
+ "PreInstalledAppsEverEnabled", 0)
+ );
+ Log.LogInformation("Preinstalled apps have been disabled.");
+
+ return Task.CompletedTask;
+ }
+ }
+
+ public class RemoveMicrosoftEdge : IOptimizationTweak
+ {
+ public string Name { get; } = "Debloat Microsoft Edge";
+
+ public string Description { get; } =
+ "Removes unnecessary Microsoft Edge features and reduces its system integration for improved performance";
+
+ public bool EnabledByDefault { get; } = false;
+
+ public Task Apply(SystemSnapshot s)
+ {
+ using var tracker = ServiceTracker.Begin();
+ RegistryService.Write(
+ // thank you again, WinUtil (CTT)
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\EdgeUpdate", "CreateDesktopShortcutDefault", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Edge", "PersonalizationReportingEnabled", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Edge", "ShowRecommendationsEnabled", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Edge", "HideFirstRunExperience", 1),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Edge", "UserFeedbackAllowed", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Edge", "ConfigureDoNotTrack", 1),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Edge", "AlternateErrorPagesEnabled", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Edge", "EdgeCollectionsEnabled", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Edge", "EdgeShoppingAssistantEnabled", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Edge", "MicrosoftEdgeInsiderPromotionEnabled", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Edge", "ShowMicrosoftRewards", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Edge", "WebWidgetAllowed", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Edge", "DiagnosticData", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Edge", "EdgeAssetDeliveryServiceEnabled", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Edge", "CryptoWalletEnabled", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Edge", "WalletDonationEnabled", 0)
+ );
+ Log.LogInformation("Microsoft Edge has been debloated.");
+ return Task.CompletedTask;
+ }
+ }
+
+ public class ConfigureServices : IOptimizationTweak
+ {
+ public string Name { get; } = "Configure Services";
+
+ public string Description { get; } =
+ "Optimizes Windows services by disabling unnecessary background services that consume system resources";
+
+ public bool EnabledByDefault { get; } = true;
+
+ public Task Apply(SystemSnapshot s)
+ {
+ using var tracker = ServiceTracker.Begin();
+
+ ServiceProcessService.ChangeServiceStartupType(
+ // based on WinUtil (CTT) configuration
+ new ServiceItem("AJRouter", ServiceStartupType.Disabled),
+ new ServiceItem("ALG", ServiceStartupType.Manual),
+ new ServiceItem("AppIDSvc", ServiceStartupType.Manual),
+ new ServiceItem("AppMgmt", ServiceStartupType.Manual),
+ new ServiceItem("AppReadiness", ServiceStartupType.Manual),
+ new ServiceItem("AppVClient", ServiceStartupType.Disabled),
+ new ServiceItem("AppXSvc", ServiceStartupType.Manual),
+ new ServiceItem("Appinfo", ServiceStartupType.Manual),
+ new ServiceItem("AssignedAccessManagerSvc", ServiceStartupType.Disabled),
+ new ServiceItem("AudioEndpointBuilder", ServiceStartupType.Automatic),
+ new ServiceItem("Audiosrv", ServiceStartupType.Automatic),
+ new ServiceItem("AxInstSV", ServiceStartupType.Manual),
+ new ServiceItem("BDESVC", ServiceStartupType.Manual),
+ new ServiceItem("BFE", ServiceStartupType.Automatic),
+ new ServiceItem("BITS", ServiceStartupType.Manual),
+ new ServiceItem("BTAGService", ServiceStartupType.Manual),
+ new ServiceItem("BrokerInfrastructure", ServiceStartupType.Automatic),
+ new ServiceItem("Browser", ServiceStartupType.Manual),
+ new ServiceItem("BthAvctpSvc", ServiceStartupType.Automatic),
+ new ServiceItem("BthHFSrv", ServiceStartupType.Automatic),
+ new ServiceItem("CDPSvc", ServiceStartupType.Manual),
+ new ServiceItem("COMSysApp", ServiceStartupType.Manual),
+ new ServiceItem("CertPropSvc", ServiceStartupType.Manual),
+ new ServiceItem("ClipSVC", ServiceStartupType.Manual),
+ new ServiceItem("CoreMessagingRegistrar", ServiceStartupType.Automatic),
+ new ServiceItem("CryptSvc", ServiceStartupType.Automatic),
+ new ServiceItem("CscService", ServiceStartupType.Manual),
+ new ServiceItem("DPS", ServiceStartupType.Automatic),
+ new ServiceItem("DcomLaunch", ServiceStartupType.Automatic),
+ new ServiceItem("DcpSvc", ServiceStartupType.Disabled),
+ new ServiceItem("DevQueryBroker", ServiceStartupType.Manual),
+ new ServiceItem("DeviceAssociationService", ServiceStartupType.Manual),
+ new ServiceItem("DeviceInstall", ServiceStartupType.Manual),
+ new ServiceItem("Dhcp", ServiceStartupType.Automatic),
+ new ServiceItem("DiagTrack", ServiceStartupType.Disabled),
+ new ServiceItem("DialogBlockingService", ServiceStartupType.Disabled),
+ new ServiceItem("DispBrokerDesktopSvc", ServiceStartupType.Automatic),
+ new ServiceItem("DisplayEnhancementService", ServiceStartupType.Manual),
+ new ServiceItem("DmEnrollmentSvc", ServiceStartupType.Manual),
+ new ServiceItem("Dnscache", ServiceStartupType.Automatic),
+ new ServiceItem("EFS", ServiceStartupType.Manual),
+ new ServiceItem("EapHost", ServiceStartupType.Manual),
+ new ServiceItem("EntAppSvc", ServiceStartupType.Manual),
+ new ServiceItem("EventLog", ServiceStartupType.Automatic),
+ new ServiceItem("EventSystem", ServiceStartupType.Automatic),
+ new ServiceItem("FDResPub", ServiceStartupType.Manual),
+ new ServiceItem("Fax", ServiceStartupType.Disabled),
+ new ServiceItem("FontCache", ServiceStartupType.Automatic),
+ new ServiceItem("FrameServer", ServiceStartupType.Manual),
+ new ServiceItem("FrameServerMonitor", ServiceStartupType.Manual),
+ new ServiceItem("GraphicsPerfSvc", ServiceStartupType.Manual),
+ new ServiceItem("HomeGroupListener", ServiceStartupType.Disabled),
+ new ServiceItem("HomeGroupProvider", ServiceStartupType.Disabled),
+ new ServiceItem("HvHost", ServiceStartupType.Manual),
+ new ServiceItem("IEEtwCollectorService", ServiceStartupType.Manual),
+ new ServiceItem("IKEEXT", ServiceStartupType.Manual),
+ new ServiceItem("InstallService", ServiceStartupType.Manual),
+ new ServiceItem("InventorySvc", ServiceStartupType.Manual),
+ new ServiceItem("IpxlatCfgSvc", ServiceStartupType.Manual),
+ new ServiceItem("KeyIso", ServiceStartupType.Automatic),
+ new ServiceItem("KtmRm", ServiceStartupType.Manual),
+ new ServiceItem("LSM", ServiceStartupType.Automatic),
+ new ServiceItem("LanmanServer", ServiceStartupType.Automatic),
+ new ServiceItem("LanmanWorkstation", ServiceStartupType.Automatic),
+ new ServiceItem("LicenseManager", ServiceStartupType.Manual),
+ new ServiceItem("LxpSvc", ServiceStartupType.Manual),
+ new ServiceItem("MSDTC", ServiceStartupType.Manual),
+ new ServiceItem("MSiSCSI", ServiceStartupType.Manual),
+ new ServiceItem("MapsBroker", ServiceStartupType.AutomaticDelayedStart),
+ new ServiceItem("McpManagementService", ServiceStartupType.Manual),
+ new ServiceItem("MicrosoftEdgeElevationService", ServiceStartupType.Manual),
+ new ServiceItem("MixedRealityOpenXRSvc", ServiceStartupType.Manual),
+ new ServiceItem("MpsSvc", ServiceStartupType.Automatic),
+ new ServiceItem("MsKeyboardFilter", ServiceStartupType.Manual),
+ new ServiceItem("NaturalAuthentication", ServiceStartupType.Manual),
+ new ServiceItem("NcaSvc", ServiceStartupType.Manual),
+ new ServiceItem("NcbService", ServiceStartupType.Manual),
+ new ServiceItem("NcdAutoSetup", ServiceStartupType.Manual),
+ new ServiceItem("NetSetupSvc", ServiceStartupType.Manual),
+ new ServiceItem("NetTcpPortSharing", ServiceStartupType.Disabled),
+ new ServiceItem("Netlogon", ServiceStartupType.Automatic),
+ new ServiceItem("Netman", ServiceStartupType.Manual),
+ new ServiceItem("NgcCtnrSvc", ServiceStartupType.Manual),
+ new ServiceItem("NgcSvc", ServiceStartupType.Manual),
+ new ServiceItem("NlaSvc", ServiceStartupType.Manual),
+ new ServiceItem("PNRPAutoReg", ServiceStartupType.Manual),
+ new ServiceItem("PNRPsvc", ServiceStartupType.Manual),
+ new ServiceItem("PcaSvc", ServiceStartupType.Manual),
+ new ServiceItem("PeerDistSvc", ServiceStartupType.Manual),
+ new ServiceItem("PerfHost", ServiceStartupType.Manual),
+ new ServiceItem("PhoneSvc", ServiceStartupType.Manual),
+ new ServiceItem("PlugPlay", ServiceStartupType.Automatic),
+ new ServiceItem("PolicyAgent", ServiceStartupType.Manual),
+ new ServiceItem("Power", ServiceStartupType.Automatic),
+ new ServiceItem("PrintNotify", ServiceStartupType.Disabled),
+ new ServiceItem("ProfSvc", ServiceStartupType.Automatic),
+ new ServiceItem("PushToInstall", ServiceStartupType.Manual),
+ new ServiceItem("QWAVE", ServiceStartupType.Manual),
+ new ServiceItem("RasAuto", ServiceStartupType.Manual),
+ new ServiceItem("RasMan", ServiceStartupType.Manual),
+ new ServiceItem("RemoteAccess", ServiceStartupType.Disabled),
+ new ServiceItem("RemoteRegistry", ServiceStartupType.Disabled),
+ new ServiceItem("RetailDemo", ServiceStartupType.Disabled),
+ new ServiceItem("RmSvc", ServiceStartupType.Manual),
+ new ServiceItem("RpcEptMapper", ServiceStartupType.Automatic),
+ new ServiceItem("RpcLocator", ServiceStartupType.Manual),
+ new ServiceItem("RpcSs", ServiceStartupType.Automatic),
+ new ServiceItem("SCPolicySvc", ServiceStartupType.Manual),
+ new ServiceItem("SCardSvr", ServiceStartupType.Manual),
+ new ServiceItem("SDRSVC", ServiceStartupType.Manual),
+ new ServiceItem("SEMgrSvc", ServiceStartupType.Manual),
+ new ServiceItem("SENS", ServiceStartupType.Automatic),
+ new ServiceItem("SNMPTRAP", ServiceStartupType.Manual),
+ new ServiceItem("SSDPSRV", ServiceStartupType.Manual),
+ new ServiceItem("SamSs", ServiceStartupType.Automatic),
+ new ServiceItem("ScDeviceEnum", ServiceStartupType.Manual),
+ new ServiceItem("Schedule", ServiceStartupType.Automatic),
+ new ServiceItem("SecurityHealthService", ServiceStartupType.Manual),
+ new ServiceItem("Sense", ServiceStartupType.Manual),
+ new ServiceItem("SensorDataService", ServiceStartupType.Manual),
+ new ServiceItem("SensorService", ServiceStartupType.Manual),
+ new ServiceItem("SensrSvc", ServiceStartupType.Manual),
+ new ServiceItem("SessionEnv", ServiceStartupType.Manual),
+ new ServiceItem("SharedAccess", ServiceStartupType.Manual),
+ new ServiceItem("SharedRealitySvc", ServiceStartupType.Manual),
+ new ServiceItem("ShellHWDetection", ServiceStartupType.Automatic),
+ new ServiceItem("SmsRouter", ServiceStartupType.Manual),
+ new ServiceItem("Spooler", ServiceStartupType.Manual),
+ new ServiceItem("SstpSvc", ServiceStartupType.Manual),
+ new ServiceItem("StiSvc", ServiceStartupType.Manual),
+ new ServiceItem("StorSvc", ServiceStartupType.Manual),
+ new ServiceItem("SysMain", ServiceStartupType.Disabled),
+ new ServiceItem("SystemEventsBroker", ServiceStartupType.Automatic),
+ new ServiceItem("TabletInputService", ServiceStartupType.Manual),
+ new ServiceItem("TapiSrv", ServiceStartupType.Manual),
+ new ServiceItem("TermService", ServiceStartupType.Automatic),
+ new ServiceItem("Themes", ServiceStartupType.Automatic),
+ new ServiceItem("TieringEngineService", ServiceStartupType.Manual),
+ new ServiceItem("TimeBroker", ServiceStartupType.Manual),
+ new ServiceItem("TimeBrokerSvc", ServiceStartupType.Manual),
+ new ServiceItem("TokenBroker", ServiceStartupType.Manual),
+ new ServiceItem("TrkWks", ServiceStartupType.Automatic),
+ new ServiceItem("TroubleshootingSvc", ServiceStartupType.Manual),
+ new ServiceItem("UI0Detect", ServiceStartupType.Manual),
+ new ServiceItem("UevAgentService", ServiceStartupType.Disabled),
+ new ServiceItem("UmRdpService", ServiceStartupType.Manual),
+ new ServiceItem("UserManager", ServiceStartupType.Automatic),
+ new ServiceItem("UsoSvc", ServiceStartupType.Manual),
+ new ServiceItem("VGAuthService", ServiceStartupType.Automatic),
+ new ServiceItem("VMTools", ServiceStartupType.Automatic),
+ new ServiceItem("VSS", ServiceStartupType.Manual),
+ new ServiceItem("VacSvc", ServiceStartupType.Manual),
+ new ServiceItem("VaultSvc", ServiceStartupType.Automatic),
+ new ServiceItem("W32Time", ServiceStartupType.Manual),
+ new ServiceItem("WEPHOSTSVC", ServiceStartupType.Manual),
+ new ServiceItem("WFDSConMgrSvc", ServiceStartupType.Manual),
+ new ServiceItem("WMPNetworkSvc", ServiceStartupType.Disabled),
+ new ServiceItem("WManSvc", ServiceStartupType.Manual),
+ new ServiceItem("WPDBusEnum", ServiceStartupType.Manual),
+ new ServiceItem("WSService", ServiceStartupType.Manual),
+ new ServiceItem("WSearch", ServiceStartupType.Disabled),
+ new ServiceItem("WaaSMedicSvc", ServiceStartupType.Manual),
+ new ServiceItem("WalletService", ServiceStartupType.Manual),
+ new ServiceItem("WarpJITSvc", ServiceStartupType.Manual),
+ new ServiceItem("WbioSrvc", ServiceStartupType.Manual),
+ new ServiceItem("Wcmsvc", ServiceStartupType.Automatic),
+ new ServiceItem("WcsPlugInService", ServiceStartupType.Manual),
+ new ServiceItem("WdNisSvc", ServiceStartupType.Manual),
+ new ServiceItem("WdiServiceHost", ServiceStartupType.Manual),
+ new ServiceItem("WdiSystemHost", ServiceStartupType.Manual),
+ new ServiceItem("WebClient", ServiceStartupType.Manual),
+ new ServiceItem("Wecsvc", ServiceStartupType.Manual),
+ new ServiceItem("WerSvc", ServiceStartupType.Disabled),
+ new ServiceItem("WiaRpc", ServiceStartupType.Manual),
+ new ServiceItem("WinDefend", ServiceStartupType.Automatic),
+ new ServiceItem("WinHttpAutoProxySvc", ServiceStartupType.Manual),
+ new ServiceItem("WinRM", ServiceStartupType.Manual),
+ new ServiceItem("Winmgmt", ServiceStartupType.Automatic),
+ new ServiceItem("WlanSvc", ServiceStartupType.Automatic),
+ new ServiceItem("WpcMonSvc", ServiceStartupType.Manual),
+ new ServiceItem("WpnService", ServiceStartupType.Manual),
+ new ServiceItem("XblAuthManager", ServiceStartupType.Manual),
+ new ServiceItem("XblGameSave", ServiceStartupType.Manual),
+ new ServiceItem("XboxGipSvc", ServiceStartupType.Manual),
+ new ServiceItem("XboxNetApiSvc", ServiceStartupType.Manual),
+ new ServiceItem("autotimesvc", ServiceStartupType.Manual),
+ new ServiceItem("bthserv", ServiceStartupType.Manual),
+ new ServiceItem("camsvc", ServiceStartupType.Manual),
+ new ServiceItem("cloudidsvc", ServiceStartupType.Manual),
+ new ServiceItem("dcsvc", ServiceStartupType.Manual),
+ new ServiceItem("defragsvc", ServiceStartupType.Manual),
+ new ServiceItem("diagnosticshub.standardcollector.service", ServiceStartupType.Disabled),
+ new ServiceItem("diagsvc", ServiceStartupType.Manual),
+ new ServiceItem("dmwappushservice", ServiceStartupType.Disabled),
+ new ServiceItem("1394ohci", ServiceStartupType.Disabled),
+ new ServiceItem("bowser", ServiceStartupType.Disabled),
+ new ServiceItem("beep", ServiceStartupType.Disabled),
+ new ServiceItem("dot3svc", ServiceStartupType.Manual),
+ new ServiceItem("cdrom", ServiceStartupType.Manual),
+ new ServiceItem("cdfs", ServiceStartupType.Manual),
+ new ServiceItem("edgeupdate", ServiceStartupType.Manual),
+ new ServiceItem("edgeupdatem", ServiceStartupType.Manual),
+ new ServiceItem("embeddedmode", ServiceStartupType.Manual),
+ new ServiceItem("fdPHost", ServiceStartupType.Manual),
+ new ServiceItem("fhsvc", ServiceStartupType.Manual),
+ new ServiceItem("gpsvc", ServiceStartupType.Automatic),
+ new ServiceItem("hidserv", ServiceStartupType.Manual),
+ new ServiceItem("icssvc", ServiceStartupType.Manual),
+ new ServiceItem("iphlpsvc", ServiceStartupType.Automatic),
+ new ServiceItem("lfsvc", ServiceStartupType.Manual),
+ new ServiceItem("lltdsvc", ServiceStartupType.Manual),
+ new ServiceItem("lmhosts", ServiceStartupType.Manual),
+ new ServiceItem("msiserver", ServiceStartupType.Manual),
+ new ServiceItem("netprofm", ServiceStartupType.Manual),
+ new ServiceItem("nsi", ServiceStartupType.Automatic),
+ new ServiceItem("p2pimsvc", ServiceStartupType.Manual),
+ new ServiceItem("p2psvc", ServiceStartupType.Manual),
+ new ServiceItem("perceptionsimulation", ServiceStartupType.Manual),
+ new ServiceItem("pla", ServiceStartupType.Manual),
+ new ServiceItem("seclogon", ServiceStartupType.Manual),
+ new ServiceItem("shpamsvc", ServiceStartupType.Disabled),
+ new ServiceItem("smphost", ServiceStartupType.Manual),
+ new ServiceItem("spectrum", ServiceStartupType.Manual),
+ new ServiceItem("sppsvc", ServiceStartupType.AutomaticDelayedStart),
+ new ServiceItem("ssh-agent", ServiceStartupType.Disabled),
+ new ServiceItem("svsvc", ServiceStartupType.Manual),
+ new ServiceItem("swprv", ServiceStartupType.Manual),
+ new ServiceItem("tiledatamodelsvc", ServiceStartupType.Automatic),
+ new ServiceItem("tzautoupdate", ServiceStartupType.Disabled),
+ new ServiceItem("uhssvc", ServiceStartupType.Disabled),
+ new ServiceItem("upnphost", ServiceStartupType.Manual),
+ new ServiceItem("vds", ServiceStartupType.Manual),
+ new ServiceItem("vm3dservice", ServiceStartupType.Manual),
+ new ServiceItem("vmicguestinterface", ServiceStartupType.Manual),
+ new ServiceItem("vmicheartbeat", ServiceStartupType.Manual),
+ new ServiceItem("vmickvpexchange", ServiceStartupType.Manual),
+ new ServiceItem("vmicrdv", ServiceStartupType.Manual),
+ new ServiceItem("vmicshutdown", ServiceStartupType.Manual),
+ new ServiceItem("vmictimesync", ServiceStartupType.Manual),
+ new ServiceItem("vmicvmsession", ServiceStartupType.Manual),
+ new ServiceItem("vmicvss", ServiceStartupType.Manual),
+ new ServiceItem("vmvss", ServiceStartupType.Manual),
+ new ServiceItem("wbengine", ServiceStartupType.Manual),
+ new ServiceItem("wcncsvc", ServiceStartupType.Manual),
+ new ServiceItem("webthreatdefsvc", ServiceStartupType.Manual),
+ new ServiceItem("wercplsupport", ServiceStartupType.Manual),
+ new ServiceItem("wisvc", ServiceStartupType.Manual),
+ new ServiceItem("wlidsvc", ServiceStartupType.Manual),
+ new ServiceItem("wlpasvc", ServiceStartupType.Manual),
+ new ServiceItem("wmiApSrv", ServiceStartupType.Manual),
+ new ServiceItem("workfolderssvc", ServiceStartupType.Manual),
+ new ServiceItem("wscsvc", ServiceStartupType.AutomaticDelayedStart),
+ new ServiceItem("wuauserv", ServiceStartupType.Manual),
+ new ServiceItem("wudfsvc", ServiceStartupType.Manual)
+ );
+ Log.LogInformation("Services have been configured.");
+ return Task.CompletedTask;
+ }
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/Core/Optimizers/GamingOptimizations.cs b/optimizerDuck/src/Core/Optimizers/GamingOptimizations.cs
new file mode 100644
index 0000000..c3fb862
--- /dev/null
+++ b/optimizerDuck/src/Core/Optimizers/GamingOptimizations.cs
@@ -0,0 +1,225 @@
+using Microsoft.Extensions.Logging;
+using optimizerDuck.Core.Services;
+using optimizerDuck.Interfaces;
+using optimizerDuck.Models;
+using optimizerDuck.UI.Logger;
+
+namespace optimizerDuck.Core.Optimizers;
+
+public class GamingOptimizations : IOptimizationGroup
+{
+ public string Name { get; } = "Gaming Optimizations";
+ public int Priority { get; } = (int)OptimizationGroupPriority.GamingOptimizations;
+ public static ILogger Log { get; } = Logger.CreateLogger<GamingOptimizations>();
+
+ public class DisableGameBar : IOptimizationTweak
+ {
+ public string Name { get; } = "Disable Game Bar";
+
+ public string Description { get; } =
+ "Disables the Xbox Game Bar overlay and background services to prevent performance drops and improve in-game responsiveness.";
+
+ public bool EnabledByDefault { get; } = true;
+
+ public Task Apply(SystemSnapshot s)
+ {
+ using var tracker = ServiceTracker.Begin();
+
+ RegistryService.Write(
+ new RegistryItem(@"HKCU\System\GameConfigStore", "GameBarEnabled", 0),
+ new RegistryItem(@"HKCU\Software\Microsoft\GameBar", "ShowStartupPanel", 0),
+ new RegistryItem(@"HKCU\Software\Microsoft\GameBar", "UseNexusForGameBarEnabled", 0),
+ new RegistryItem(@"HKCU\Software\Microsoft\GameBar", "GamePanelStartupTipIndex", 0)
+ );
+ Log.LogInformation("Game Bar has been disabled.");
+ return Task.CompletedTask;
+ }
+ }
+
+ public class DisableGameDVR : IOptimizationTweak
+ {
+ public string Name { get; } = "Disable Game DVR";
+
+ public string Description { get; } =
+ "Turns off Game DVR recording features to eliminate background video capture and reduce latency during gameplay.";
+
+ public bool EnabledByDefault { get; } = true;
+
+ public Task Apply(SystemSnapshot s)
+ {
+ using var tracker = ServiceTracker.Begin();
+
+ RegistryService.Write(
+ new RegistryItem(@"HKCU\Software\Microsoft\Windows\CurrentVersion\GameDVR", "AppCaptureEnabled", 0),
+ new RegistryItem(@"HKCU\System\GameConfigStore", "GameDVR_Enabled", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Windows\GameDVR", "AllowGameDVR", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Microsoft\PolicyManager\default\ApplicationManagement\AllowGameDVR",
+ "value", 0)
+ );
+ Log.LogInformation("Game DVR has been disabled.");
+ return Task.CompletedTask;
+ }
+ }
+
+ public class GPUTweaks : IOptimizationTweak
+ {
+ public string Name { get; } = "GPU Tweaks";
+
+ public string Description { get; } =
+ "Applies GPU tweaks to disable extras and boost stability & performance";
+
+ public bool EnabledByDefault { get; } = true;
+
+ public Task Apply(SystemSnapshot s)
+ {
+ using var tracker = ServiceTracker.Begin();
+ Log.LogInformation("Applying GPU tweaks for {GpuCount} GPUs...", s.Gpus.Count);
+
+ const string basePath =
+ @"HKLM\SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}";
+
+ foreach (var gpu in s.Gpus)
+ {
+ if (string.IsNullOrWhiteSpace(gpu.DeviceId))
+ {
+ Log.LogWarning("Skipping GPU with no Device ID: {GpuName} (Device ID: {DeviceId})", gpu.Name,
+ gpu.DeviceId ?? "null");
+ continue;
+ }
+
+ if (!TryParseDeviceIdToIndex(gpu.DeviceId, out var index))
+ {
+ Log.LogWarning("Skipping GPU with invalid Device ID: {GpuName} (Device ID: {DeviceId})", gpu.Name,
+ gpu.DeviceId ?? "null");
+ continue;
+ }
+
+ var path = $"{basePath}\\{index:D4}";
+
+ switch (gpu.Vendor)
+ {
+ case GpuVendor.AMD:
+ RegistryService.Write(
+ new RegistryItem(path, "DisableDynamicPstate", 1),
+ new RegistryItem(path, "DisableVCEPowerGating", 1),
+ new RegistryItem(path, "EnableULPS", 0),
+ new RegistryItem(path, "EnableAspmL0s", 0),
+ new RegistryItem(path, "EnableAspmL1", 0),
+ new RegistryItem(path, "EnableUvdClockGating", 0),
+ new RegistryItem(path, "EnableVceSwClockGating", 0),
+ new RegistryItem(path, "KMD_EnableContextBasedPowerManagement", 0),
+ new RegistryItem(path, "PP_GPUPowerDownEnabled", 0),
+ new RegistryItem(path, "DisablePowerGating", 1),
+ new RegistryItem(path, "DisableVceClockGating", 1)
+ );
+ Log.LogInformation("Applied AMD GPU tweaks for {GpuName} at index {GpuIndex:D4}.", gpu.Name,
+ index);
+ break;
+ case GpuVendor.NVIDIA:
+ RegistryService.Write(
+ new RegistryItem(path, "DisableDynamicPstate", 1),
+ new RegistryItem(path, "DisableASyncPstates", 1)
+ );
+ Log.LogInformation("Applied NVIDIA GPU tweaks for {GpuName} at index {GpuIndex:D4}.", gpu.Name,
+ index);
+ break;
+ case GpuVendor.Intel:
+ RegistryService.Write(
+ new RegistryItem(path, "Disable_OverlayDSQualityEnhancement", 1),
+ new RegistryItem(path, "IncreaseFixedSegment", 1),
+ new RegistryItem(path, "AdaptiveVsyncEnable", 0),
+ new RegistryItem(path, "DisablePFonDP", 1),
+ new RegistryItem(path, "EnableCompensationForDVI", 1),
+ new RegistryItem(path, "Display1_DisableAsyncFlips", 1)
+ );
+ Log.LogInformation("Applied Intel GPU tweaks for {GpuName} at index {GpuIndex:D4}.", gpu.Name,
+ index);
+ break;
+ case GpuVendor.Unknown:
+ default:
+ Log.LogWarning("Unsupported GPU vendor: {GpuVendor} for {GpuName} at index {GpuIndex:D4}.",
+ gpu.Vendor, gpu.Name, index);
+ break;
+ }
+ }
+
+ return Task.CompletedTask;
+ }
+
+
+ /// <summary>
+ /// Attempts to parse a WMI <c>DeviceID</c> (e.g., "VideoController1") into a zero-based registry index
+ /// used in the Display Class registry path (e.g., "0000", "0001").
+ /// </summary>
+ /// <remarks>
+ /// <para>
+ /// Windows stores display adapter settings under:
+ /// <c>HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}\XXXX</c>
+ /// where <c>XXXX</c> is a 4-digit zero-padded index (e.g., <c>0000</c>).
+ /// </para>
+ /// <para>
+ /// The <see cref="Win32_VideoController" /> WMI class provides a <c>DeviceID</c> property in the format:
+ /// <c>"VideoController1"</c>, <c>"VideoController2"</c>, etc. This method converts:
+ /// <list type="bullet">
+ /// <item>
+ /// <description><c>"VideoController1"</c> → index <c>0</c> → registry subkey <c>"0000"</c></description>
+ /// </item>
+ /// <item>
+ /// <description><c>"VideoController2"</c> → index <c>1</c> → registry subkey <c>"0001"</c></description>
+ /// </item>
+ /// </list>
+ /// </para>
+ /// <para>
+ /// This mapping is <strong>required</strong> because the order of GPUs in <see cref="SystemSnapshot.Gpus" />
+ /// does <strong>not</strong> guarantee alignment with registry index order. Using array index (0, 1, 2...)
+ /// leads to applying tweaks to the wrong GPU (e.g., iGPU instead of dGPU).
+ /// </para>
+ /// </remarks>
+ /// <param name="deviceId">
+ /// The <c>DeviceID</c> string from <c>Win32_VideoController</c>, typically in the form
+ /// <c>"VideoControllerN"</c> where <c>N</c> is a positive integer starting from 1.
+ /// </param>
+ /// <param name="index">
+ /// When the method returns <c>true</c>, contains the zero-based index suitable for formatting with
+ /// <c>:D4</c> (e.g., <c>0</c> → <c>"0000"</c>). When <c>false</c>, the value is <c>-1</c>.
+ /// </param>
+ /// <returns>
+ /// <c>true</c> if <paramref name="deviceId" /> is valid and successfully parsed; otherwise, <c>false</c>.
+ /// </returns>
+ /// <example>
+ /// <code>
+ /// string deviceId = "VideoController1";
+ /// if (TryParseDeviceIdToIndex(deviceId, out int index))
+ /// {
+ /// string regPath = $@"HKLM\...\{{4d36e968-...\}}\{index:D4}"; // → "0000"
+ /// Console.WriteLine($"Apply tweak to GPU at registry index: {index:D4}");
+ /// }
+ /// </code>
+ /// </example>
+ /// <exception cref="ArgumentNullException">
+ /// Thrown if <paramref name="deviceId" /> is <c>null</c> — but this method uses <c>string.IsNullOrWhiteSpace</c>
+ /// and returns <c>false</c> instead for consistency with TryParse pattern.
+ /// </exception>
+ /// <seealso cref="GpuInfo.DeviceId" />
+ /// <seealso href="https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-videocontroller">
+ /// Win32_VideoController WMI class
+ /// </seealso>
+ private static bool TryParseDeviceIdToIndex(string deviceId, out int index)
+ {
+ index = -1;
+ if (string.IsNullOrWhiteSpace(deviceId))
+ return false;
+
+ const string prefix = "VideoController";
+ if (!deviceId.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
+ return false;
+
+ var numberPart = deviceId[prefix.Length..];
+ if (!int.TryParse(numberPart, out var deviceNumber) || deviceNumber <= 0)
+ return false;
+
+ index = deviceNumber - 1; // convert to zero-based index
+ return true;
+ }
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/Core/Optimizers/PerformanceAndPower.cs b/optimizerDuck/src/Core/Optimizers/PerformanceAndPower.cs
new file mode 100644
index 0000000..48fcbea
--- /dev/null
+++ b/optimizerDuck/src/Core/Optimizers/PerformanceAndPower.cs
@@ -0,0 +1,219 @@
+using Microsoft.Extensions.Logging;
+using Microsoft.Win32;
+using optimizerDuck.Core.Helpers;
+using optimizerDuck.Core.Services;
+using optimizerDuck.Interfaces;
+using optimizerDuck.Models;
+using optimizerDuck.UI;
+using optimizerDuck.UI.Logger;
+
+namespace optimizerDuck.Core.Optimizers;
+
+public class PerformanceAndPower : IOptimizationGroup
+{
+ public string Name => "Performance & Power";
+ public int Priority => (int)OptimizationGroupPriority.PerformanceAndPower;
+ public static ILogger Log { get; } = Logger.CreateLogger<PerformanceAndPower>();
+
+ public class PerformanceTweaks : IOptimizationTweak
+ {
+ public string Name { get; } = "Performance Tweaks";
+
+ public string Description { get; } =
+ "Applies performance tweaks to optimize Windows for speed, responsiveness, and smoother gaming";
+
+ public bool EnabledByDefault { get; } = true;
+
+ public Task Apply(SystemSnapshot s)
+ {
+ RegistryService.Write(
+ new RegistryItem(
+ @"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\BackgroundAccessApplications",
+ "GlobalUserDisabled", 1),
+ new RegistryItem(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Search", "BackgroundAppGlobalToggle",
+ 0)
+ );
+ Log.LogInformation("Disabled background applications");
+
+ /*
+ ref: https://forums.blurbusters.com/viewtopic.php?t=8535
+ 42 Dec, 2A Hex = Short, Fixed , High foreground boost.
+ 41 Dec, 29 Hex = Short, Fixed , Medium foreground boost.
+ 40 Dec, 28 Hex = Short, Fixed , No foreground boost.
+
+ 38 Dec, 26 Hex = Short, Variable , High foreground boost.
+ 37 Dec, 25 Hex = Short, Variable , Medium foreground boost.
+ 36 Dec, 24 Hex = Short, Variable , No foreground boost.
+
+ 26 Dec, 1A Hex = Long, Fixed, High foreground boost.
+ 25 Dec, 19 Hex = Long, Fixed, Medium foreground boost.
+ 24 Dec, 18 Hex = Long, Fixed, No foreground boost.
+
+ 22 Dec, 16 Hex = Long, Variable, High foreground boost.
+ 21 Dec, 15 Hex = Long, Variable, Medium foreground boost.
+ 20 Dec, 14 Hex = Long, Variable, No foreground boost.
+ */
+
+ const int win32Priority = 38;
+
+ RegistryService.Write(
+ new RegistryItem(@"HKLM\SYSTEM\CurrentControlSet\Control\PriorityControl", "Win32PrioritySeparation",
+ win32Priority),
+ new RegistryItem(
+ @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile\Tasks\Games",
+ "Priority", 6),
+ new RegistryItem(
+ @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile\Tasks\Games",
+ "Scheduling Category", "High"),
+ new RegistryItem(
+ @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile\Tasks\Games",
+ "SFIO Priority", "High"),
+ new RegistryItem(
+ @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile\Tasks\Games",
+ "GPU Priority", 8),
+ new RegistryItem(@"HKCU\Control Panel\Desktop", "AutoEndTasks", 1),
+ new RegistryItem(
+ @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile",
+ "NetworkThrottlingIndex", unchecked((int)0xFFFFFFFF), RegistryValueKind.DWord),
+ new RegistryItem(
+ @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile",
+ "SystemResponsiveness", 0),
+ new RegistryItem(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\GraphicsDrivers", "HwSchMode",
+ 2) // idk
+ );
+ Log.LogInformation("Applied performance tweaks.");
+
+ if (s.Ram.TotalKB > 0)
+ {
+ RegistryService.Write(new RegistryItem(@"HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control",
+ "SvcHostSplitThresholdInKB", s.Ram.TotalKB, RegistryValueKind.DWord));
+ Log.LogInformation("Set SvcHostSplitThresholdInKB to {SvcHostSplitThresholdInKB}.", s.Ram.TotalKB);
+ }
+
+ if (int.TryParse(s.Os.Version, out var version) && version >= 11)
+ {
+ RegistryService.Write(
+ new RegistryItem(@"HKEY_CURRENT_USER\Software\Microsoft\GameBar", "AllowAutoGameMode", 1),
+ new RegistryItem(@"HKEY_CURRENT_USER\Software\Microsoft\GameBar", "AutoGameModeEnabled", 1)
+ );
+ Log.LogInformation("Enabled Game Mode.");
+ }
+
+ return Task.CompletedTask;
+ }
+ }
+
+ public class InstallOptimizerDuckPowerPlan : IOptimizationTweak
+ {
+ public string Name { get; } = "Install optimizerDuck Power Plan";
+
+ public string Description { get; } =
+ "Installs a custom high-performance power plan optimized for gaming and maximum CPU performance";
+
+ public bool EnabledByDefault { get; } = true;
+
+ public async Task Apply(SystemSnapshot s)
+ {
+ using var tracker = ServiceTracker.Begin();
+ var (success, powerPlanPath) =
+ await StreamHelper.TryDownloadAsync(Defaults.PowerPlanUrl, "optimizerDuck.pow");
+ if (success && !string.IsNullOrEmpty(powerPlanPath))
+ {
+ // set other power plan to delete old one (if exists)
+ ShellService.CMD("powercfg /duplicatescheme 381b4222-f694-41f0-9685-ff5bb260df2e"); // Balanced
+ ShellService.CMD("powercfg /setactive 381b4222-f694-41f0-9685-ff5bb260df2e"); // Balanced
+ ShellService.CMD($"powercfg /delete {Defaults.PowerPlanGUID}");
+ Log.LogInformation("Deleted old power plan.");
+
+ ShellService.CMD($"powercfg /import \"{powerPlanPath}\" {Defaults.PowerPlanGUID}");
+ ShellService.CMD($"powercfg /setactive {Defaults.PowerPlanGUID}");
+ Log.LogInformation($"Installed [{Theme.Primary}]optimizerDuck[/] power plan successfully!");
+ }
+ else
+ {
+ Log.LogError("Failed to download optimizerDuck power plan! Skipping...");
+ }
+ }
+ }
+
+ public class DisablePowerSavingTweak : IOptimizationTweak
+ {
+ public string Name { get; } = "Disable Power Saving";
+
+ public string Description { get; } =
+ "Disables power throttling and enables AlwaysOn multimedia mode for maximum responsiveness.";
+
+ public bool EnabledByDefault { get; } = true;
+
+ public Task Apply(SystemSnapshot s)
+ {
+ RegistryService.Write(
+ new RegistryItem(@"HKLM\SYSTEM\CurrentControlSet\Control\USB\AutomaticSurpriseRemoval",
+ "AttemptRecoveryFromUsbPowerDrain", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile",
+ "NoLazyMode", 1),
+ new RegistryItem(@"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile",
+ "AlwaysOn", 1),
+ new RegistryItem(@"HKLM\SYSTEM\CurrentControlSet\Control\Power\PowerThrottling", "PowerThrottlingOff",
+ 1)
+ );
+
+ Log.LogInformation("Disabled power saving features.");
+ return Task.CompletedTask;
+ }
+ }
+
+ public class DisableHibernateTweak : IOptimizationTweak
+ {
+ public string Name { get; } = "Disable Hibernate";
+
+ public string Description { get; } =
+ "Disables hibernate, fast startup, and removes hibernate option from power menu.";
+
+ public bool EnabledByDefault { get; } = true;
+
+ public Task Apply(SystemSnapshot s)
+ {
+ RegistryService.Write(
+ new RegistryItem(@"HKLM\SYSTEM\CurrentControlSet\Control\Power", "HibernateEnabled", 0),
+ new RegistryItem(@"HKLM\SYSTEM\CurrentControlSet\Control\Power\PowerThrottling",
+ "HibernateEnabledDefault", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FlyoutMenuSettings",
+ "ShowHibernateOption", 0),
+ new RegistryItem(@"HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Power", "HiberbootEnabled", 0)
+ );
+
+ Log.LogInformation("Disabled hibernate & fast startup.");
+ return Task.CompletedTask;
+ }
+ }
+
+ public class DisableUSBPowerSaving : IOptimizationTweak
+ {
+ public string Name { get; } = "Disable USB Power Saving";
+
+ public string Description { get; } =
+ "Disables USB selective suspend and other power management features that can cause input lag and performance drops";
+
+ public bool EnabledByDefault { get; } = true;
+
+ public Task Apply(SystemSnapshot s)
+ {
+ using var tracker = ServiceTracker.Begin();
+ //https://discord.com/channels/1298592513816530994/1359513721738629140/1359524213047824517
+ //from FrameSync Labs
+ ShellService.PowerShell("""
+ $devicesUSB = Get-PnpDevice | where {$_.InstanceId -like "*USB\ROOT*"} |
+ ForEach-Object -Process {
+ Get-CimInstance -ClassName MSPower_DeviceEnable -Namespace root\wmi
+ }
+ foreach ( $device in $devicesUSB )
+ {
+ Set-CimInstance -Namespace root\wmi -Query "SELECT * FROM MSPower_DeviceEnable WHERE InstanceName LIKE '%$($device.PNPDeviceID)%'" -Property @{Enable=$False} -PassThru
+ }
+ """);
+ Log.LogInformation("Disabled USB power saving.");
+ return Task.CompletedTask;
+ }
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/Core/Optimizers/SecurityAndPrivacy.cs b/optimizerDuck/src/Core/Optimizers/SecurityAndPrivacy.cs
new file mode 100644
index 0000000..00ce73e
--- /dev/null
+++ b/optimizerDuck/src/Core/Optimizers/SecurityAndPrivacy.cs
@@ -0,0 +1,211 @@
+using Microsoft.Extensions.Logging;
+using optimizerDuck.Core.Services;
+using optimizerDuck.Interfaces;
+using optimizerDuck.Models;
+using optimizerDuck.UI.Logger;
+
+namespace optimizerDuck.Core.Optimizers;
+
+public class SecurityAndPrivacy : IOptimizationGroup
+{
+ public string Name => "Security & Privacy";
+ public int Priority => (int)OptimizationGroupPriority.SecurityAndPrivacy;
+ public static ILogger Log { get; } = Logger.CreateLogger<SecurityAndPrivacy>();
+
+ public class DisableUAC : IOptimizationTweak
+ {
+ public string Name { get; } = "Disable UAC";
+
+ public string Description { get; } =
+ "Disables User Account Control to reduce interruptions and improve system responsiveness (dangerous)";
+
+ public bool EnabledByDefault { get; } = false;
+
+ public Task Apply(SystemSnapshot s)
+ {
+ using var tracker = ServiceTracker.Begin();
+ RegistryService.Write(new RegistryItem(@"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System",
+ "EnableLUA", 0));
+ Log.LogInformation("Disabled UAC");
+ return Task.CompletedTask;
+ }
+ }
+
+ public class DisableTelemetry : IOptimizationTweak
+ {
+ public string Name { get; } = "Disable Telemetry";
+
+ public string Description { get; } =
+ "Disables Windows telemetry and data collection to improve privacy and reduce background network usage";
+
+ public bool EnabledByDefault { get; } = true;
+
+ /// <summary>
+ /// thank you https://github.com/ChrisTitusTech/winutil
+ /// </summary>
+ public Task Apply(SystemSnapshot s)
+ {
+ using var tracker = ServiceTracker.Begin();
+ // @formatter:off
+ RegistryService.Write(
+ new RegistryItem(@"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\DataCollection", "AllowTelemetry", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Windows\DataCollection", "AllowTelemetry", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Windows\DataCollection", "DoNotShowFeedbackNotifications", 1),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Windows\DataCollection", "AllowCommercialDataPipeline", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Windows\DataCollection", "AllowDeviceNameInTelemetry", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Windows\DataCollection", "MicrosoftEdgeDataOptIn", 0),
+ new RegistryItem(@"HKCU\SOFTWARE\Microsoft\Siuf\Rules", "NumberOfSIUFInPeriod", 0),
+ new RegistryItem(@"HKCU\Software\Policies\Microsoft\Windows\EdgeUI", "DisableMFUTracking", 1),
+ new RegistryItem(@"HKLM\SOFTWARE\Microsoft\Windows\Windows Error Reporting", "Disabled", 1),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Windows\AppCompat", "DisableInventory", 1),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Windows\AppCompat", "AITEnable", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\AdvertisingInfo", "Enabled", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Windows\AdvertisingInfo", "DisabledByGroupPolicy", 1),
+ new RegistryItem(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Privacy", "TailoredExperiencesWithDiagnosticDataEnabled", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Windows\CloudContent", "DisableTailoredExperiencesWithDiagnosticData", 1),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Windows\CloudContent", "DisableWindowsConsumerFeatures", 1),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Windows\CloudContent", "DisableSoftLanding", 1),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Windows\CloudContent", "DisableThirdPartySuggestions", 1),
+ new RegistryItem(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager", "ContentDeliveryAllowed", 0),
+ new RegistryItem(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager", "OemPreInstalledAppsEnabled", 0),
+ new RegistryItem(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager", "PreInstalledAppsEnabled", 0),
+ new RegistryItem(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager", "PreInstalledAppsEverEnabled", 0),
+ new RegistryItem(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager", "SilentInstalledAppsEnabled", 0),
+ new RegistryItem(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager", "SubscribedContent-338387Enabled", 0),
+ new RegistryItem(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager", "SubscribedContent-338388Enabled", 0),
+ new RegistryItem(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager", "SubscribedContent-338389Enabled", 0),
+ new RegistryItem(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager", "SubscribedContent-353698Enabled", 0),
+ new RegistryItem(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager", "SystemPaneSuggestionsEnabled", 0),
+ new RegistryItem(@"HKCU\Software\Microsoft\Windows\CurrentVersion\Feeds", "ShellFeedsTaskbarViewMode", 2),
+ new RegistryItem(@"HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer", "HideSCAMeetNow", 1),
+ new RegistryItem(@"HKCU\Software\Microsoft\Windows\CurrentVersion\UserProfileEngagement", "ScoobeSystemSettingEnabled", 0),
+ new RegistryItem(@"HKCU\SOFTWARE\Microsoft\InputPersonalization", "RestrictImplicitInkCollection", 1),
+ new RegistryItem(@"HKCU\SOFTWARE\Microsoft\InputPersonalization", "RestrictImplicitTextCollection", 1),
+ new RegistryItem(@"HKCU\SOFTWARE\Microsoft\InputPersonalization\TrainedDataStore", "HarvestContacts", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Windows\LocationAndSensors", "DisableLocation", 1),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Windows\LocationAndSensors", "DisableSensors", 1),
+ new RegistryItem(@"HKLM\SYSTEM\Maps", "AutoUpdateEnabled", 0),
+ new RegistryItem(@"HKCU\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Sensor\Permissions\{BFA794E4-F964-4FDB-90F6-51056BFE4B44}", "SensorPermissionState", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Windows\System", "PublishUserActivities", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Windows\System", "EnableActivityFeed", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Windows\System", "PublishUserActivitiesOnUserConsent", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Windows\System", "UploadUserActivities", 0),
+ new RegistryItem(@"HKCU\SOFTWARE\Policies\Microsoft\Assistance\Client\1.0", "NoExplicitFeedback", 1),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Assistance\Client\1.0", "NoActiveHelp", 1),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Windows\HandwritingErrorReports", "PreventHandwritingErrorReports", 1),
+ new RegistryItem(@"HKCU\Control Panel\International\User Profile", "HttpAcceptLanguageOptOut", 1),
+ new RegistryItem(@"HKLM\SYSTEM\CurrentControlSet\Control\WMI\Autologger\AppModel", "Start", 0),
+ new RegistryItem(@"HKLM\SYSTEM\CurrentControlSet\Control\WMI\Autologger\Cellcore", "Start", 0),
+ new RegistryItem(@"HKLM\SYSTEM\CurrentControlSet\Control\WMI\Autologger\CloudExperienceHostOobe", "Start", 0),
+ new RegistryItem(@"HKLM\SYSTEM\CurrentControlSet\Control\WMI\Autologger\DataMarket", "Start", 0),
+ new RegistryItem(@"HKLM\SYSTEM\CurrentControlSet\Control\WMI\Autologger\DefenderApiLogger", "Start", 0),
+ new RegistryItem(@"HKLM\SYSTEM\CurrentControlSet\Control\WMI\Autologger\DefenderAuditLogger", "Start", 0),
+ new RegistryItem(@"HKLM\SYSTEM\CurrentControlSet\Control\WMI\Autologger\DiagLog", "Start", 0),
+ new RegistryItem(@"HKLM\SYSTEM\CurrentControlSet\Control\WMI\Autologger\Diagtrack-Listener", "Start", 0),
+ new RegistryItem(@"HKLM\SYSTEM\CurrentControlSet\Control\WMI\Autologger\LwtNetLog", "Start", 0),
+ new RegistryItem(@"HKLM\SYSTEM\CurrentControlSet\Control\WMI\Autologger\SQMLogger", "Start", 0),
+ new RegistryItem(@"HKLM\SYSTEM\CurrentControlSet\Control\WMI\Autologger\WdiContextLog", "Start", 0),
+ new RegistryItem(@"HKLM\SYSTEM\CurrentControlSet\Control\WMI\Autologger\WiFiSession", "Start", 0),
+ new RegistryItem(@"HKCU\Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\location", "Value", "Deny"),
+ new RegistryItem(@"HKLM\Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\location", "Value", "Deny"),
+ new RegistryItem(@"HKCU\Software\Microsoft\Windows\CurrentVersion\Geolocation", "Status", 0),
+ new RegistryItem(@"HKLM\SYSTEM\CurrentControlSet\Services\lfsvc\Service\Configuration", "Status", 0),
+ new RegistryItem(@"HKCU\Software\Microsoft\Windows\CurrentVersion\StorageSense\Parameters\StoragePolicy", "01", 0),
+ new RegistryItem(@"HKCU\Software\Microsoft\Windows\CurrentVersion\StorageSense\Parameters\StoragePolicy", "02", 0),
+ new RegistryItem(@"HKLM\Software\Microsoft\PolicyManager\default\WiFi\AllowWiFiHotSpotReporting", "Value", 0),
+ new RegistryItem(@"HKLM\Software\Microsoft\PolicyManager\default\WiFi\AllowAutoConnectToWiFiSenseHotspots", "Value", 0)
+ );
+ RegistryService.DeleteValue([
+ new RegistryItem(@"HKCU\SOFTWARE\Microsoft\Siuf\Rules", "PeriodInNanoSeconds")
+ ]);
+
+ ServiceProcessService.ChangeServiceStartupType(
+ new ServiceItem("DiagTrack", ServiceStartupType.Disabled), // Connected User Experiences and Telemetry (The main telemetry service)
+ new ServiceItem("dmwappushservice", ServiceStartupType.Disabled), // WAP Push Message Routing Service (Used for telemetry)
+ new ServiceItem("DcpSvc", ServiceStartupType.Disabled), // Data Collection and Publishing Service
+ new ServiceItem("diagnosticshub.standardcollector.service", ServiceStartupType.Disabled), // Diagnostic Hub Standard Collector Service
+ new ServiceItem("DusmSvc", ServiceStartupType.Disabled), // Data Usage (Monitors app data usage)
+ new ServiceItem("WerSvc", ServiceStartupType.Disabled), // Windows Error Reporting Service (Sends error data to Microsoft)
+ new ServiceItem("PcaSvc", ServiceStartupType.Disabled) // Program Compatibility Assistant Service (Monitors apps and sends data)
+ );
+
+ var tasksToDelete = new HashSet<string>([
+ @"\Microsoft\Windows\Application Experience\Microsoft Compatibility Appraiser",
+ @"\Microsoft\Windows\Application Experience\ProgramDataUpdater",
+ @"\Microsoft\Windows\Application Experience\MareBackup",
+ @"\Microsoft\Windows\Application Experience\StartupAppTask",
+ @"\Microsoft\Windows\Application Experience\PcaPatchDbTask",
+ @"\Microsoft\Windows\Autochk\Proxy",
+ @"\Microsoft\Windows\Customer Experience Improvement Program\Consolidator",
+ @"\Microsoft\Windows\Customer Experience Improvement Program\UsbCeip",
+ @"\Microsoft\Windows\DiskDiagnostic\Microsoft-Windows-DiskDiagnosticDataCollector",
+ @"\Microsoft\Windows\Feedback\Siuf\DmClient",
+ @"\Microsoft\Windows\Feedback\Siuf\DmClientOnScenarioDownload",
+ @"\Microsoft\Windows\Windows Error Reporting\QueueReporting",
+ @"\Microsoft\Windows\Maps\MapsUpdateTask",
+ @"\Microsoft\Windows\Diagnosis\Scheduled",
+ @"\Microsoft\Windows\DiskDiagnostic\Microsoft-Windows-DiskDiagnosticResolver"
+ ]);
+
+ foreach (var task in tasksToDelete)
+ if (ShellService.CMD($"schtasks /Change /TN \"{task}\" /Disable").ExitCode != 0)
+ Log.LogError("Failed to disable task {Task}.", task);
+
+ Log.LogInformation("Disabled almost all telemetry.");
+ // @formatter:on
+ return Task.CompletedTask;
+ }
+ }
+
+ public class DisableCortanaTweak : IOptimizationTweak
+ {
+ public string Name { get; } = "Disable Cortana & Search AI";
+
+ public string Description { get; } =
+ "Disables Cortana, cloud search, web search integration, and related AI-powered search features.";
+
+ public bool EnabledByDefault { get; } = true;
+
+ public Task Apply(SystemSnapshot s)
+ {
+ using var tracker = ServiceTracker.Begin();
+
+ RegistryService.Write(
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Windows\Windows Search", "AllowCortana", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Windows\Windows Search", "AllowCloudSearch", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Windows\Windows Search", "AllowCortanaAboveLock", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Windows\Windows Search", "AllowSearchToUseLocation", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Windows\Windows Search", "ConnectedSearchUseWeb", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Windows\Windows Search",
+ "ConnectedSearchUseWebOverMeteredConnections", 0),
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Windows\Windows Search", "DisableWebSearch", 1)
+ );
+
+ Log.LogInformation("Cortana and AI-powered search features disabled.");
+ return Task.CompletedTask;
+ }
+ }
+
+ public class DisableCopilotTweak : IOptimizationTweak
+ {
+ public string Name { get; } = "Disable Windows Copilot";
+
+ public string Description { get; } =
+ "Disables Windows Copilot integration in Explorer and system UI.";
+
+ public bool EnabledByDefault { get; } = true;
+
+ public Task Apply(SystemSnapshot s)
+ {
+ using var tracker = ServiceTracker.Begin();
+
+ RegistryService.Write(
+ new RegistryItem(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced",
+ "TurnOffWindowsCopilot", 1)
+ );
+
+ Log.LogInformation("Windows Copilot disabled.");
+ return Task.CompletedTask;
+ }
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/Core/Optimizers/UserExperience.cs b/optimizerDuck/src/Core/Optimizers/UserExperience.cs
new file mode 100644
index 0000000..97741d8
--- /dev/null
+++ b/optimizerDuck/src/Core/Optimizers/UserExperience.cs
@@ -0,0 +1,207 @@
+using Microsoft.Extensions.Logging;
+using Microsoft.Win32;
+using optimizerDuck.Core.Helpers;
+using optimizerDuck.Core.Services;
+using optimizerDuck.Interfaces;
+using optimizerDuck.Models;
+using optimizerDuck.UI.Logger;
+
+namespace optimizerDuck.Core.Optimizers;
+
+public class UserExperience : IOptimizationGroup
+{
+ public string Name { get; } = "User Experience";
+ public int Priority { get; } = (int)OptimizationGroupPriority.UserExperience;
+ public static ILogger Log { get; } = Logger.CreateLogger<UserExperience>();
+
+ public class OptimizeVisuals : IOptimizationTweak
+ {
+ public string Name { get; } = "Optimize Visuals";
+
+ public string Description { get; } =
+ "Adjusts visual effects and animations for better performance, prioritizing speed over visual appeal";
+
+ public bool EnabledByDefault { get; } = true;
+
+ public Task Apply(SystemSnapshot s)
+ {
+ using var tracker = ServiceTracker.Begin();
+ // @formatter:off
+ // taskbar
+ RegistryService.Write(
+ new RegistryItem(@"HKLM\SOFTWARE\Policies\Microsoft\Dsh", "AllowNewsAndInterests", 0),
+ new RegistryItem(@"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced", "TaskbarDa", 0),
+ new RegistryItem(@"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced", "TaskbarMn", 0),
+ new RegistryItem(@"HKCU\Software\Microsoft\Windows\CurrentVersion\Search", "SearchboxTaskbarMode", 0),
+ new RegistryItem(@"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced\TaskbarDeveloperSettings", "TaskbarEndTask", 1),
+ new RegistryItem(@"HKCU\Software\Microsoft\Windows\CurrentVersion\Search", "BingSearchEnabled", 0),
+ new RegistryItem(@"HKCU\Software\Microsoft\Windows\CurrentVersion\Search", "CortanaConsent", 0),
+ new RegistryItem(@"HKCU\Software\Microsoft\Windows\CurrentVersion\Search", "CortanaConsent2", 0),
+ new RegistryItem(@"HKCU\Software\Microsoft\Windows\CurrentVersion\Search", "BackgroundAppGlobalToggle", 0),
+ new RegistryItem(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced", "ShowTaskViewButton", 0),
+ new RegistryItem(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\People", "PeopleBand", 0),
+ new RegistryItem(@"HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer", "HideSCAMeetNow", 1),
+ new RegistryItem(@"HKCU\SOFTWARE\Policies\Microsoft\Windows\Windows Feeds", "EnableFeeds", 0),
+ new RegistryItem(@"HKCU\Software\Microsoft\Windows\CurrentVersion\Feeds", "ShellFeedsTaskbarViewMode", 2),
+ new RegistryItem(@"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced", "ListviewShadow", 0),
+ new RegistryItem(@"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced", "TaskbarAnimations", 0)
+ );
+ Log.LogInformation("Taskbar cleaned up and simplified.");
+
+ // dark mode
+ RegistryService.Write(
+ new RegistryItem(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize", "AppsUseLightTheme", 0),
+ new RegistryItem(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize", "SystemUsesLightTheme", 0)
+ );
+ Log.LogInformation("Switched to dark mode.");
+
+ // explorer
+ RegistryService.Write(
+ new RegistryItem(@"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced", "ShowSyncProviderNotifications", 0),
+ new RegistryItem(@"HKCU\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager", "SystemPaneSuggestionsEnabled", 0),
+ new RegistryItem(@"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced", "HideFileExt", 0),
+ new RegistryItem(@"HKCU\Software\Microsoft\Windows\DWM", "EnableAeroPeek", 0),
+ new RegistryItem(@"HKCU\Control Panel\Desktop\WindowMetrics", "MinAnimate", "0"),
+ new RegistryItem(@"HKCU\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize", "EnableTransparency", 0),
+ new RegistryItem(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced", "Hidden", 1),
+ new RegistryItem(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Serialize", "StartupDelayInMSec", 0),
+ new RegistryItem(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced", "ShowSecondsInSystemClock", 1),
+ new RegistryItem(@"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced", "ShowInfoTip", 0),
+ new RegistryItem(@"HKCU\SOFTWARE\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\InprocServer32", ""), // to use old Windows 10 context menu
+ new RegistryItem(@"HKCU\Control Panel\Desktop", "MenuShowDelay", "0")
+ );
+ Log.LogInformation("Explorer visuals optimized.");
+
+ // visual performance
+ RegistryService.Write(
+ new RegistryItem(@"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\VisualEffects", "VisualFXSetting", 3),
+ new RegistryItem(@"HKCU\Control Panel\Desktop", "DragFullWindows", "0"),
+ new RegistryItem(@"HKCU\Control Panel\Desktop", "UserPreferencesMask", new byte[] { 144, 18, 3, 128, 16, 0, 0, 0 }, RegistryValueKind.Binary)
+ );
+ Log.LogInformation("Visual performance set to best.");
+ // @formatter:on
+ return Task.CompletedTask;
+ }
+ }
+
+
+ public class DisableNotifications : IOptimizationTweak
+ {
+ public string Name { get; } = "Disable Notifications";
+
+ public string Description { get; } =
+ "Disables Windows notifications and action center to minimize distractions during gaming";
+
+ public bool EnabledByDefault { get; } = true;
+
+ public Task Apply(SystemSnapshot s)
+ {
+ using var tracker = ServiceTracker.Begin();
+
+ RegistryService.Write(
+ new RegistryItem(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\PushNotifications",
+ "ToastEnabled", 0),
+ new RegistryItem(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\PushNotifications",
+ "LockScreenToastEnabled", 0),
+ new RegistryItem(@"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced",
+ "EnableBalloonTips", 0)
+ );
+ Log.LogInformation("Notifications disabled.");
+ return Task.CompletedTask;
+ }
+ }
+
+ public class OptimizeMouse : IOptimizationTweak
+ {
+ public string Name { get; } = "Optimize Mouse";
+
+ public string Description { get; } =
+ "Reduces mouse input lag and improves accuracy by disabling mouse acceleration and adjusting sensitivity.";
+
+ public bool EnabledByDefault { get; } = true;
+
+ public Task Apply(SystemSnapshot s)
+ {
+ using var tracker = ServiceTracker.Begin();
+
+ RegistryService.Write(
+ new RegistryItem(@"HKCU\Control Panel\Mouse", "MouseSpeed", "0"),
+ new RegistryItem(@"HKCU\Control Panel\Mouse", "MouseThreshold1", "0"),
+ new RegistryItem(@"HKCU\Control Panel\Mouse", "MouseThreshold2", "0"),
+ new RegistryItem(@"HKCU\Control Panel\Mouse", "MouseSensitivity", "10")
+ );
+ Log.LogInformation("Mouse acceleration disabled.");
+ return Task.CompletedTask;
+ }
+ }
+
+ public class OptimizeKeyboard : IOptimizationTweak
+ {
+ public string Name { get; } = "Optimize Keyboard";
+
+ public string Description { get; } =
+ "Improves keyboard responsiveness and disables unwanted accessibility features.";
+
+ public bool EnabledByDefault { get; } = true;
+
+ public Task Apply(SystemSnapshot s)
+ {
+ using var tracker = ServiceTracker.Begin();
+
+ RegistryService.Write(
+ new RegistryItem(@"HKEY_CURRENT_USER\Control Panel\Keyboard", "KeyboardDelay", "0"),
+ new RegistryItem(@"HKEY_CURRENT_USER\Control Panel\Keyboard", "KeyboardSpeed", "31"),
+ new RegistryItem(@"HKEY_CURRENT_USER\Control Panel\Accessibility\StickyKeys", "Flags", "506"),
+ new RegistryItem(@"HKEY_CURRENT_USER\Control Panel\Accessibility\Keyboard Response", "Flags", "122"),
+ new RegistryItem(@"HKEY_CURRENT_USER\Control Panel\Accessibility\ToggleKeys", "Flags", "58")
+ );
+ Log.LogInformation("Keyboard accessibility features disabled.");
+ return Task.CompletedTask;
+ }
+ }
+
+ public class InstallZwTimerResolution : IOptimizationTweak
+ {
+ public string Name => "Install ZwTimerResolution";
+
+ public string Description =>
+ "Installs and configures ZwTimerResolution to reduce input lag and improve system responsiveness";
+
+ public bool EnabledByDefault => true;
+
+ public async Task Apply(SystemSnapshot s)
+ {
+ using var tracker = ServiceTracker.Begin();
+
+ var (success, zwtPath) = await StreamHelper.TryDownloadAsync(Defaults.ZwtDownloadUrl, "zwtimer.exe")
+ .ConfigureAwait(false);
+ if (success && !string.IsNullOrEmpty(zwtPath))
+ {
+ Log.LogInformation("ZwTimerResolution downloaded successfully!");
+ /*
+ https://github.com/LuSlower/ZwTimerResolution/tree/main
+ If you have Windows Server 2022/Windows 11 you must have in your registry:
+ [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\kernel] "GlobalTimerResolutionRequests"=dword:00000001
+ */
+ if (int.TryParse(s.Os.Version, out var version) &&
+ version >= 11) // i dont check for server versions..................
+ RegistryService.Write(new RegistryItem(
+ @"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\kernel",
+ "GlobalTimerResolutionRequests", 1));
+
+ RegistryService.Write(
+ new RegistryItem(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run", "ZwTimer",
+ zwtPath),
+ new RegistryItem(@"HKEY_CURRENT_USER\Software\ZwTimer", "Start", "1"),
+ new RegistryItem(@"HKEY_CURRENT_USER\Software\ZwTimer", "CustomTimer", "5052")
+ );
+
+ Log.LogInformation("Set ZwTimerResolution Start with System and value to 5052hns.");
+ }
+ else
+ {
+ Log.LogError("Failed to download ZwTimerResolution! Skipping...");
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/Core/Services/RegistryService.cs b/optimizerDuck/src/Core/Services/RegistryService.cs
new file mode 100644
index 0000000..8f82353
--- /dev/null
+++ b/optimizerDuck/src/Core/Services/RegistryService.cs
@@ -0,0 +1,276 @@
+using System.Diagnostics.CodeAnalysis;
+using Microsoft.Extensions.Logging;
+using Microsoft.Win32;
+using optimizerDuck.Models;
+using optimizerDuck.UI.Logger;
+
+namespace optimizerDuck.Core.Services;
+
+public static class RegistryService
+{
+ private static readonly Dictionary<string, RegistryKey> RootKeysMap =
+ new(StringComparer.OrdinalIgnoreCase)
+ {
+ ["HKLM"] = Registry.LocalMachine,
+ ["HKLM:"] = Registry.LocalMachine,
+ ["HKEY_LOCAL_MACHINE"] = Registry.LocalMachine,
+
+ ["HKCU"] = Registry.CurrentUser,
+ ["HKCU:"] = Registry.CurrentUser,
+ ["HKEY_CURRENT_USER"] = Registry.CurrentUser,
+
+ ["HKCR"] = Registry.ClassesRoot,
+ ["HKCR:"] = Registry.ClassesRoot,
+ ["HKEY_CLASSES_ROOT"] = Registry.ClassesRoot,
+
+ ["HKU"] = Registry.Users,
+ ["HKU:"] = Registry.Users,
+ ["HKEY_USERS"] = Registry.Users,
+
+ ["HKCC"] = Registry.CurrentConfig,
+ ["HKCC:"] = Registry.CurrentConfig,
+ ["HKEY_CURRENT_CONFIG"] = Registry.CurrentConfig
+ };
+
+ private static bool TryParsePath(
+ string fullPath,
+ [NotNullWhen(true)] out RegistryKey? rootKey,
+ [NotNullWhen(true)] out string? subPath)
+ {
+ rootKey = null;
+ subPath = null;
+
+ if (string.IsNullOrWhiteSpace(fullPath))
+ {
+ ServiceTracker.Current?.Log.LogWarning("Registry path is null or empty");
+ ServiceTracker.Current?.Track(nameof(RegistryService), false);
+ return false;
+ }
+
+ var parts = fullPath.AsSpan();
+ var idx = parts.IndexOf('\\');
+ var rootToken = idx > 0 ? parts[..idx].ToString() : parts.ToString();
+
+ if (!RootKeysMap.TryGetValue(rootToken, out rootKey))
+ {
+ ServiceTracker.Current?.Log.LogWarning("Unknown root key: {RootToken}", rootToken);
+ ServiceTracker.Current?.Track(nameof(RegistryService), false);
+ return false;
+ }
+
+ subPath = idx > 0 ? parts[(idx + 1)..].ToString() : string.Empty;
+ return true;
+ }
+
+ private static bool TryOpenSubKey(
+ RegistryKey rootKey,
+ string? subPath,
+ [NotNullWhen(true)] out RegistryKey? key,
+ bool writable,
+ bool createIfMissing,
+ out bool shouldDispose)
+ {
+ key = null;
+ shouldDispose = false;
+
+ if (string.IsNullOrEmpty(subPath))
+ {
+ key = rootKey;
+ return true;
+ }
+
+ try
+ {
+ var opened = writable
+ ? rootKey.OpenSubKey(subPath, true)
+ : rootKey.OpenSubKey(subPath);
+
+ if (opened == null && writable && createIfMissing)
+ opened = rootKey.CreateSubKey(subPath, true);
+
+ if (opened != null)
+ {
+ key = opened;
+ shouldDispose = true;
+ return true;
+ }
+
+ ServiceTracker.Current?.Log.LogWarning("SubKey not found: {Root}\\{SubPath}", rootKey.Name, subPath);
+ ServiceTracker.Current?.Track(nameof(RegistryService), false);
+ return false;
+ }
+ catch (Exception ex)
+ {
+ ServiceTracker.Current?.Log.LogError(ex, "Failed to {Operation} sub key: {RootKey}\\{SubPath}",
+ writable ? "create/open" : "open", rootKey.Name, subPath);
+ ServiceTracker.Current?.Track(nameof(RegistryService), false);
+ return false;
+ }
+ }
+
+ private static T? WithKey<T>(RegistryItem item, Func<RegistryKey, T?> action, bool writable = false,
+ bool createIfMissing = false)
+ {
+ if (!TryParsePath(item.Path, out var rootKey, out var subPath))
+ return default;
+
+ if (!TryOpenSubKey(rootKey, subPath, out var subKey, writable, createIfMissing, out var shouldDispose))
+ return default;
+
+ try
+ {
+ return action(subKey);
+ }
+ finally
+ {
+ if (shouldDispose)
+ subKey.Dispose();
+ }
+ }
+
+ public static T? Read<T>(RegistryItem item)
+ {
+ return WithKey(item, key =>
+ {
+ try
+ {
+ var value = key.GetValue(item.Name);
+ if (value is null) return default;
+ if (value is T tValue) return tValue;
+
+ if (typeof(T) == typeof(byte[]) && value is byte[] bytes) return (T)(object)bytes;
+ if (typeof(T) == typeof(string[]) && value is string[] arr) return (T)(object)arr;
+
+ if (typeof(T) == typeof(int) && value is int i) return (T)(object)i;
+ if (typeof(T) == typeof(bool) && value is int i2) return (T)(object)(i2 != 0);
+
+ return (T)Convert.ChangeType(value, typeof(T));
+ }
+ catch (Exception ex)
+ {
+ ServiceTracker.Current?.Log.LogError(ex, "Failed to read or convert registry value {Path}:{Name}",
+ item.Path, item.Name);
+ return default;
+ }
+ });
+ }
+
+ public static bool Write(RegistryItem registryItem)
+ {
+ if (registryItem.Value == null)
+ {
+ ServiceTracker.Current?.Log.LogError("Value can't be null when writing! {Path}:{Name}", registryItem.Path,
+ registryItem.Name);
+ ServiceTracker.Current?.Track(nameof(Write), false);
+ return false;
+ }
+
+ return WithKey(registryItem, key =>
+ {
+ try
+ {
+ key.SetValue(registryItem.Name, registryItem.Value, registryItem.Kind);
+ ServiceTracker.Current?.Track(nameof(Write), true);
+ return true;
+ }
+ catch (UnauthorizedAccessException)
+ {
+ ServiceTracker.Current?.Log.LogError(
+ "Failed to write registry value {Path}:{Name} due to missing access",
+ registryItem.Path, registryItem.Name);
+ ServiceTracker.Current?.Track(nameof(Write), false);
+ return false;
+ }
+ catch (Exception ex)
+ {
+ ServiceTracker.Current?.Log.LogError(ex, "Failed to write registry value {Path}:{Name}",
+ registryItem.Path, registryItem.Name);
+ ServiceTracker.Current?.Track(nameof(Write), false);
+ return false;
+ }
+ }, true, true);
+ }
+
+ public static bool DeleteValue(RegistryItem item)
+ {
+ return WithKey(item, key =>
+ {
+ try
+ {
+ if (key.GetValue(item.Name) == null)
+ {
+ //ServiceTracker.Current?.Log.LogWarning("Attempted to delete non-existent registry value {Path}:{Name}", item.Path, item.Name);
+ ServiceTracker.Current?.Track(nameof(DeleteValue), true);
+ return true; // after all, we try to delete this value.
+ }
+
+ key.DeleteValue(item.Name!, false);
+ ServiceTracker.Current?.Track(nameof(DeleteValue), true);
+ return true;
+ }
+ catch (UnauthorizedAccessException)
+ {
+ ServiceTracker.Current?.Log.LogError(
+ "Failed to delete registry value {Path}:{Name} due to missing access", item.Path,
+ item.Name);
+ ServiceTracker.Current?.Track(nameof(DeleteValue), false);
+ return false;
+ }
+ catch (Exception ex)
+ {
+ ServiceTracker.Current?.Log.LogError(ex, "Failed to delete registry value {Path}:{Name}", item.Path,
+ item.Name);
+ ServiceTracker.Current?.Track(nameof(DeleteValue), false);
+ return false;
+ }
+ }, true);
+ }
+
+ public static bool DeleteSubKey(RegistryItem item)
+ {
+ if (!TryParsePath(item.Path, out var rootKey, out var subPath))
+ return false;
+
+ if (string.IsNullOrWhiteSpace(subPath))
+ {
+ ServiceTracker.Current?.Log.LogError("DeleteSubKey called with empty subpath! {Path}:{Name}", item.Path,
+ item.Name);
+ ServiceTracker.Current?.Track(nameof(DeleteSubKey), false);
+ return false;
+ }
+
+ try
+ {
+ rootKey.DeleteSubKeyTree(subPath, false);
+ ServiceTracker.Current?.Track(nameof(DeleteSubKey), true);
+ return true;
+ }
+ catch (UnauthorizedAccessException)
+ {
+ ServiceTracker.Current?.Log.LogError("Failed to delete subkey {Path} due to missing access", item.Path);
+ ServiceTracker.Current?.Track(nameof(DeleteSubKey), false);
+ return false;
+ }
+ catch (Exception ex)
+ {
+ ServiceTracker.Current?.Log.LogError(ex, "Failed to delete subkey {Path}", item.Path);
+ ServiceTracker.Current?.Track(nameof(DeleteSubKey), false);
+ return false;
+ }
+ }
+
+ public static void Write(params RegistryItem[] items)
+ {
+ foreach (var item in items.Distinct()) Write(item);
+ }
+
+ public static void DeleteValue(params RegistryItem[] items)
+ {
+ foreach (var item in items.Distinct()) DeleteValue(item);
+ }
+
+ public static void DeleteSubKey(params RegistryItem[] items)
+ {
+ foreach (var item in items.Distinct()) DeleteSubKey(item);
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/Core/Services/ServiceProcessService.cs b/optimizerDuck/src/Core/Services/ServiceProcessService.cs
new file mode 100644
index 0000000..b8f8413
--- /dev/null
+++ b/optimizerDuck/src/Core/Services/ServiceProcessService.cs
@@ -0,0 +1,72 @@
+using System.Management;
+using Microsoft.Extensions.Logging;
+using optimizerDuck.Models;
+using optimizerDuck.UI.Logger;
+
+namespace optimizerDuck.Core.Services;
+
+public static class ServiceProcessService
+{
+ private static readonly ManagementScope Scope = new(@"\\.\root\cimv2");
+
+ public static bool ChangeServiceStartupType(ServiceItem item)
+ {
+ try
+ {
+ if (!Scope.IsConnected)
+ Scope.Connect();
+
+ using var searcher = new ManagementObjectSearcher(Scope,
+ new ObjectQuery($"SELECT * FROM Win32_Service WHERE Name='{item.ServiceName.Replace("'", "''")}'"));
+ var service = searcher.Get().OfType<ManagementObject>().FirstOrDefault();
+
+ if (service == null)
+ {
+ ServiceTracker.Current?.Log.LogWarning("Service '{ServiceName}' not found.", item.ServiceName);
+ ServiceTracker.Current?.Track(nameof(ChangeServiceStartupType), false);
+ return false;
+ }
+
+ using var inParams = service.GetMethodParameters("ChangeStartMode");
+ inParams["StartMode"] = item.StartupType switch
+ {
+ ServiceStartupType.AutomaticDelayedStart => "Automatic",
+ _ => item.StartupType.ToString()
+ };
+
+ using var outParams = service.InvokeMethod("ChangeStartMode", inParams, null);
+
+ var resultCode = outParams?["ReturnValue"] is uint val ? val : 1;
+
+ if (resultCode == 0)
+ {
+ var result = item.StartupType == ServiceStartupType.AutomaticDelayedStart
+ ? RegistryService.Write(new RegistryItem(
+ @$"HKLM\SYSTEM\CurrentControlSet\Services\{item.ServiceName}", "DelayedAutoStart", 1))
+ : RegistryService.DeleteValue(new RegistryItem(
+ @$"HKLM\SYSTEM\CurrentControlSet\Services\{item.ServiceName}", "DelayedAutoStart"));
+
+ ServiceTracker.Current?.Track(nameof(ChangeServiceStartupType), result);
+ return result;
+ }
+
+ ServiceTracker.Current?.Log.LogWarning(
+ "Failed to change startup type for '{ServiceName}'. ReturnValue: {Result}", item.ServiceName,
+ resultCode);
+ ServiceTracker.Current?.Track(nameof(ChangeServiceStartupType), false);
+ return false;
+ }
+ catch (Exception ex)
+ {
+ ServiceTracker.Current?.Log.LogError(ex, "Failed to change startup type for '{ServiceName}'.",
+ item.ServiceName);
+ ServiceTracker.Current?.Track(nameof(ChangeServiceStartupType), false);
+ return false;
+ }
+ }
+
+ public static void ChangeServiceStartupType(params ServiceItem[] items)
+ {
+ foreach (var item in items) ChangeServiceStartupType(item);
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/Core/Services/ShellService.cs b/optimizerDuck/src/Core/Services/ShellService.cs
new file mode 100644
index 0000000..c1f8b6b
--- /dev/null
+++ b/optimizerDuck/src/Core/Services/ShellService.cs
@@ -0,0 +1,111 @@
+using System.Diagnostics;
+using System.Text;
+using Microsoft.Extensions.Logging;
+using optimizerDuck.Core.Extensions;
+using optimizerDuck.UI.Logger;
+using Spectre.Console;
+
+namespace optimizerDuck.Core.Services;
+
+public record ShellResult(
+ string Command,
+ string Stdout,
+ string Stderr,
+ int ExitCode,
+ TimeSpan Duration);
+
+public static class ShellService
+{
+ private static ShellResult Run(string fileName, string arguments, string command, string serviceName)
+ {
+ var fullCommand =
+ $"{fileName} {arguments.Replace("-EncodedCommand", "-Command")} {command.DecodeBase64()}"; // let user see the real command
+
+ var psi = new ProcessStartInfo
+ {
+ FileName = fileName,
+ Arguments = $"{arguments} {command}",
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ StandardOutputEncoding = Encoding.UTF8,
+ StandardErrorEncoding = Encoding.UTF8,
+ UseShellExecute = false,
+ CreateNoWindow = true
+ };
+
+ using var process = new Process { StartInfo = psi };
+
+ var stdoutBuilder = new StringBuilder();
+ var stderrBuilder = new StringBuilder();
+
+ process.OutputDataReceived += (_, e) =>
+ {
+ if (e.Data == null) return;
+ stdoutBuilder.AppendLine(e.Data);
+ };
+
+ process.ErrorDataReceived += (_, e) =>
+ {
+ if (e.Data == null) return;
+ stderrBuilder.AppendLine(e.Data);
+ };
+ process.Start();
+
+ process.BeginOutputReadLine();
+ process.BeginErrorReadLine();
+
+ process.WaitForExit();
+
+ var duration = process.ExitTime - process.StartTime;
+
+ var stdout = Markup.Escape(stdoutBuilder.ToString().Trim());
+ var stderr = stderrBuilder.ToString().ParseCliXml().Trim();
+
+ var success = process.ExitCode == 0;
+
+ var stdoutDisplay = string.IsNullOrWhiteSpace(stdout) ? "N/A" : stdout;
+ var stderrDisplay = string.IsNullOrWhiteSpace(stderr) ? "N/A" : stderr;
+
+ ServiceTracker.Current?.Track(serviceName, success);
+ ServiceTracker.Current?.Log.LogDebug(
+ """
+ {FullCommand}
+ | Stdout: {Stdout}
+ | Stderr: {Stderr}
+ | ExitCode: {ProcessExitCode}
+ | Duration: {TimeSpan}
+ """, fullCommand, stdoutDisplay, stderrDisplay, process.ExitCode, ServiceTracker.FormatTime(duration));
+
+ return new ShellResult(
+ $"{fileName} {arguments} {command}",
+ stdoutDisplay,
+ stderrDisplay,
+ process.ExitCode,
+ duration);
+ }
+
+ public static ShellResult CMD(string command)
+ {
+ return Run("cmd.exe", "/c", command, nameof(CMD));
+ }
+
+ public static ShellResult PowerShell(string command)
+ {
+ command = "$ProgressPreference='SilentlyContinue'; " + command; // to hide progress bar clixml
+ return Run("powershell.exe",
+ "-NonInteractive -NoLogo -NoProfile -ExecutionPolicy Bypass -EncodedCommand",
+ EncodePowerShellCommand(command),
+ nameof(PowerShell));
+ }
+
+ /// <summary>
+ /// encode command to base64 for better script handling
+ /// </summary>
+ /// <param name="command"></param>
+ /// <returns></returns>
+ private static string EncodePowerShellCommand(string command)
+ {
+ var bytes = Encoding.Unicode.GetBytes(command);
+ return Convert.ToBase64String(bytes);
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/Core/Services/SystemInfoService.cs b/optimizerDuck/src/Core/Services/SystemInfoService.cs
new file mode 100644
index 0000000..c4934b5
--- /dev/null
+++ b/optimizerDuck/src/Core/Services/SystemInfoService.cs
@@ -0,0 +1,756 @@
+using System.Management;
+using Microsoft.Extensions.Logging;
+using optimizerDuck.UI;
+using Spectre.Console;
+using Spectre.Console.Rendering;
+
+namespace optimizerDuck.Core.Services;
+
+// ============================================================================
+// MODELS (Immutable Records)
+// ============================================================================
+
+public enum GpuVendor
+{
+ Unknown,
+ NVIDIA,
+ AMD,
+ Intel
+}
+
+public sealed record GpuInfo(
+ string Name,
+ string DriverVersion,
+ GpuVendor Vendor,
+ int? MemoryMB,
+ string? DeviceId,
+ string? PnpDeviceId
+)
+{
+ public static readonly GpuInfo Unknown = new("Unknown", "Unknown", GpuVendor.Unknown, null, null, null);
+}
+
+public sealed record CpuInfo(
+ string Name,
+ string Manufacturer,
+ string Vendor,
+ string Architecture,
+ int Cores,
+ int Threads,
+ int MaxClockMHz,
+ int CurrentClockMHz,
+ int L2CacheKB,
+ int L3CacheKB
+)
+{
+ public static readonly CpuInfo Unknown = new("Unknown", "Unknown", "Unknown", "Unknown", 0, 0, 0, 0, 0, 0);
+}
+
+public sealed record RamModule(
+ double CapacityGB,
+ string SpeedMHz,
+ string Manufacturer,
+ string PartNumber,
+ string DeviceLocator
+);
+
+public sealed record RamInfo(
+ double TotalGB,
+ long TotalMB,
+ long TotalKB,
+ double AvailableGB,
+ double UsedPercent,
+ IReadOnlyList<RamModule> Modules
+)
+{
+ public static readonly RamInfo Unknown = new(0, 0, 0, 0, 0, []);
+}
+
+public sealed record OsInfo(
+ string Name,
+ string Version,
+ string BuildNumber,
+ string Edition,
+ string Architecture,
+ string DeviceType,
+ string InstallDate,
+ string LastBoot
+)
+{
+ public static readonly OsInfo Unknown = new("Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown",
+ "Unknown", "Unknown");
+}
+
+public sealed record BiosInfo(
+ string Manufacturer,
+ string Version,
+ string ReleaseDate,
+ string SmbiosVersion,
+ string SerialNumber
+)
+{
+ public static readonly BiosInfo Unknown = new("Unknown", "Unknown", "Unknown", "Unknown", "Unknown");
+}
+
+public sealed record SystemSnapshot(
+ CpuInfo Cpu,
+ RamInfo Ram,
+ OsInfo Os,
+ BiosInfo Bios,
+ IReadOnlyList<GpuInfo> Gpus,
+ GpuInfo? PrimaryGpu
+)
+{
+ public static readonly SystemSnapshot Unknown = new(
+ CpuInfo.Unknown,
+ RamInfo.Unknown,
+ OsInfo.Unknown,
+ BiosInfo.Unknown,
+ [],
+ null
+ );
+}
+
+// ============================================================================
+// WMI HELPER
+// ============================================================================
+
+internal static class WmiHelper
+{
+ public static IEnumerable<ManagementObject> Query(string query)
+ {
+ try
+ {
+ using var searcher = new ManagementObjectSearcher(query);
+ return searcher.Get().Cast<ManagementObject>().ToArray();
+ }
+ catch
+ {
+ return [];
+ }
+ }
+
+ public static string GetString(ManagementObject mo, string property, string fallback = "Unknown")
+ {
+ try
+ {
+ var value = mo[property];
+ return value switch
+ {
+ null => fallback,
+ string[] arr => arr.Length > 0 ? arr[0].Trim() : fallback,
+ _ => value.ToString()?.Trim() ?? fallback
+ };
+ }
+ catch
+ {
+ return fallback;
+ }
+ }
+
+ public static int GetInt(ManagementObject mo, string property, int fallback = 0)
+ {
+ try
+ {
+ var value = mo[property];
+ return value == null ? fallback : Convert.ToInt32(value);
+ }
+ catch
+ {
+ return fallback;
+ }
+ }
+
+ public static long GetLong(ManagementObject mo, string property, long fallback = 0)
+ {
+ try
+ {
+ var value = mo[property];
+ return value == null ? fallback : Convert.ToInt64(value);
+ }
+ catch
+ {
+ return fallback;
+ }
+ }
+
+ public static ManagementObject? GetFirst(string query)
+ {
+ return Query(query).FirstOrDefault();
+ }
+}
+
+// ============================================================================
+// COMPONENT PROVIDERS
+// ============================================================================
+
+internal static class CpuProvider
+{
+ public static CpuInfo Get()
+ {
+ try
+ {
+ var cpu = WmiHelper.GetFirst("SELECT * FROM Win32_Processor");
+ if (cpu == null) return CpuInfo.Unknown;
+
+ var name = WmiHelper.GetString(cpu, "Name");
+ var manufacturer = WmiHelper.GetString(cpu, "Manufacturer");
+ var cores = WmiHelper.GetInt(cpu, "NumberOfCores");
+ var threads = WmiHelper.GetInt(cpu, "NumberOfLogicalProcessors");
+ var maxMHz = WmiHelper.GetInt(cpu, "MaxClockSpeed");
+ var curMHz = WmiHelper.GetInt(cpu, "CurrentClockSpeed");
+ var l2kb = WmiHelper.GetInt(cpu, "L2CacheSize");
+ var l3kb = WmiHelper.GetInt(cpu, "L3CacheSize");
+ var addressWidth = WmiHelper.GetInt(cpu, "AddressWidth");
+
+ var vendor = DetectCpuVendor(manufacturer);
+ var architecture = addressWidth == 64 ? "64-bit" : addressWidth == 32 ? "32-bit" : "Unknown";
+
+ return new CpuInfo(name, manufacturer, vendor, architecture, cores, threads, maxMHz, curMHz, l2kb, l3kb);
+ }
+ catch
+ {
+ return CpuInfo.Unknown;
+ }
+ }
+
+ private static string DetectCpuVendor(string manufacturer)
+ {
+ var lower = manufacturer.ToLowerInvariant();
+ if (lower.Contains("intel") || lower.Contains("genuineintel")) return "Intel";
+ if (lower.Contains("amd") || lower.Contains("authenticamd")) return "AMD";
+ return "Unknown";
+ }
+}
+
+internal static class RamProvider
+{
+ public static RamInfo Get()
+ {
+ try
+ {
+ var modules = GetPhysicalModules();
+ var (totalGB, totalMB, totalKB, availableGB, usedPercent) = GetMemoryStats(modules);
+
+ return new RamInfo(totalGB, totalMB, totalKB, availableGB, usedPercent, modules);
+ }
+ catch
+ {
+ return RamInfo.Unknown;
+ }
+ }
+
+ private static List<RamModule> GetPhysicalModules()
+ {
+ var modules = new List<RamModule>();
+ var physicalMemory = WmiHelper.Query("SELECT * FROM Win32_PhysicalMemory");
+
+ foreach (var mem in physicalMemory)
+ {
+ var capacityBytes = WmiHelper.GetLong(mem, "Capacity");
+ var capacityGB = capacityBytes > 0 ? capacityBytes / Math.Pow(1024, 3) : 0;
+ var speed = WmiHelper.GetString(mem, "Speed");
+ var manufacturer = WmiHelper.GetString(mem, "Manufacturer");
+ var partNumber = WmiHelper.GetString(mem, "PartNumber");
+ var deviceLocator = WmiHelper.GetString(mem, "DeviceLocator");
+
+ modules.Add(new RamModule(Math.Round(capacityGB, 2), speed, manufacturer, partNumber, deviceLocator));
+ }
+
+ return modules;
+ }
+
+ private static (double totalGB, long totalMB, long totalKB, double availableGB, double usedPercent) GetMemoryStats(
+ List<RamModule> modules)
+ {
+ var totalGB = modules.Sum(m => m.CapacityGB);
+
+ // Fallback to OS-reported total if modules don't provide accurate info
+ if (totalGB <= 0)
+ {
+ var os = WmiHelper.GetFirst("SELECT TotalVisibleMemorySize FROM Win32_OperatingSystem");
+ if (os != null)
+ {
+ var totalKBFromOs = WmiHelper.GetLong(os, "TotalVisibleMemorySize");
+ totalGB = totalKBFromOs / 1024.0 / 1024.0;
+ }
+ }
+
+ var totalMB = (long)(totalGB * 1024);
+ var totalKB = totalMB * 1024;
+
+ // Get available memory and usage
+ var (availableGB, usedPercent) = GetMemoryUsage();
+
+ return (Math.Round(totalGB, 2), totalMB, totalKB, availableGB, usedPercent);
+ }
+
+ private static (double availableGB, double usedPercent) GetMemoryUsage()
+ {
+ var os = WmiHelper.GetFirst("SELECT FreePhysicalMemory, TotalVisibleMemorySize FROM Win32_OperatingSystem");
+ if (os == null) return (0, 0);
+
+ var freeKB = WmiHelper.GetLong(os, "FreePhysicalMemory");
+ var totalKB = WmiHelper.GetLong(os, "TotalVisibleMemorySize");
+
+ if (totalKB == 0) return (0, 0);
+
+ var availableGB = freeKB / 1024.0 / 1024.0;
+ var usedKB = totalKB - freeKB;
+ var usedPercent = Math.Round(usedKB * 100.0 / totalKB, 1);
+
+ return (Math.Round(availableGB, 2), usedPercent);
+ }
+}
+
+internal static class GpuProvider
+{
+ public static IReadOnlyList<GpuInfo> GetAll()
+ {
+ var gpus = new List<GpuInfo>();
+ var controllers = WmiHelper.Query("SELECT * FROM Win32_VideoController");
+
+ foreach (var controller in controllers)
+ {
+ var gpu = ParseGpu(controller);
+ if (gpu != null && !IsVirtualAdapter(gpu.Name)) gpus.Add(gpu);
+ }
+
+ return gpus.Count > 0 ? gpus : [GpuInfo.Unknown];
+ }
+
+ private static GpuInfo? ParseGpu(ManagementObject controller)
+ {
+ var name = WmiHelper.GetString(controller, "Name", "");
+ if (string.IsNullOrWhiteSpace(name)) return null;
+
+ var driver = WmiHelper.GetString(controller, "DriverVersion");
+ var deviceId = WmiHelper.GetString(controller, "DeviceID");
+ var pnpId = WmiHelper.GetString(controller, "PNPDeviceID");
+ var adapterRam = WmiHelper.GetLong(controller, "AdapterRAM");
+
+ int? memoryMB = adapterRam > 0 ? (int)(adapterRam / (1024 * 1024)) : null;
+ var vendor = DetectGpuVendor(name, pnpId);
+
+ return new GpuInfo(name, driver, vendor, memoryMB, deviceId, pnpId);
+ }
+
+ private static bool IsVirtualAdapter(string name)
+ {
+ var lower = name.ToLowerInvariant();
+ return lower.Contains("microsoft basic") ||
+ lower.Contains("remote desktop") ||
+ lower.Contains("virtual");
+ }
+
+ private static GpuVendor DetectGpuVendor(string name, string? pnpId)
+ {
+ var nameLower = name.ToLowerInvariant();
+ var pnpLower = pnpId?.ToLowerInvariant() ?? "";
+
+ if (nameLower.Contains("nvidia") || nameLower.Contains("geforce") ||
+ nameLower.Contains("quadro") || nameLower.Contains("tesla") || pnpLower.Contains("ven_10de"))
+ return GpuVendor.NVIDIA;
+
+ if (nameLower.Contains("amd") || nameLower.Contains("radeon") ||
+ nameLower.Contains("ryzen") || pnpLower.Contains("ven_1002"))
+ return GpuVendor.AMD;
+
+ if (nameLower.Contains("intel") || nameLower.Contains("iris") ||
+ nameLower.Contains("uhd") || pnpLower.Contains("ven_8086"))
+ return GpuVendor.Intel;
+
+ return GpuVendor.Unknown;
+ }
+
+ public static GpuInfo? GetPrimary(IReadOnlyList<GpuInfo> gpus)
+ {
+ if (gpus == null || gpus.Count == 0) return null;
+
+ return gpus
+ .OrderByDescending(CalculateGpuScore)
+ .FirstOrDefault();
+ }
+
+ private static int CalculateGpuScore(GpuInfo gpu)
+ {
+ var vendorScore = gpu.Vendor switch
+ {
+ GpuVendor.NVIDIA => 3,
+ GpuVendor.AMD => 2,
+ GpuVendor.Intel => 1,
+ _ => 0
+ };
+
+ var memoryBonus = gpu.MemoryMB is > 1024 ? 10 : 0;
+
+ return vendorScore + memoryBonus;
+ }
+}
+
+internal static class OsProvider
+{
+ public static OsInfo Get()
+ {
+ try
+ {
+ var os = WmiHelper.GetFirst("SELECT * FROM Win32_OperatingSystem");
+ if (os == null) return OsInfo.Unknown;
+
+ var caption = WmiHelper.GetString(os, "Caption", "Windows");
+ var buildNumber = WmiHelper.GetString(os, "BuildNumber");
+ var version = MapWindowsVersion(WmiHelper.GetString(os, "Version"), buildNumber);
+ var edition = ExtractEdition(caption);
+ var architecture = Environment.Is64BitOperatingSystem ? "64-bit" : "32-bit";
+ var deviceType = GetDeviceType();
+ var installDate = FormatWmiDate(WmiHelper.GetString(os, "InstallDate", ""));
+ var lastBoot = FormatWmiDateTime(WmiHelper.GetString(os, "LastBootUpTime", ""));
+ var name = $"Windows {version}";
+
+ return new OsInfo(name, version, buildNumber, edition, architecture, deviceType, installDate, lastBoot);
+ }
+ catch
+ {
+ return OsInfo.Unknown;
+ }
+ }
+
+ private static string MapWindowsVersion(string version, string build)
+ {
+ if (version.StartsWith("6.1")) return "7";
+ if (version.StartsWith("6.2")) return "8";
+ if (version.StartsWith("6.3")) return "8.1";
+ if (!version.StartsWith("10.0")) return "Unknown";
+
+ return int.TryParse(build, out var buildNum) && buildNum >= 22000 ? "11" : "10";
+ }
+
+ private static string ExtractEdition(string caption)
+ {
+ if (string.IsNullOrWhiteSpace(caption)) return "Unknown";
+
+ var parts = caption.Split(' ', StringSplitOptions.RemoveEmptyEntries);
+ return parts.Length > 2 ? parts.Last() : caption;
+ }
+
+ private static string GetDeviceType()
+ {
+ var chassis = WmiHelper.GetFirst("SELECT ChassisTypes FROM Win32_SystemEnclosure");
+ if (chassis == null) return "Unknown";
+
+ try
+ {
+ return chassis["ChassisTypes"] is ushort[] { Length: > 0 } types ? MapChassisType(types) : "Unknown";
+ }
+ catch
+ {
+ return "Unknown";
+ }
+ }
+
+ private static string MapChassisType(IEnumerable<ushort> types)
+ {
+ foreach (var type in types)
+ {
+ if (type is 8 or 9 or 10 or 11 or 14 or 30 or 31 or 32)
+ return "Laptop";
+
+ if (type is >= 1 and <= 7 or 12 or 13 or >= 15 and <= 29 or >= 33 and <= 36)
+ return "Desktop";
+ }
+
+ return "Unknown";
+ }
+
+ private static string FormatWmiDate(string wmiDate)
+ {
+ if (wmiDate.Length < 8) return "Unknown";
+ return $"{wmiDate[..4]}-{wmiDate.Substring(4, 2)}-{wmiDate.Substring(6, 2)}";
+ }
+
+ private static string FormatWmiDateTime(string wmiDate)
+ {
+ if (wmiDate.Length < 12) return "Unknown";
+ return
+ $"{wmiDate[..4]}-{wmiDate.Substring(4, 2)}-{wmiDate.Substring(6, 2)} {wmiDate.Substring(8, 2)}:{wmiDate.Substring(10, 2)}";
+ }
+}
+
+internal static class BiosProvider
+{
+ public static BiosInfo Get()
+ {
+ try
+ {
+ var bios = WmiHelper.GetFirst("SELECT * FROM Win32_BIOS");
+ if (bios == null) return BiosInfo.Unknown;
+
+ var manufacturer = WmiHelper.GetString(bios, "Manufacturer");
+ var version = WmiHelper.GetString(bios, "BIOSVersion");
+ var smbiosVersion = WmiHelper.GetString(bios, "SMBIOSBIOSVersion");
+ var serialNumber = WmiHelper.GetString(bios, "SerialNumber");
+ var releaseDate = FormatWmiDate(WmiHelper.GetString(bios, "ReleaseDate", ""));
+
+ return new BiosInfo(manufacturer, version, releaseDate, smbiosVersion, serialNumber);
+ }
+ catch
+ {
+ return BiosInfo.Unknown;
+ }
+ }
+
+ private static string FormatWmiDate(string wmiDate)
+ {
+ if (wmiDate.Length < 8) return "Unknown";
+ return $"{wmiDate[..4]}-{wmiDate.Substring(4, 2)}-{wmiDate.Substring(6, 2)}";
+ }
+}
+
+// ============================================================================
+// MAIN SERVICE (Public API)
+// ============================================================================
+
+public static class SystemInfoService
+{
+ private static readonly SemaphoreSlim _semaphore = new(1, 1);
+
+ public static SystemSnapshot Snapshot { get; private set; } = SystemSnapshot.Unknown;
+
+ public static async Task<SystemSnapshot> RefreshAsync(CancellationToken ct = default)
+ {
+ await _semaphore.WaitAsync(ct).ConfigureAwait(false);
+ try
+ {
+ var tasks = new Task[]
+ {
+ Task.Run(CpuProvider.Get, ct),
+ Task.Run(RamProvider.Get, ct),
+ Task.Run(OsProvider.Get, ct),
+ Task.Run(BiosProvider.Get, ct),
+ Task.Run(GpuProvider.GetAll, ct)
+ };
+
+ await Task.WhenAll(tasks).ConfigureAwait(false);
+
+ var cpu = ((Task<CpuInfo>)tasks[0]).Result;
+ var ram = ((Task<RamInfo>)tasks[1]).Result;
+ var os = ((Task<OsInfo>)tasks[2]).Result;
+ var bios = ((Task<BiosInfo>)tasks[3]).Result;
+ var gpus = ((Task<IReadOnlyList<GpuInfo>>)tasks[4]).Result;
+ var primaryGpu = GpuProvider.GetPrimary(gpus);
+
+ var snapshot = new SystemSnapshot(cpu, ram, os, bios, gpus, primaryGpu);
+ Snapshot = snapshot;
+
+ return snapshot;
+ }
+ finally
+ {
+ _semaphore.Release();
+ }
+ }
+
+ public static void GetSummary(SystemSnapshot s, ILogger log)
+ {
+ log.LogDebug("OS : {OsName} {OsEdition} {OsArchitecture} ({OsDeviceType})",
+ s.Os.Name, s.Os.Edition, s.Os.Architecture, s.Os.DeviceType);
+
+ LogGpuSummary(s, log);
+
+ log.LogDebug("CPU: {CpuName} ({CpuVendor}) [{CpuCores} Cores/{CpuThreads} Threads]",
+ s.Cpu.Name, s.Cpu.Vendor, s.Cpu.Cores, s.Cpu.Threads);
+
+ log.LogDebug("RAM: {RamTotalGb:F1} GB (Used: {RamUsedPercent:F1}%)",
+ s.Ram.TotalGB, s.Ram.UsedPercent);
+ }
+
+ private static void LogGpuSummary(SystemSnapshot s, ILogger log)
+ {
+ var gpuCount = s.Gpus.Count;
+
+ if (gpuCount == 0 || (gpuCount == 1 && s.Gpus[0] == GpuInfo.Unknown))
+ {
+ log.LogDebug("GPU: None detected");
+ return;
+ }
+
+ if (gpuCount == 1)
+ {
+ var gpu = s.Gpus[0];
+ var memoryInfo = gpu.MemoryMB.HasValue ? $" [{gpu.MemoryMB.Value / 1024.0:F0} GB]" : "";
+ log.LogDebug("GPU: {GpuName} ({GpuVendor}){MemoryInfo}", gpu.Name, gpu.Vendor, memoryInfo);
+ return;
+ }
+
+ // Multiple GPUs
+ if (s.PrimaryGpu != null)
+ {
+ var memoryInfo = s.PrimaryGpu.MemoryMB.HasValue
+ ? $" [{s.PrimaryGpu.MemoryMB.Value / 1024.0:F0} GB]"
+ : "";
+ log.LogDebug("GPU (Primary): {PrimaryGpuName} ({PrimaryGpuVendor}){MemoryInfo}",
+ s.PrimaryGpu.Name, s.PrimaryGpu.Vendor, memoryInfo);
+ }
+
+ log.LogDebug("Total GPUs : {GpuCount}", gpuCount);
+ }
+
+ public static Panel GetDetailedPanel(SystemSnapshot s)
+ {
+ // Operating System Information
+ var osGroup = new List<IRenderable>
+ {
+ new Rule("Operating System Information") { Style = Theme.Primary },
+ new Markup($"[{Theme.Info}]Name :[/] [bold]{s.Os.Name}[/]"),
+ new Markup($"[{Theme.Info}]Version :[/] [{Theme.Success}]{s.Os.Version}[/]"),
+ new Markup($"[{Theme.Info}]Build Number :[/] [{Theme.Success}]{s.Os.BuildNumber}[/]"),
+ new Markup($"[{Theme.Info}]Edition :[/] [{Theme.Warning}]{s.Os.Edition}[/]"),
+ new Markup($"[{Theme.Info}]Architecture :[/] [bold]{s.Os.Architecture}[/]"),
+ new Markup($"[{Theme.Info}]Device Type :[/] [bold]{s.Os.DeviceType}[/]"),
+ new Markup($"[{Theme.Info}]Install Date :[/] [{Theme.Success}]{s.Os.InstallDate}[/]"),
+ new Markup($"[{Theme.Info}]Last Boot :[/] [{Theme.Success}]{s.Os.LastBoot}[/]")
+ };
+
+ // BIOS Information
+ var biosGroup = new List<IRenderable>
+ {
+ new Rule("BIOS Information") { Style = Theme.Success },
+ new Markup($"[{Theme.Info}]Manufacturer :[/] [bold]{s.Bios.Manufacturer}[/]"),
+ new Markup($"[{Theme.Info}]Version :[/] [{Theme.Success}]{s.Bios.Version}[/]"),
+ new Markup($"[{Theme.Info}]Release Date :[/] [{Theme.Success}]{s.Bios.ReleaseDate}[/]"),
+ new Markup($"[{Theme.Info}]SMBIOS Version :[/] [{Theme.Success}]{s.Bios.SmbiosVersion}[/]")
+ };
+
+ // CPU Information
+ var cpuVendorColor = s.Cpu.Vendor == "AMD" ? Theme.Error : s.Cpu.Vendor == "Intel" ? Theme.Info : Theme.Muted;
+ var cpuGroup = new List<IRenderable>
+ {
+ new Rule("CPU Information") { Style = Theme.Info },
+ new Markup($"[{Theme.Info}]Name :[/] [bold]{s.Cpu.Name}[/]"),
+ new Markup($"[{Theme.Info}]Vendor :[/] [{cpuVendorColor}]{s.Cpu.Vendor}[/]"),
+ new Markup($"[{Theme.Info}]Manufacturer :[/] [bold]{s.Cpu.Manufacturer}[/]"),
+ new Markup($"[{Theme.Info}]Cores :[/] [{Theme.Success}]{s.Cpu.Cores}[/]"),
+ new Markup($"[{Theme.Info}]Threads :[/] [{Theme.Success}]{s.Cpu.Threads}[/]"),
+ new Markup($"[{Theme.Info}]Architecture :[/] [bold]{s.Cpu.Architecture}[/]"),
+ new Markup($"[{Theme.Info}]Max Clock Speed:[/] [{Theme.Warning}]{s.Cpu.MaxClockMHz}[/] [dim]MHz[/]"),
+ new Markup($"[{Theme.Info}]Current Speed :[/] [{Theme.Warning}]{s.Cpu.CurrentClockMHz}[/] [dim]MHz[/]"),
+ new Markup($"[{Theme.Info}]L2 Cache :[/] [{Theme.Success}]{s.Cpu.L2CacheKB}[/] [dim]KB[/]"),
+ new Markup($"[{Theme.Info}]L3 Cache :[/] [{Theme.Success}]{s.Cpu.L3CacheKB}[/] [dim]KB[/]")
+ };
+
+ // RAM Information
+ var usedColor = s.Ram.UsedPercent > 80 ? Theme.Error : s.Ram.UsedPercent > 60 ? Theme.Warning : Theme.Success;
+ var ramGroup = new List<IRenderable>
+ {
+ new Rule("Memory Information") { Style = new Style(Color.Yellow) },
+ new Markup(
+ $"[{Theme.Info}]Total :[/] [{Theme.Success}]{s.Ram.TotalGB:F2}[/] [dim]GB[/] [dim]([/][blue]{s.Ram.TotalMB}[/] [dim]MB)[/]"),
+ new Markup($"[{Theme.Info}]Available :[/] [{Theme.Success}]{s.Ram.AvailableGB:F2}[/] [dim]GB[/]"),
+ new Markup($"[{Theme.Info}]Used :[/] [{usedColor}]{s.Ram.UsedPercent:F1}%[/]")
+ };
+
+ if (s.Ram.Modules.Count > 0)
+ {
+ ramGroup.Add(new Markup(
+ $"[{Theme.Info}]Modules :[/] [{Theme.Success}]{s.Ram.Modules.Count}[/] [dim]detected[/]"));
+ for (var i = 0; i < s.Ram.Modules.Count; i++)
+ {
+ var module = s.Ram.Modules[i];
+ ramGroup.Add(new Markup(
+ $" [{Theme.Info}]Module {i + 1} :[/] [{Theme.Warning}]{module.CapacityGB:F2}[/] [dim]GB @[/] [{Theme.Success}]{module.SpeedMHz}[/] [dim]MHz[/]"));
+ ramGroup.Add(new Markup($" [dim]Manufacturer:[/] [{Theme.Info}]{module.Manufacturer}[/]"));
+ ramGroup.Add(new Markup($" [dim]Part Number :[/] [bold]{module.PartNumber}[/]"));
+ ramGroup.Add(new Markup($" [dim]Location :[/] [bold]{module.DeviceLocator}[/]"));
+ }
+ }
+
+ // GPU Information
+ var gpuCount = s.Gpus.Count;
+ var gpuGroup = new List<IRenderable>();
+
+ if (gpuCount == 0 || (gpuCount == 1 && s.Gpus[0] == GpuInfo.Unknown))
+ {
+ gpuGroup.Add(new Rule("GPU Information") { Style = new Style(Color.Red) });
+ gpuGroup.Add(new Markup($"[{Theme.Error}]No GPUs detected[/]"));
+ }
+ else if (gpuCount == 1)
+ {
+ gpuGroup.Add(new Rule("GPU Information") { Style = new Style(Color.Green) });
+ var gpu = s.Gpus[0];
+ var vendorColor = gpu.Vendor switch
+ {
+ GpuVendor.NVIDIA => Theme.Success,
+ GpuVendor.AMD => Theme.Error,
+ GpuVendor.Intel => Theme.Accent,
+ _ => Theme.Muted
+ };
+
+ gpuGroup.Add(new Markup($"[{Theme.Info}]Name :[/] [bold]{gpu.Name}[/]"));
+ gpuGroup.Add(new Markup($"[{Theme.Info}]Vendor :[/] [{vendorColor}]{gpu.Vendor}[/]"));
+ gpuGroup.Add(new Markup($"[{Theme.Info}]Driver Version :[/] [{Theme.Warning}]{gpu.DriverVersion}[/]"));
+
+ if (gpu.MemoryMB.HasValue)
+ gpuGroup.Add(new Markup(
+ $"[{Theme.Info}]Memory :[/] [{Theme.Success}]{gpu.MemoryMB.Value}[/] [dim]MB[/] [dim]([/][{Theme.Success}]{gpu.MemoryMB.Value / 1024.0:F2}[/] [dim]GB)[/]"));
+
+ if (!string.IsNullOrEmpty(gpu.DeviceId))
+ gpuGroup.Add(new Markup($"[{Theme.Info}]Device ID :[/] [dim]{gpu.DeviceId}[/]"));
+
+ if (!string.IsNullOrEmpty(gpu.PnpDeviceId))
+ gpuGroup.Add(new Markup($"[{Theme.Info}]PCI Device ID :[/] [dim]{gpu.PnpDeviceId}[/]"));
+ }
+ else
+ {
+ gpuGroup.Add(new Rule($"GPU Information ({gpuCount} detected)") { Style = new Style(Color.Green) });
+ for (var i = 0; i < s.Gpus.Count; i++)
+ {
+ var gpu = s.Gpus[i];
+ var isPrimary = s.PrimaryGpu != null && gpu.Name == s.PrimaryGpu.Name ? " (Primary)" : "";
+ var vendorColor = gpu.Vendor switch
+ {
+ GpuVendor.NVIDIA => Theme.Success,
+ GpuVendor.AMD => Theme.Error,
+ GpuVendor.Intel => Theme.Accent,
+ _ => Theme.Muted
+ };
+
+ gpuGroup.Add(new Markup($"[{Theme.Info}]GPU {i + 1}{isPrimary}:[/]"));
+ gpuGroup.Add(new Markup($" [{Theme.Info}]Name :[/] [bold]{gpu.Name}[/]"));
+ gpuGroup.Add(
+ new Markup($" [{Theme.Info}]Vendor :[/] [{vendorColor}]{gpu.Vendor}[/{vendorColor}]"));
+ gpuGroup.Add(new Markup($" [{Theme.Info}]Driver :[/] [{Theme.Warning}]{gpu.DriverVersion}[/]"));
+
+ if (gpu.MemoryMB.HasValue)
+ gpuGroup.Add(new Markup(
+ $" [{Theme.Info}]Memory :[/] [{Theme.Success}]{gpu.MemoryMB.Value}[/] [dim]MB[/] [dim]([/][{Theme.Success}]{gpu.MemoryMB.Value / 1024.0:F2}[/] [dim]GB)[/]"));
+
+ if (!string.IsNullOrEmpty(gpu.DeviceId))
+ gpuGroup.Add(new Markup($" [{Theme.Info}]Device ID :[/] [dim]{gpu.DeviceId}[/]"));
+
+ if (!string.IsNullOrEmpty(gpu.PnpDeviceId))
+ gpuGroup.Add(new Markup($" [{Theme.Info}]PCI Device ID:[/] [dim]{gpu.PnpDeviceId}[/]"));
+ }
+ }
+
+ // Combine all groups
+ var allGroups = new List<IRenderable>();
+ allGroups.AddRange(osGroup);
+ allGroups.Add(Text.Empty);
+ allGroups.AddRange(biosGroup);
+ allGroups.Add(Text.Empty);
+ allGroups.AddRange(cpuGroup);
+ allGroups.Add(Text.Empty);
+ allGroups.AddRange(ramGroup);
+ allGroups.Add(Text.Empty);
+ allGroups.AddRange(gpuGroup);
+
+ var panel = new Panel(new Rows(allGroups))
+ {
+ Border = BoxBorder.Rounded,
+ BorderStyle = Theme.PrimaryMuted,
+ Width = 90
+ };
+
+ return panel;
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/Interfaces/IOptimizationGroup.cs b/optimizerDuck/src/Interfaces/IOptimizationGroup.cs
new file mode 100644
index 0000000..a60c157
--- /dev/null
+++ b/optimizerDuck/src/Interfaces/IOptimizationGroup.cs
@@ -0,0 +1,10 @@
+using Microsoft.Extensions.Logging;
+
+namespace optimizerDuck.Interfaces;
+
+public interface IOptimizationGroup
+{
+ public string Name { get; }
+ public int Priority { get; }
+ public static abstract ILogger Log { get; }
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/Interfaces/IOptimizationTweak.cs b/optimizerDuck/src/Interfaces/IOptimizationTweak.cs
new file mode 100644
index 0000000..91ccb1e
--- /dev/null
+++ b/optimizerDuck/src/Interfaces/IOptimizationTweak.cs
@@ -0,0 +1,11 @@
+using optimizerDuck.Core.Services;
+
+namespace optimizerDuck.Interfaces;
+
+public interface IOptimizationTweak
+{
+ public string Name { get; }
+ public string Description { get; }
+ public bool EnabledByDefault { get; }
+ public Task Apply(SystemSnapshot s);
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/Models/OptimizationGroupChoice.cs b/optimizerDuck/src/Models/OptimizationGroupChoice.cs
new file mode 100644
index 0000000..788a759
--- /dev/null
+++ b/optimizerDuck/src/Models/OptimizationGroupChoice.cs
@@ -0,0 +1,3 @@
+namespace optimizerDuck.Models;
+
+public record struct OptimizationGroupChoice(string Name, int Priority, List<OptimizationTweakChoice> Tweaks);
\ No newline at end of file
diff --git a/optimizerDuck/src/Models/OptimizationGroupPriority.cs b/optimizerDuck/src/Models/OptimizationGroupPriority.cs
new file mode 100644
index 0000000..53d78be
--- /dev/null
+++ b/optimizerDuck/src/Models/OptimizationGroupPriority.cs
@@ -0,0 +1,10 @@
+namespace optimizerDuck.Models;
+
+public enum OptimizationGroupPriority
+{
+ SecurityAndPrivacy,
+ PerformanceAndPower,
+ GamingOptimizations,
+ UserExperience,
+ BloatwareAndServices
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/Models/OptimizationTweakChoice.cs b/optimizerDuck/src/Models/OptimizationTweakChoice.cs
new file mode 100644
index 0000000..7bce0ee
--- /dev/null
+++ b/optimizerDuck/src/Models/OptimizationTweakChoice.cs
@@ -0,0 +1,9 @@
+using optimizerDuck.Interfaces;
+
+namespace optimizerDuck.Models;
+
+public record struct OptimizationTweakChoice(
+ IOptimizationTweak? Instance,
+ string Name,
+ string? Description,
+ bool EnabledByDefault);
\ No newline at end of file
diff --git a/optimizerDuck/src/Models/RegistryItem.cs b/optimizerDuck/src/Models/RegistryItem.cs
new file mode 100644
index 0000000..1f29797
--- /dev/null
+++ b/optimizerDuck/src/Models/RegistryItem.cs
@@ -0,0 +1,57 @@
+using Microsoft.Win32;
+
+namespace optimizerDuck.Models;
+
+public record struct RegistryItem
+{
+ public readonly RegistryValueKind Kind;
+ public readonly string? Name;
+ public readonly string Path;
+ public readonly object? Value;
+
+ public RegistryItem(string path, string name, object value, RegistryValueKind kind)
+ {
+ Path = path;
+ Name = name;
+ Value = value;
+ Kind = kind;
+ }
+
+ public RegistryItem(string path, string name, object value)
+ {
+ Path = path;
+ Name = name;
+ Value = value;
+ Kind = AutoDetectKind(value);
+ }
+
+ public RegistryItem(string path, string name)
+ {
+ Path = path;
+ Name = name;
+ Value = null;
+ Kind = RegistryValueKind.Unknown;
+ }
+
+ public RegistryItem(string path)
+ {
+ Path = path;
+ Name = null;
+ Value = null;
+ Kind = RegistryValueKind.Unknown;
+ }
+
+ private static RegistryValueKind AutoDetectKind(object? value)
+ {
+ return value switch
+ {
+ null => RegistryValueKind.Unknown,
+ int => RegistryValueKind.DWord,
+ long => RegistryValueKind.QWord,
+ string => RegistryValueKind.String,
+ string[] => RegistryValueKind.MultiString,
+ byte[] => RegistryValueKind.Binary,
+ _ => RegistryValueKind.Unknown
+ };
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/Models/ServiceItem.cs b/optimizerDuck/src/Models/ServiceItem.cs
new file mode 100644
index 0000000..670ec01
--- /dev/null
+++ b/optimizerDuck/src/Models/ServiceItem.cs
@@ -0,0 +1,3 @@
+namespace optimizerDuck.Models;
+
+public record struct ServiceItem(string ServiceName, ServiceStartupType StartupType);
\ No newline at end of file
diff --git a/optimizerDuck/src/Models/ServiceStartupType.cs b/optimizerDuck/src/Models/ServiceStartupType.cs
new file mode 100644
index 0000000..a7efbe1
--- /dev/null
+++ b/optimizerDuck/src/Models/ServiceStartupType.cs
@@ -0,0 +1,9 @@
+namespace optimizerDuck.Models;
+
+public enum ServiceStartupType
+{
+ Automatic,
+ Manual,
+ Disabled,
+ AutomaticDelayedStart
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/UI/Components/CustomBoxBorder.cs b/optimizerDuck/src/UI/Components/CustomBoxBorder.cs
new file mode 100644
index 0000000..d79a53e
--- /dev/null
+++ b/optimizerDuck/src/UI/Components/CustomBoxBorder.cs
@@ -0,0 +1,68 @@
+using Spectre.Console;
+using Spectre.Console.Rendering;
+
+namespace optimizerDuck.UI.Components;
+
+public static class CustomBoxBorder
+{
+ public static BoxBorder UnderlineBorder => new CUnderlineBorder();
+ public static BoxBorder LeftBorder => new CLeftBorder();
+ public static BoxBorder EmptyBorder => new CEmptyBorder();
+
+ private sealed class CUnderlineBorder : BoxBorder
+ {
+ public override string GetPart(BoxBorderPart part)
+ {
+ return part switch
+ {
+ BoxBorderPart.TopLeft => " ",
+ BoxBorderPart.Top => " ",
+ BoxBorderPart.TopRight => " ",
+ BoxBorderPart.Left => " ",
+ BoxBorderPart.Right => " ",
+ BoxBorderPart.BottomLeft => "─",
+ BoxBorderPart.Bottom => "─",
+ BoxBorderPart.BottomRight => "─",
+ _ => throw new InvalidOperationException("Unknown border part.")
+ };
+ }
+ }
+
+ private sealed class CLeftBorder : BoxBorder
+ {
+ public override string GetPart(BoxBorderPart part)
+ {
+ return part switch
+ {
+ BoxBorderPart.TopLeft => " ",
+ BoxBorderPart.Top => " ",
+ BoxBorderPart.TopRight => " ",
+ BoxBorderPart.Left => "│",
+ BoxBorderPart.Right => " ",
+ BoxBorderPart.BottomLeft => " ",
+ BoxBorderPart.Bottom => " ",
+ BoxBorderPart.BottomRight => " ",
+ _ => throw new InvalidOperationException("Unknown border part.")
+ };
+ }
+ }
+
+ private sealed class CEmptyBorder : BoxBorder
+ {
+ public override string GetPart(BoxBorderPart part)
+ {
+ return part switch
+ {
+ BoxBorderPart.TopLeft => " ",
+ BoxBorderPart.Top => " ",
+ BoxBorderPart.TopRight => " ",
+ BoxBorderPart.Left => " ",
+ BoxBorderPart.Right => " ",
+ BoxBorderPart.BottomLeft => " ",
+ BoxBorderPart.Bottom => " ",
+ BoxBorderPart.BottomRight => " ",
+ _ => throw new InvalidOperationException("Unknown border part.")
+ };
+ }
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/UI/Components/EscapeCancellableConsole.cs b/optimizerDuck/src/UI/Components/EscapeCancellableConsole.cs
new file mode 100644
index 0000000..7cd9e78
--- /dev/null
+++ b/optimizerDuck/src/UI/Components/EscapeCancellableConsole.cs
@@ -0,0 +1,97 @@
+using Spectre.Console;
+using Spectre.Console.Rendering;
+
+namespace optimizerDuck.UI.Components;
+
+// original from https://github.com/spectreconsole/spectre.console/discussions/700#discussioncomment-12960984
+internal sealed class EscapeCancellableConsole : IAnsiConsole, IDisposable
+{
+ private readonly IAnsiConsole _console;
+ private readonly CancellationTokenSource _cts = new();
+ private readonly EscapeCancellableInput _input;
+
+ public EscapeCancellableConsole(IAnsiConsole console)
+ {
+ _console = console ?? throw new ArgumentNullException(nameof(console));
+ _input = new EscapeCancellableInput(console.Input, _cts);
+
+ Console.CancelKeyPress += OnCancelKeyPress;
+ }
+
+ public Profile Profile => _console.Profile;
+ public IAnsiConsoleCursor Cursor => _console.Cursor;
+ public IAnsiConsoleInput Input => _input;
+ public IExclusivityMode ExclusivityMode => _console.ExclusivityMode;
+ public RenderPipeline Pipeline => _console.Pipeline;
+
+ public void Clear(bool home)
+ {
+ _console.Clear(home);
+ }
+
+ public void Write(IRenderable renderable)
+ {
+ _console.Write(renderable);
+ }
+
+ public void Dispose()
+ {
+ Console.CancelKeyPress -= OnCancelKeyPress;
+ _cts.Dispose();
+ }
+
+
+ private void OnCancelKeyPress(object? sender, ConsoleCancelEventArgs e)
+ {
+ e.Cancel = true;
+ if (!_cts.IsCancellationRequested)
+ {
+ _cts.Cancel();
+ Console.CancelKeyPress -= OnCancelKeyPress;
+ }
+ }
+
+ public Task<T> PromptAsync<T>(IPrompt<T> prompt, CancellationToken cancellationToken = default)
+ {
+ return AnsiConsoleExtensions.PromptAsync(this, prompt, MergeToken(cancellationToken));
+ }
+
+ private CancellationToken MergeToken(CancellationToken external)
+ {
+ if (external == CancellationToken.None || external == _cts.Token)
+ return _cts.Token;
+
+ var linked = CancellationTokenSource.CreateLinkedTokenSource(external, _cts.Token);
+ return linked.Token;
+ }
+}
+
+internal sealed class EscapeCancellableInput(IAnsiConsoleInput original, CancellationTokenSource cts)
+ : IAnsiConsoleInput
+{
+ private readonly CancellationTokenSource _cts = cts ?? throw new ArgumentNullException(nameof(cts));
+ private readonly IAnsiConsoleInput _original = original ?? throw new ArgumentNullException(nameof(original));
+
+ public bool IsKeyAvailable()
+ {
+ return _original.IsKeyAvailable();
+ }
+
+ public ConsoleKeyInfo? ReadKey(bool intercept)
+ {
+ var key = _original.ReadKey(intercept);
+ if (key?.Key == ConsoleKey.Escape)
+ _cts.Cancel();
+
+ return key;
+ }
+
+ public async Task<ConsoleKeyInfo?> ReadKeyAsync(bool intercept, CancellationToken cancellationToken)
+ {
+ var key = await _original.ReadKeyAsync(intercept, cancellationToken).ConfigureAwait(false);
+ if (key?.Key == ConsoleKey.Escape)
+ await _cts.CancelAsync();
+
+ return key;
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/UI/Components/PromptDialog.cs b/optimizerDuck/src/UI/Components/PromptDialog.cs
new file mode 100644
index 0000000..ec8c4af
--- /dev/null
+++ b/optimizerDuck/src/UI/Components/PromptDialog.cs
@@ -0,0 +1,198 @@
+using Microsoft.Extensions.Logging;
+using optimizerDuck.Core.Helpers;
+using optimizerDuck.UI.Logger;
+using Spectre.Console;
+
+namespace optimizerDuck.UI.Components;
+
+public record PromptOption
+{
+ public PromptOption(string key, string color, Action? action = null)
+ {
+ Key = key;
+ Color = color;
+ if (action != null)
+ OnSelected = () =>
+ {
+ action();
+ return true;
+ }; // default to return true
+ else
+ OnSelected = () => true;
+ }
+
+ public PromptOption(string key, string color, Func<bool> func)
+ {
+ Key = key;
+ Color = color;
+ OnSelected = func;
+ }
+
+ public string Key { get; }
+ public string Color { get; }
+ public Func<bool> OnSelected { get; }
+}
+
+public class PromptDialog
+{
+ private static readonly ILogger Log = Logger.Logger.CreateLogger<PromptDialog>();
+ private static string _previousTitle = "";
+
+ private readonly List<PromptOption> _options = [];
+ private string _borderColor = "grey";
+ private string _description = "";
+
+ private string _title = "";
+ private string _titleColor = "white";
+
+ public PromptDialog Title(string title)
+ {
+ _title = title;
+ return this;
+ }
+
+ public PromptDialog TitleColor(string color)
+ {
+ _titleColor = color;
+ return this;
+ }
+
+ public PromptDialog Description(string description)
+ {
+ _description = description;
+ return this;
+ }
+
+ public PromptDialog AddOption(params PromptOption[] options)
+ {
+ _options.AddRange(options);
+ return this;
+ }
+
+ public PromptDialog BorderColor(string color)
+ {
+ _borderColor = color;
+ return this;
+ }
+
+ private string Prompt()
+ {
+ var buttonList = new List<string>();
+ var keyMap = new Dictionary<char, string>(); // "Yes" => Y: Yes
+ foreach (var (option, key, rest, color) in from option in _options
+ let key = char.ToUpper(option.Key[0])
+ let rest = option.Key.Substring(1)
+ let color = option.Color
+ select (option, key, rest, color))
+ {
+ buttonList.Add($"[{color}][underline]{key}[/]{rest}[/]");
+ keyMap[key] = option.Key;
+ }
+
+ var buttons = string.Join(" ", buttonList);
+
+ var panelContent = new Rows(
+ new Markup(_description).Centered(),
+ new Text("\n"),
+ new Markup(buttons).Centered()
+ );
+ var panel = new Panel(panelContent)
+ {
+ Header = new PanelHeader($"[bold {_titleColor}] {_title} [/]", Justify.Center),
+ Border = BoxBorder.Rounded,
+ BorderStyle = _borderColor,
+ Padding = new Padding(5, 1, 5, 1)
+ };
+ AnsiConsole.Write(Align.Center(panel));
+ Console.Beep();
+
+ _previousTitle = Console.Title;
+ SystemHelper.Title(_title);
+
+
+ using (new StatusContextScope(
+ GlobalStatus.Current,
+ Spinner.Known.SimpleDotsScrolling,
+ _borderColor,
+ "Select an option to continue"))
+ {
+ while (true)
+ {
+ Console.CursorVisible = false;
+ var keyInfo = Console.ReadKey(true);
+ Console.CursorVisible = true;
+
+ var pressed = char.ToUpper(keyInfo.KeyChar);
+
+ if (keyMap.TryGetValue(pressed, out var value))
+ {
+ Log.LogDebug("[{Title}] User selected option: {Option}", _title, value);
+ Console.Title = _previousTitle;
+ return value;
+ }
+
+ AnsiConsole.MarkupLine("[red]Invalid key![/] [dim]Press the first character of the option![/]");
+ }
+ }
+ }
+
+
+ public static bool Warning(string title, string description, params PromptOption[] options)
+ {
+ var panel = new PromptDialog()
+ .Title(title)
+ .Description(description);
+
+ var finalOptions = options is { Length: > 0 }
+ ? options
+ :
+ [
+ new PromptOption("Continue anyways", Theme.Success),
+ new PromptOption("Exit", Theme.Error, () => Environment.Exit(1))
+ ];
+
+ panel.AddOption(finalOptions)
+ .TitleColor($"black on {Theme.Warning}")
+ .BorderColor(Theme.WarningMuted);
+
+ var choice = panel.Prompt();
+ var selected = finalOptions.FirstOrDefault(o => o.Key == choice)!;
+
+ return selected!.OnSelected!.Invoke();
+ }
+
+
+ public static void Exception(Exception exception, string title, string description, params PromptOption[] options)
+ {
+ var panel = new PromptDialog()
+ .Title(title)
+ .Description($"""
+ {description}
+
+ [bold {Theme.Error}]Exception:[/]
+ [italic]{exception.GetType().Name}[/]
+ [bold {Theme.Error}]{exception.Message}[/]
+
+ [dim]──────────────────────────────[/]
+ [grey]Please check the log file for more details.[/]
+ """);
+
+ var finalOptions = options is { Length: > 0 }
+ ? options
+ :
+ [
+ new PromptOption("Exit", Theme.Error, () => Environment.Exit(1)),
+ new PromptOption("Restart Application", Theme.Success, () => RequirementChecker.Restart(true)),
+ new PromptOption("Open log", Theme.Warning, SystemHelper.OpenLogFile)
+ ];
+
+ panel.AddOption(finalOptions)
+ .TitleColor($"black on {Theme.Error}")
+ .BorderColor(Theme.ErrorMuted);
+
+ var choice = panel.Prompt();
+
+ var selected = finalOptions.FirstOrDefault(o => o.Key == choice);
+ selected!.OnSelected.Invoke();
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/UI/Components/PromptPanel.cs b/optimizerDuck/src/UI/Components/PromptPanel.cs
new file mode 100644
index 0000000..e45c493
--- /dev/null
+++ b/optimizerDuck/src/UI/Components/PromptPanel.cs
@@ -0,0 +1,48 @@
+using optimizerDuck.Core.Extensions;
+using Spectre.Console;
+
+namespace optimizerDuck.UI.Components;
+
+public class PromptPanel
+{
+ private readonly BoxBorder _border = BoxBorder.Rounded;
+ private readonly string _color = "white";
+ private readonly string _description = "";
+ private readonly char _index = ' ';
+ private readonly string _title = "";
+ private readonly int? _width;
+
+ public PromptPanel(char index, string title, string description, string color, BoxBorder? border = null,
+ int? width = null)
+ {
+ _index = index;
+ _title = title;
+ _description = description;
+ _color = color;
+ _width = width ?? _width;
+ _border = border ?? _border;
+ }
+
+ public Panel Build()
+ {
+ var desc = _width.HasValue
+ ? _description.LimitWidth(_width.Value)
+ : _description;
+
+ var panel = new Panel(
+ $"[black on {_color}] {_index} [/] " +
+ $"[bold {_color}]{_title}[/]\n[{Theme.Muted}]{desc}[/]"
+ )
+ {
+ Padding = new Padding(2, 0),
+ Border = _border,
+ BorderStyle = _color,
+ Expand = false
+ };
+
+ if (_width.HasValue)
+ panel.Width = _width.Value;
+
+ return panel;
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/UI/Logger/GlobalStatus.cs b/optimizerDuck/src/UI/Logger/GlobalStatus.cs
new file mode 100644
index 0000000..00598f3
--- /dev/null
+++ b/optimizerDuck/src/UI/Logger/GlobalStatus.cs
@@ -0,0 +1,8 @@
+using Spectre.Console;
+
+namespace optimizerDuck.UI.Logger;
+
+public static class GlobalStatus
+{
+ public static StatusContext? Current { get; set; }
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/UI/Logger/Logger.cs b/optimizerDuck/src/UI/Logger/Logger.cs
new file mode 100644
index 0000000..ad471c2
--- /dev/null
+++ b/optimizerDuck/src/UI/Logger/Logger.cs
@@ -0,0 +1,200 @@
+using System.Reflection;
+using Microsoft.Extensions.Logging;
+using optimizerDuck.Core;
+using Serilog;
+using Serilog.Core;
+using Serilog.Events;
+using Serilog.Formatting;
+using Serilog.Parsing;
+using Spectre.Console;
+using Vertical.SpectreLogger;
+using Vertical.SpectreLogger.Options;
+using Vertical.SpectreLogger.Rendering;
+using ILogger = Microsoft.Extensions.Logging.ILogger;
+
+namespace optimizerDuck.UI.Logger;
+
+public class PlainTextFormatter : ITextFormatter
+{
+ public void Format(LogEvent logEvent, TextWriter output)
+ {
+ // [2025/10/30 21:15:43]
+ output.Write($"[{logEvent.Timestamp:yyyy/MM/dd HH:mm:ss}]");
+
+ // [SourceContext]
+ if (logEvent.Properties.TryGetValue("SourceContext", out var ctx) && ctx is ScalarValue sv)
+ output.Write($" [{sv.Value,-25}]");
+
+
+
+ // [INFO ]
+ var levelText = logEvent.Level switch
+ {
+ LogEventLevel.Verbose => "VERBOSE",
+ LogEventLevel.Debug => "DEBUG",
+ LogEventLevel.Information => "INFO",
+ LogEventLevel.Warning => "WARNING",
+ LogEventLevel.Error => "ERROR",
+ LogEventLevel.Fatal => "FATAL",
+ _ => "UNKNOWN"
+ };
+ output.Write($" [{levelText,-7}]");
+
+ // [Scope1] [Scope2] ...
+ if (logEvent.Properties.TryGetValue("Scope", out var scopeValue))
+ {
+ if (scopeValue is SequenceValue seq)
+ foreach (var scope in seq.Elements)
+ {
+ var text = scope switch
+ {
+ ScalarValue s => s.Value?.ToString(),
+ _ => scope.ToString()
+ };
+
+ if (!string.IsNullOrWhiteSpace(text))
+ output.Write($" [{text}]");
+ }
+ else if (scopeValue is ScalarValue single) output.Write($" [{single.Value}]");
+ }
+
+
+ // Message
+ var message = RenderWithoutQuotes(logEvent);
+ if (logEvent.Level == LogEventLevel.Debug) // i want to keep markup for debug logs
+ output.Write($" {message}");
+ else
+ output.Write($" {Markup.Remove(message)}");
+
+ // Include exception details if present
+ if (logEvent.Exception != null)
+ {
+ output.WriteLine();
+ output.Write(logEvent.Exception.ToString());
+ }
+
+ // Add a new line at the end of the log event
+ output.WriteLine();
+ }
+
+ private static string RenderWithoutQuotes(LogEvent logEvent)
+ {
+ var output = new StringWriter();
+ foreach (var token in logEvent.MessageTemplate.Tokens)
+ if (token is PropertyToken pt && logEvent.Properties.TryGetValue(pt.PropertyName, out var value))
+ {
+ if (value is ScalarValue { Value: string s })
+ // write string without quotes
+ output.Write(s);
+ else
+ // use default rendering for other types
+ pt.Render(logEvent.Properties, output);
+ }
+ else
+ {
+ token.Render(logEvent.Properties, output);
+ }
+
+ return output.ToString();
+ }
+}
+
+public class ShortSourceContextEnricher : ILogEventEnricher
+{
+ //private readonly string _rootNamespace = Assembly.GetEntryAssembly()?.GetName().Name?.Replace(' ', '_') + ".";
+
+ public void Enrich(LogEvent logEvent, ILogEventPropertyFactory factory)
+ {
+ if (logEvent.Properties.TryGetValue("SourceContext", out var value))
+ {
+ //Console.WriteLine(_rootNamespace);
+
+ var fullName = value.ToString().Trim('"');
+
+
+ // if the source context is in the root namespace, remove it
+ // var name = fullName.StartsWith(_rootNamespace)
+ // ? fullName.Substring(_rootNamespace.Length)
+ // : fullName;
+
+ var name = fullName.Split('.').Last();
+
+ logEvent.AddOrUpdateProperty(factory.CreateProperty("SourceContext", name));
+ }
+ }
+}
+
+public static class Logger
+{
+ public static readonly string LogFilePath = Path.Combine(Defaults.RootPath, "debug.log");
+ private static readonly ILoggerFactory _loggerFactory;
+
+ static Logger()
+ {
+ Log.Logger = new LoggerConfiguration()
+ .MinimumLevel.Debug()
+ .Enrich.With<ShortSourceContextEnricher>()
+ .WriteTo.File(new PlainTextFormatter(), LogFilePath, shared:true)
+ .CreateLogger();
+
+ // add a header to the log file
+ Log.Logger.Information("\n\n{Logo}\nVersion: {Version}\n\n", Defaults.RawLogo, Defaults.FileVersion);
+
+ _loggerFactory = LoggerFactory.Create(builder =>
+ {
+ builder.AddSpectreConsole(config =>
+ {
+ config.SetMinimumLevel(Environment.GetCommandLineArgs().Contains("--debug")
+ ? LogLevel.Debug
+ : LogLevel.Information);
+
+ config.ConfigureProfiles(profile =>
+ {
+ // https://github.com/verticalsoftware/vertical-spectreconsolelogger/issues/31
+ profile.PreserveMarkupInFormatStrings = true;
+
+ // https://github.com/verticalsoftware/vertical-spectreconsolelogger/blob/dev/src/Options/SerilogStyleLoggerOptions.cs
+ // https://github.com/verticalsoftware/vertical-spectreconsolelogger/blob/dev/docs/styling.md
+ profile
+ .AddTypeFormatter<LogLevel>((_, value, _) =>
+ value switch
+ {
+ LogLevel.Trace => "TRACE",
+ LogLevel.Debug => "DEBUG",
+ LogLevel.Information => "INFO",
+ LogLevel.Warning => "WARNING",
+ LogLevel.Error => "ERROR",
+ LogLevel.Critical => "CRITICAL",
+ _ => "UNKNOWN"
+ })
+ .AddTypeStyle<int>($"[{Theme.Primary}]")
+ .AddTypeStyle<string>($"[{Theme.Primary}]")
+ .AddTypeStyle<DateTimeRenderer.Value>($"[{Theme.Muted}]");
+
+ profile.OutputTemplate = "{DateTime:yyyy/MM/dd HH:mm:ss} {LogLevel,-7} {Message}{NewLine}";
+ profile.DefaultLogValueStyle = $"[{Theme.Primary}]";
+ });
+ config.ConfigureProfile(LogLevel.Information,
+ profile => profile.AddTypeStyle<LogLevel>($"[{Theme.Info}]"));
+ config.ConfigureProfile(LogLevel.Debug,
+ profile => profile.AddTypeStyle<LogLevel>($"[{Theme.Warning}]"));
+ config.ConfigureProfile(LogLevel.Warning,
+ profile => profile.AddTypeStyle<LogLevel>($"[{Theme.Warning}]"));
+ config.ConfigureProfile(LogLevel.Error, profile => profile.AddTypeStyle<LogLevel>($"[{Theme.Error}]"));
+ config.ConfigureProfile(LogLevel.Critical,
+ profile => profile.AddTypeStyle<LogLevel>($"[{Theme.Error}]"));
+ });
+ builder.AddSerilog(Log.Logger);
+ });
+ }
+
+ public static ILogger CreateLogger<T>()
+ {
+ return _loggerFactory.CreateLogger<T>();
+ }
+
+ public static ILogger CreateLogger(Type type)
+ {
+ return _loggerFactory.CreateLogger(type);
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/UI/Logger/ServiceTracker.cs b/optimizerDuck/src/UI/Logger/ServiceTracker.cs
new file mode 100644
index 0000000..44a7c88
--- /dev/null
+++ b/optimizerDuck/src/UI/Logger/ServiceTracker.cs
@@ -0,0 +1,67 @@
+using System.Diagnostics;
+using Microsoft.Extensions.Logging;
+
+namespace optimizerDuck.UI.Logger;
+
+public class ServiceTracker : IDisposable
+{
+ private static readonly AsyncLocal<ServiceTracker?> _current = new();
+
+ private readonly Dictionary<string, (int Success, int Fail)> _serviceStats;
+ private readonly Stopwatch _stopwatch;
+
+ private ServiceTracker(ILogger logger)
+ {
+ Log = logger;
+ _stopwatch = Stopwatch.StartNew();
+ _serviceStats = new Dictionary<string, (int Success, int Fail)>();
+ }
+
+ public static ServiceTracker? Current => _current.Value;
+
+ public ILogger Log { get; }
+
+ public void Dispose()
+ {
+ _stopwatch.Stop();
+ var time = FormatTime(_stopwatch.Elapsed);
+
+ var stats = string.Join(" [dim]|[/] ", _serviceStats.Select(kvp =>
+ $"{kvp.Key}: [{Theme.Success}]{kvp.Value.Success}[/][dim]/[/][{Theme.Error}]{kvp.Value.Fail}[/]"));
+
+ Log.LogInformation($"[{Theme.Muted}]Time: {time}[/] [dim]|[/] {stats}");
+
+ _current.Value = null;
+ GC.SuppressFinalize(this); // https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1816
+ }
+
+
+ public static ServiceTracker Begin(ILogger? logger = null)
+ {
+ var log = logger ?? Logger.CreateLogger<ServiceTracker>();
+ var tracker = new ServiceTracker(log);
+ _current.Value = tracker;
+ return tracker;
+ }
+
+ internal void Track(string serviceName, bool success)
+ {
+ if (!_serviceStats.ContainsKey(serviceName)) _serviceStats[serviceName] = (0, 0);
+
+ var current = _serviceStats[serviceName];
+ _serviceStats[serviceName] = success
+ ? (current.Success + 1, current.Fail)
+ : (current.Success, current.Fail + 1);
+ }
+
+ public static string FormatTime(TimeSpan time)
+ {
+ return time.TotalSeconds >= 1
+ ? $"{time.TotalSeconds:F1}s"
+ : time.TotalMilliseconds >= 1
+ ? $"{time.TotalMilliseconds:F0}ms"
+ : time.Ticks > 0
+ ? $"{time.Ticks} ticks"
+ : "0";
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/UI/Logger/StatusContext.cs b/optimizerDuck/src/UI/Logger/StatusContext.cs
new file mode 100644
index 0000000..d4831d8
--- /dev/null
+++ b/optimizerDuck/src/UI/Logger/StatusContext.cs
@@ -0,0 +1,43 @@
+using Spectre.Console;
+
+namespace optimizerDuck.UI.Logger;
+
+public sealed class StatusContextScope : IDisposable
+{
+ private readonly StatusContext? _ctx;
+ private readonly Spinner? _spinner;
+ private readonly Style? _spinnerStyle;
+ private readonly string? _status;
+
+ public StatusContextScope(StatusContext? ctx, Spinner newSpinner, Style newStyle, string newStatus)
+ {
+ if (ctx is null)
+ {
+ _ctx = null;
+ _spinner = null;
+ _spinnerStyle = null;
+ _status = null;
+ return;
+ }
+
+ _ctx = ctx;
+ _spinner = ctx.Spinner;
+ _spinnerStyle = ctx.SpinnerStyle;
+ _status = ctx.Status;
+
+ // Apply temporary state
+ ctx.Spinner(newSpinner);
+ ctx.SpinnerStyle(newStyle);
+ ctx.Status(newStatus);
+ }
+
+ public void Dispose()
+ {
+ if (_ctx is null)
+ return;
+
+ _ctx.Spinner(_spinner!);
+ _ctx.SpinnerStyle = _spinnerStyle;
+ _ctx.Status = _status!;
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck/src/UI/Theme.cs b/optimizerDuck/src/UI/Theme.cs
new file mode 100644
index 0000000..2232dda
--- /dev/null
+++ b/optimizerDuck/src/UI/Theme.cs
@@ -0,0 +1,20 @@
+namespace optimizerDuck.UI;
+
+public static class Theme
+{
+ public const string Primary = "#ffffb8";
+ public const string Secondary = "#fb7a03";
+ public const string Bright = "#fdf5ff";
+ public const string Accent = "#fed114";
+ public const string Warning = "#ffc16b";
+ public const string Info = "#80ade0";
+ public const string Success = "#70C27F";
+ public const string Error = "#e67a7a";
+
+ public const string Muted = "#9c9c9c";
+ public const string PrimaryMuted = "#a8a37b";
+ public const string ErrorMuted = "#aa7b7b";
+ public const string SecondaryMuted = "#a6a279";
+ public const string SuccessMuted = "#86c084";
+ public const string WarningMuted = "#bfa682";
+}
\ No newline at end of file