Skip to content

Commit

Permalink
Merge pull request #272 from emoacht/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
emoacht authored Dec 24, 2021
2 parents 0b63594 + c528f27 commit 6011f5d
Show file tree
Hide file tree
Showing 21 changed files with 141 additions and 37 deletions.
2 changes: 1 addition & 1 deletion Source/Installer/Product.wxs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
<Product Id="*" Name="Monitorian" Manufacturer="emoacht" Version="3.8.0"
<Product Id="*" Name="Monitorian" Manufacturer="emoacht" Version="3.8.2"
Language="1033" Codepage="1252" UpgradeCode="{81A4D148-75D3-462E-938D-8C208FB48E3C}">
<Package Id="*" InstallerVersion="500" Compressed="yes"
InstallScope="perMachine" InstallPrivileges="elevated"
Expand Down
2 changes: 1 addition & 1 deletion Source/Monitorian.Core/AppControllerCore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -430,7 +430,7 @@ protected internal virtual void SaveCustomization(string deviceInstanceId, strin

protected virtual void EnsureUnisonWorkable(MonitorViewModel monitor)
{
if (_isUnisonWorkable || (monitor?.IsUnison is not true))
if (_isUnisonWorkable || (monitor is not { IsUnison: true }))
return;

_current.Dispatcher.Invoke(() =>
Expand Down
4 changes: 3 additions & 1 deletion Source/Monitorian.Core/AppKeeper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.Windows.Threading;

using Monitorian.Core.Models;
using Monitorian.Core.Models.Monitor;
using Monitorian.Core.Views;
using StartupAgency;

Expand Down Expand Up @@ -70,6 +71,7 @@ public static string[] GetDefinedOptions() =>
new[]
{
StartupAgent.Options,
MonitorManager.Options,
LanguageService.Options,
WindowPainter.Options
}
Expand All @@ -85,7 +87,7 @@ private async Task ParseArgumentsAsync(StartupEventArgs e, string[] definedOptio
// The first element of StartupEventArgs.Args is not executing assembly's path unlike
// that of arguments provided by Environment.GetCommandLineArgs method.
args = e.Args.Concat(args).ToArray();
if (args.Any() is not true)
if (args is not { Length: > 0 })
return;

const char optionMark = '/';
Expand Down
37 changes: 36 additions & 1 deletion Source/Monitorian.Core/Models/AppDataService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,34 @@ public static void Rename(string oldFileName, string newFileName)

#region Load/Save

/// <summary>
/// Loads saved instance from a specified file and copies its properties to current instance.
/// </summary>
/// <typeparam name="T">Type of instance</typeparam>
/// <param name="instance">Current instance</param>
/// <param name="fileName">File name of saved instance</param>
/// <param name="knownTypes">Known types of members of instance</param>
/// <remarks>
/// Only values of public and instance properties will be copied.
/// An indexer will be ignored.
/// </remarks>
public static void Load<T>(T instance, string fileName, IEnumerable<Type> knownTypes = null) where T : class
{
Load(instance, fileName, BindingFlags.Public | BindingFlags.Instance, knownTypes);
}

/// <summary>
/// Loads saved instance from a specified file and copies its properties to current instance.
/// </summary>
/// <typeparam name="T">Type of instance</typeparam>
/// <param name="instance">Current instance</param>
/// <param name="fileName">File name of saved instance</param>
/// <param name="flags">Flags to search properties to be copied</param>
/// <param name="knownTypes">Known types of members of instance</param>
/// <remarks>
/// An indexer will be ignored.
/// </remarks>
public static void Load<T>(T instance, string fileName, BindingFlags flags, IEnumerable<Type> knownTypes = null) where T : class
{
var filePath = Path.Combine(FolderPath, fileName);
var fileInfo = new FileInfo(filePath);
Expand All @@ -95,8 +122,9 @@ public static void Load<T>(T instance, string fileName, IEnumerable<Type> knownT
var serializer = new DataContractSerializer(type, knownTypes);
var loaded = (T)serializer.ReadObject(xr);

type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
type.GetProperties(flags)
.Where(x => x.CanWrite)
.Where(x => x.GetIndexParameters().Length == 0) // Exclude indexer to prevent TargetParameterCountException.
.ToList()
.ForEach(x => x.SetValue(instance, x.GetValue(loaded)));
}
Expand All @@ -110,6 +138,13 @@ public static void Load<T>(T instance, string fileName, IEnumerable<Type> knownT
}
}

/// <summary>
/// Saves current instance to a specified file.
/// </summary>
/// <typeparam name="T">Type of instance</typeparam>
/// <param name="instance">Current instance</param>
/// <param name="fileName">File name of saved instance</param>
/// <param name="knownTypes">Known types of members of instance</param>
public static void Save<T>(T instance, string fileName, IEnumerable<Type> knownTypes = null) where T : class
{
AssureFolder();
Expand Down
1 change: 1 addition & 0 deletions Source/Monitorian.Core/Models/Monitor/DdcMonitorItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ internal class DdcMonitorItem : MonitorItem

public override bool IsBrightnessSupported => _capability.IsBrightnessSupported;
public override bool IsContrastSupported => _capability.IsContrastSupported;
public override bool IsPrecleared => _capability.IsPrecleared;

public DdcMonitorItem(
string deviceInstanceId,
Expand Down
38 changes: 34 additions & 4 deletions Source/Monitorian.Core/Models/Monitor/MonitorConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@
using System.Text;
using System.Threading.Tasks;

using Monitorian.Core.Helper;

namespace Monitorian.Core.Models.Monitor
{
/// <summary>
Expand Down Expand Up @@ -559,12 +557,15 @@ internal class MonitorCapability
public bool IsContrastSupported { get; }

[DataMember(Order = 3)]
public string CapabilitiesString { get; }
public bool IsPrecleared { get; }

[DataMember(Order = 4)]
public string CapabilitiesReport { get; }
public string CapabilitiesString { get; }

[DataMember(Order = 5)]
public string CapabilitiesReport { get; }

[DataMember(Order = 6)]
public string CapabilitiesData { get; }

public MonitorCapability(
Expand All @@ -582,5 +583,34 @@ public MonitorCapability(
this.CapabilitiesReport = capabilitiesReport;
this.CapabilitiesData = (capabilitiesData is not null) ? Convert.ToBase64String(capabilitiesData) : null;
}

private MonitorCapability(
bool isHighLevelBrightnessSupported,
bool isLowLevelBrightnessSupported,
bool isContrastSupported,
bool isPrecleared,
string capabilitiesString,
string capabilitiesReport,
byte[] capabilitiesData) : this(
isHighLevelBrightnessSupported: isHighLevelBrightnessSupported,
isLowLevelBrightnessSupported: isLowLevelBrightnessSupported,
isContrastSupported: isContrastSupported,
capabilitiesString: capabilitiesString,
capabilitiesReport: capabilitiesReport,
capabilitiesData: capabilitiesData)
{
this.IsPrecleared = isPrecleared;
}

public static MonitorCapability PreclearedCapability => _preclearedCapability.Value;
private static readonly Lazy<MonitorCapability> _preclearedCapability = new(() =>
new MonitorCapability(
isHighLevelBrightnessSupported: false,
isLowLevelBrightnessSupported: true,
isContrastSupported: true,
isPrecleared: true,
capabilitiesString: null,
capabilitiesReport: null,
capabilitiesData: null));
}
}
2 changes: 2 additions & 0 deletions Source/Monitorian.Core/Models/Monitor/MonitorItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ internal abstract class MonitorItem : IMonitor, IDisposable

public virtual bool IsBrightnessSupported => IsReachable;
public virtual bool IsContrastSupported => false;
public virtual bool IsPrecleared => false;

public MonitorItem(
string deviceInstanceId,
Expand Down Expand Up @@ -65,6 +66,7 @@ public override string ToString()
(nameof(IsReachable), IsReachable),
(nameof(IsBrightnessSupported), IsBrightnessSupported),
(nameof(IsContrastSupported), IsContrastSupported),
(nameof(IsPrecleared), IsPrecleared),
(nameof(Brightness), Brightness),
(nameof(BrightnessSystemAdjusted), BrightnessSystemAdjusted),
(nameof(Contrast), Contrast));
Expand Down
50 changes: 43 additions & 7 deletions Source/Monitorian.Core/Models/Monitor/MonitorManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,32 @@ public DeviceItemPlus(

#endregion

#region Preclearance

public static IReadOnlyCollection<string> Options => new[] { Option };
private const string Option = "/preclear";

private static readonly Lazy<HashSet<string>> _preclearedIds = new(() =>
{
var buffer = AppKeeper.DefinedArguments
.SkipWhile(x => !string.Equals(x, Option, StringComparison.OrdinalIgnoreCase))
.Skip(1) // 1 means option.
.TakeWhile(x => x.StartsWith("DISPLAY"))
.Select(x => x.Replace(@"\\", @"\")); // Backslash will be escaped in JSON.
return new HashSet<string>(buffer);
});

#endregion

public static async Task<IEnumerable<IMonitor>> EnumerateMonitorsAsync()
{
var deviceItems = await GetMonitorDevicesAsync();

return EnumerateMonitors(deviceItems);
}

private static HashSet<string> _ids;
private static HashSet<string> _foundIds;

private static async Task<List<DeviceItemPlus>> GetMonitorDevicesAsync()
{
Expand All @@ -58,7 +76,7 @@ private static async Task<List<DeviceItemPlus>> GetMonitorDevicesAsync()
: DisplayConfig.EnumerateDisplayConfigs().ToArray();

var deviceItems = DeviceContext.EnumerateMonitorDevices().ToArray();
_ids = new HashSet<string>(deviceItems.Select(x => x.DeviceInstanceId));
_foundIds = new HashSet<string>(deviceItems.Select(x => x.DeviceInstanceId));

IEnumerable<DeviceItemPlus> Enumerate()
{
Expand Down Expand Up @@ -90,7 +108,7 @@ IEnumerable<DeviceItemPlus> Enumerate()

private static IEnumerable<IMonitor> EnumerateMonitors(List<DeviceItemPlus> deviceItems)
{
if (deviceItems?.Any() is not true)
if (deviceItems is not { Count: > 0 })
yield break;

var handleItems = DeviceContext.GetMonitorHandles();
Expand All @@ -101,9 +119,11 @@ private static IEnumerable<IMonitor> EnumerateMonitors(List<DeviceItemPlus> devi
foreach (var physicalItem in MonitorConfiguration.EnumeratePhysicalMonitors(handleItem.MonitorHandle))
{
int index = -1;
if (physicalItem.Capability.IsBrightnessSupported)
if (physicalItem.Capability.IsBrightnessSupported ||
_preclearedIds.Value.Any())
{
index = deviceItems.FindIndex(x =>
!x.IsInternal &&
(x.DisplayIndex == handleItem.DisplayIndex) &&
(x.MonitorIndex == physicalItem.MonitorIndex) &&
string.Equals(x.Description, physicalItem.Description, StringComparison.OrdinalIgnoreCase));
Expand All @@ -115,14 +135,30 @@ private static IEnumerable<IMonitor> EnumerateMonitors(List<DeviceItemPlus> devi
}

var deviceItem = deviceItems[index];

MonitorCapability capability = null;
if (physicalItem.Capability.IsBrightnessSupported)
{
capability = physicalItem.Capability;
}
else if (_preclearedIds.Value.Contains(deviceItem.DeviceInstanceId))
{
capability = MonitorCapability.PreclearedCapability;
}
else
{
physicalItem.Handle.Dispose();
continue;
}

yield return new DdcMonitorItem(
deviceInstanceId: deviceItem.DeviceInstanceId,
description: deviceItem.AlternateDescription,
displayIndex: deviceItem.DisplayIndex,
monitorIndex: deviceItem.MonitorIndex,
monitorRect: handleItem.MonitorRect,
handle: physicalItem.Handle,
capability: physicalItem.Capability);
capability: capability);

deviceItems.RemoveAt(index);
if (deviceItems.Count == 0)
Expand Down Expand Up @@ -175,8 +211,8 @@ private static IEnumerable<IMonitor> EnumerateMonitors(List<DeviceItemPlus> devi
public static bool CheckMonitorsChanged()
{
var newIds = new HashSet<string>(DeviceContext.EnumerateMonitorDevices().Select(x => x.DeviceInstanceId));
var oldIds = _ids;
_ids = newIds;
var oldIds = _foundIds;
_foundIds = newIds;
return (oldIds?.SetEquals(newIds) is not true);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ protected override void WndProc(ref Message m)

public void RegisterPowerSettingEvent(IReadOnlyCollection<Guid> settingGuids)
{
if (settingGuids?.Any() is not true)
if (settingGuids is not { Count: > 0 })
return;

if (!TryGetSystemEventsWindowHandle(out IntPtr windowHandle))
Expand Down Expand Up @@ -135,7 +135,7 @@ public void UnregisterPowerSettingEvent()
{
PowerSettingChanged = null;

if (_registrationHandles?.Any() is true)
if (_registrationHandles is { Count: > 0 })
{
foreach (var handle in _registrationHandles)
UnregisterPowerSettingNotification(handle);
Expand Down
4 changes: 2 additions & 2 deletions Source/Monitorian.Core/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.8.0.0")]
[assembly: AssemblyFileVersion("3.8.0.0")]
[assembly: AssemblyVersion("3.8.2.0")]
[assembly: AssemblyFileVersion("3.8.2.0")]
[assembly: NeutralResourcesLanguage("en-US")]

// For unit test
Expand Down
2 changes: 1 addition & 1 deletion Source/Monitorian.Core/ViewModels/MonitorViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public MonitorViewModel(AppControllerCore controller, IMonitor monitor)

internal void Replace(IMonitor monitor)
{
if (monitor?.IsReachable is true)
if (monitor is { IsReachable: true })
{
lock (_lock)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ protected virtual bool UpdateValue(double value)
#region Drag

protected bool CanDrag { get; private set; }
protected bool IsDragging => (_thumb?.IsDragging is true);
protected bool IsDragging => (_thumb is { IsDragging: true });

private void CheckCanDrag()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public object Convert(object value, Type targetType, object parameter, CultureIn

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
throw new NotSupportedException();
}
}
}
2 changes: 1 addition & 1 deletion Source/Monitorian.Core/Views/WindowPainter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ protected override void PaintBackground(Window window)

private bool ChangeColors(Window window)
{
if (_colors?.Any() is not true)
if (_colors is not { Count: > 0 })
return false;

var isBackgroundChanged = false;
Expand Down
2 changes: 1 addition & 1 deletion Source/Monitorian.Supplement/DisplayInformation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ public static async Task<DisplayItem[]> GetDisplayMonitorsAsync()
try
{
var devices = await DeviceInformation.FindAllAsync(DisplayMonitor.GetDeviceSelector(), new[] { deviceInstanceIdKey });
if (devices?.Any() is true)
if (devices is { Count: > 0 })
{
var items = new List<DisplayItem>(devices.Count);
foreach (var device in devices)
Expand Down
4 changes: 2 additions & 2 deletions Source/Monitorian.Supplement/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,6 @@
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.5.0.0")]
[assembly: AssemblyFileVersion("3.5.0.0")]
[assembly: AssemblyVersion("3.8.2.0")]
[assembly: AssemblyFileVersion("3.8.2.0")]
[assembly: NeutralResourcesLanguage("en-US")]
4 changes: 2 additions & 2 deletions Source/Monitorian/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.8.0.0")]
[assembly: AssemblyFileVersion("3.8.0.0")]
[assembly: AssemblyVersion("3.8.2.0")]
[assembly: AssemblyFileVersion("3.8.2.0")]
[assembly: Guid("a4cc5362-9b08-465b-ad64-5cfabc72a4c7")]
[assembly: NeutralResourcesLanguage("en-US")]
Loading

0 comments on commit 6011f5d

Please sign in to comment.