add check on connection before executing LG actions, update AMD API, improve NVIDIA dithering with multiple displays, add NVIDIA driver settings , fix some crashes

This commit is contained in:
Vincent Maas committed 2023-01-07 14:56:04 +01:00
1 parent 43f038e9ee
commit c85b33127b
20 files changed
+6570 -6992

No files matched your search

+3 -3
View File
@@ -19,8 +19,8 @@
<PublisherName>Maassoft</PublisherName>
<Company>Maassoft</Company>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>8.2.0.0</ApplicationVersion>
<Version>8.2.0.0</Version>
<ApplicationVersion>8.3.0.0</ApplicationVersion>
<Version>8.3.0.0</Version>
<UseApplicationTrust>false</UseApplicationTrust>
<PublishWizardCompleted>true</PublishWizardCompleted>
<BootstrapperEnabled>false</BootstrapperEnabled>
@@ -30,7 +30,7 @@
<ImportWindowsDesktopTargets>true</ImportWindowsDesktopTargets>
<ApplicationIcon>pngbarn.ico</ApplicationIcon>
<SupportedOSPlatformVersion>10.0.20348.0</SupportedOSPlatformVersion>
<Copyright>2020-2022 Maassoft</Copyright>
<Copyright>2020-2023 Maassoft</Copyright>
<Authors>Maassoft</Authors>
<ManifestCertificateThumbprint>CF0BC153EA664CD97AC6F234B91F45D34630958F</ManifestCertificateThumbprint>
<ManifestKeyFile>ColorControl_1_TemporaryKey.pfx</ManifestKeyFile>
+12 -8
View File
@@ -12,26 +12,30 @@ namespace ColorControl.Common
var processesByName = processes == null ? Process.GetProcessesByName(processName) : processes.Where(p => p.ProcessName.Equals(processName, StringComparison.OrdinalIgnoreCase)).ToArray();
string processIndexedName = null;
for (var index = 0; index < processesByName.Length; index++)
try
{
processIndexedName = index == 0 ? processName : processName + "#" + index;
var processId = new PerformanceCounter("Process", "ID Process", processIndexedName);
if ((int)processId.NextValue() == pid)
for (var index = 0; index < processesByName.Length; index++)
{
return processIndexedName;
processIndexedName = index == 0 ? processName : processName + "#" + index;
var processId = new PerformanceCounter("Process", "ID Process", processIndexedName);
if ((int)processId.NextValue() == pid)
{
return processIndexedName;
}
}
}
catch (Exception) { }
return processIndexedName;
}
private static Process FindPidFromIndexedProcessName(string indexedProcessName, IEnumerable<Process> processes = null)
{
var parentId = new PerformanceCounter("Process", "Creating Process ID", indexedProcessName);
var parentProcessId = (int)parentId.NextValue();
try
{
var parentId = new PerformanceCounter("Process", "Creating Process ID", indexedProcessName);
var parentProcessId = (int)parentId.NextValue();
return processes == null ? Process.GetProcessById(parentProcessId) : processes.FirstOrDefault(p => p.Id == parentProcessId);
}
catch (Exception)
+1 -1
View File
@@ -281,7 +281,7 @@ The best and suggested method to provide this is via a Windows Service. Only whe
if (ElevatedProcessWindowHandle != IntPtr.Zero)
{
Thread.Sleep(100);
Thread.Sleep(500);
break;
}
+1 -1
View File
@@ -77,7 +77,7 @@ namespace ColorControl.Common
Logger.Debug($"Broadcast WOL in network: {ni.Name} ({ni.Description}), local address: {uip.Address}, destination IP-address: {ipAddressString ?? "broadcast"}");
if (ipAddress != null)
if (ipAddress != null && Utils.IsAdministrator())
{
var localEP = new IPEndPoint(uip.Address, 0);
+13
View File
@@ -281,6 +281,8 @@ namespace ColorControl.Forms
if (!presets.Any(x => x.id == preset.id))
{
presets.Add(preset);
listView.SelectedIndices.Clear();
listView.SelectedIndices.Add(item.Index);
}
}
else
@@ -472,6 +474,17 @@ namespace ColorControl.Forms
}
}
public static string ExtendedDisplayName(string displayName)
{
var name = displayName;
var screen = Screen.AllScreens.FirstOrDefault(x => x.DeviceName.Equals(name));
if (screen != null)
{
name += " (" + screen.DeviceFriendlyName() + ")";
}
return name;
}
}
public class EnumComboBoxItem
+38 -7
View File
@@ -204,6 +204,8 @@
this.lvGamePresets = new System.Windows.Forms.ListView();
this.tabOptions = new System.Windows.Forms.TabPage();
this.grpNvidiaOptions = new System.Windows.Forms.GroupBox();
this.lblDitheringDisplay = new System.Windows.Forms.Label();
this.cbxDitheringDisplay = new System.Windows.Forms.ComboBox();
this.lblDitheringMode = new System.Windows.Forms.Label();
this.cbxDitheringMode = new System.Windows.Forms.ComboBox();
this.lblDitheringBitDepth = new System.Windows.Forms.Label();
@@ -260,6 +262,7 @@
this.miNvProfileInspector = new System.Windows.Forms.ToolStripMenuItem();
this.miNvSettings = new System.Windows.Forms.ToolStripMenuItem();
this.btnUpdate = new System.Windows.Forms.Button();
this.lvNvPresetsToolTip = new System.Windows.Forms.ToolTip(this.components);
this.tcMain.SuspendLayout();
this.tabNVIDIA.SuspendLayout();
this.mnuNvPresets.SuspendLayout();
@@ -780,6 +783,8 @@
this.lvNvPresets.ItemChecked += new System.Windows.Forms.ItemCheckedEventHandler(this.lvNvPresets_ItemChecked);
this.lvNvPresets.SelectedIndexChanged += new System.EventHandler(this.lvNvPresets_SelectedIndexChanged);
this.lvNvPresets.DoubleClick += new System.EventHandler(this.btnApply_Click);
this.lvNvPresets.MouseLeave += new System.EventHandler(this.lvNvPresets_MouseLeave);
this.lvNvPresets.MouseMove += new System.Windows.Forms.MouseEventHandler(this.lvNvPresets_MouseMove);
//
// tabAMD
//
@@ -2241,6 +2246,8 @@
this.grpNvidiaOptions.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.grpNvidiaOptions.Controls.Add(this.lblDitheringDisplay);
this.grpNvidiaOptions.Controls.Add(this.cbxDitheringDisplay);
this.grpNvidiaOptions.Controls.Add(this.lblDitheringMode);
this.grpNvidiaOptions.Controls.Add(this.cbxDitheringMode);
this.grpNvidiaOptions.Controls.Add(this.lblDitheringBitDepth);
@@ -2256,10 +2263,31 @@
this.grpNvidiaOptions.TabStop = false;
this.grpNvidiaOptions.Text = "NVIDIA options - test dithering";
//
// lblDitheringDisplay
//
this.lblDitheringDisplay.AutoSize = true;
this.lblDitheringDisplay.Location = new System.Drawing.Point(7, 23);
this.lblDitheringDisplay.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.lblDitheringDisplay.Name = "lblDitheringDisplay";
this.lblDitheringDisplay.Size = new System.Drawing.Size(48, 15);
this.lblDitheringDisplay.TabIndex = 9;
this.lblDitheringDisplay.Text = "Display:";
//
// cbxDitheringDisplay
//
this.cbxDitheringDisplay.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbxDitheringDisplay.FormattingEnabled = true;
this.cbxDitheringDisplay.Location = new System.Drawing.Point(75, 17);
this.cbxDitheringDisplay.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.cbxDitheringDisplay.Name = "cbxDitheringDisplay";
this.cbxDitheringDisplay.Size = new System.Drawing.Size(212, 23);
this.cbxDitheringDisplay.TabIndex = 8;
this.cbxDitheringDisplay.SelectedIndexChanged += new System.EventHandler(this.cbxDitheringDisplay_SelectedIndexChanged);
//
// lblDitheringMode
//
this.lblDitheringMode.AutoSize = true;
this.lblDitheringMode.Location = new System.Drawing.Point(7, 81);
this.lblDitheringMode.Location = new System.Drawing.Point(7, 105);
this.lblDitheringMode.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.lblDitheringMode.Name = "lblDitheringMode";
this.lblDitheringMode.Size = new System.Drawing.Size(41, 15);
@@ -2270,7 +2298,7 @@
//
this.cbxDitheringMode.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbxDitheringMode.FormattingEnabled = true;
this.cbxDitheringMode.Location = new System.Drawing.Point(75, 75);
this.cbxDitheringMode.Location = new System.Drawing.Point(75, 99);
this.cbxDitheringMode.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.cbxDitheringMode.Name = "cbxDitheringMode";
this.cbxDitheringMode.Size = new System.Drawing.Size(136, 23);
@@ -2280,7 +2308,7 @@
// lblDitheringBitDepth
//
this.lblDitheringBitDepth.AutoSize = true;
this.lblDitheringBitDepth.Location = new System.Drawing.Point(7, 50);
this.lblDitheringBitDepth.Location = new System.Drawing.Point(7, 74);
this.lblDitheringBitDepth.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.lblDitheringBitDepth.Name = "lblDitheringBitDepth";
this.lblDitheringBitDepth.Size = new System.Drawing.Size(60, 15);
@@ -2291,7 +2319,7 @@
//
this.cbxDitheringBitDepth.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbxDitheringBitDepth.FormattingEnabled = true;
this.cbxDitheringBitDepth.Location = new System.Drawing.Point(75, 44);
this.cbxDitheringBitDepth.Location = new System.Drawing.Point(75, 68);
this.cbxDitheringBitDepth.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.cbxDitheringBitDepth.Name = "cbxDitheringBitDepth";
this.cbxDitheringBitDepth.Size = new System.Drawing.Size(136, 23);
@@ -2303,7 +2331,7 @@
this.chkDitheringEnabled.AutoSize = true;
this.chkDitheringEnabled.Checked = true;
this.chkDitheringEnabled.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkDitheringEnabled.Location = new System.Drawing.Point(7, 22);
this.chkDitheringEnabled.Location = new System.Drawing.Point(7, 46);
this.chkDitheringEnabled.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.chkDitheringEnabled.Name = "chkDitheringEnabled";
this.chkDitheringEnabled.Size = new System.Drawing.Size(120, 19);
@@ -2319,10 +2347,10 @@
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.pbGradient.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.pbGradient.Location = new System.Drawing.Point(7, 106);
this.pbGradient.Location = new System.Drawing.Point(7, 128);
this.pbGradient.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.pbGradient.Name = "pbGradient";
this.pbGradient.Size = new System.Drawing.Size(555, 250);
this.pbGradient.Size = new System.Drawing.Size(555, 228);
this.pbGradient.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pbGradient.TabIndex = 0;
this.pbGradient.TabStop = false;
@@ -3244,6 +3272,9 @@
private System.Windows.Forms.CheckBox chkAutoInstallUpdates;
private System.Windows.Forms.CheckBox chkLgSetSelectedDeviceByPowerOn;
private System.Windows.Forms.Button btnUpdate;
private System.Windows.Forms.Label lblDitheringDisplay;
private System.Windows.Forms.ComboBox cbxDitheringDisplay;
private System.Windows.Forms.ToolTip lvNvPresetsToolTip;
}
}
+126 -14
View File
@@ -117,6 +117,7 @@ namespace ColorControl
new ToolStripSeparator(),
new ToolStripMenuItem("Open", null, OpenForm),
new ToolStripSeparator(),
new ToolStripMenuItem("Restart", null, Restart),
new ToolStripMenuItem("Exit", null, Exit)
});
@@ -315,7 +316,7 @@ namespace ColorControl
// _keyboardHookManager = new KeyboardHookManager();
// _keyboardHookManager.Start();
//}
//_keyboardHookManager.RegisterHotkey(NonInvasiveKeyboardHookLibrary.ModifierKeys.Control | NonInvasiveKeyboardHookLibrary.ModifierKeys.Alt, 0x47, new Action(Invoke));
//_keyboardHookManager.RegisterHotkey(NonInvasiveKeyboardHookLibrary.ModifierKeys.Control | NonInvasiveKeyboardHookLibrary.ModifierKeys.Alt, (int)Keys.F9, new Action(TestKey));
edtLgGameBarShortcut.Text = _lgService.Config.GameBarShortcut;
}
@@ -326,6 +327,16 @@ namespace ColorControl
}
}
private void TestKey()
{
BeginInvoke(async () =>
{
var preset = _lgService.GetPresets().FirstOrDefault(p => p.name == "Backlight 20");
await _lgService.ApplyPreset(preset);
});
}
private void _lgService_SelectedDeviceChangedEvent(object sender, EventArgs e)
{
BeginInvoke(() => SetLgDevicesSelectedIndex(sender));
@@ -437,6 +448,11 @@ namespace ColorControl
Close();
}
void Restart(object sender, EventArgs e)
{
Program.Restart();
}
private void trayIcon_MouseDoubleClick(object sender, MouseEventArgs e)
{
Show();
@@ -970,6 +986,11 @@ namespace ColorControl
if (_config.ElevationMethodAsked)
{
if (Debugger.IsAttached)
{
return;
}
if (_config.ElevationMethod == ElevationMethod.UseService && !Utils.IsServiceInstalled() &&
(MessageForms.QuestionYesNo("The elevation method is set to Windows Service but it is not installed. Do you want to install it now?") == DialogResult.Yes))
{
@@ -1151,12 +1172,7 @@ NOTE: installing the service may cause a User Account Control popup.");
for (var i = 0; i < displays.Length; i++)
{
var display = displays[i];
var name = display.Name;
var screen = Screen.AllScreens.FirstOrDefault(x => x.DeviceName.Equals(name));
if (screen != null)
{
name += " (" + screen.DeviceFriendlyName() + ")";
}
var name = FormUtils.ExtendedDisplayName(display.Name);
var item = mnuNvDisplay.DropDownItems.Add(name);
item.Tag = display;
@@ -1791,6 +1807,18 @@ NOTE: installing the service may cause a User Account Control popup.");
FillGradient();
}
if (cbxDitheringDisplay.Items.Count == 0)
{
var displays = _nvService.GetDisplayInfos();
var primaryDisplay = _nvService.GetPrimaryDisplay();
var primaryDisplayInfo = displays.FirstOrDefault(d => d.Display == primaryDisplay);
var index = primaryDisplayInfo != null ? displays.IndexOf(primaryDisplayInfo) : 0;
cbxDitheringDisplay.Items.AddRange(displays.ToArray());
cbxDitheringDisplay.SelectedIndex = index;
}
UpdateDitherSettings();
}
@@ -1816,7 +1844,8 @@ NOTE: installing the service may cause a User Account Control popup.");
private void UpdateDitherSettings()
{
var ditherInfo = _nvService.GetDithering();
var display = ((NvDisplayInfo)cbxDitheringDisplay.SelectedItem)?.Display;
var ditherInfo = _nvService.GetDithering(display);
if (ditherInfo.state == -1)
{
@@ -2590,8 +2619,9 @@ Do you want to continue?";
var state = chkDitheringEnabled.CheckState switch { CheckState.Checked => NvDitherState.Enabled, CheckState.Unchecked => NvDitherState.Disabled, _ => NvDitherState.Auto };
var bitDepth = cbxDitheringBitDepth.SelectedIndex;
var mode = cbxDitheringMode.SelectedIndex;
var display = ((NvDisplayInfo)cbxDitheringDisplay.SelectedItem)?.Display;
if (_nvService.SetDithering(state, (uint)bitDepth, (uint)(mode > -1 ? mode : (int)NvDitherMode.Temporal)) && state == NvDitherState.Auto)
if (_nvService.SetDithering(state, (uint)bitDepth, (uint)(mode > -1 ? mode : (int)NvDitherMode.Temporal), currentDisplay: display) && state == NvDitherState.Auto)
{
UpdateDitherSettings();
}
@@ -2629,10 +2659,6 @@ Do you want to continue?";
AddOrUpdateItem();
}
private void btnLGRemoteControl_Click(object sender, EventArgs e)
{
}
private void AfterInitialized()
{
ApplyNvPresetOnStartup();
@@ -3442,7 +3468,16 @@ Do you want to continue?"
return;
}
_lgService.SelectedDevice?.ExecuteAction(action, new[] { value });
try
{
_lgService.SelectedDevice?.ExecuteAction(action, new[] { value });
}
catch (InvalidOperationException ex)
{
Logger.Error(ex);
MessageForms.ErrorOk("Error exectuting action: " + ex.Message);
}
}
private void ApplyLgExpertValueRange(LgDevice.InvokableAction action)
@@ -4501,5 +4536,82 @@ Currently ColorControl is {(Utils.IsAdministrator() ? "" : "not ")}running as ad
Program.Restart();
}
internal void CloseForRestart()
{
Hide();
_trayIcon.Visible = false;
}
private void cbxDitheringDisplay_SelectedIndexChanged(object sender, EventArgs e)
{
if (!_initialized)
{
return;
}
UpdateDitherSettings();
}
private ListViewItem _lastItem;
private int _lastSubItemIndex;
private void lvNvPresets_MouseMove(object sender, MouseEventArgs e)
{
var item = lvNvPresets.GetItemAt(e.X, e.Y);
var subItem = item?.GetSubItemAt(e.X, e.Y);
if (item == null || subItem == null || subItem?.Text?.Length < 20)
{
lvNvPresetsToolTip.Active = false;
_lastItem = null;
return;
}
var index = item.SubItems.IndexOf(subItem);
lvNvPresets.ShowItemToolTips = false;
if (item == _lastItem && index == _lastSubItemIndex)
{
return;
}
_lastItem = item;
_lastSubItemIndex = index;
var text = subItem.Text;
if (index == 7)
{
text = text.Replace(", ", "\r\n");
}
var point = lvNvPresets.PointToClient(Cursor.Position);
point.X += 10;
point.Y += 0;
if (index >= 0)
{
if (lvNvPresetsToolTip.Active)
{
lvNvPresetsToolTip.Active = false;
}
lvNvPresetsToolTip.Active = true;
lvNvPresetsToolTip.Show("", lvNvPresets, point);
lvNvPresetsToolTip.Show(text, lvNvPresets, point);
}
else
{
lvNvPresetsToolTip.Active = false;
}
}
private void lvNvPresets_MouseLeave(object sender, EventArgs e)
{
lvNvPresetsToolTip.Active = false;
}
}
}
+3
View File
@@ -81,6 +81,9 @@
<metadata name="mnuNvSettings.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>15, 47</value>
</metadata>
<metadata name="lvNvPresetsToolTip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>590, 47</value>
</metadata>
<assembly alias="System.Drawing" name="System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<data name="$this.Icon" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
@@ -3,7 +3,6 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
namespace NonInvasiveKeyboardHookLibrary
{
@@ -182,7 +181,7 @@ namespace NonInvasiveKeyboardHookLibrary
if (keybindToRemove == null || !this._registeredCallbacks.Remove(keybindToRemove))
{
throw new HotkeyNotRegisteredException();
}
}
}
#endregion
@@ -220,7 +219,7 @@ namespace NonInvasiveKeyboardHookLibrary
return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
userLibrary, 0);
}
private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0)
@@ -229,8 +228,12 @@ namespace NonInvasiveKeyboardHookLibrary
// Debug.WriteLine("Starting");
// To prevent slowing keyboard input down, we use handle keyboard inputs in a separate thread
ThreadPool.QueueUserWorkItem(this.HandleSingleKeyboardInput, new KeyboardParams(wParam, vkCode));
//ThreadPool.QueueUserWorkItem(this.HandleSingleKeyboardInput, new KeyboardParams(wParam, vkCode));
// Debug.WriteLine("Ending");
HandleSingleKeyboardInput(new KeyboardParams(wParam, vkCode));
//return IntPtr.Zero;
}
return CallNextHookEx(_hookId, nCode, wParam, lParam);
@@ -248,6 +251,8 @@ namespace NonInvasiveKeyboardHookLibrary
var modifierKey = ModifierKeysUtilities.GetModifierKeyFromCode(vkCode);
Debug.WriteLine("Modifiers: " + string.Join("+", _downModifierKeys) + ", ModKey: " + modifierKey + ", Key: " + vkCode);
// If the keyboard event is a KeyDown event (i.e. key pressed)
if (wParam == (IntPtr)WM_KEYDOWN || wParam == (IntPtr)WM_SYSKEYDOWN)
{
@@ -298,7 +303,7 @@ namespace NonInvasiveKeyboardHookLibrary
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
IntPtr wParam, IntPtr lParam);
/// <summary>
/// Loads the library.
/// </summary>
+15 -15
View File
@@ -34,6 +34,7 @@ namespace ColorControl
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private static Mutex _mutex;
private static MainForm _mainForm;
/// <summary>
/// The main entry point for the application.
@@ -45,12 +46,12 @@ namespace ColorControl
//Utils.UpdateFiles(@"H:\temp\ColorControl\ColorControl", @"C:\Users\vinni\source\repos\ColorControl\ColorControl\bin\Debug\net6.0-windows10.0.20348.0");
var runAsService = args.Contains("--service") || Process.GetCurrentProcess().Parent()?.ProcessName?.Equals("services", StringComparison.InvariantCultureIgnoreCase) == true;
var runAsService = args.Contains("--service") || Utils.IsAdministrator() && Process.GetCurrentProcess().Parent()?.ProcessName?.Equals("services", StringComparison.InvariantCultureIgnoreCase) == true;
InitLogger(runAsService);
Logger.Debug($"Using data path: {DataDir}");
Logger.Debug("Parent process: " + Process.GetCurrentProcess().Parent()?.ProcessName);
//Logger.Debug("Parent process: " + Process.GetCurrentProcess().Parent()?.ProcessName);
if (runAsService)
{
@@ -111,19 +112,20 @@ namespace ColorControl
_mutex.WaitOne();
try
{
if (Debugger.IsAttached)
{
Utils.StartService();
}
//if (Debugger.IsAttached)
//{
// Utils.StartService();
//}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm(AppContext));
_mainForm = new MainForm(AppContext);
Application.Run(_mainForm);
if (Debugger.IsAttached && !IsRestarting)
{
Utils.StopService();
}
//if (Debugger.IsAttached && !IsRestarting)
//{
// Utils.StopService();
//}
}
catch (Exception ex)
{
@@ -144,14 +146,12 @@ namespace ColorControl
{
IsRestarting = true;
_mainForm?.CloseForRestart();
_mutex?.Close();
_mutex = null;
Thread.Sleep(1000);
Application.Restart();
Thread.Sleep(1000);
Environment.Exit(0);
}
+20 -20
View File
@@ -24,9 +24,9 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using ADL_CONTEXT_HANDLE = System.IntPtr;
using FARPROC = System.IntPtr;
using HMODULE = System.IntPtr;
using ADL_CONTEXT_HANDLE = System.IntPtr;
#endregion Using
@@ -90,7 +90,7 @@ namespace ATI.ADL
}
#endregion ADLAdapterInfo
#region ADLDisplayInfo
/// <summary> ADLDisplayID Structure</summary>
[StructLayout(LayoutKind.Sequential)]
@@ -188,20 +188,20 @@ namespace ATI.ADL
/// <summary> ADL Function to get the number of adapters</summary>
/// <param name="numAdapters">return number of adapters</param>
/// <returns> retrun ADL Error Code</returns>
internal delegate int ADL_Adapter_NumberOfAdapters_Get(ref int numAdapters);
internal delegate int ADL2_Adapter_NumberOfAdapters_Get(ADL_CONTEXT_HANDLE context, ref int numAdapters);
/// <summary> ADL Function to get the GPU adapter information</summary>
/// <param name="info">return GPU adapter information</param>
/// <param name="inputSize">the size of the GPU adapter struct</param>
/// <returns> retrun ADL Error Code</returns>
internal delegate int ADL_Adapter_AdapterInfo_Get(IntPtr info, int inputSize);
internal delegate int ADL2_Adapter_AdapterInfo_Get(ADL_CONTEXT_HANDLE context, IntPtr info, int inputSize);
/// <summary> Function to determine if the adapter is active or not.</summary>
/// <remarks>The function is used to check if the adapter associated with iAdapterIndex is active</remarks>
/// <param name="adapterIndex"> Adapter Index.</param>
/// <param name="status"> Status of the adapter. True: Active; False: Dsiabled</param>
/// <returns>Non zero is successfull</returns>
internal delegate int ADL_Adapter_Active_Get(int adapterIndex, ref int status);
internal delegate int ADL2_Adapter_Active_Get(ADL_CONTEXT_HANDLE context, int adapterIndex, ref int status);
/// <summary>Get display information based on adapter index</summary>
/// <param name="adapterIndex">Adapter Index</param>
@@ -209,18 +209,18 @@ namespace ATI.ADL
/// <param name="displayInfoArray">return ADLDisplayInfo Array for supported displays' information</param>
/// <param name="forceDetect">force detect or not</param>
/// <returns>return ADL Error Code</returns>
internal delegate int ADL_Display_DisplayInfo_Get(int adapterIndex, ref int numDisplays, out IntPtr displayInfoArray, int forceDetect);
internal delegate int ADL2_Display_DisplayInfo_Get(ADL_CONTEXT_HANDLE context, int adapterIndex, ref int numDisplays, out IntPtr displayInfoArray, int forceDetect);
internal delegate int ADL_Display_Size_Get(int adapterIndex, int displayIndex, ref int lpWidth, ref int lpHeight, ref int lpDefaultWidth, ref int lpDefaultHeight, ref int lpMinWidth, ref int lpMinHeight, ref int lpMaxWidth, ref int lpMaxHeight, ref int lpStepWidth, ref int lpStepHeight);
internal delegate int ADL2_Display_Size_Get(ADL_CONTEXT_HANDLE context, int adapterIndex, int displayIndex, ref int lpWidth, ref int lpHeight, ref int lpDefaultWidth, ref int lpDefaultHeight, ref int lpMinWidth, ref int lpMinHeight, ref int lpMaxWidth, ref int lpMaxHeight, ref int lpStepWidth, ref int lpStepHeight);
internal delegate int ADL_Display_PixelFormat_Get(int adapterIndex, int displayIndex, ref int pixelFormat);
internal delegate int ADL_Display_PixelFormat_Set(int adapterIndex, int displayIndex, int pixelFormat);
internal delegate int ADL2_Display_PixelFormat_Get(ADL_CONTEXT_HANDLE context, int adapterIndex, int displayIndex, ref int pixelFormat);
internal delegate int ADL2_Display_PixelFormat_Set(ADL_CONTEXT_HANDLE context, int adapterIndex, int displayIndex, int pixelFormat);
internal delegate int ADL_Display_ColorDepth_Get(int adapterIndex, int displayIndex, ref int colorDepth);
internal delegate int ADL_Display_ColorDepth_Set(int adapterIndex, int displayIndex, int colorDepth);
internal delegate int ADL2_Display_ColorDepth_Get(ADL_CONTEXT_HANDLE context, int adapterIndex, int displayIndex, ref int colorDepth);
internal delegate int ADL2_Display_ColorDepth_Set(ADL_CONTEXT_HANDLE context, int adapterIndex, int displayIndex, int colorDepth);
internal delegate int ADL_Display_DitherState_Get(int adapterIndex, int displayIndex, ref int ditherState);
internal delegate int ADL_Display_DitherState_Set(int adapterIndex, int displayIndex, int ditherState);
internal delegate int ADL2_Display_DitherState_Get(ADL_CONTEXT_HANDLE context, int adapterIndex, int displayIndex, ref int ditherState);
internal delegate int ADL2_Display_DitherState_Set(ADL_CONTEXT_HANDLE context, int adapterIndex, int displayIndex, int ditherState);
internal delegate int ADL2_Display_HDRState_Get(ADL_CONTEXT_HANDLE context, int adapterIndex, ADLDisplayID displayID, ref int support, ref int enable);
internal delegate int ADL2_Display_HDRState_Set(ADL_CONTEXT_HANDLE context, int adapterIndex, ADLDisplayID displayID, int enable);
@@ -240,7 +240,7 @@ namespace ATI.ADL
#region DLLImport
[DllImport(Kernel32_FileName)]
internal static extern HMODULE GetModuleHandle (string moduleName);
internal static extern HMODULE GetModuleHandle(string moduleName);
[DllImport(Atiadlxx_FileName)]
internal static extern int ADL_Main_Control_IsFunctionValid(HMODULE module, string procName);
@@ -267,7 +267,7 @@ namespace ATI.ADL
#region Constructor
/// <summary> Constructor</summary>
private ADLCheckLibrary ()
private ADLCheckLibrary()
{
try
{
@@ -284,7 +284,7 @@ namespace ATI.ADL
#region Destructor
/// <summary> Destructor to force calling ADL Destroy function before free up the ADL library</summary>
~ADLCheckLibrary ()
~ADLCheckLibrary()
{
if (IntPtr.Zero != ADLCheckLibrary_.ADLLibrary)
{
@@ -301,7 +301,7 @@ namespace ATI.ADL
/// <summary> Check the import function to see it exists or not</summary>
/// <param name="functionName"> function name</param>
/// <returns>return true, if function exists</returns>
internal static bool IsFunctionValid (string functionName)
internal static bool IsFunctionValid(string functionName)
{
var result = false;
if (IntPtr.Zero != ADLCheckLibrary_.ADLLibrary)
@@ -319,7 +319,7 @@ namespace ATI.ADL
/// <summary> Get the unmanaged function pointer </summary>
/// <param name="functionName"> function name</param>
/// <returns>return function pointer, if function exists</returns>
internal static FARPROC GetProcAddress (string functionName)
internal static FARPROC GetProcAddress(string functionName)
{
var result = IntPtr.Zero;
if (IntPtr.Zero != ADLCheckLibrary_.ADLLibrary)
@@ -340,7 +340,7 @@ namespace ATI.ADL
/// <summary> Build in memory allocation function</summary>
/// <param name="size">input size</param>
/// <returns>return the memory buffer</returns>
private static IntPtr ADL_Main_Memory_Alloc_ (int size)
private static IntPtr ADL_Main_Memory_Alloc_(int size)
{
IntPtr result = Marshal.AllocCoTaskMem(size);
return result;
@@ -350,7 +350,7 @@ namespace ATI.ADL
#region ADL_Main_Memory_Free
/// <summary> Build in memory free function</summary>
/// <param name="buffer">input buffer</param>
internal static void ADL_Main_Memory_Free (IntPtr buffer)
internal static void ADL_Main_Memory_Free(IntPtr buffer)
{
if (IntPtr.Zero != buffer)
{
+37 -33
View File
@@ -1,6 +1,7 @@
using ATI.ADL;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
@@ -10,6 +11,7 @@ namespace ColorControl.Services.AMD
{
enum ADLPixelFormat
{
[Description("Unknown/unsupported")]
UNKNOWN = 0,
RGB_FULL_RANGE = 1,
YCRCB444 = 2,
@@ -20,6 +22,7 @@ namespace ColorControl.Services.AMD
enum ADLColorDepth
{
[Description("Unknown/unsupported")]
UNKNOWN = 0,
BPC6 = 1,
BPC8 = 2,
@@ -46,7 +49,7 @@ namespace ColorControl.Services.AMD
TRUN8 = 12,
TRUN10 = 13,
TRUN8_DITH8 = 14,
TRUN10_DUTH6 = 15,
TRUN10_DITH6 = 15,
TRUN10_FM8 = 16,
TRUN10_FM6 = 17,
TRUN10_DITH8_FM6 = 18,
@@ -61,7 +64,7 @@ namespace ColorControl.Services.AMD
{
private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
private static ADL_CONTEXT_HANDLE context = IntPtr.Zero;
public static bool Initialize()
{
int ADLRet = -1;
@@ -116,11 +119,11 @@ namespace ColorControl.Services.AMD
int ADLRet = -1;
int NumberOfAdapters = 0;
var delNumberOfAdapters = ADL.GetDelegate<ADL.ADL_Adapter_NumberOfAdapters_Get>();
var delNumberOfAdapters = ADL.GetDelegate<ADL.ADL2_Adapter_NumberOfAdapters_Get>();
if (null != delNumberOfAdapters)
{
delNumberOfAdapters(ref NumberOfAdapters);
delNumberOfAdapters(context, ref NumberOfAdapters);
}
Logger.Debug("Number Of Adapters: " + NumberOfAdapters.ToString() + "\n");
@@ -130,7 +133,7 @@ namespace ColorControl.Services.AMD
ADLAdapterInfoArray OSAdapterInfoData;
OSAdapterInfoData = new ADLAdapterInfoArray();
var delAdapterInfo = ADL.GetDelegate<ADL.ADL_Adapter_AdapterInfo_Get>();
var delAdapterInfo = ADL.GetDelegate<ADL.ADL2_Adapter_AdapterInfo_Get>();
if (null != delAdapterInfo)
{
@@ -139,19 +142,19 @@ namespace ColorControl.Services.AMD
AdapterBuffer = Marshal.AllocCoTaskMem((int)size);
Marshal.StructureToPtr(OSAdapterInfoData, AdapterBuffer, false);
ADLRet = delAdapterInfo(AdapterBuffer, size);
ADLRet = delAdapterInfo(context, AdapterBuffer, size);
if (ADL.ADL_SUCCESS == ADLRet)
{
OSAdapterInfoData = (ADLAdapterInfoArray)Marshal.PtrToStructure(AdapterBuffer, OSAdapterInfoData.GetType());
int IsActive = 0;
var delActive = ADL.GetDelegate<ADL.ADL_Adapter_Active_Get>();
var delActive = ADL.GetDelegate<ADL.ADL2_Adapter_Active_Get>();
for (int i = 0; i < NumberOfAdapters; i++)
{
// Check if the adapter is active
if (null != delActive)
ADLRet = delActive(OSAdapterInfoData.ADLAdapterInfo[i].AdapterIndex, ref IsActive);
ADLRet = delActive(context, OSAdapterInfoData.ADLAdapterInfo[i].AdapterIndex, ref IsActive);
if (ADL.ADL_SUCCESS == ADLRet)
{
@@ -190,7 +193,7 @@ namespace ColorControl.Services.AMD
ADLDisplayInfo oneDisplayInfo = new ADLDisplayInfo();
var del = ADL.GetDelegate<ADL.ADL_Display_DisplayInfo_Get>();
var del = ADL.GetDelegate<ADL.ADL2_Display_DisplayInfo_Get>();
if (null != del)
{
@@ -198,13 +201,14 @@ namespace ColorControl.Services.AMD
int j = 0;
// Force the display detection and get the Display Info. Use 0 as last parameter to NOT force detection
ADLRet = del(primaryAdapter.AdapterIndex, ref NumberOfDisplays, out DisplayBuffer, 1);
ADLRet = del(context, primaryAdapter.AdapterIndex, ref NumberOfDisplays, out DisplayBuffer, 1);
if (ADL.ADL_SUCCESS == ADLRet)
{
for (j = 0; j < NumberOfDisplays; j++)
{
oneDisplayInfo = (ADLDisplayInfo)Marshal.PtrToStructure(new IntPtr(DisplayBuffer.ToInt64() + j * Marshal.SizeOf(oneDisplayInfo)), oneDisplayInfo.GetType());
if (!connected || (1 == (oneDisplayInfo.DisplayInfoValue & 1))) {
if (!connected || (1 == (oneDisplayInfo.DisplayInfoValue & 1)))
{
DisplayInfoData.Add(oneDisplayInfo);
}
}
@@ -261,105 +265,105 @@ namespace ColorControl.Services.AMD
horizontal = bounds.Width;
vertical = bounds.Height;
Logger.Debug($"GetDisplayResolution: {horizontal}x{vertical}");
//var del = ADL.GetDelegate<ADL.ADL_Display_Size_Get>();
//var del = ADL.GetDelegate<ADL.ADL2_Display_Size_Get>();
//if (display.DisplayID.DisplayPhysicalIndex >= 0 && del != null)
//{
// int lpDefaultWidth, lpDefaultHeight, lpMinWidth, lpMinHeight, lpMaxWidth, lpMaxHeight, lpStepWidth, lpStepHeight;
// lpDefaultWidth = lpDefaultHeight = lpMinWidth = lpMinHeight = lpMaxWidth = lpMaxHeight = lpStepWidth = lpStepHeight = 0;
// var ADLRet = del(display.DisplayID.DisplayLogicalAdapterIndex, display.DisplayID.DisplayLogicalIndex, ref horizontal, ref vertical, ref lpDefaultWidth, ref lpDefaultHeight, ref lpMinWidth, ref lpMinHeight, ref lpMaxWidth, ref lpMaxHeight, ref lpStepWidth, ref lpStepHeight);
// var ADLRet = del(context, display.DisplayID.DisplayLogicalAdapterIndex, display.DisplayID.DisplayLogicalIndex, ref horizontal, ref vertical, ref lpDefaultWidth, ref lpDefaultHeight, ref lpMinWidth, ref lpMinHeight, ref lpMaxWidth, ref lpMaxHeight, ref lpStepWidth, ref lpStepHeight);
// return CheckError(ADLRet, nameof(ADL.ADL_Display_Size_Get));
// return CheckError(ADLRet, nameof(ADL.ADL2_Display_Size_Get));
//}
return true;
}
public static bool GetDisplayPixelFormat(ADLDisplayInfo display, ref ADLPixelFormat pixelFormat)
{
var del = ADL.GetDelegate<ADL.ADL_Display_PixelFormat_Get>();
var del = ADL.GetDelegate<ADL.ADL2_Display_PixelFormat_Get>();
if (display.DisplayID.DisplayPhysicalIndex >= 0 && del != null)
{
int pixelFormatInt = 0;
var ADLRet = del(display.DisplayID.DisplayLogicalAdapterIndex, display.DisplayID.DisplayLogicalIndex, ref pixelFormatInt);
var ADLRet = del(context, display.DisplayID.DisplayLogicalAdapterIndex, display.DisplayID.DisplayLogicalIndex, ref pixelFormatInt);
pixelFormat = (ADLPixelFormat)pixelFormatInt;
return CheckError(ADLRet, nameof(ADL.ADL_Display_PixelFormat_Get));
return CheckError(ADLRet, nameof(ADL.ADL2_Display_PixelFormat_Get));
}
return false;
}
public static bool SetDisplayPixelFormat(ADLDisplayInfo display, ADLPixelFormat pixelFormat)
{
var del = ADL.GetDelegate<ADL.ADL_Display_PixelFormat_Set>();
var del = ADL.GetDelegate<ADL.ADL2_Display_PixelFormat_Set>();
if (display.DisplayID.DisplayPhysicalIndex >= 0 && del != null)
{
var ADLRet = del(display.DisplayID.DisplayLogicalAdapterIndex, display.DisplayID.DisplayLogicalIndex, (int)pixelFormat);
var ADLRet = del(context, display.DisplayID.DisplayLogicalAdapterIndex, display.DisplayID.DisplayLogicalIndex, (int)pixelFormat);
return CheckError(ADLRet, nameof(ADL.ADL_Display_PixelFormat_Set));
return CheckError(ADLRet, nameof(ADL.ADL2_Display_PixelFormat_Set));
}
return false;
}
public static bool GetDisplayColorDepth(ADLDisplayInfo display, ref ADLColorDepth colorDepth)
{
var del = ADL.GetDelegate<ADL.ADL_Display_ColorDepth_Get>();
var del = ADL.GetDelegate<ADL.ADL2_Display_ColorDepth_Get>();
if (display.DisplayID.DisplayPhysicalIndex >= 0 && del != null)
{
int colorDepthInt = 0;
var ADLRet = del(display.DisplayID.DisplayLogicalAdapterIndex, display.DisplayID.DisplayLogicalIndex, ref colorDepthInt);
var ADLRet = del(context, display.DisplayID.DisplayLogicalAdapterIndex, display.DisplayID.DisplayLogicalIndex, ref colorDepthInt);
colorDepth = (ADLColorDepth)colorDepthInt;
return CheckError(ADLRet, nameof(ADL.ADL_Display_ColorDepth_Get));
return CheckError(ADLRet, nameof(ADL.ADL2_Display_ColorDepth_Get));
}
return false;
}
public static bool SetDisplayColorDepth(ADLDisplayInfo display, ADLColorDepth colorDepth)
{
var del = ADL.GetDelegate<ADL.ADL_Display_ColorDepth_Set>();
var del = ADL.GetDelegate<ADL.ADL2_Display_ColorDepth_Set>();
if (display.DisplayID.DisplayPhysicalIndex >= 0 && del != null)
{
var ADLRet = del(display.DisplayID.DisplayLogicalAdapterIndex, display.DisplayID.DisplayLogicalIndex, (int)colorDepth);
var ADLRet = del(context, display.DisplayID.DisplayLogicalAdapterIndex, display.DisplayID.DisplayLogicalIndex, (int)colorDepth);
return CheckError(ADLRet, nameof(ADL.ADL_Display_ColorDepth_Set));
return CheckError(ADLRet, nameof(ADL.ADL2_Display_ColorDepth_Set));
}
return false;
}
public static bool GetDisplayDitherState(ADLDisplayInfo display, ref ADLDitherState ditherState)
{
var del = ADL.GetDelegate<ADL.ADL_Display_DitherState_Get>();
var del = ADL.GetDelegate<ADL.ADL2_Display_DitherState_Get>();
if (display.DisplayID.DisplayPhysicalIndex >= 0 && del != null)
{
var ditherStateInt = 0;
var ADLRet = del(display.DisplayID.DisplayLogicalAdapterIndex, display.DisplayID.DisplayLogicalIndex, ref ditherStateInt);
var ADLRet = del(context, display.DisplayID.DisplayLogicalAdapterIndex, display.DisplayID.DisplayLogicalIndex, ref ditherStateInt);
ditherState = (ADLDitherState)ditherStateInt;
return CheckError(ADLRet, nameof(ADL.ADL_Display_DitherState_Get));
return CheckError(ADLRet, nameof(ADL.ADL2_Display_DitherState_Get));
}
return false;
}
public static bool SetDisplayDitherState(ADLDisplayInfo display, ADLDitherState ditherState)
{
var del = ADL.GetDelegate<ADL.ADL_Display_DitherState_Set>();
var del = ADL.GetDelegate<ADL.ADL2_Display_DitherState_Set>();
if (display.DisplayID.DisplayPhysicalIndex >= 0 && del != null)
{
var ADLRet = del(display.DisplayID.DisplayLogicalAdapterIndex, display.DisplayID.DisplayLogicalIndex, (int)ditherState);
var ADLRet = del(context, display.DisplayID.DisplayLogicalAdapterIndex, display.DisplayID.DisplayLogicalIndex, (int)ditherState);
return CheckError(ADLRet, nameof(ADL.ADL_Display_DitherState_Set));
return CheckError(ADLRet, nameof(ADL.ADL2_Display_DitherState_Set));
}
return false;
}
+2 -2
View File
@@ -317,14 +317,14 @@ namespace ColorControl.Services.AMD
var pixelFormat = ADLPixelFormat.UNKNOWN;
ADLWrapper.GetDisplayPixelFormat(display, ref pixelFormat);
var colorSettings = $"{colorDepth}, {pixelFormat}";
var colorSettings = $"{colorDepth.GetDescription()}, {pixelFormat.GetDescription()}";
values.Add(colorSettings);
var refreshRate = GetCurrentRefreshRate(screen?.DeviceName);
values.Add($"{refreshRate}Hz");
var ditherState = GetDithering(display);
values.Add(ditherState.ToString());
values.Add(ditherState.GetDescription());
var hdrEnabled = IsHDREnabled();
values.Add(hdrEnabled ? "Yes" : "No");
+61 -32
View File
@@ -145,7 +145,7 @@ namespace ColorControl.Services.LG
public LgDevice(string name, string ipAddress, string macAddress, bool isCustom = true, bool isDummy = false)
{
PictureSettings = new LgDevicePictureSettings();
ActionsOnGameBar = new List<string> { "backlight", "contrast", "brightness", "color" };
ActionsOnGameBar = new List<string>(DefaultActionsOnGameBar);
Name = name;
IpAddress = ipAddress;
@@ -189,6 +189,7 @@ namespace ColorControl.Services.LG
AddGenericPictureAction("truMotionBlur", minValue: 0, maxValue: 10, title: "TruMotion Blur");
AddGenericPictureAction("motionProOLED", typeof(OffToHigh), title: "OLED Motion Pro", fromModelYear: ModelYear.Series2019);
AddGenericPictureAction("motionPro", typeof(OffToOn), title: "Motion Pro");
AddGenericPictureAction("realCinema", typeof(OffToOn), title: "Real Cinema");
AddGenericPictureAction("uhdDeepColorHDMI1", typeof(OffToOn), category: "other");
AddGenericPictureAction("uhdDeepColorHDMI2", typeof(OffToOn), category: "other");
AddGenericPictureAction("uhdDeepColorHDMI3", typeof(OffToOn), category: "other");
@@ -719,9 +720,29 @@ namespace ColorControl.Services.LG
public async Task<LgWebOsMouseService> GetMouseAsync()
{
await CheckConnectionAsync();
return await _lgTvApi.GetMouse();
}
private async Task CheckConnectionAsync()
{
if (!await Connected())
{
throw new InvalidOperationException("Not connected");
}
}
private void CheckConnection()
{
var task = CheckConnectionAsync();
if (task.Status != TaskStatus.RanToCompletion)
{
throw new InvalidOperationException("Not connected");
}
}
public async Task<IEnumerable<LgApp>> GetApps(bool force = false)
{
if (!force)
@@ -789,15 +810,6 @@ namespace ColorControl.Services.LG
{
try
{
//if (wakeDelay == 0)
//{
// if (await ConnectToSelectedDevice())
// {
// Logger.Debug("Already connected, no wake needed?");
// return;
// };
//}
await Task.Delay(wakeDelay);
var result = Wake();
if (!result)
@@ -878,12 +890,6 @@ namespace ColorControl.Services.LG
return actions.Where(a => ActionsOnGameBar.Contains(a.Name)).ToList();
}
public async Task PowerOn()
{
var mouse = await _lgTvApi.GetMouse();
mouse.SendButton(ButtonType.POWER);
}
public void Test()
{
try
@@ -918,30 +924,40 @@ namespace ColorControl.Services.LG
public bool IsUsingHDRPictureMode()
{
// Temporary workaround because I cannot read the picture mode at this time
return PictureSettings.Backlight == 100 && PictureSettings.Contrast == 100;
return PictureSettings.Contrast == 100;
}
internal async Task SetBacklight(int backlight)
{
await CheckConnectionAsync();
await _lgTvApi.SetSystemSettings("backlight", backlight.ToString());
}
internal async Task SetContrast(int contrast)
{
await CheckConnectionAsync();
await _lgTvApi.SetSystemSettings("contrast", contrast.ToString());
}
public async Task SetOLEDMotionPro(string mode)
{
await CheckConnectionAsync();
await _lgTvApi.SetConfig("tv.model.motionProMode", mode);
}
internal async Task SetConfig(string key, object value)
{
await CheckConnectionAsync();
await _lgTvApi.SetConfig(key, value);
}
internal async Task SetSystemSettings(string name, string value)
{
await CheckConnectionAsync();
await _lgTvApi.SetSystemSettings(name, value);
UpdateCurrentValueOfAction(name, value);
@@ -952,6 +968,8 @@ namespace ColorControl.Services.LG
//var keys = new[] { "backlight", "brightness", "contrast", "color", "pictureMode", "colorGamut", "dynamicContrast", "peakBrightness", "smoothGradation", "energySaving", "motionProOLED" };
//var keys = new[] { "backlight", "brightness", "contrast", "color" };
await CheckConnectionAsync();
return await _lgTvApi.GetSystemSettings2("picture");
}
@@ -962,6 +980,8 @@ namespace ColorControl.Services.LG
private bool TurnScreenOffAction(Dictionary<string, object> parameters)
{
CheckConnection();
var task = _lgTvApi.TurnScreenOff();
Utils.WaitForTask(task);
@@ -970,6 +990,8 @@ namespace ColorControl.Services.LG
private bool TurnScreenOnAction(Dictionary<string, object> parameters)
{
CheckConnection();
var task = _lgTvApi.TurnScreenOn();
Utils.WaitForTask(task);
@@ -978,6 +1000,8 @@ namespace ColorControl.Services.LG
private bool GenericPictureAction(Dictionary<string, object> parameters)
{
CheckConnection();
var settingName = parameters["name"].ToString();
var stringValues = parameters["value"] as string[];
var category = parameters["category"].ToString();
@@ -996,6 +1020,8 @@ namespace ColorControl.Services.LG
private bool GenericDeviceConfigAction(Dictionary<string, object> parameters)
{
CheckConnection();
var id = parameters["name"].ToString().Replace("_icon", string.Empty);
var stringValues = parameters["value"] as string[];
var value = stringValues[0];
@@ -1010,6 +1036,8 @@ namespace ColorControl.Services.LG
private bool GenericSetConfigAction(Dictionary<string, object> parameters)
{
CheckConnection();
var key = parameters["name"].ToString();
var values = parameters["value"] as object[];
var value = values[0];
@@ -1022,25 +1050,26 @@ namespace ColorControl.Services.LG
private void UpdateCurrentValueOfAction(string settingName, string value)
{
if (settingName != "backlight" && settingName != "contrast" && settingName != "brightness" && settingName != "color")
if (settingName == "backlight" || settingName == "contrast" || settingName == "brightness" || settingName == "color")
{
var action = _invokableActions.FirstOrDefault(a => a.Name == settingName);
if (action != null)
return;
}
var action = _invokableActions.FirstOrDefault(a => a.Name == settingName);
if (action != null)
{
if (action.EnumType != null)
{
if (action.EnumType != null)
try
{
try
{
var enumValue = Enum.Parse(action.EnumType, value);
var intEnum = (int)enumValue;
action.CurrentValue = intEnum;
}
catch (Exception) { }
}
else
{
action.CurrentValue = 0;
var enumValue = Enum.Parse(action.EnumType, value);
var intEnum = (int)enumValue;
action.CurrentValue = intEnum;
}
catch (Exception) { }
}
else
{
action.CurrentValue = 0;
}
}
}
+6
View File
@@ -320,6 +320,7 @@ namespace ColorControl.Services.LG
foreach (var device in Devices)
{
device.PowerStateChangedEvent += LgDevice_PowerStateChangedEvent;
device.PictureSettingsChangedEvent += Device_PictureSettingsChangedEvent;
}
if (connect && SelectedDevice != null)
@@ -335,6 +336,11 @@ namespace ColorControl.Services.LG
}
}
private void Device_PictureSettingsChangedEvent(object sender, EventArgs e)
{
//
}
public async Task<bool> ApplyPreset(string presetName)
{
var preset = _presets.FirstOrDefault(p => p.name.Equals(presetName, StringComparison.OrdinalIgnoreCase));
@@ -11,11 +11,19 @@ namespace ColorControl.Services.NVIDIA
public string InfoLine { get; }
public NvDisplayInfo(Display display, List<string> values, string infoLine)
public string Name { get; }
public NvDisplayInfo(Display display, List<string> values, string infoLine, string name)
{
Display = display;
Values = values;
InfoLine = infoLine;
Name = name;
}
public override string ToString()
{
return Name;
}
}
}
+2 -2
View File
@@ -133,7 +133,7 @@ namespace ColorControl.Services.NVIDIA
return values;
}
public string GetDriverSettingsDescription()
public string GetDriverSettingsDescription(bool useNewLines = false)
{
if (driverSettings.Count == 0)
{
@@ -151,7 +151,7 @@ namespace ColorControl.Services.NVIDIA
values.Add($"{settingMeta.SettingName}: {settingValue?.ValueName ?? "Unknown"}");
}
return string.Join(", ", values);
return string.Join(useNewLines ? "\r\n" : ", ", values);
}
public string GetDitheringDescription(string disabledText = "Disabled")
+35 -76
View File
@@ -1,4 +1,5 @@
using ColorControl.Common;
using ColorControl.Forms;
using ColorControl.Services.Common;
using nspector.Common;
using nspector.Common.Meta;
@@ -12,8 +13,6 @@ using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ColorControl.Services.NVIDIA
{
@@ -99,7 +98,13 @@ namespace ColorControl.Services.NVIDIA
public const uint DRS_PRERENDERED_FRAMES = 8102046;
public const uint DRS_FRAME_RATE_LIMITER_V3 = 277041154;
private static readonly List<uint> _driverSettingIds = new() { DRS_GSYNC_APPLICATION_MODE, DRS_VSYNC_CONTROL, DRS_PRERENDERED_FRAMES, DRS_FRAME_RATE_LIMITER_V3 };
public const uint DRS_ANISOTROPIC_FILTERING_SETTING = 0x101E61A9;
public const uint DRS_ANISOTROPIC_FILTER_OPTIMIZATION = 0x0084CD70;
public const uint DRS_ANISOTROPIC_FILTER_SAMPLE_OPTIMIZATION = 0x00E73211;
public const uint DRS_TEXTURE_FILTERING_QUALITY = 0x00CE2691;
public const uint DRS_TEXTURE_FILTERING_NEGATIVE_LOD_BIAS = 0x0019BB68;
private static readonly List<uint> _driverSettingIds = new() { DRS_GSYNC_APPLICATION_MODE, DRS_VSYNC_CONTROL, DRS_PRERENDERED_FRAMES, DRS_FRAME_RATE_LIMITER_V3, DRS_ANISOTROPIC_FILTERING_SETTING, DRS_ANISOTROPIC_FILTER_OPTIMIZATION, DRS_TEXTURE_FILTERING_QUALITY, DRS_TEXTURE_FILTERING_NEGATIVE_LOD_BIAS, DRS_ANISOTROPIC_FILTER_SAMPLE_OPTIMIZATION };
public NvService(string dataPath) : base(dataPath, "NvPresets.json")
{
@@ -192,8 +197,7 @@ namespace ColorControl.Services.NVIDIA
{
if (preset.primaryDisplay)
{
var displayId = DisplayDevice.GetGDIPrimaryDisplayDevice().DisplayId;
_currentDisplay = Display.GetDisplays().FirstOrDefault(x => x.DisplayDevice.DisplayId == displayId);
_currentDisplay = GetPrimaryDisplay();
}
else
{
@@ -201,6 +205,11 @@ namespace ColorControl.Services.NVIDIA
}
}
public Display GetPrimaryDisplay()
{
var displayId = DisplayDevice.GetGDIPrimaryDisplayDevice().DisplayId;
return Display.GetDisplays().FirstOrDefault(x => x.DisplayDevice.DisplayId == displayId);
}
public bool ApplyPreset(string idOrName)
{
@@ -245,13 +254,6 @@ namespace ColorControl.Services.NVIDIA
if (preset.applyColorData && (ColorDataDiffers(preset.colorData) || (!newHdrEnabled && preset.applyColorData && preset.colorData.Colorimetry != ColorDataColorimetry.Auto)))
{
//if (hdrEnabled)
//{
// SetHDRState(display, false);
// applyHdr = false;
//}
if (preset.applyRefreshRate || preset.applyResolution)
{
var timing = display.DisplayDevice.CurrentTiming;
@@ -261,15 +263,6 @@ namespace ColorControl.Services.NVIDIA
}
}
//if (preset.applyRefreshRate)
//{
// var timing = display.DisplayDevice.CurrentTiming;
// if (preset.refreshRate < timing.Extra.RefreshRate)
// {
// SetRefreshRate(preset.refreshRate, true);
// }
//}
try
{
display.DisplayDevice.SetColorData(preset.colorData);
@@ -279,13 +272,6 @@ namespace ColorControl.Services.NVIDIA
Logger.Error($"SetColorData threw an exception: {ex.Message}");
result = false;
}
//if (hdrEnabled && newHdrEnabled)
//{
// SetHDRState(display, true, useSwitch: appContext.StartUpParams.NoGui);
// applyHdr = false;
//}
}
if (applyHdr)
@@ -301,13 +287,6 @@ namespace ColorControl.Services.NVIDIA
{
result = false;
}
//var timing = display.DisplayDevice.CurrentTiming;
//if (preset.refreshRate != timing.Extra.RefreshRate && !SetRefreshRate(preset.refreshRate, true))
//{
// result = false;
//}
}
if (preset.applyDithering)
@@ -381,7 +360,7 @@ namespace ColorControl.Services.NVIDIA
{
if (useSwitch)
{
if (enabled != IsHDREnabled())
if (enabled != IsHDREnabled(display))
{
CCD.SetHDRState(enabled, display.Name);
//ToggleHDR();
@@ -390,26 +369,9 @@ namespace ColorControl.Services.NVIDIA
}
CCD.SetHDRState(enabled, display.Name);
//var newMaster = new MasteringDisplayColorData();
//var hdr = new HDRColorData(enabled ? ColorDataHDRMode.UHDA : ColorDataHDRMode.Off, newMaster, colorData?.ColorFormat, colorData?.DynamicRange, colorData?.ColorDepth);
//display.DisplayDevice.SetHDRColorData(hdr);
// HDR will not always be disabled this way, then we can only disable it through the display settings
//if (!enabled && IsHDREnabled())
//{
// CCD.SetHDRState(enabled);
// //ToggleHDR();
//}
//else if (enabled)
//{
// // Currectly there seems to be a bug that after enabling HDR via NVAPI, some settings are only applied upon opening the Display Settings...
// ////OpenDisplaySettings();
//}
}
public bool SetDithering(NvDitherState state, uint bits = 1, uint mode = 4, NvPreset preset = null)
public bool SetDithering(NvDitherState state, uint bits = 1, uint mode = 4, NvPreset preset = null, Display currentDisplay = null)
{
var result = true;
@@ -418,7 +380,7 @@ namespace ColorControl.Services.NVIDIA
{
var delegateValue = Marshal.GetDelegateForFunctionPointer(ptr, typeof(NvAPI_Disp_SetDitherControl)) as NvAPI_Disp_SetDitherControl;
var display = GetCurrentDisplay();
var display = currentDisplay ?? GetCurrentDisplay();
if (display == null)
{
return false;
@@ -457,7 +419,7 @@ namespace ColorControl.Services.NVIDIA
return result;
}
public NV_GPU_DITHER_CONTROL_V1 GetDithering()
public NV_GPU_DITHER_CONTROL_V1 GetDithering(Display currentDisplay = null)
{
var dither = new NV_GPU_DITHER_CONTROL_V1 { version = 0x10018 };
@@ -466,7 +428,7 @@ namespace ColorControl.Services.NVIDIA
{
var delegateValue = Marshal.GetDelegateForFunctionPointer(ptr, typeof(NvAPI_Disp_GetDitherControl)) as NvAPI_Disp_GetDitherControl;
var display = GetCurrentDisplay();
var display = currentDisplay ?? GetCurrentDisplay();
if (display == null)
{
dither.state = -1;
@@ -556,9 +518,9 @@ namespace ColorControl.Services.NVIDIA
return GetAvailableResolutionsInternal(display.Name, portrait, (uint)(timing.Extra.RefreshRate));
}
public bool IsHDREnabled()
public bool IsHDREnabled(Display currentDisplay = null)
{
var display = GetCurrentDisplay();
var display = currentDisplay ?? GetCurrentDisplay();
if (display == null)
{
return false;
@@ -585,17 +547,12 @@ namespace ColorControl.Services.NVIDIA
foreach (var display in displays)
{
var values = new List<string>();
values.Add("Current settings");
var name = display.Name;
var screen = Screen.AllScreens.FirstOrDefault(x => x.DeviceName.Equals(name));
if (screen != null)
var values = new List<string>
{
name += " (" + screen.DeviceFriendlyName() + ")";
}
"Current settings"
};
var name = FormUtils.ExtendedDisplayName(display.Name);
values.Add(name);
@@ -613,7 +570,7 @@ namespace ColorControl.Services.NVIDIA
values.Add($"{desktopRect.Width}x{desktopRect.Height}");
var ditherInfo = GetDithering();
var ditherInfo = GetDithering(display);
string dithering;
if (ditherInfo.state == -1)
@@ -634,7 +591,7 @@ namespace ColorControl.Services.NVIDIA
values.Add(dithering);
var hdrEnabled = IsHDREnabled();
var hdrEnabled = IsHDREnabled(display);
values.Add(hdrEnabled ? "Yes" : "No");
var settings = GetVisibleSettings();
@@ -653,7 +610,7 @@ namespace ColorControl.Services.NVIDIA
var infoLine = string.Format("{0}: {1}, {2}Hz, HDR: {3}", name, colorSettings, refreshRate, hdrEnabled ? "Yes" : "No");
var displayInfo = new NvDisplayInfo(display, values, infoLine);
var displayInfo = new NvDisplayInfo(display, values, infoLine, name);
list.Add(displayInfo);
}
@@ -719,10 +676,10 @@ namespace ColorControl.Services.NVIDIA
_drs.GetProfileNames(ref _baseProfileName, false);
Task.Run(() =>
{
RefreshProfileSettings();
});
//Task.Run(() =>
//{
// RefreshProfileSettings();
//});
}
private void RefreshProfileSettings()
@@ -730,6 +687,8 @@ namespace ColorControl.Services.NVIDIA
_semaphore.WaitOne();
try
{
DrsSessionScope.DestroyGlobalSession();
var applications = new Dictionary<string, string>();
var normalSettings = _drs.GetSettingsForProfile(_baseProfileName, SettingViewMode.Normal, ref applications);
+2
View File
@@ -300,6 +300,8 @@ namespace nspector.Common
public int StoreSettingsToProfile(string profileName, List<KeyValuePair<uint, string>> settings)
{
DrsSessionScope.DestroyGlobalSession();
DrsSession((hSession) =>
{
var hProfile = GetProfileHandle(hSession, profileName);
File diff suppressed because it is too large. Load diff