diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..5f57113 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,4 @@ +[*.cs] + +# Default severity for analyzer diagnostics with category 'CommunityToolkit.Mvvm.SourceGenerators.ObservablePropertyGenerator' +dotnet_analyzer_diagnostic.category-CommunityToolkit.Mvvm.SourceGenerators.ObservablePropertyGenerator.severity = none diff --git a/.github/workflows/cd-winui.yml b/.github/workflows/cd-winui.yml new file mode 100644 index 0000000..b9b4d30 --- /dev/null +++ b/.github/workflows/cd-winui.yml @@ -0,0 +1,82 @@ +name: Release WinUI + +on: + workflow_dispatch: + inputs: + version: + description: 'Version' + required: true + +jobs: + build: + runs-on: windows-latest + + env: + App_Packages_Archive: IdeapadToolkit.WinUI.zip + License_Path: IdeapadToolkit.WinUI\Properties\PublishProfiles\3RD_PARTY_LICENSES.txt + App_Publish_Directory: bin\win-x64\publish\win-x64 + App_Project_Directory: IdeapadToolkit.WinUI\ + Solution_Path: IdeapadToolkit.sln + Project_Path: IdeapadToolkit.WinUI\IdeapadToolkit.WinUI3.csproj + Actions_Allow_Unsecure_Commands: true # Allows AddPAth and SetEnv commands + Configuration: Release + RuntimeIdentifier: win-x64 + + steps: + - name: Checkout + uses: actions/checkout@v2 + with: + fetch-depth: 0 # avoid shallow clone so nbgv can do its work. + + # Install the .NET Core workload + - name: Install .NET + uses: actions/setup-dotnet@v3 + with: + dotnet-version: '8.0.x' + + # Add MsBuild to the PATH: https://github.com/microsoft/setup-msbuild + - name: Setup MSBuild.exe + uses: microsoft/setup-msbuild@v1.1 + + # Restore the application + - name: Restore the Wpf application to populate the obj folder + run: msbuild $env:Solution_Path /t:Restore /p:Configuration=$env:Configuration /p:RuntimeIdentifier=$env:RuntimeIdentifier + + # Build the Windows Application Packaging project for Prod_Store + - name: Build using the publish profile + run: dotnet publish /p:Configuration=Release /p:PublishProfile=win-x64 + + # Copy license file to the publish directory + - name: Copy license file to the publish directory + run: Copy-Item -Path $env:License_Path -Destination $env:App_Project_Directory\$env:App_Publish_Directory\ + + - name: Remove all *.pdb files + run: Remove-Item -Path $env:App_Project_Directory\$env:App_Publish_Directory\*.pdb -Force + + # Create archive + - name: Create archive + run: Compress-Archive -Path $env:App_Project_Directory\$env:App_Publish_Directory\* -DestinationPath $env:App_Project_Directory\$env:App_Publish_Directory\$env:App_Packages_Archive + + # Create the release: https://github.com/actions/create-release + - name: Create release + id: create_release + uses: actions/create-release@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token + with: + tag_name: ${{ github.event.inputs.version }} + release_name: Release ${{ github.event.inputs.version }} + draft: false + prerelease: true + + # Upload release asset: https://github.com/actions/upload-release-asset + - name: Update release asset + id: upload-release-asset + uses: actions/upload-release-asset@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ steps.create_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps + asset_path: ${{ env.App_Project_Directory }}\${{ env.App_Publish_Directory }}\${{ env.App_Packages_Archive }} + asset_name: ${{ env.App_Packages_Archive }} + asset_content_type: application/zip \ No newline at end of file diff --git a/IdeapadToolkit.Core/Helpers/Win32.cs b/IdeapadToolkit.Core/Helpers/Win32.cs new file mode 100644 index 0000000..c3c864e --- /dev/null +++ b/IdeapadToolkit.Core/Helpers/Win32.cs @@ -0,0 +1,72 @@ +using System.Runtime.InteropServices; +using static IdeapadToolkit.Core.Services.UEFISettingsService; + +namespace IdeapadToolkit.Core.Helpers +{ + internal partial class Win32 + { + [LibraryImport("kernel32.dll")] + public static partial nint OpenProcess( + int dwDesiredAccess, + [MarshalAs(UnmanagedType.Bool)] + bool bInheritHandle, + int dwProcessId); + + [LibraryImport("kernel32.dll", SetLastError = true)] + public static partial int GetFirmwareEnvironmentVariableExW([MarshalAs(UnmanagedType.LPWStr)] string lpName, [MarshalAs(UnmanagedType.LPWStr)] string lpGuid, ref LenovoFlipToBootSwInterface pBuffer, int nSize, nint pAttribute); + + [LibraryImport("kernel32.dll", SetLastError = true)] + public static partial int SetFirmwareEnvironmentVariableExW( + [MarshalAs(UnmanagedType.LPWStr)] string lpName, + [MarshalAs(UnmanagedType.LPWStr)] string lpGuid, + ref LenovoFlipToBootSwInterface pBuffer, + int nSize, + int attribute); + + [LibraryImport("kernel32.dll")] + public static partial nint GetCurrentProcess(); + + [LibraryImport("advapi32.dll", StringMarshalling = StringMarshalling.Utf8)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool LookupPrivilegeValue( + string lpSystemName, + string lpName, + ref long lpLuid); + + [LibraryImport("advapi32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool AdjustTokenPrivileges( + nint tokenHandle, + [MarshalAs(UnmanagedType.Bool)] bool disableAllPrivileges, + ref TokenPrivelege newState, + int zero, + nint null1, + nint null2); + + [LibraryImport("advapi32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool OpenProcessToken( + nint processHandle, + uint desiredAccess, + ref nint tokenHandle); + + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool GetFirmwareType(ref FirmwareType firmwareType); + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct TokenPrivelege + { + public int Count; + public long Luid; + public int Attr; + } + public enum FirmwareType + { + FirmwareTypeUnknown, + FirmwareTypeBios, + FirmwareTypeUefi, + FirmwareTypeMax, + } +} diff --git a/IdeapadToolkit.Core/IdeapadToolkit.Core.csproj b/IdeapadToolkit.Core/IdeapadToolkit.Core.csproj new file mode 100644 index 0000000..d213122 --- /dev/null +++ b/IdeapadToolkit.Core/IdeapadToolkit.Core.csproj @@ -0,0 +1,15 @@ + + + + net8.0 + enable + enable + true + true + + + + + + + diff --git a/IdeapadToolkit/Models/CChargingMode.cs b/IdeapadToolkit.Core/Models/CChargingMode.cs similarity index 84% rename from IdeapadToolkit/Models/CChargingMode.cs rename to IdeapadToolkit.Core/Models/CChargingMode.cs index 59403d2..accc23a 100644 --- a/IdeapadToolkit/Models/CChargingMode.cs +++ b/IdeapadToolkit.Core/Models/CChargingMode.cs @@ -1,12 +1,12 @@ -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace IdeapadToolkit.Models -{ - [NativeCppClass] - [StructLayout(LayoutKind.Sequential, Size = 16)] - public struct CChargingMode - { - private long value; - } -} +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace IdeapadToolkit.Core.Models +{ + [NativeCppClass] + [StructLayout(LayoutKind.Sequential, Size = 16)] + public struct CChargingMode + { + private long value; + } +} diff --git a/IdeapadToolkit/Models/CIntelligentCooling.cs b/IdeapadToolkit.Core/Models/CIntelligentCooling.cs similarity index 84% rename from IdeapadToolkit/Models/CIntelligentCooling.cs rename to IdeapadToolkit.Core/Models/CIntelligentCooling.cs index 32039ee..c6c5a04 100644 --- a/IdeapadToolkit/Models/CIntelligentCooling.cs +++ b/IdeapadToolkit.Core/Models/CIntelligentCooling.cs @@ -1,12 +1,12 @@ -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace IdeapadToolkit.Models -{ - [NativeCppClass] - [StructLayout(LayoutKind.Sequential, Size = 16)] - public struct CIntelligentCooling - { - private long value; - } -} +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace IdeapadToolkit.Core.Models +{ + [NativeCppClass] + [StructLayout(LayoutKind.Sequential, Size = 16)] + public struct CIntelligentCooling + { + private long value; + } +} diff --git a/IdeapadToolkit/Models/CUSBBatteryCharger.cs b/IdeapadToolkit.Core/Models/CUSBBatteryCharger.cs similarity index 84% rename from IdeapadToolkit/Models/CUSBBatteryCharger.cs rename to IdeapadToolkit.Core/Models/CUSBBatteryCharger.cs index 5a3f97b..d377faa 100644 --- a/IdeapadToolkit/Models/CUSBBatteryCharger.cs +++ b/IdeapadToolkit.Core/Models/CUSBBatteryCharger.cs @@ -1,12 +1,12 @@ -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace IdeapadToolkit.Models -{ - [NativeCppClass] - [StructLayout(LayoutKind.Sequential, Size = 16)] - public struct CUSBBatteryCharger - { - private long value; - } -} +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace IdeapadToolkit.Core.Models +{ + [NativeCppClass] + [StructLayout(LayoutKind.Sequential, Size = 16)] + public struct CUSBBatteryCharger + { + private long value; + } +} diff --git a/IdeapadToolkit/Models/CUSBCharger.cs b/IdeapadToolkit.Core/Models/CUSBCharger.cs similarity index 83% rename from IdeapadToolkit/Models/CUSBCharger.cs rename to IdeapadToolkit.Core/Models/CUSBCharger.cs index 672e376..b808cc2 100644 --- a/IdeapadToolkit/Models/CUSBCharger.cs +++ b/IdeapadToolkit.Core/Models/CUSBCharger.cs @@ -1,12 +1,12 @@ -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace IdeapadToolkit.Models -{ - [NativeCppClass] - [StructLayout(LayoutKind.Sequential, Size = 16)] - public struct CUSBCharger - { - private long value; - } -} +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace IdeapadToolkit.Core.Models +{ + [NativeCppClass] + [StructLayout(LayoutKind.Sequential, Size = 16)] + public struct CUSBCharger + { + private long value; + } +} diff --git a/IdeapadToolkit/Models/ChargingMode.cs b/IdeapadToolkit.Core/Models/ChargingMode.cs similarity index 71% rename from IdeapadToolkit/Models/ChargingMode.cs rename to IdeapadToolkit.Core/Models/ChargingMode.cs index ab3fe8b..6f5626a 100644 --- a/IdeapadToolkit/Models/ChargingMode.cs +++ b/IdeapadToolkit.Core/Models/ChargingMode.cs @@ -1,9 +1,9 @@ -namespace IdeapadToolkit.Models -{ - public enum ChargingMode - { - Conservation = 1, - Normal = 0, - Rapid = 2 - } -} +namespace IdeapadToolkit.Core.Models +{ + public enum ChargingMode + { + Conservation = 1, + Normal = 0, + Rapid = 2 + } +} diff --git a/IdeapadToolkit/Models/PowerPlanEnum.cs b/IdeapadToolkit.Core/Models/PowerPlanEnum.cs similarity index 75% rename from IdeapadToolkit/Models/PowerPlanEnum.cs rename to IdeapadToolkit.Core/Models/PowerPlanEnum.cs index 712ac2f..68e9a28 100644 --- a/IdeapadToolkit/Models/PowerPlanEnum.cs +++ b/IdeapadToolkit.Core/Models/PowerPlanEnum.cs @@ -1,9 +1,9 @@ -namespace IdeapadToolkit.Models -{ - public enum PowerPlan - { - IntelligentCooling = 1, - ExtremePerformance = 3, - EfficiencyMode = 2 - } -} +namespace IdeapadToolkit.Core.Models +{ + public enum PowerPlan + { + IntelligentCooling = 1, + ExtremePerformance = 3, + EfficiencyMode = 2 + } +} diff --git a/IdeapadToolkit/Services/AdministratorPermissionService.cs b/IdeapadToolkit.Core/Services/AdministratorPermissionService.cs similarity index 87% rename from IdeapadToolkit/Services/AdministratorPermissionService.cs rename to IdeapadToolkit.Core/Services/AdministratorPermissionService.cs index 9d007ba..b0650cf 100644 --- a/IdeapadToolkit/Services/AdministratorPermissionService.cs +++ b/IdeapadToolkit.Core/Services/AdministratorPermissionService.cs @@ -1,30 +1,29 @@ -using System; -using System.Diagnostics; -using System.Security.Principal; - -namespace IdeapadToolkit.Services -{ - public class AdministratorPermissionService : IAdministratorPermissionService - { - public bool IsAdministrator - { - get - { - var identity = WindowsIdentity.GetCurrent(); - var principal = new WindowsPrincipal(identity); - return principal.IsInRole(WindowsBuiltInRole.Administrator); - } - } - - public void RelaunchAsAdmin() - { - var proc = new Process - { - StartInfo = - {FileName = Environment.ProcessPath, UseShellExecute = true, Verb = "runas", Arguments="ignoreRunning"} - }; - proc.Start(); - Environment.Exit(0); - } - } -} +using System.Diagnostics; +using System.Security.Principal; + +namespace IdeapadToolkit.Core.Services +{ + public class AdministratorPermissionService : IAdministratorPermissionService + { + public bool IsAdministrator + { + get + { + var identity = WindowsIdentity.GetCurrent(); + var principal = new WindowsPrincipal(identity); + return principal.IsInRole(WindowsBuiltInRole.Administrator); + } + } + + public void RelaunchAsAdmin() + { + var proc = new Process + { + StartInfo = + {FileName = Environment.ProcessPath, UseShellExecute = true, Verb = "runas", Arguments="ignoreRunning"} + }; + proc.Start(); + Environment.Exit(0); + } + } +} diff --git a/IdeapadToolkit/Services/IAdministratorPermissionService.cs b/IdeapadToolkit.Core/Services/IAdministratorPermissionService.cs similarity index 77% rename from IdeapadToolkit/Services/IAdministratorPermissionService.cs rename to IdeapadToolkit.Core/Services/IAdministratorPermissionService.cs index 53b36c1..d508983 100644 --- a/IdeapadToolkit/Services/IAdministratorPermissionService.cs +++ b/IdeapadToolkit.Core/Services/IAdministratorPermissionService.cs @@ -1,8 +1,8 @@ -namespace IdeapadToolkit.Services -{ - public interface IAdministratorPermissionService - { - public bool IsAdministrator { get; } - public void RelaunchAsAdmin(); - } -} +namespace IdeapadToolkit.Core.Services +{ + public interface IAdministratorPermissionService + { + public bool IsAdministrator { get; } + public void RelaunchAsAdmin(); + } +} diff --git a/IdeapadToolkit/Services/ILenovoPowerSettingsService.cs b/IdeapadToolkit.Core/Services/ILenovoPowerSettingsService.cs similarity index 85% rename from IdeapadToolkit/Services/ILenovoPowerSettingsService.cs rename to IdeapadToolkit.Core/Services/ILenovoPowerSettingsService.cs index d35671c..9d93e1b 100644 --- a/IdeapadToolkit/Services/ILenovoPowerSettingsService.cs +++ b/IdeapadToolkit.Core/Services/ILenovoPowerSettingsService.cs @@ -1,19 +1,19 @@ -using IdeapadToolkit.Models; - -namespace IdeapadToolkit.Services -{ - public interface ILenovoPowerSettingsService - { - public PowerPlan GetPowerPlan(); - public void SetPowerPlan(PowerPlan plan); - - public ChargingMode GetChargingMode(); - public void SetChargingMode(ChargingMode chargingMode); - - public bool IsAlwaysOnUsbEnabled(); - public void SetAlwaysOnUsb(bool alwaysOnUsbEnabled); - - public bool IsAlwaysOnUsbBatteryEnabled(); - public void SetAlwaysOnUsbBattery(bool alwaysOnUsbBattryEnabled); - } -} +using IdeapadToolkit.Core.Models; + +namespace IdeapadToolkit.Core.Services +{ + public interface ILenovoPowerSettingsService + { + public PowerPlan GetPowerPlan(); + public void SetPowerPlan(PowerPlan plan); + + public ChargingMode GetChargingMode(); + public void SetChargingMode(ChargingMode chargingMode); + + public bool IsAlwaysOnUsbEnabled(); + public void SetAlwaysOnUsb(bool alwaysOnUsbEnabled); + + public bool IsAlwaysOnUsbBatteryEnabled(); + public void SetAlwaysOnUsbBattery(bool alwaysOnUsbBattryEnabled); + } +} diff --git a/IdeapadToolkit/Services/IRunOnStartupService.cs b/IdeapadToolkit.Core/Services/IRunOnStartupService.cs similarity index 74% rename from IdeapadToolkit/Services/IRunOnStartupService.cs rename to IdeapadToolkit.Core/Services/IRunOnStartupService.cs index 98eab1f..9fe5db2 100644 --- a/IdeapadToolkit/Services/IRunOnStartupService.cs +++ b/IdeapadToolkit.Core/Services/IRunOnStartupService.cs @@ -1,8 +1,8 @@ -namespace IdeapadToolkit.Services -{ - public interface IRunOnStartupService - { - bool IsRunOnStartupEnabled(); - void ToggleRunOnStartup(); - } -} +namespace IdeapadToolkit.Core.Services +{ + public interface IRunOnStartupService + { + bool IsRunOnStartupEnabled(); + void ToggleRunOnStartup(); + } +} diff --git a/IdeapadToolkit/Services/IUEFISettingsService.cs b/IdeapadToolkit.Core/Services/IUEFISettingsService.cs similarity index 77% rename from IdeapadToolkit/Services/IUEFISettingsService.cs rename to IdeapadToolkit.Core/Services/IUEFISettingsService.cs index 5fdab95..c839b73 100644 --- a/IdeapadToolkit/Services/IUEFISettingsService.cs +++ b/IdeapadToolkit.Core/Services/IUEFISettingsService.cs @@ -1,8 +1,8 @@ -namespace IdeapadToolkit.Services -{ - public interface IUEFISettingsService - { - public bool GetFlipToBootStatus(); - public int SetFlipToBootStatus(bool newStatus); - } -} +namespace IdeapadToolkit.Core.Services +{ + public interface IUEFISettingsService + { + public bool GetFlipToBootStatus(); + public int SetFlipToBootStatus(bool newStatus); + } +} diff --git a/IdeapadToolkit.Core/Services/LenovoPowerSettingsService.cs b/IdeapadToolkit.Core/Services/LenovoPowerSettingsService.cs new file mode 100644 index 0000000..cc75a13 --- /dev/null +++ b/IdeapadToolkit.Core/Services/LenovoPowerSettingsService.cs @@ -0,0 +1,164 @@ +using IdeapadToolkit.Core.Models; +using System.Runtime.InteropServices; + +namespace IdeapadToolkit.Core.Services +{ + public partial class LenovoPowerSettingsService : ILenovoPowerSettingsService + { + [LibraryImport("PowerBattery.dll", EntryPoint = "?SetITSMode@CIntelligentCooling@PowerBattery@@QEAAHAEAW4ITSMode@12@@Z", SetLastError = true)] + [UnmanagedCallConv(CallConvs = new Type[] { typeof(System.Runtime.CompilerServices.CallConvCdecl) })] + internal static partial int SetITSMode(ref CIntelligentCooling var1, ref PowerPlan var2); + + [LibraryImport("PowerBattery.dll", EntryPoint = "??0CIntelligentCooling@PowerBattery@@QEAA@XZ", SetLastError = true)] + [UnmanagedCallConv(CallConvs = new Type[] { typeof(System.Runtime.CompilerServices.CallConvCdecl) })] + internal static partial CIntelligentCooling CIntelligentCooling(ref CIntelligentCooling var1); + + [LibraryImport("PowerBattery.dll", EntryPoint = "?GetITSMode@CIntelligentCooling@PowerBattery@@QEAAHAEAHAEAW4ITSMode@12@@Z", SetLastError = true)] + [UnmanagedCallConv(CallConvs = new Type[] { typeof(System.Runtime.CompilerServices.CallConvCdecl) })] + internal static partial int GetITSMode(ref CIntelligentCooling var1, ref int var2, ref PowerPlan var3); + + [LibraryImport("PowerBattery.dll", EntryPoint = "??0CChargingMode@PowerBattery@@QEAA@XZ", SetLastError = true)] + [UnmanagedCallConv(CallConvs = new Type[] { typeof(System.Runtime.CompilerServices.CallConvCdecl) })] + internal static partial CChargingMode CChargingMode(ref CChargingMode var1); + + [LibraryImport("PowerBattery.dll", EntryPoint = "?GetChargingMode@CChargingMode@PowerBattery@@QEBAHXZ", SetLastError = true)] + [UnmanagedCallConv(CallConvs = new Type[] { typeof(System.Runtime.CompilerServices.CallConvCdecl) })] + internal static partial int GetChargingMode(ref CChargingMode var1); + + [LibraryImport("PowerBattery.dll", EntryPoint = "?SetChargingMode@CChargingMode@PowerBattery@@QEBAHH@Z", SetLastError = true)] + [UnmanagedCallConv(CallConvs = new Type[] { typeof(System.Runtime.CompilerServices.CallConvCdecl) })] + internal static partial int SetChargingMode(ref CChargingMode var1, int var2); + + [LibraryImport("PowerBattery.dll", EntryPoint = "?SetChargingMode@CChargingMode@PowerBattery@@QEBAHH_N@Z", SetLastError = true)] + [UnmanagedCallConv(CallConvs = new Type[] { typeof(System.Runtime.CompilerServices.CallConvCdecl) })] + // I don't know what the newly added boolean does, but it doesn't seem to matter + internal static partial int SetChargingModeFallBack(ref CChargingMode var1, int var2, [MarshalAs(UnmanagedType.Bool)] bool var3); + + [LibraryImport("PowerBattery.dll", EntryPoint = "??0CUSBCharger@PowerBattery@@QEAA@XZ", SetLastError = true)] + [UnmanagedCallConv(CallConvs = new Type[] { typeof(System.Runtime.CompilerServices.CallConvCdecl) })] + internal static partial CUSBCharger CUSBCharger(ref CUSBCharger var1); + + [LibraryImport("PowerBattery.dll", EntryPoint = "??0CUSBBatteryCharger@PowerBattery@@QEAA@XZ", SetLastError = true)] + [UnmanagedCallConv(CallConvs = new Type[] { typeof(System.Runtime.CompilerServices.CallConvCdecl) })] + internal static partial CUSBBatteryCharger CUSBBatteryCharger(ref CUSBBatteryCharger var1); + + [LibraryImport("PowerBattery.dll", EntryPoint = "?OpenOrClose@CUSBBatteryCharger@PowerBattery@@UEAAHXZ", SetLastError = true)] + [UnmanagedCallConv(CallConvs = new Type[] { typeof(System.Runtime.CompilerServices.CallConvCdecl) })] + internal static partial int OpenOrClose(ref CUSBBatteryCharger var1); + + [LibraryImport("PowerBattery.dll", EntryPoint = "?OpenOrClose@CUSBCharger@PowerBattery@@UEAAHXZ", SetLastError = true)] + [UnmanagedCallConv(CallConvs = new Type[] { typeof(System.Runtime.CompilerServices.CallConvCdecl) })] + internal static partial int OpenOrClose(ref CUSBCharger var1); + + [LibraryImport("PowerBattery.dll", EntryPoint = "?OpenFeature@CUSBCharger@PowerBattery@@UEAAHXZ", SetLastError = true)] + [UnmanagedCallConv(CallConvs = new Type[] { typeof(System.Runtime.CompilerServices.CallConvCdecl) })] + internal static partial int OpenFeature(ref CUSBCharger var1); + + [LibraryImport("PowerBattery.dll", EntryPoint = "?OpenFeature@CUSBBatteryCharger@PowerBattery@@UEAAHXZ", SetLastError = true)] + [UnmanagedCallConv(CallConvs = new Type[] { typeof(System.Runtime.CompilerServices.CallConvCdecl) })] + internal static partial int OpenFeature(ref CUSBBatteryCharger var1); + + [LibraryImport("PowerBattery.dll", EntryPoint = "?CloseFeature@CUSBCharger@PowerBattery@@UEAAHXZ", SetLastError = true)] + [UnmanagedCallConv(CallConvs = new Type[] { typeof(System.Runtime.CompilerServices.CallConvCdecl) })] + internal static partial int CloseFeature(ref CUSBCharger var1); + + [LibraryImport("PowerBattery.dll", EntryPoint = "?CloseFeature@CUSBBatteryCharger@PowerBattery@@UEAAHXZ", SetLastError = true)] + [UnmanagedCallConv(CallConvs = new Type[] { typeof(System.Runtime.CompilerServices.CallConvCdecl) })] + internal static partial int CloseFeature(ref CUSBBatteryCharger var1); + + public PowerPlan GetPowerPlan() + { + CIntelligentCooling instance = new(); + instance = CIntelligentCooling(ref instance); + PowerPlan newmode = new(); + int trash = 0; + _ = GetITSMode(ref instance, ref trash, ref newmode); + return newmode; + } + + public void SetPowerPlan(PowerPlan plan) + { + CIntelligentCooling instance = new(); + instance = CIntelligentCooling(ref instance); + _ = SetITSMode(ref instance, ref plan); + } + + public ChargingMode GetChargingMode() + { + CChargingMode instance = new(); + instance = CChargingMode(ref instance); + ChargingMode mode = (ChargingMode)GetChargingMode(ref instance); + return mode; + } + + public void SetChargingMode(ChargingMode chargingMode) + { + CChargingMode instance = new(); + instance = CChargingMode(ref instance); + try + { + _ = SetChargingMode(ref instance, (int)chargingMode); + } + catch (SystemException) + { + _ = SetChargingModeFallBack(ref instance, (int)chargingMode, false); + } + } + + public bool IsAlwaysOnUsbEnabled() + { + CUSBCharger instance = new(); + instance = CUSBCharger(ref instance); + var res = OpenOrClose(ref instance); + return res switch + { + 2 => false, + 1 => true, + _ => false + }; + } + + public void SetAlwaysOnUsb(bool alwaysOnUsbEnabled) + { + CUSBCharger instance = new(); + instance = CUSBCharger(ref instance); + switch (alwaysOnUsbEnabled) + { + case true: + _ = OpenFeature(ref instance); + break; + case false: + _ = CloseFeature(ref instance); + break; + } + } + + public bool IsAlwaysOnUsbBatteryEnabled() + { + CUSBBatteryCharger instance = new(); + instance = CUSBBatteryCharger(ref instance); + var res = OpenOrClose(ref instance); + return res switch + { + 2 => false, + 1 => true, + _ => false + }; + } + + public void SetAlwaysOnUsbBattery(bool alwaysOnUsbBattryEnabled) + { + CUSBBatteryCharger instance = new(); + instance = CUSBBatteryCharger(ref instance); + switch (alwaysOnUsbBattryEnabled) + { + case true: + _ = OpenFeature(ref instance); + break; + case false: + _ = CloseFeature(ref instance); + break; + } + } + } +} diff --git a/IdeapadToolkit/Services/RunOnStartupService.cs b/IdeapadToolkit.Core/Services/RunOnStartupService.cs similarity index 89% rename from IdeapadToolkit/Services/RunOnStartupService.cs rename to IdeapadToolkit.Core/Services/RunOnStartupService.cs index efadf86..e2a1430 100644 --- a/IdeapadToolkit/Services/RunOnStartupService.cs +++ b/IdeapadToolkit.Core/Services/RunOnStartupService.cs @@ -1,68 +1,67 @@ -using Microsoft.Win32; -using System; - -namespace IdeapadToolkit.Services -{ - public class RunOnStartupService : IRunOnStartupService - { - private static string _assemblyPath - { - get - { - return Environment.ProcessPath; - } - } - public bool IsRunOnStartupEnabled() - { - bool result; - using (RegistryKey key = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run")) - { - bool flag = key == null; - if (flag) - { - result = false; - } - else - { - object o = key.GetValue("IdeapadToolkit"); - result = (o != null); - } - } - return result; - } - - public void ToggleRunOnStartup() - { - if (!this.IsRunOnStartupEnabled()) - { - EnableRunAtStartup(); - } - else - { - DisableRunAtStartup(); - } - } - - private static void DisableRunAtStartup() - { - using RegistryKey key = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run", true); - bool flag = key != null; - if (flag) - { - try - { - key.DeleteValue("IdeapadToolkit"); - } - catch (ArgumentException) - { - } - } - } - - private static void EnableRunAtStartup() - { - using RegistryKey key = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run", true); - key.SetValue("IdeapadToolkit", _assemblyPath + " nogui"); - } - } -} +using Microsoft.Win32; + +namespace IdeapadToolkit.Core.Services +{ + public class RunOnStartupService : IRunOnStartupService + { + private static string _assemblyPath + { + get + { + return Environment.ProcessPath; + } + } + public bool IsRunOnStartupEnabled() + { + bool result; + using (RegistryKey key = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run")) + { + bool flag = key == null; + if (flag) + { + result = false; + } + else + { + object o = key.GetValue("IdeapadToolkit"); + result = o != null; + } + } + return result; + } + + public void ToggleRunOnStartup() + { + if (!IsRunOnStartupEnabled()) + { + EnableRunAtStartup(); + } + else + { + DisableRunAtStartup(); + } + } + + private static void DisableRunAtStartup() + { + using RegistryKey key = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run", true); + bool flag = key != null; + if (flag) + { + try + { + key.DeleteValue("IdeapadToolkit"); + } + catch (ArgumentException) + { + } + } + } + + private static void EnableRunAtStartup() + { + using RegistryKey key = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run", true); + key.SetValue("IdeapadToolkit", _assemblyPath + " nogui"); + } + } +} diff --git a/IdeapadToolkit/Services/UEFISettingsService.cs b/IdeapadToolkit.Core/Services/UEFISettingsService.cs similarity index 83% rename from IdeapadToolkit/Services/UEFISettingsService.cs rename to IdeapadToolkit.Core/Services/UEFISettingsService.cs index 3c52c08..b631c0b 100644 --- a/IdeapadToolkit/Services/UEFISettingsService.cs +++ b/IdeapadToolkit.Core/Services/UEFISettingsService.cs @@ -1,127 +1,126 @@ -using IdeapadToolkitService.Helpers; -using Serilog; -using System; -using System.Runtime.InteropServices; - -namespace IdeapadToolkit.Services -{ - public class UEFISettingsService : IUEFISettingsService - { - private static readonly string Guid = "{D743491E-F484-4952-A87D-8D5DD189B70C}"; - private static readonly string ScopeName = "FBSWIF"; - private static readonly int ScopeAttribute = 7; - private readonly ILogger _logger; - - public UEFISettingsService(ILogger logger) - { - this._logger = logger; - } - private bool SetPrivilege(bool enable) - { - try - { - IntPtr zero = IntPtr.Zero; - if (!Win32.OpenProcessToken(Win32.GetCurrentProcess(), 40U, ref zero)) - { - return false; - } - TokenPrivelege newState; - newState.Count = 1; - newState.Luid = 0L; - newState.Attr = enable ? 2 : 0; - if (!Win32.LookupPrivilegeValue((string)null, "SeSystemEnvironmentPrivilege", ref newState.Luid)) - { - return false; - } - if (!Win32.AdjustTokenPrivileges(zero, false, ref newState, 0, IntPtr.Zero, IntPtr.Zero)) - { - return false; - } - } - catch (Exception ex) - { - _logger.Error(ex, "Exception while getting UEFI privilege"); - return false; - } - return true; - } - public bool GetFlipToBootStatus() - { - if (!SetPrivilege(true)) throw new Exception(); - int dataFromUefi = -1; - try - { - LenovoFlipToBootSwInterface structure = new() - { - FlipToBootEn = 0, - Reserved1 = 0, - Reserved2 = 0, - Reserved3 = 0 - }; - - var res = Win32.GetFirmwareEnvironmentVariableExW(ScopeName, Guid, ref structure, Marshal.SizeOf(), IntPtr.Zero); - if (res != 0) - { - dataFromUefi = ((LenovoFlipToBootSwInterface)structure).FlipToBootEn; - } - else - { - int lastWin32Error = Marshal.GetLastWin32Error(); - dataFromUefi = lastWin32Error * -1; - } - } - catch (Exception ex) - { - _logger.Error(ex, "Exception while getting UEFI FlipToBoot status"); - } - finally - { - _ = SetPrivilege(false); - } - return dataFromUefi switch - { - 0 => false, - 1 => true, - _ => throw new Exception() - }; - } - - public int SetFlipToBootStatus(bool newStatus) - { - if (!SetPrivilege(true)) return -1; - int num1 = -1; - try - { - LenovoFlipToBootSwInterface structure = new() - { - FlipToBootEn = newStatus ? (byte)1 : (byte)0, - Reserved1 = 0, - Reserved2 = 0, - Reserved3 = 0 - }; - - var res = (Win32.SetFirmwareEnvironmentVariableExW(ScopeName, Guid, ref structure, Marshal.SizeOf(), ScopeAttribute)); - if (res != 0) return 0; - } - catch (Exception ex) - { - _logger.Error(ex, "Error while setting UEFI FlipToBoot status"); - } - finally { _ = SetPrivilege(false); } - return num1; - } - - [StructLayout(LayoutKind.Sequential)] - public struct LenovoFlipToBootSwInterface - { - [MarshalAs(UnmanagedType.U1)] - public byte FlipToBootEn; - [MarshalAs(UnmanagedType.U1)] - public byte Reserved1; - [MarshalAs(UnmanagedType.U1)] - public byte Reserved2; - [MarshalAs(UnmanagedType.U1)] - public byte Reserved3; - } - } -} +using IdeapadToolkit.Core.Helpers; +using Serilog; +using System.Runtime.InteropServices; + +namespace IdeapadToolkit.Core.Services +{ + public class UEFISettingsService : IUEFISettingsService + { + private static readonly string Guid = "{D743491E-F484-4952-A87D-8D5DD189B70C}"; + private static readonly string ScopeName = "FBSWIF"; + private static readonly int ScopeAttribute = 7; + private readonly ILogger _logger; + + public UEFISettingsService(ILogger logger) + { + _logger = logger; + } + private bool SetPrivilege(bool enable) + { + try + { + nint zero = nint.Zero; + if (!Win32.OpenProcessToken(Win32.GetCurrentProcess(), 40U, ref zero)) + { + return false; + } + TokenPrivelege newState; + newState.Count = 1; + newState.Luid = 0L; + newState.Attr = enable ? 2 : 0; + if (!Win32.LookupPrivilegeValue(null, "SeSystemEnvironmentPrivilege", ref newState.Luid)) + { + return false; + } + if (!Win32.AdjustTokenPrivileges(zero, false, ref newState, 0, nint.Zero, nint.Zero)) + { + return false; + } + } + catch (Exception ex) + { + _logger.Error(ex, "Exception while getting UEFI privilege"); + return false; + } + return true; + } + public bool GetFlipToBootStatus() + { + if (!SetPrivilege(true)) throw new Exception(); + int dataFromUefi = -1; + try + { + LenovoFlipToBootSwInterface structure = new() + { + FlipToBootEn = 0, + Reserved1 = 0, + Reserved2 = 0, + Reserved3 = 0 + }; + + var res = Win32.GetFirmwareEnvironmentVariableExW(ScopeName, Guid, ref structure, Marshal.SizeOf(), nint.Zero); + if (res != 0) + { + dataFromUefi = structure.FlipToBootEn; + } + else + { + int lastWin32Error = Marshal.GetLastWin32Error(); + dataFromUefi = lastWin32Error * -1; + } + } + catch (Exception ex) + { + _logger.Error(ex, "Exception while getting UEFI FlipToBoot status"); + } + finally + { + _ = SetPrivilege(false); + } + return dataFromUefi switch + { + 0 => false, + 1 => true, + _ => throw new Exception() + }; + } + + public int SetFlipToBootStatus(bool newStatus) + { + if (!SetPrivilege(true)) return -1; + int num1 = -1; + try + { + LenovoFlipToBootSwInterface structure = new() + { + FlipToBootEn = newStatus ? (byte)1 : (byte)0, + Reserved1 = 0, + Reserved2 = 0, + Reserved3 = 0 + }; + + var res = Win32.SetFirmwareEnvironmentVariableExW(ScopeName, Guid, ref structure, Marshal.SizeOf(), ScopeAttribute); + if (res != 0) return 0; + } + catch (Exception ex) + { + _logger.Error(ex, "Error while setting UEFI FlipToBoot status"); + } + finally { _ = SetPrivilege(false); } + return num1; + } + + [StructLayout(LayoutKind.Sequential)] + public struct LenovoFlipToBootSwInterface + { + [MarshalAs(UnmanagedType.U1)] + public byte FlipToBootEn; + [MarshalAs(UnmanagedType.U1)] + public byte Reserved1; + [MarshalAs(UnmanagedType.U1)] + public byte Reserved2; + [MarshalAs(UnmanagedType.U1)] + public byte Reserved3; + } + } +} diff --git a/IdeapadToolkit.WinUI/App.config b/IdeapadToolkit.WinUI/App.config new file mode 100644 index 0000000..b8a0d28 --- /dev/null +++ b/IdeapadToolkit.WinUI/App.config @@ -0,0 +1,18 @@ + + + + +
+ + + + + + + + + True + + + + \ No newline at end of file diff --git a/IdeapadToolkit.WinUI/App.xaml b/IdeapadToolkit.WinUI/App.xaml new file mode 100644 index 0000000..1db6c1c --- /dev/null +++ b/IdeapadToolkit.WinUI/App.xaml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + diff --git a/IdeapadToolkit.WinUI/App.xaml.cs b/IdeapadToolkit.WinUI/App.xaml.cs new file mode 100644 index 0000000..2166d94 --- /dev/null +++ b/IdeapadToolkit.WinUI/App.xaml.cs @@ -0,0 +1,154 @@ +global using System; +using IdeapadToolkit.Core.Services; +using IdeapadToolkit.WinUI3.Helpers; +using IdeapadToolkit.WinUI3.Localization; +using IdeapadToolkit.WinUI3.Services; +using IdeapadToolkit.WinUI3.ViewModels; +using IdeapadToolkit.WinUI3.Views; +using Microsoft.UI.Dispatching; +using Microsoft.UI.Xaml; +using Pure.DI; +using Serilog; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Threading; +using WinUIEx; + +// To learn more about WinUI, the WinUI project structure, +// and more about our project templates, see: http://aka.ms/winui-project-info. + +namespace IdeapadToolkit.WinUI3; +/// +/// Provides application-specific behavior to supplement the default Application class. +/// +public partial class App : Application +{ + /// + /// Initializes the singleton application object. This is the first line of authored code + /// executed, and as such is the logical equivalent of main() or WinMain(). + /// + public App() + { + this.InitializeComponent(); + } + + private void ConfigureServices() + { + DI.Setup("Composition", CompositionKind.Public) + .RootBind().As(Lifetime.Singleton).To(_ => + { + return new LoggerConfiguration() + .MinimumLevel.Error() + .WriteTo.File("log.txt", rollingInterval: RollingInterval.Day, retainedFileCountLimit: 7) + .CreateLogger(); + }) + .RootBind().As(Lifetime.Singleton).To() + .RootBind().As(Lifetime.Singleton).To() + .RootBind().As(Lifetime.Singleton).To() + .Bind().As(Lifetime.Singleton).To().Root() + .Bind().As(Lifetime.Singleton).To() + .Bind().To().Root() + .Bind().To().Root() + .Bind().To().Root() + .RootBind().As(Lifetime.Singleton).To() + .Bind().As(Lifetime.Transient).To() + .Root(); + } + + /// + /// Invoked when the application is launched. + /// + /// Details about the launch request and process. + /// + + protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args) + { + ConfigureServices(); + Composition = new Composition(); + + var arguments = Environment.GetCommandLineArgs(); + + AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; + + bool exists = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(Environment.ProcessPath)).Length > 1; + TrySetCulture(); + if (exists && (arguments?.Any(x => x.Contains("ignoreRunning")) != true)) + { + Win32.MessageBox(IntPtr.Zero, Strings.ALREADY_RUNNING, "", Win32.MB_OK | Win32.MB_ICONASTERISK); + Environment.Exit(1); + return; + } + else + { + base.DispatcherShutdownMode = DispatcherShutdownMode.OnExplicitShutdown; + } + + if (!File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PowerBattery.dll"))) + { + Win32.MessageBox(IntPtr.Zero, Strings.DLL_MISSING_ERROR, "", Win32.MB_OK | Win32.MB_ICONASTERISK); + Environment.Exit(1); + return; + } + if (arguments?.Any(x => x.Contains("nogui")) != true) + { + ShowMainWindow(null, null); + } + + var iconView = Composition.Resolve(); + iconView.MakeVisible(); + iconView.TrayIconClicked += ShowMainWindow; + } + + private void CurrentDomain_UnhandledException(object sender, System.UnhandledExceptionEventArgs e) + { + Composition.Resolve().Fatal((Exception)e.ExceptionObject, "Unhandled exception"); + } + + private void ShowMainWindow(object sender, EventArgs args) + { + if (MainWindow == null) + { + TrySetCulture(); + var window = Composition.Resolve(); + MainWindow = window; + window.Activate(); + } + else + { + MainWindow.Activate(); + } + } + + private void TrySetCulture() + { + try + { + var culture = Settings.Instance.Language; + if (!String.IsNullOrWhiteSpace(culture)) + { + var cultureInfo = CultureInfo.GetCultureInfo(culture); + if (cultureInfo != null) + { + DispatcherQueue.GetForCurrentThread().TryEnqueue(() => + { + Thread.CurrentThread.CurrentUICulture = cultureInfo; + }); + } + } + } + catch (Exception ex) + { + } + } + + private void MenuItemExit_Click(object sender, RoutedEventArgs e) + { + Environment.Exit(0); + } + + internal static MainWindow? MainWindow = null!; + + internal static Composition Composition = null!; +} diff --git a/IdeapadToolkit.WinUI/Helpers/BooleanToVisibilityConverter.cs b/IdeapadToolkit.WinUI/Helpers/BooleanToVisibilityConverter.cs new file mode 100644 index 0000000..25a0e67 --- /dev/null +++ b/IdeapadToolkit.WinUI/Helpers/BooleanToVisibilityConverter.cs @@ -0,0 +1,46 @@ +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Data; + +namespace IdeapadToolkit.WinUI3.Helpers; + +public partial class BoolToVisibilityConverter : IValueConverter +{ + public object Convert(object value, Type targetType, object parameter, string language) + { + if (value is bool booleanValue) + { + return booleanValue ? Visibility.Visible : Visibility.Collapsed; + } + return Visibility.Collapsed; + } + + public object ConvertBack(object value, Type targetType, object parameter, string language) + { + if (value is Visibility visibility) + { + return visibility == Visibility.Visible; + } + return false; + } +} + +public partial class InvertedBoolToVisibilityConverter : IValueConverter +{ + public object Convert(object value, Type targetType, object parameter, string language) + { + if (value is bool booleanValue) + { + return !booleanValue ? Visibility.Visible : Visibility.Collapsed; + } + return Visibility.Collapsed; + } + + public object ConvertBack(object value, Type targetType, object parameter, string language) + { + if (value is Visibility visibility) + { + return visibility != Visibility.Visible; + } + return false; + } +} diff --git a/IdeapadToolkit.WinUI/Helpers/Win32Helpers.cs b/IdeapadToolkit.WinUI/Helpers/Win32Helpers.cs new file mode 100644 index 0000000..27c25b6 --- /dev/null +++ b/IdeapadToolkit.WinUI/Helpers/Win32Helpers.cs @@ -0,0 +1,17 @@ +using Microsoft.UI.Xaml.Markup; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; + +namespace IdeapadToolkit.WinUI3.Helpers; +public static partial class Win32 +{ + [LibraryImport("user32.dll", EntryPoint = "MessageBoxW", StringMarshalling = StringMarshalling.Utf16)] + public static partial int MessageBox(IntPtr hWnd, string text, string caption, uint type); + + public const uint MB_OK = 0x00000000; + public const uint MB_ICONASTERISK = 0x00000040; +} diff --git a/IdeapadToolkit.WinUI/IdeapadToolkit.WinUI3.csproj b/IdeapadToolkit.WinUI/IdeapadToolkit.WinUI3.csproj new file mode 100644 index 0000000..96d1224 --- /dev/null +++ b/IdeapadToolkit.WinUI/IdeapadToolkit.WinUI3.csproj @@ -0,0 +1,142 @@ + + + WinExe + net8.0-windows10.0.22621.0 + 10.0.17763.0 + 10.0.22621.38 + IdeapadToolkit.WinUI3 + app.manifest + x64 + win-x64 + win-$(Platform).pubxml + true + None + true + Speed + true + true + full + enable + Resources\icon.ico + + + + + + + + + + + + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + + + Strings.resx + True + True + + + + + Strings.Designer.cs + PublicResXFileCodeGenerator + + + + + Always + + + + + MSBuild:Compile + + + + + MSBuild:Compile + + + + + MSBuild:Compile + + + + + + true + + + + + False + True + False + True + + \ No newline at end of file diff --git a/IdeapadToolkit.WinUI/Localization/Strings.Designer.cs b/IdeapadToolkit.WinUI/Localization/Strings.Designer.cs new file mode 100644 index 0000000..fe6ee3b --- /dev/null +++ b/IdeapadToolkit.WinUI/Localization/Strings.Designer.cs @@ -0,0 +1,225 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace IdeapadToolkit.WinUI3.Localization { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + public class Strings { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Strings() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("IdeapadToolkit.WinUI3.Localization.Strings", typeof(Strings).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to The app is already running. + /// + public static string ALREADY_RUNNING { + get { + return ResourceManager.GetString("ALREADY_RUNNING", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Always on USB. + /// + public static string ALWAYS_ON_USB { + get { + return ResourceManager.GetString("ALWAYS_ON_USB", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Always on USB on battery. + /// + public static string ALWAYS_ON_USB_BATTERY { + get { + return ResourceManager.GetString("ALWAYS_ON_USB_BATTERY", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Battery Charging Mode. + /// + public static string BATTERY_CHARGING_MODE { + get { + return ResourceManager.GetString("BATTERY_CHARGING_MODE", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Battery Saving. + /// + public static string BATTERY_SAVING { + get { + return ResourceManager.GetString("BATTERY_SAVING", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Conservation. + /// + public static string CONSERVATION { + get { + return ResourceManager.GetString("CONSERVATION", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to PowerBattery.dll has to be present in the same folder as IdeapadToolkit.exe. + /// + public static string DLL_MISSING_ERROR { + get { + return ResourceManager.GetString("DLL_MISSING_ERROR", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Extreme Performance. + /// + public static string EXTREME_PERFORMANCE { + get { + return ResourceManager.GetString("EXTREME_PERFORMANCE", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Flip to Boot. + /// + public static string FLIP_TO_BOOT { + get { + return ResourceManager.GetString("FLIP_TO_BOOT", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Home. + /// + public static string HOME { + get { + return ResourceManager.GetString("HOME", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Intelligent Cooling. + /// + public static string INTELLIGENT_COOLING { + get { + return ResourceManager.GetString("INTELLIGENT_COOLING", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Keep running in the background. + /// + public static string KEEP_IN_TRAY { + get { + return ResourceManager.GetString("KEEP_IN_TRAY", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Language. + /// + public static string LANGUAGE { + get { + return ResourceManager.GetString("LANGUAGE", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Normal. + /// + public static string NORMAL { + get { + return ResourceManager.GetString("NORMAL", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Other. + /// + public static string OTHER { + get { + return ResourceManager.GetString("OTHER", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Power Profile. + /// + public static string POWER_PROFILE { + get { + return ResourceManager.GetString("POWER_PROFILE", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Rapid. + /// + public static string RAPID { + get { + return ResourceManager.GetString("RAPID", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Run On Startup. + /// + public static string RUN_ON_STARTUP { + get { + return ResourceManager.GetString("RUN_ON_STARTUP", resourceCulture); + } + } + } +} diff --git a/IdeapadToolkit.WinUI/Localization/Strings.cs-CZ.resx b/IdeapadToolkit.WinUI/Localization/Strings.cs-CZ.resx new file mode 100644 index 0000000..c7a7269 --- /dev/null +++ b/IdeapadToolkit.WinUI/Localization/Strings.cs-CZ.resx @@ -0,0 +1,174 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Aplikace je již spuštěná + + + USB vždy zapnuté + + + USB vždy zapnuté i na baterii + + + Režim nabíjení baterie + + + Úspora baterie + + + Šetrný + + + Soubor PowerBattery.dll musí být přítomen ve stejné složce jako IdeapadToolkit.exe + + + Extrémní výkon + + + Zapnout při otevření + + + Domů + + + Chytré chlazení + + + Jazyk + + + Normální + + + Ostatní + + + Výkonnostní profil + + + Rychlý + + + Spustit při startu + + + Ponechat spuštěné na pozadí + + \ No newline at end of file diff --git a/IdeapadToolkit.WinUI/Localization/Strings.fr-FR.resx b/IdeapadToolkit.WinUI/Localization/Strings.fr-FR.resx new file mode 100644 index 0000000..0ef53e6 --- /dev/null +++ b/IdeapadToolkit.WinUI/Localization/Strings.fr-FR.resx @@ -0,0 +1,174 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + L'application est déjà en cours d'exécution + + + USB toujours activé + + + USB toujours activé sur batterie + + + Mode de charge de la batterie + + + Économie de batterie + + + Conservation + + + PowerBattery.dll doit être présent dans le même dossier que IdeapadToolkit.exe + + + Performances maximales + + + Ouvrir le capot pour démarrer + + + Accueil + + + Refroidissement intelligent + + + Langue + + + Normal + + + Autres + + + Profil de performance + + + Rapide + + + Lancer au démarrage + + + Laisser en cours d'exécution en arrière-plan + + \ No newline at end of file diff --git a/IdeapadToolkit.WinUI/Localization/Strings.resx b/IdeapadToolkit.WinUI/Localization/Strings.resx new file mode 100644 index 0000000..fcc272b --- /dev/null +++ b/IdeapadToolkit.WinUI/Localization/Strings.resx @@ -0,0 +1,174 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The app is already running + + + Always on USB + + + Always on USB on battery + + + Battery Charging Mode + + + Battery Saving + + + Conservation + + + PowerBattery.dll has to be present in the same folder as IdeapadToolkit.exe + + + Extreme Performance + + + Flip to Boot + + + Home + + + Intelligent Cooling + + + Language + + + Normal + + + Other + + + Power Profile + + + Rapid + + + Run On Startup + + + Keep running in the background + + \ No newline at end of file diff --git a/IdeapadToolkit.WinUI/Localization/Strings.zh-CN.resx b/IdeapadToolkit.WinUI/Localization/Strings.zh-CN.resx new file mode 100644 index 0000000..4d92bd4 --- /dev/null +++ b/IdeapadToolkit.WinUI/Localization/Strings.zh-CN.resx @@ -0,0 +1,174 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 应用程序已经在运行 + + + USB持续供电 + + + 电池模式USB持续供电 + + + 电池充电模式 + + + 省电模式 + + + 电池养护 + + + PowerBattery.dll 必须与 IdeapadToolkit.exe 放在同一文件夹中 + + + 野兽模式 + + + 开盖开机 + + + 主页 + + + 智能模式 + + + 语言 + + + 正常模式 + + + 其他 + + + 电源配置 + + + 快速充电 + + + 开机时自动启动 + + + 在后台运行 + + \ No newline at end of file diff --git a/IdeapadToolkit.WinUI/MainWindow.xaml b/IdeapadToolkit.WinUI/MainWindow.xaml new file mode 100644 index 0000000..a7b4b64 --- /dev/null +++ b/IdeapadToolkit.WinUI/MainWindow.xaml @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/IdeapadToolkit.WinUI/MainWindow.xaml.cs b/IdeapadToolkit.WinUI/MainWindow.xaml.cs new file mode 100644 index 0000000..b1eb12b --- /dev/null +++ b/IdeapadToolkit.WinUI/MainWindow.xaml.cs @@ -0,0 +1,53 @@ +using IdeapadToolkit.WinUI3.Services; +using IdeapadToolkit.WinUI3.ViewModels; +using IdeapadToolkit.WinUI3.Views; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Media.Animation; +using WinUIEx; + +namespace IdeapadToolkit.WinUI3; +public sealed partial class MainWindow : WinUIEx.WindowEx +{ + private readonly INavigationService _navigationService; + internal MainWindow(INavigationService navigationService) + { + this.InitializeComponent(); + this.ExtendsContentIntoTitleBar = true; + NavigationView.SelectedItem = NavigationView.MenuItems[0]; + _navigationService = navigationService; + _navigationService.NavFrame = RootFrame; + _navigationService.Navigate(null, new EntranceNavigationTransitionInfo()); + } + + private void NavigationView_ItemInvoked(NavigationView sender, NavigationViewItemInvokedEventArgs args) + { + if (args?.IsSettingsInvoked == true) + { + _navigationService.Navigate(null, args.RecommendedNavigationTransitionInfo); + } + + var page = args?.InvokedItemContainer?.Tag as string; + if (page != null) + { + switch (page) + { + case "Home": + _navigationService.Navigate(null, args.RecommendedNavigationTransitionInfo); + break; + } + } + } + + private void Window_Closed(object sender, WindowEventArgs args) + { + if (!Settings.Instance.KeepInTray) + { + Environment.Exit(0); + } + else + { + App.MainWindow = null; + } + } +} diff --git a/IdeapadToolkit.WinUI/Package.appxmanifest b/IdeapadToolkit.WinUI/Package.appxmanifest new file mode 100644 index 0000000..4c5a6b7 --- /dev/null +++ b/IdeapadToolkit.WinUI/Package.appxmanifest @@ -0,0 +1,51 @@ + + + + + + + + + + IdeapadToolkit.WinUI + maste + Assets\StoreLogo.png + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/IdeapadToolkit.WinUI/Properties/PublishProfiles/3RD_PARTY_LICENSES.txt b/IdeapadToolkit.WinUI/Properties/PublishProfiles/3RD_PARTY_LICENSES.txt new file mode 100644 index 0000000..d85c4c2 --- /dev/null +++ b/IdeapadToolkit.WinUI/Properties/PublishProfiles/3RD_PARTY_LICENSES.txt @@ -0,0 +1,270 @@ +Pure.DI + +The MIT License + +Copyright (c) 2024 Nikolay Pianikov + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + + + +H.NotifyIcon + +MIT License + +Copyright (c) 2020 havendv + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + + + +.Net Community Toolkit +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +Serilog + +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, "control" means (i) the power, direct or +indirect, to cause the direction or management of such entity, whether by +contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the +outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising +permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + +"Object" form shall mean any form resulting from mechanical transformation or +translation of a Source form, including but not limited to compiled object code, +generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made +available under the License, as indicated by a copyright notice that is included +in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that +is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative Works +shall not include works that remain separable from, or merely link (or bind by +name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative Works +thereof, that is intentionally submitted to Licensor for inclusion in the Work +by the copyright owner or by an individual or Legal Entity authorized to submit +on behalf of the copyright owner. For the purposes of this definition, +"submitted" means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor for +the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently +incorporated within the Work. + +2. Grant of Copyright License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form. + +3. Grant of Patent License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable (except as stated in this section) patent license to make, have +made, use, offer to sell, sell, import, and otherwise transfer the Work, where +such license applies only to those patent claims licensable by such Contributor +that are necessarily infringed by their Contribution(s) alone or by combination +of their Contribution(s) with the Work to which such Contribution(s) was +submitted. If You institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work or a +Contribution incorporated within the Work constitutes direct or contributory +patent infringement, then any patent licenses granted to You under this License +for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. + +You may reproduce and distribute copies of the Work or Derivative Works thereof +in any medium, with or without modifications, and in Source or Object form, +provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of +this License; and +You must cause any modified files to carry prominent notices stating that You +changed the files; and +You must retain, in the Source form of any Derivative Works that You distribute, +all copyright, patent, trademark, and attribution notices from the Source form +of the Work, excluding those notices that do not pertain to any part of the +Derivative Works; and +If the Work includes a "NOTICE" text file as part of its distribution, then any +Derivative Works that You distribute must include a readable copy of the +attribution notices contained within such NOTICE file, excluding those notices +that do not pertain to any part of the Derivative Works, in at least one of the +following places: within a NOTICE text file distributed as part of the +Derivative Works; within the Source form or documentation, if provided along +with the Derivative Works; or, within a display generated by the Derivative +Works, if and wherever such third-party notices normally appear. The contents of +the NOTICE file are for informational purposes only and do not modify the +License. You may add Your own attribution notices within Derivative Works that +You distribute, alongside or as an addendum to the NOTICE text from the Work, +provided that such additional attribution notices cannot be construed as +modifying the License. +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as a whole, +provided Your use, reproduction, and distribution of the Work otherwise complies +with the conditions stated in this License. + +5. Submission of Contributions. + +Unless You explicitly state otherwise, any Contribution intentionally submitted +for inclusion in the Work by You to the Licensor shall be under the terms and +conditions of this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify the terms of +any separate license agreement you may have executed with Licensor regarding +such Contributions. + +6. Trademarks. + +This License does not grant permission to use the trade names, trademarks, +service marks, or product names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. + +Unless required by applicable law or agreed to in writing, Licensor provides the +Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, +including, without limitation, any warranties or conditions of TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your exercise of +permissions under this License. + +8. Limitation of Liability. + +In no event and under no legal theory, whether in tort (including negligence), +contract, or otherwise, unless required by applicable law (such as deliberate +and grossly negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, incidental, +or consequential damages of any character arising as a result of this License or +out of the use or inability to use the Work (including but not limited to +damages for loss of goodwill, work stoppage, computer failure or malfunction, or +any and all other commercial damages or losses), even if such Contributor has +been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. + +While redistributing the Work or Derivative Works thereof, You may choose to +offer, and charge a fee for, acceptance of support, warranty, indemnity, or +other liability obligations and/or rights consistent with this License. However, +in accepting such obligations, You may act only on Your own behalf and on Your +sole responsibility, not on behalf of any other Contributor, and only if You +agree to indemnify, defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason of your +accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work + +To apply the Apache License to your work, attach the following boilerplate +notice, with the fields enclosed by brackets "[]" replaced with your own +identifying information. (Don't include the brackets!) The text should be +enclosed in the appropriate comment syntax for the file format. We also +recommend that a file or class name and description of purpose be included on +the same "printed page" as the copyright notice for easier identification within +third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + +WinUiEx + +MIT License + +Copyright (c) 2021 Morten Nielsen + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/IdeapadToolkit.WinUI/Properties/PublishProfiles/win-x64.pubxml b/IdeapadToolkit.WinUI/Properties/PublishProfiles/win-x64.pubxml new file mode 100644 index 0000000..86115ea --- /dev/null +++ b/IdeapadToolkit.WinUI/Properties/PublishProfiles/win-x64.pubxml @@ -0,0 +1,17 @@ + + + + + FileSystem + Any CPU + win-x64 + bin\\\win-x64\publish\ + true + Release + net8.0-windows10.0.22621.0 + false + false + + \ No newline at end of file diff --git a/IdeapadToolkit.WinUI/Properties/launchSettings.json b/IdeapadToolkit.WinUI/Properties/launchSettings.json new file mode 100644 index 0000000..02537a7 --- /dev/null +++ b/IdeapadToolkit.WinUI/Properties/launchSettings.json @@ -0,0 +1,10 @@ +{ + "profiles": { + "IdeapadToolkit.WinUI (Package)": { + "commandName": "MsixPackage" + }, + "IdeapadToolkit.WinUI (Unpackaged)": { + "commandName": "Project" + } + } +} \ No newline at end of file diff --git a/IdeapadToolkit.WinUI/Resources/admin.png b/IdeapadToolkit.WinUI/Resources/admin.png new file mode 100644 index 0000000..8dd0bd2 Binary files /dev/null and b/IdeapadToolkit.WinUI/Resources/admin.png differ diff --git a/IdeapadToolkit.WinUI/Resources/icon.ico b/IdeapadToolkit.WinUI/Resources/icon.ico new file mode 100644 index 0000000..a2581db Binary files /dev/null and b/IdeapadToolkit.WinUI/Resources/icon.ico differ diff --git a/IdeapadToolkit.WinUI/Resources/intelligent_conservation.ico b/IdeapadToolkit.WinUI/Resources/intelligent_conservation.ico new file mode 100644 index 0000000..aea6ddf Binary files /dev/null and b/IdeapadToolkit.WinUI/Resources/intelligent_conservation.ico differ diff --git a/IdeapadToolkit.WinUI/Resources/intelligent_normal.ico b/IdeapadToolkit.WinUI/Resources/intelligent_normal.ico new file mode 100644 index 0000000..7bad765 Binary files /dev/null and b/IdeapadToolkit.WinUI/Resources/intelligent_normal.ico differ diff --git a/IdeapadToolkit.WinUI/Resources/intelligent_quick.ico b/IdeapadToolkit.WinUI/Resources/intelligent_quick.ico new file mode 100644 index 0000000..bf5138a Binary files /dev/null and b/IdeapadToolkit.WinUI/Resources/intelligent_quick.ico differ diff --git a/IdeapadToolkit.WinUI/Resources/performance_conservation.ico b/IdeapadToolkit.WinUI/Resources/performance_conservation.ico new file mode 100644 index 0000000..80b7d9a Binary files /dev/null and b/IdeapadToolkit.WinUI/Resources/performance_conservation.ico differ diff --git a/IdeapadToolkit.WinUI/Resources/performance_normal.ico b/IdeapadToolkit.WinUI/Resources/performance_normal.ico new file mode 100644 index 0000000..9295fca Binary files /dev/null and b/IdeapadToolkit.WinUI/Resources/performance_normal.ico differ diff --git a/IdeapadToolkit.WinUI/Resources/performance_quick.ico b/IdeapadToolkit.WinUI/Resources/performance_quick.ico new file mode 100644 index 0000000..c8ef6e1 Binary files /dev/null and b/IdeapadToolkit.WinUI/Resources/performance_quick.ico differ diff --git a/IdeapadToolkit.WinUI/Resources/saving_conservation.ico b/IdeapadToolkit.WinUI/Resources/saving_conservation.ico new file mode 100644 index 0000000..3d6d9d0 Binary files /dev/null and b/IdeapadToolkit.WinUI/Resources/saving_conservation.ico differ diff --git a/IdeapadToolkit.WinUI/Resources/saving_normal.ico b/IdeapadToolkit.WinUI/Resources/saving_normal.ico new file mode 100644 index 0000000..cdad68c Binary files /dev/null and b/IdeapadToolkit.WinUI/Resources/saving_normal.ico differ diff --git a/IdeapadToolkit.WinUI/Resources/saving_quick.ico b/IdeapadToolkit.WinUI/Resources/saving_quick.ico new file mode 100644 index 0000000..b793ffb Binary files /dev/null and b/IdeapadToolkit.WinUI/Resources/saving_quick.ico differ diff --git a/IdeapadToolkit.WinUI/Services/INavigationService.cs b/IdeapadToolkit.WinUI/Services/INavigationService.cs new file mode 100644 index 0000000..75ab665 --- /dev/null +++ b/IdeapadToolkit.WinUI/Services/INavigationService.cs @@ -0,0 +1,14 @@ +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Media.Animation; +using System; + +namespace IdeapadToolkit.WinUI3.Services; +internal interface INavigationService +{ + public Frame? NavFrame { get; set; } + public bool CanGoBack { get; } + public void GoBack(); + public void Navigate(object? args = null, NavigationTransitionInfo? navigationTransitionInfo = null) where TElement : UIElement; + public void Navigate(Type page, object? args = null, NavigationTransitionInfo? navigationTransitionInfo = null); +} diff --git a/IdeapadToolkit.WinUI/Services/NavigationService.cs b/IdeapadToolkit.WinUI/Services/NavigationService.cs new file mode 100644 index 0000000..6a2f96b --- /dev/null +++ b/IdeapadToolkit.WinUI/Services/NavigationService.cs @@ -0,0 +1,35 @@ +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Media.Animation; +using System; + +namespace IdeapadToolkit.WinUI3.Services; +internal class NavigationService : INavigationService +{ + public Frame? NavFrame { get; set; } + + public bool CanGoBack + { + get + { + return this.NavFrame?.CanGoBack ?? false; + } + } + public void GoBack() + { + NavFrame?.GoBack(); + } + + public void Navigate(object? args, NavigationTransitionInfo? navigationTransitionInfo = null) where TElement : UIElement + { + NavFrame.Navigate(typeof(TElement), args, navigationTransitionInfo); + NavFrame.BackStack.Clear(); + } + + public void Navigate(Type page, object? args, NavigationTransitionInfo? navigationTransitionInfo = null) + { + NavFrame.Navigate(page, args, navigationTransitionInfo); + NavFrame.BackStack.Clear(); + } + +} diff --git a/IdeapadToolkit.WinUI/ViewModels/MainPageViewModel.cs b/IdeapadToolkit.WinUI/ViewModels/MainPageViewModel.cs new file mode 100644 index 0000000..87f8f6d --- /dev/null +++ b/IdeapadToolkit.WinUI/ViewModels/MainPageViewModel.cs @@ -0,0 +1,258 @@ +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using IdeapadToolkit.Core.Models; +using IdeapadToolkit.Core.Services; +using Microsoft.UI.Xaml.Controls; +using Serilog; +using System.Threading.Tasks; + +namespace IdeapadToolkit.WinUI3.ViewModels; +internal partial class MainPageViewModel : ObservableObject +{ + private readonly ILenovoPowerSettingsService _lenovoPowerSettingsService; + private readonly IUEFISettingsService _uEFISettingsService; + private IAdministratorPermissionService _administratorPermissionService; + private ILogger _logger; + + internal MainPageViewModel() + { + _lenovoPowerSettingsService = App.Composition.Resolve(); + _uEFISettingsService = App.Composition.Resolve(); + _administratorPermissionService = App.Composition.Resolve(); + _logger = App.Composition.Resolve(); + } + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(IsEfficientChecked), nameof(IsIntelligentCoolingChecked), nameof(IsExtremePerformanceChecked), nameof(IconSource))] + private PowerPlan _plan; + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(IsConservationModeEnabled), nameof(IsNormalModeEnabled), nameof(IsRapidModeEnabled), nameof(IconSource))] + private ChargingMode _mode; + public void Refresh() + { + try + { + Plan = _lenovoPowerSettingsService.GetPowerPlan(); + Mode = _lenovoPowerSettingsService.GetChargingMode(); + } + catch (Exception ex) + { + _logger.Error(ex, "Exception while fetching current settings"); + } + } + + #region PowerPlanProperties + public bool IsEfficientChecked + { + get => _plan == PowerPlan.EfficiencyMode; + set + { + } + } + + public bool IsIntelligentCoolingChecked + { + get => _plan == PowerPlan.IntelligentCooling; + set + { + } + } + + public bool IsExtremePerformanceChecked + { + get => _plan == PowerPlan.ExtremePerformance; + set + { + } + } + #endregion + + #region OtherProperties + public bool IsFlipToBootEnabled + { + get + { + if (IsAdministrator) + { + bool res = false; + try + { + res = _uEFISettingsService.GetFlipToBootStatus(); + } + catch (Exception ex) + { + _logger.Error(ex, "Exception while getting FlipToBoot status"); + } + return res; + } + else + { + return false; + } + } + set + { + try + { + _uEFISettingsService.SetFlipToBootStatus(value); + } + catch (Exception ex) + { + _logger.Error(ex, "Exception while setting FlipToBoot status"); + } + } + } + + public bool IsAlwaysOnUsbEnabled + { + get + { + try + { + return _lenovoPowerSettingsService.IsAlwaysOnUsbEnabled(); + } + catch (Exception ex) + { + _logger.Error(ex, "Error while getting Always on usb setting"); + return false; + } + } + set + { + try + { + _lenovoPowerSettingsService.SetAlwaysOnUsb(value); + } + catch (Exception ex) + { + _logger.Error(ex, "Error while setting Always on usb setting"); + } + OnPropertyChanged(nameof(IsAlwaysOnUsbEnabled)); + } + } + + public bool IsAlwaysOnUsbBatteryEnabled + { + get + { + try + { + return _lenovoPowerSettingsService.IsAlwaysOnUsbBatteryEnabled(); + } + catch (Exception ex) + { + _logger.Error(ex, "Error while getting Always on usb battery setting"); + return false; + } + } + set + { + try + { + _lenovoPowerSettingsService.SetAlwaysOnUsbBattery(value); + } + catch (Exception ex) + { + _logger.Error(ex, "Error while setting Always on usb battery setting"); + } + } + } + #endregion + + #region ChargingModeProperties + public bool IsConservationModeEnabled + { + get => _mode == ChargingMode.Conservation; + set + { + } + } + + public bool IsNormalModeEnabled + { + get => _mode == ChargingMode.Normal; + set + { + } + } + + public bool IsRapidModeEnabled + { + get => _mode == ChargingMode.Rapid; + set + { + } + } + + #endregion + + public string IconSource + { + get + { + string path = (_plan, _mode) switch + { + (PowerPlan.IntelligentCooling, ChargingMode.Normal) => "ms-appx:///Resources/intelligent_normal.ico", + (PowerPlan.IntelligentCooling, ChargingMode.Conservation) => "ms-appx:///Resources/intelligent_conservation.ico", + (PowerPlan.IntelligentCooling, ChargingMode.Rapid) => "ms-appx:///Resources/intelligent_quick.ico", + (PowerPlan.EfficiencyMode, ChargingMode.Normal) => "ms-appx:///Resources/saving_normal.ico", + (PowerPlan.EfficiencyMode, ChargingMode.Conservation) => "ms-appx:///Resources/saving_conservation.ico", + (PowerPlan.EfficiencyMode, ChargingMode.Rapid) => "ms-appx:///Resources/saving_quick.ico", + (PowerPlan.ExtremePerformance, ChargingMode.Normal) => "ms-appx:///Resources/performance_normal.ico", + (PowerPlan.ExtremePerformance, ChargingMode.Conservation) => "ms-appx:///Resources/performance_conservation.ico", + (PowerPlan.ExtremePerformance, ChargingMode.Rapid) => "ms-appx:///Resources/performance_quick.ico", + _ => "ms-appx:///Resources/intelligent_normal.ico" + }; + return path; + } + } + public bool IsAdministrator => _administratorPermissionService.IsAdministrator; + + [RelayCommand] + private void SetChargingMode(int? mode) + { + if (mode == null) return; + try + { + _lenovoPowerSettingsService.SetChargingMode((ChargingMode)mode); + Refresh(); + } + catch (Exception ex) + { + _logger.Error(ex, "Error while setting charging mode"); + } + } + + [RelayCommand] + private async Task RestartAsAdmin() + { + var res = await new ContentDialog + { + Title = "Permission required", + Content = "The program will now restart as administrator", + PrimaryButtonText = "Ok", + SecondaryButtonText = "Cancel", + XamlRoot = App.MainWindow.Content.XamlRoot + }.ShowAsync(); + + if (res == ContentDialogResult.Primary) + { + _administratorPermissionService.RelaunchAsAdmin(); + } + } + + [RelayCommand] + private void SetPlan(int? plan) + { + if (plan == null) return; + try + { + _lenovoPowerSettingsService.SetPowerPlan((PowerPlan)plan); + Refresh(); + } + catch (Exception ex) + { + _logger.Error(ex, "Exception while setting power plan"); + } + } +} diff --git a/IdeapadToolkit.WinUI/ViewModels/SettingsViewModel.cs b/IdeapadToolkit.WinUI/ViewModels/SettingsViewModel.cs new file mode 100644 index 0000000..fd54690 --- /dev/null +++ b/IdeapadToolkit.WinUI/ViewModels/SettingsViewModel.cs @@ -0,0 +1,135 @@ +using System.Globalization; +using System.IO; +using System.Linq; +using System.Threading; +using CommunityToolkit.Mvvm.ComponentModel; +using IdeapadToolkit.Core.Services; +using Microsoft.UI.Dispatching; +using Microsoft.UI.Xaml.Controls; +using Microsoft.Windows.Storage; + +namespace IdeapadToolkit.WinUI3.ViewModels; + +internal class Settings +{ + internal static Settings Instance { get; private set; } = Load(); + private Settings() { } + + private static readonly string _path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "IdeapadToolkit", "settings.txt"); + + public string Language { get; set; } + public bool KeepInTray { get; set; } + + public void Save() + { + File.WriteAllText(_path, $"{Language};{KeepInTray}"); + } + + private static Settings Load() + { + var settings = new Settings(); + try + { + string contents = File.ReadAllText(_path); + var segments = contents.Split(";"); + if (segments.Length > 0) + { + settings.Language = segments[0]; + } + if (segments.Length > 1) + { + if (bool.TryParse(segments[1], out var intray)) + { + settings.KeepInTray = intray; + } + else + { + settings.KeepInTray = true; + } + } + } + catch + { + settings.Language = "en-US"; + settings.KeepInTray = true; + } + return settings; + } +} + +public record Locale(string Name, string CultureInfoCode); + +internal partial class SettingsViewModel : ObservableObject +{ + private readonly IRunOnStartupService _runOnStartupService; + + public SettingsViewModel(IRunOnStartupService runOnStartupService) + { + _runOnStartupService = runOnStartupService; + } + + public Locale[] SupportedLanguages + { + get; init; + } = + [new Locale("English", "en-US"), + new Locale("Čeština", "cs-CZ"), + new Locale("Français", "fr-FR"), + new Locale("简体中文", "zh-CN")]; + + public bool IsRunOnStartupEnabled + { + get => _runOnStartupService.IsRunOnStartupEnabled(); + set + { + try + { + _runOnStartupService.ToggleRunOnStartup(); + } + catch (Exception ex) + { + var dialog = new ContentDialog + { + Title = "Error", + Content = ex.Message, + CloseButtonText = "Ok", + XamlRoot = App.MainWindow.Content.XamlRoot + }.ShowAsync(); + } + } + } + + public Locale SelectedLocale + { + get + { + var setting = Settings.Instance.Language; + var locale = SupportedLanguages.FirstOrDefault(x => x.CultureInfoCode == setting); + return locale ?? new Locale(String.Empty, String.Empty); + } + set + { + if (String.IsNullOrEmpty(value?.Name)) + return; + + Settings.Instance.Language = value.CultureInfoCode; + var culture = CultureInfo.GetCultureInfo(value.CultureInfoCode); + if (culture != null) + DispatcherQueue.GetForCurrentThread().TryEnqueue(() => + { + Thread.CurrentThread.CurrentUICulture = culture; + }); + Settings.Instance.Save(); + } + } + + public bool KeepInTray + { + get => Settings.Instance.KeepInTray; + set + { + Settings.Instance.KeepInTray = value; + Settings.Instance.Save(); + } + } +} diff --git a/IdeapadToolkit.WinUI/Views/MainPage.xaml b/IdeapadToolkit.WinUI/Views/MainPage.xaml new file mode 100644 index 0000000..082fbfa --- /dev/null +++ b/IdeapadToolkit.WinUI/Views/MainPage.xaml @@ -0,0 +1,109 @@ + + + + + + + + + + + + + 2 + + + + + 1 + + + + + 3 + + + + + + + + + 1 + + + + + 0 + + + + + 2 + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/IdeapadToolkit.WinUI/Views/MainPage.xaml.cs b/IdeapadToolkit.WinUI/Views/MainPage.xaml.cs new file mode 100644 index 0000000..6f8e848 --- /dev/null +++ b/IdeapadToolkit.WinUI/Views/MainPage.xaml.cs @@ -0,0 +1,38 @@ +using IdeapadToolkit.WinUI3.ViewModels; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Controls.Primitives; +using Microsoft.UI.Xaml.Data; +using Microsoft.UI.Xaml.Input; +using Microsoft.UI.Xaml.Media; +using Microsoft.UI.Xaml.Navigation; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices.WindowsRuntime; +using Windows.Foundation; +using Windows.Foundation.Collections; + +// To learn more about WinUI, the WinUI project structure, +// and more about our project templates, see: http://aka.ms/winui-project-info. + +namespace IdeapadToolkit.WinUI3.Views; +/// +/// An empty page that can be used on its own or navigated to within a Frame. +/// +public sealed partial class MainPage : Page +{ + public MainPage() + { + this.InitializeComponent(); + ViewModel = App.Composition.Resolve(); + } + + internal MainPageViewModel ViewModel { get; set; } + + private void Page_Loaded(object sender, RoutedEventArgs e) + { + ViewModel.Refresh(); + } +} diff --git a/IdeapadToolkit.WinUI/Views/SettingsPage.xaml b/IdeapadToolkit.WinUI/Views/SettingsPage.xaml new file mode 100644 index 0000000..9c365ad --- /dev/null +++ b/IdeapadToolkit.WinUI/Views/SettingsPage.xaml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + diff --git a/IdeapadToolkit.WinUI/Views/SettingsPage.xaml.cs b/IdeapadToolkit.WinUI/Views/SettingsPage.xaml.cs new file mode 100644 index 0000000..81fa23c --- /dev/null +++ b/IdeapadToolkit.WinUI/Views/SettingsPage.xaml.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices.WindowsRuntime; +using IdeapadToolkit.WinUI3.ViewModels; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Controls.Primitives; +using Microsoft.UI.Xaml.Data; +using Microsoft.UI.Xaml.Input; +using Microsoft.UI.Xaml.Media; +using Microsoft.UI.Xaml.Navigation; +using Windows.Foundation; +using Windows.Foundation.Collections; + +// To learn more about WinUI, the WinUI project structure, +// and more about our project templates, see: http://aka.ms/winui-project-info. + +namespace IdeapadToolkit.WinUI3.Views; +/// +/// An empty page that can be used on its own or navigated to within a Frame. +/// +public sealed partial class SettingsPage : Page +{ + public SettingsPage() + { + this.InitializeComponent(); + ViewModel = App.Composition.Resolve(); + } + + internal SettingsViewModel ViewModel { get; set; } +} diff --git a/IdeapadToolkit.WinUI/Views/TrayIconView.xaml b/IdeapadToolkit.WinUI/Views/TrayIconView.xaml new file mode 100644 index 0000000..f923c1d --- /dev/null +++ b/IdeapadToolkit.WinUI/Views/TrayIconView.xaml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/IdeapadToolkit.WinUI/Views/TrayIconView.xaml.cs b/IdeapadToolkit.WinUI/Views/TrayIconView.xaml.cs new file mode 100644 index 0000000..fb28272 --- /dev/null +++ b/IdeapadToolkit.WinUI/Views/TrayIconView.xaml.cs @@ -0,0 +1,92 @@ +using CommunityToolkit.Mvvm.Input; +using IdeapadToolkit.Core.Models; +using IdeapadToolkit.WinUI3.Localization; +using IdeapadToolkit.WinUI3.ViewModels; +using Microsoft.UI; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Media; +using Microsoft.UI.Xaml.Media.Imaging; + +namespace IdeapadToolkit.WinUI3.Views; + +public sealed partial class TrayIconView : Page +{ + public TrayIconView() + { + InitializeComponent(); + ViewModel = App.Composition.Resolve(); + } + + internal MainPageViewModel ViewModel + { + get; + } + + public event EventHandler TrayIconClicked; + + [RelayCommand] + private void OnTrayIconClicked() + { + TrayIconClicked?.Invoke(this, EventArgs.Empty); + } + + public void MakeVisible() + { + TrayIcon.ForceCreate(); + TrayIcon.Visibility = Visibility.Visible; + TrayIcon.LeftClickCommand = TrayIconClickedCommand; + ViewModel.PropertyChanged += ViewModel_PropertyChanged; + RefreshBindings(); + } + + private void ViewModel_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e) + { + TrayIcon.IconSource = new BitmapImage(new Uri(ViewModel.IconSource)); + } + + private void MenuItemExit_Click(object sender, RoutedEventArgs e) + { + Environment.Exit(0); + } + + private void RefreshBindings() + { + ViewModel.Refresh(); + + RadioConservation.Text = Strings.CONSERVATION; + RadioConservation.Command = ViewModel.SetChargingModeCommand; + RadioConservation.CommandParameter = (int)ChargingMode.Conservation; + RadioConservation.Background = ViewModel.IsConservationModeEnabled ? new SolidColorBrush(Colors.DarkGreen) : new SolidColorBrush(Colors.Transparent); + + RadioNormal.Text = Strings.NORMAL; + RadioNormal.Command = ViewModel.SetChargingModeCommand; + RadioNormal.CommandParameter = (int)ChargingMode.Normal; + RadioNormal.Background = ViewModel.IsNormalModeEnabled ? new SolidColorBrush(Colors.DarkBlue) : new SolidColorBrush(Colors.Transparent); + + RadioRapid.Text = Strings.RAPID; + RadioRapid.Command = ViewModel.SetChargingModeCommand; + RadioRapid.CommandParameter = (int)ChargingMode.Rapid; + RadioRapid.Background = ViewModel.IsRapidModeEnabled ? new SolidColorBrush(Colors.DarkRed) : new SolidColorBrush(Colors.Transparent); + + RadioBatterySaving.Text = Strings.BATTERY_SAVING; + RadioBatterySaving.Command = ViewModel.SetPlanCommand; + RadioBatterySaving.CommandParameter = (int)PowerPlan.EfficiencyMode; + RadioBatterySaving.Background = ViewModel.IsEfficientChecked ? new SolidColorBrush(Colors.DarkGreen) : new SolidColorBrush(Colors.Transparent); + + RadioIntelligent.Text = Strings.INTELLIGENT_COOLING; + RadioIntelligent.Command = ViewModel.SetPlanCommand; + RadioIntelligent.CommandParameter = (int)PowerPlan.IntelligentCooling; + RadioIntelligent.Background = ViewModel.IsIntelligentCoolingChecked ? new SolidColorBrush(Colors.DarkBlue) : new SolidColorBrush(Colors.Transparent); + + RadioExtreme.Text = Strings.EXTREME_PERFORMANCE; + RadioExtreme.Command = ViewModel.SetPlanCommand; + RadioExtreme.CommandParameter = (int)PowerPlan.ExtremePerformance; + RadioExtreme.Background = ViewModel.IsExtremePerformanceChecked ? new SolidColorBrush(Colors.DarkRed) : new SolidColorBrush(Colors.Transparent); + } + + private void RadioConservation_Loaded(object sender, RoutedEventArgs e) + { + RefreshBindings(); + } +} \ No newline at end of file diff --git a/IdeapadToolkit.WinUI/app.manifest b/IdeapadToolkit.WinUI/app.manifest new file mode 100644 index 0000000..2b8f1fb --- /dev/null +++ b/IdeapadToolkit.WinUI/app.manifest @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + PerMonitorV2 + + + \ No newline at end of file diff --git a/IdeapadToolkit.sln b/IdeapadToolkit.sln index 0d2e4e8..048641d 100644 --- a/IdeapadToolkit.sln +++ b/IdeapadToolkit.sln @@ -7,6 +7,15 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IdeapadToolkit", "IdeapadTo EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IdeapadToolkitTests", "IdeapadToolkitTests\IdeapadToolkitTests.csproj", "{0E651F63-5A07-42B8-AD6E-0363D540A779}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IdeapadToolkit.Core", "IdeapadToolkit.Core\IdeapadToolkit.Core.csproj", "{FE5A0D0C-D865-4590-8D63-4A587D7094A9}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IdeapadToolkit.WinUI3", "IdeapadToolkit.WinUI\IdeapadToolkit.WinUI3.csproj", "{556130B7-65E1-4B15-944A-998F9D9407F4}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{ED86D2E1-346D-46FE-87BB-1D090D7D372E}" + ProjectSection(SolutionItems) = preProject + .editorconfig = .editorconfig + EndProjectSection +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -21,6 +30,16 @@ Global {0E651F63-5A07-42B8-AD6E-0363D540A779}.Debug|Any CPU.Build.0 = Debug|Any CPU {0E651F63-5A07-42B8-AD6E-0363D540A779}.Release|Any CPU.ActiveCfg = Release|Any CPU {0E651F63-5A07-42B8-AD6E-0363D540A779}.Release|Any CPU.Build.0 = Release|Any CPU + {FE5A0D0C-D865-4590-8D63-4A587D7094A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FE5A0D0C-D865-4590-8D63-4A587D7094A9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FE5A0D0C-D865-4590-8D63-4A587D7094A9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FE5A0D0C-D865-4590-8D63-4A587D7094A9}.Release|Any CPU.Build.0 = Release|Any CPU + {556130B7-65E1-4B15-944A-998F9D9407F4}.Debug|Any CPU.ActiveCfg = Debug|x64 + {556130B7-65E1-4B15-944A-998F9D9407F4}.Debug|Any CPU.Build.0 = Debug|x64 + {556130B7-65E1-4B15-944A-998F9D9407F4}.Debug|Any CPU.Deploy.0 = Debug|x64 + {556130B7-65E1-4B15-944A-998F9D9407F4}.Release|Any CPU.ActiveCfg = Release|x64 + {556130B7-65E1-4B15-944A-998F9D9407F4}.Release|Any CPU.Build.0 = Release|x64 + {556130B7-65E1-4B15-944A-998F9D9407F4}.Release|Any CPU.Deploy.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/IdeapadToolkit/App.xaml.cs b/IdeapadToolkit/App.xaml.cs index 43153fa..0cb5d7c 100644 --- a/IdeapadToolkit/App.xaml.cs +++ b/IdeapadToolkit/App.xaml.cs @@ -12,6 +12,7 @@ using System.Globalization; using System.Threading; using IdeapadToolkit.Localization; +using IdeapadToolkit.Core.Services; namespace IdeapadToolkit { diff --git a/IdeapadToolkit/Helpers/Win32.cs b/IdeapadToolkit/Helpers/Win32.cs deleted file mode 100644 index 9064d03..0000000 --- a/IdeapadToolkit/Helpers/Win32.cs +++ /dev/null @@ -1,89 +0,0 @@ -using System; -using System.Runtime.InteropServices; -using System.Text; -using static IdeapadToolkit.Services.UEFISettingsService; - -namespace IdeapadToolkitService.Helpers -{ - internal class Win32 - { - [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] - [DllImport("kernel32.dll")] - public static extern IntPtr OpenProcess( - int dwDesiredAccess, - bool bInheritHandle, - int dwProcessId); - - [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] - [DllImport("kernel32.dll", SetLastError = true)] - public static extern int GetApplicationUserModelId( - IntPtr hProcess, - ref uint appModelIdLength, - [MarshalAs(UnmanagedType.LPWStr)] StringBuilder sbAppUserModelId); - - - [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] - [DllImport("kernel32.dll", SetLastError = true)] - public static extern int GetFirmwareEnvironmentVariableExW([MarshalAs(UnmanagedType.LPWStr)] string lpName, [MarshalAs(UnmanagedType.LPWStr)] string lpGuid, ref LenovoFlipToBootSwInterface pBuffer, int nSize, IntPtr pAttribute); - - - [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] - [DllImport("kernel32.dll", SetLastError = true)] - public static extern int SetFirmwareEnvironmentVariableExW( - [MarshalAs(UnmanagedType.LPWStr)] string lpName, - [MarshalAs(UnmanagedType.LPWStr)] string lpGuid, - ref LenovoFlipToBootSwInterface pBuffer, - int nSize, - int attribute); - - - [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] - [DllImport("kernel32.dll")] - public static extern IntPtr GetCurrentProcess(); - - [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] - [DllImport("advapi32.dll", CharSet = CharSet.Unicode)] - public static extern bool LookupPrivilegeValue( - string lpSystemName, - string lpName, - ref long lpLuid); - - [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] - [DllImport("advapi32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool AdjustTokenPrivileges( - IntPtr tokenHandle, - [MarshalAs(UnmanagedType.Bool)] bool disableAllPrivileges, - ref TokenPrivelege newState, - int zero, - IntPtr null1, - IntPtr null2); - - [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] - [DllImport("advapi32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool OpenProcessToken( - IntPtr processHandle, - uint desiredAccess, - ref IntPtr tokenHandle); - - [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] - [DllImport("kernel32.dll", SetLastError = true)] - public static extern bool GetFirmwareType(ref FirmwareType firmwareType); - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public struct TokenPrivelege - { - public int Count; - public long Luid; - public int Attr; - } - public enum FirmwareType - { - FirmwareTypeUnknown, - FirmwareTypeBios, - FirmwareTypeUefi, - FirmwareTypeMax, - } -} diff --git a/IdeapadToolkit/IdeapadToolkit.csproj b/IdeapadToolkit/IdeapadToolkit.csproj index f596814..05b0ceb 100644 --- a/IdeapadToolkit/IdeapadToolkit.csproj +++ b/IdeapadToolkit/IdeapadToolkit.csproj @@ -37,6 +37,10 @@ + + + + diff --git a/IdeapadToolkit/Properties/PublishProfiles/FolderProfile.pubxml b/IdeapadToolkit/Properties/PublishProfiles/FolderProfile.pubxml index 995e639..02977b6 100644 --- a/IdeapadToolkit/Properties/PublishProfiles/FolderProfile.pubxml +++ b/IdeapadToolkit/Properties/PublishProfiles/FolderProfile.pubxml @@ -11,7 +11,7 @@ https://go.microsoft.com/fwlink/?LinkID=208121. <_TargetId>Folder net8.0-windows win-x64 - false + true true true diff --git a/IdeapadToolkit/Services/LenovoPowerSettingsService.cs b/IdeapadToolkit/Services/LenovoPowerSettingsService.cs deleted file mode 100644 index 783b7a4..0000000 --- a/IdeapadToolkit/Services/LenovoPowerSettingsService.cs +++ /dev/null @@ -1,155 +0,0 @@ -using IdeapadToolkit.Models; -using System; -using System.Runtime.InteropServices; - -namespace IdeapadToolkit.Services -{ - public class LenovoPowerSettingsService : ILenovoPowerSettingsService - { - [DllImport("PowerBattery.dll", EntryPoint = "?SetITSMode@CIntelligentCooling@PowerBattery@@QEAAHAEAW4ITSMode@12@@Z", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] - internal static extern int SetITSMode(ref CIntelligentCooling var1, ref PowerPlan var2); - - - [DllImport("PowerBattery.dll", EntryPoint = "??0CIntelligentCooling@PowerBattery@@QEAA@XZ", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] - internal static extern CIntelligentCooling CIntelligentCooling(ref CIntelligentCooling var1); - - - [DllImport("PowerBattery.dll", EntryPoint = "?GetITSMode@CIntelligentCooling@PowerBattery@@QEAAHAEAHAEAW4ITSMode@12@@Z", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] - internal static extern int GetITSMode(ref CIntelligentCooling var1, ref int var2, ref PowerPlan var3); - - - [DllImport("PowerBattery.dll", EntryPoint = "??0CChargingMode@PowerBattery@@QEAA@XZ", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] - internal static extern CChargingMode CChargingMode(ref CChargingMode var1); - - - [DllImport("PowerBattery.dll", EntryPoint = "?GetChargingMode@CChargingMode@PowerBattery@@QEBAHXZ", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] - internal static extern int GetChargingMode(ref CChargingMode var1); - - [DllImport("PowerBattery.dll", EntryPoint = "?SetChargingMode@CChargingMode@PowerBattery@@QEBAHH@Z", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] - internal static extern int SetChargingMode(ref CChargingMode var1, int var2); - - [DllImport("PowerBattery.dll", EntryPoint = "?SetChargingMode@CChargingMode@PowerBattery@@QEBAHH_N@Z", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] - // I don't know what the newly added boolean does, but it doesn't seem to matter - internal static extern int SetChargingModeFallBack(ref CChargingMode var1, int var2, bool var3); - - [DllImport("PowerBattery.dll", EntryPoint = "??0CUSBCharger@PowerBattery@@QEAA@XZ", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] - internal static extern CUSBCharger CUSBCharger(ref CUSBCharger var1); - - [DllImport("PowerBattery.dll", EntryPoint = "??0CUSBBatteryCharger@PowerBattery@@QEAA@XZ", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] - internal static extern CUSBBatteryCharger CUSBBatteryCharger(ref CUSBBatteryCharger var1); - - [DllImport("PowerBattery.dll", EntryPoint = "?OpenOrClose@CUSBBatteryCharger@PowerBattery@@UEAAHXZ", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] - internal static extern int OpenOrClose(ref CUSBBatteryCharger var1); - - [DllImport("PowerBattery.dll", EntryPoint = "?OpenOrClose@CUSBCharger@PowerBattery@@UEAAHXZ", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] - internal static extern int OpenOrClose(ref CUSBCharger var1); - - [DllImport("PowerBattery.dll", EntryPoint = "?OpenFeature@CUSBCharger@PowerBattery@@UEAAHXZ", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] - internal static extern int OpenFeature(ref CUSBCharger var1); - - [DllImport("PowerBattery.dll", EntryPoint = "?OpenFeature@CUSBBatteryCharger@PowerBattery@@UEAAHXZ", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] - internal static extern int OpenFeature(ref CUSBBatteryCharger var1); - - [DllImport("PowerBattery.dll", EntryPoint = "?CloseFeature@CUSBCharger@PowerBattery@@UEAAHXZ", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] - internal static extern int CloseFeature(ref CUSBCharger var1); - - [DllImport("PowerBattery.dll", EntryPoint = "?CloseFeature@CUSBBatteryCharger@PowerBattery@@UEAAHXZ", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] - internal static extern int CloseFeature(ref CUSBBatteryCharger var1); - - - public PowerPlan GetPowerPlan() - { - CIntelligentCooling instance = new(); - instance = CIntelligentCooling(ref instance); - PowerPlan newmode = new(); - int trash = 0; - _ = GetITSMode(ref instance, ref trash, ref newmode); - return newmode; - } - - public void SetPowerPlan(PowerPlan plan) - { - CIntelligentCooling instance = new(); - instance = CIntelligentCooling(ref instance); - _ = SetITSMode(ref instance, ref plan); - } - - public ChargingMode GetChargingMode() - { - CChargingMode instance = new(); - instance = CChargingMode(ref instance); - ChargingMode mode = (ChargingMode)(GetChargingMode(ref instance)); - return mode; - } - - public void SetChargingMode(ChargingMode chargingMode) - { - CChargingMode instance = new(); - instance = CChargingMode(ref instance); - try - { - _ = SetChargingMode(ref instance, (int)chargingMode); - } - catch (SystemException) - { - _ = SetChargingModeFallBack(ref instance, (int)chargingMode, false); - } - } - - public bool IsAlwaysOnUsbEnabled() - { - CUSBCharger instance = new(); - instance = CUSBCharger(ref instance); - var res = (OpenOrClose(ref instance)); - return res switch - { - 2 => false, - 1 => true, - _ => false - }; - } - - public void SetAlwaysOnUsb(bool alwaysOnUsbEnabled) - { - CUSBCharger instance = new(); - instance = CUSBCharger(ref instance); - switch (alwaysOnUsbEnabled) - { - case true: - _ = OpenFeature(ref instance); - break; - case false: - _ = CloseFeature(ref instance); - break; - } - } - - public bool IsAlwaysOnUsbBatteryEnabled() - { - CUSBBatteryCharger instance = new(); - instance = CUSBBatteryCharger(ref instance); - var res = (OpenOrClose(ref instance)); - return res switch - { - 2 => false, - 1 => true, - _ => false - }; - } - - public void SetAlwaysOnUsbBattery(bool alwaysOnUsbBattryEnabled) - { - CUSBBatteryCharger instance = new(); - instance = CUSBBatteryCharger(ref instance); - switch (alwaysOnUsbBattryEnabled) - { - case true: - _ = OpenFeature(ref instance); - break; - case false: - _ = CloseFeature(ref instance); - break; - } - } - } -} diff --git a/IdeapadToolkit/ViewModels/LenovoSettingsViewModel.cs b/IdeapadToolkit/ViewModels/LenovoSettingsViewModel.cs index 4f53300..4d51a2a 100644 --- a/IdeapadToolkit/ViewModels/LenovoSettingsViewModel.cs +++ b/IdeapadToolkit/ViewModels/LenovoSettingsViewModel.cs @@ -1,7 +1,7 @@ using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; -using IdeapadToolkit.Models; -using IdeapadToolkit.Services; +using IdeapadToolkit.Core.Models; +using IdeapadToolkit.Core.Services; using ModernWpf.Controls; using Serilog; using System; @@ -272,5 +272,4 @@ private void SetPlan(int? plan) } } - } diff --git a/IdeapadToolkit/ViewModels/SettingsViewModel.cs b/IdeapadToolkit/ViewModels/SettingsViewModel.cs index 4a0c187..2d137c4 100644 --- a/IdeapadToolkit/ViewModels/SettingsViewModel.cs +++ b/IdeapadToolkit/ViewModels/SettingsViewModel.cs @@ -1,11 +1,9 @@ using CommunityToolkit.Mvvm.ComponentModel; -using IdeapadToolkit.Services; +using IdeapadToolkit.Core.Services; using ModernWpf.Controls; using System; -using System.Collections.Generic; using System.Globalization; using System.Linq; -using System.Text; using System.Threading; using System.Windows; diff --git a/IdeapadToolkitTests/Services/LenovoPowerSettingsServiceTests.cs b/IdeapadToolkitTests/Services/LenovoPowerSettingsServiceTests.cs index e462586..2137fa9 100644 --- a/IdeapadToolkitTests/Services/LenovoPowerSettingsServiceTests.cs +++ b/IdeapadToolkitTests/Services/LenovoPowerSettingsServiceTests.cs @@ -1,4 +1,7 @@ -namespace IdeapadToolkit.Services.Tests +using IdeapadToolkit.Core.Models; +using IdeapadToolkit.Core.Services; + +namespace IdeapadToolkitTests.Services { [TestClass()] public class LenovoPowerSettingsServiceTests @@ -24,7 +27,6 @@ public void IsAlwaysOnUsbBattryEnabledTest() Assert.IsTrue(res); } - [TestMethod()] public void AlwaysOnUsbRandomTest() { @@ -52,14 +54,14 @@ public void AlwaysOnUsbBattryRandomTest() [TestMethod()] public void SetChargingModeRandomTest() { - _service.SetChargingMode(Models.ChargingMode.Normal); - Assert.IsTrue(_service.GetChargingMode() == Models.ChargingMode.Normal); - _service.SetChargingMode(Models.ChargingMode.Conservation); - Assert.IsTrue(_service.GetChargingMode() == Models.ChargingMode.Conservation); - _service.SetChargingMode(Models.ChargingMode.Rapid); - Assert.IsTrue(_service.GetChargingMode() == Models.ChargingMode.Rapid); - _service.SetChargingMode(Models.ChargingMode.Normal); - Assert.IsTrue(_service.GetChargingMode() == Models.ChargingMode.Normal); + _service.SetChargingMode(ChargingMode.Normal); + Assert.IsTrue(_service.GetChargingMode() == ChargingMode.Normal); + _service.SetChargingMode(ChargingMode.Conservation); + Assert.IsTrue(_service.GetChargingMode() == ChargingMode.Conservation); + _service.SetChargingMode(ChargingMode.Rapid); + Assert.IsTrue(_service.GetChargingMode() == ChargingMode.Rapid); + _service.SetChargingMode(ChargingMode.Normal); + Assert.IsTrue(_service.GetChargingMode() == ChargingMode.Normal); } } } \ No newline at end of file diff --git a/IdeapadToolkitTests/Services/UEFISettingsServiceTests.cs b/IdeapadToolkitTests/Services/UEFISettingsServiceTests.cs index 7e083d3..f8eef1a 100644 --- a/IdeapadToolkitTests/Services/UEFISettingsServiceTests.cs +++ b/IdeapadToolkitTests/Services/UEFISettingsServiceTests.cs @@ -1,7 +1,8 @@ -using Moq; +using IdeapadToolkit.Core.Services; +using Moq; using Serilog; -namespace IdeapadToolkit.Services.Tests +namespace IdeapadToolkitTests.Services { [TestClass()] public class UEFISettingsServiceTests @@ -21,7 +22,6 @@ public void IsFlipToBootOnTest() Assert.IsNotNull(res); } - [TestMethod()] public void FlipToBootSettingTest() { @@ -35,8 +35,6 @@ public void FlipToBootSettingTest() _service.SetFlipToBootStatus(false); Assert.IsFalse(_service.GetFlipToBootStatus()); _service.SetFlipToBootStatus(Convert.ToBoolean(original)); - } - } } \ No newline at end of file