Skip to content

Commit

Permalink
Merge pull request #24 from ScottyMac52/Version3.1
Browse files Browse the repository at this point in the history
Changes for 3.1
  • Loading branch information
ScottyMac52 authored Jan 23, 2022
2 parents d08a795 + 1bc6082 commit 2c3ced7
Show file tree
Hide file tree
Showing 22 changed files with 512 additions and 239 deletions.
2 changes: 1 addition & 1 deletion MFDMF-App/ConfigurationWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MFDMFApp"
mc:Ignorable="d"
Title="ConfigurationWindow" BorderThickness="0" Topmost="True" ResizeMode="NoResize" WindowStyle="None" ShowInTaskbar="False" Opacity="0" AllowsTransparency="True" Loaded="Window_Loaded" Closing="Window_Closing" Closed="Window_Closed">
Title="ConfigurationWindow" BorderThickness="0" ResizeMode="NoResize" WindowStyle="None" ShowInTaskbar="False" Opacity="0" AllowsTransparency="True" Loaded="Window_Loaded" Closing="Window_Closing" Closed="Window_Closed">
<Grid>
</Grid>
</Window>
217 changes: 82 additions & 135 deletions MFDMF-App/ConfigurationWindow.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,24 +1,23 @@
namespace MFDMFApp
using MFDMF_Models;
using MFDMF_Models.Interfaces;
using MFDMF_Models.Models;
using MFDMF_Services;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace MFDMFApp
{
using MFDMF_Models;
using MFDMF_Models.Interfaces;
using MFDMF_Models.Models;
using MFDMF_Services;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;

/// <summary>
/// Interaction logic for ConfigurationWindow.xaml
/// </summary>
Expand Down Expand Up @@ -106,17 +105,18 @@ private bool InitializeWindow()
var displayForConfig = _displayDefinitions?.FirstOrDefault(dd => dd.Name == Configuration?.Name || (Configuration?.Name?.StartsWith(dd.Name, StringComparison.CurrentCulture) ?? false));
Title = Configuration?.Name;
ResizeMode = ResizeMode.NoResize;
Width = Configuration?.Width ?? displayForConfig.Width ?? 0;
Height = Configuration?.Height ?? displayForConfig.Height ?? 0;
Left = Configuration?.Left ?? displayForConfig.Left ?? 0;
Top = Configuration?.Top ?? displayForConfig.Top ?? 0;
Width = Configuration?.Width ?? displayForConfig?.Width ?? 0;
Height = Configuration?.Height ?? displayForConfig?.Height ?? 0;
Left = Configuration?.Left ?? displayForConfig?.Left ?? 0;
Top = Configuration?.Top ?? displayForConfig?.Top ?? 0;
Opacity = Configuration?.Opacity ?? 1.0F;
var status = $"Configuration: {Title} at ({Left},{Top}) for ({Width},{Height}) Created from: {displayForConfig?.ToReadableString() ?? "Scratch"}";
_logger?.LogInformation(status);
if (_settings.ShowTooltips ?? false)
{
ToolTip = status;
}
Topmost = displayForConfig?.AlwaysOnTop ?? false;
return true;
}

Expand All @@ -131,47 +131,20 @@ private bool InitializeWindow()
private System.Windows.Controls.Image CreateNewImage(string imageName)
{
var controlGrid = Content as Grid;
while(controlGrid.Children.Count > 0)
while((controlGrid?.Children?.Count ?? 0) > 0)
{
controlGrid.Children.RemoveAt(0);
}
#pragma warning disable CS8602 // Dereference of a possibly null reference.
controlGrid.Children.RemoveAt(0);
#pragma warning restore CS8602 // Dereference of a possibly null reference.
}
var imgMain = new System.Windows.Controls.Image()
{
Name = imageName
};
controlGrid.Children.Add(imgMain);
return imgMain;
}

/// <summary>
/// Crops the image to the specified dimensions
/// </summary>
/// <param name="src"></param>
/// <param name="config"></param>
/// <param name="saveOriginal"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="Exception"></exception>
private Bitmap Crop(Bitmap src, IConfigurationDefinition config, bool saveOriginal = true)
{
if (config.IsValid)
{
if (saveOriginal)
{
SaveOriginalImageIfRequired(src);
}
var cropRect = new Rectangle(config.CroppingStart, new System.Drawing.Size(config.CroppedWidth, config.CroppedHeight));
var newBitmap = new Bitmap(config?.Width ?? 0, config?.Height ?? 0, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
using (var g = Graphics.FromImage(newBitmap))
{
g.DrawImage(src, new Rectangle(0, 0, newBitmap.Width, newBitmap.Height), cropRect, GraphicsUnit.Pixel);
}
return newBitmap;
}
else
{
throw new ArgumentException($"Unable to Crop bitmap for {config.ToReadableString()}. The configuration is not valid.");
}
#pragma warning disable CS8602 // Dereference of a possibly null reference.
controlGrid.Children.Add(imgMain);
#pragma warning restore CS8602 // Dereference of a possibly null reference.
return imgMain;
}

private void SaveOriginalImageIfRequired(Bitmap src)
Expand Down Expand Up @@ -208,42 +181,21 @@ private void CreateCroppingRectangle(IConfigurationDefinition config, Graphics g
g.DrawRectangle(Pens.Red, config.CroppingArea);
}

/*
private void SaveFileAsKneeboardRef(string path, IConfigurationDefinition config)
private void SaveFileAsKneeboardRefAsRequired(string path, IConfigurationDefinition config)
{
if (_settings.CreateKneeboard ?? false)
if ((_settings.CreateKneeboard ?? false) && !string.IsNullOrEmpty(ModuleDefinition.DCSName))
{
using var img = Crop((Bitmap)System.Drawing.Image.FromFile(path), config, false);
ConfigurationDefinition.WalkConfigurationDefinitionsWithAction(config, (subConfig) =>
{
// See if the Coonfiguration is selected
if (CheckForConfiguration(subConfig))
{
var key = $"{config.ModuleName}-{config?.Name}-{subConfig.Name}";
var insetImage = ImageDictionary.FirstOrDefault(id => id.Key == key).Value;
using var cropped = Crop(insetImage, subConfig, false);
using var g = Graphics.FromImage(img);
g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
var origin = new System.Drawing.Point(subConfig?.Left ?? 0, subConfig?.Top ?? 0);
g.DrawImage(cropped, new Rectangle(origin, new System.Drawing.Size(subConfig?.Width ?? 0, subConfig?.Height ?? 0)));
}
});
if (string.IsNullOrEmpty(ModuleDefinition.DCSName))
{
_logger.LogWarning($"Configuration {ModuleDefinition.DisplayName} doesn't have a kneeboard tag");
return;
}
using var img = System.Drawing.Image.FromFile(path);
var kneeBoardPath = Path.Combine(SavedGamesFolder, _settings.DcsSavedGamesPath, "Kneeboard", ModuleDefinition.DCSName);
var kneeBoardFile = Path.Combine(kneeBoardPath, $"{ModuleDefinition.DCSName}-{config.Name}.png");
if (!Directory.Exists(kneeBoardPath))
{
Directory.CreateDirectory(kneeBoardPath);
_logger.LogInformation($"Creating {kneeBoardPath}");
}
if (!File.Exists(kneeBoardFile))
if (!File.Exists(kneeBoardFile) || (_settings.TurnOffCache ?? false))
{
using var kneeBoardBitmap = new Bitmap(768, 1024, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
using var kneeBoardBitmap = new Bitmap(768, 1024, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
using (var gk = Graphics.FromImage(kneeBoardBitmap))
{
var cropRect = config.CroppingArea;
Expand All @@ -254,49 +206,7 @@ private void SaveFileAsKneeboardRef(string path, IConfigurationDefinition config
}
}
}
*/

private void CreateRulers(IConfigurationDefinition config, Graphics g)
{
var xCenter = (config.Width ?? 0) / 2;
var yCenter = (config.Height ?? 0) / 2;

g.DrawLine(Pens.Red, new System.Drawing.Point(0, yCenter), new System.Drawing.Point(config.Width ?? 0, yCenter));

for (int x = 0; x < (config.Width ?? 0); x++)
{
if (x % (_settings.RulerSize ?? 0) == 0)
{
var startPoint = new System.Drawing.Point(x, yCenter - 10);
var endPoint = new System.Drawing.Point(x, yCenter + 10);
g.DrawLine(Pens.OrangeRed, startPoint, endPoint);
}

if (x % 100 == 0)
{
var textPoint = new PointF(x - 10, (float) yCenter + 10);
g.DrawString($"{x}", System.Drawing.SystemFonts.DefaultFont, System.Drawing.Brushes.Red, textPoint);
}
}

g.DrawLine(Pens.Red, new System.Drawing.Point(xCenter, 0), new System.Drawing.Point(xCenter, config.Height ?? 0));

for (int y = 0; y < (config.Height ?? 0); y++)
{
if (y % (_settings.RulerSize ?? 0) == 0)
{
var startPoint = new System.Drawing.Point(xCenter - 10, y);
var endPoint = new System.Drawing.Point(xCenter + 10, y);
g.DrawLine(Pens.OrangeRed, startPoint, endPoint);
}

if(y % 100 == 0)
{
var textPoint = new PointF(xCenter + 10, y-5);
g.DrawString($"{y}", System.Drawing.SystemFonts.DefaultFont, System.Drawing.Brushes.Red, textPoint);
}
}
}

/// <summary>
/// Loads the configured image either from the test pattern, user's cache or from the original location
Expand All @@ -318,7 +228,7 @@ private void LoadImage(string cacheFile)
imgMain.StretchDirection = StretchDirection.Both;
imgMain.Stretch = Stretch.Fill;
var imgSource = new Uri(cacheFile, UriKind.RelativeOrAbsolute);
BitmapImage src = new BitmapImage();
var src = new BitmapImage();
src.BeginInit();
src.UriSource = imgSource;
src.CacheOption = BitmapCacheOption.OnLoad;
Expand Down Expand Up @@ -366,6 +276,7 @@ private void Window_Loaded(object sender, RoutedEventArgs e)
});
var selectedImage = ImageDictionary[key];
LoadImage(selectedImage.CacheFile);
SaveFileAsKneeboardRefAsRequired(selectedImage.CacheFile, Configuration);
}
watch.Stop();
_logger?.LogWarning($"Configuration {Configuration.ModuleName}-{Configuration.Name}-{SubConfigurationNames}: loaded in {watch.ElapsedMilliseconds} milliseconds");
Expand Down Expand Up @@ -398,14 +309,50 @@ private void Window_Closed(object sender, EventArgs e)

protected override void OnMouseDown(MouseButtonEventArgs e)
{
var rightButton = e.RightButton;
var mousePos = System.Windows.Forms.Control.MousePosition;
var currentRect = new Rectangle(mousePos.X, mousePos.Y, 1, 1);
var screen = GetScreen(this);
var currentDisplay = _displayDefinitions?.FirstOrDefault(dd => currentRect.IntersectsWith(new Rectangle(dd?.Left ?? 0, dd?.Top ?? 0, dd?.Width ?? 0, dd?.Height ?? 0)));
var clientLeft = mousePos.X - (currentDisplay?.Left ?? 0);
var clientTop = mousePos.Y - (currentDisplay?.Top ?? 0);
System.Windows.MessageBox.Show($"({mousePos.X}, {mousePos.Y}) ({clientLeft}, {clientTop}) in {currentDisplay?.ToReadableString() ?? "None"} on Screen {screen?.DeviceName ?? "None"}", $"{Configuration.Name}", MessageBoxButton.OK, MessageBoxImage.Information);
base.OnMouseDown(e);

IDisplayDefinition? displayDef;
var displayDefs = _displayDefinitions.Where(dd => currentRect.IntersectsWith(new Rectangle(dd?.Left ?? 0, dd?.Top ?? 0, dd?.Width ?? 0, dd?.Height ?? 0)));
if (displayDefs.Count() > 1)
{
// Get the smallest config in the area
displayDef = displayDefs.Aggregate((first, second) => ((first.Width ?? 0) * (first.Height ?? 0)) > ((second.Width ?? 0) * (second.Height ?? 0)) ? second : first);
}
else
{
displayDef = displayDefs.SingleOrDefault();
}
var relatedDisplays = _displayDefinitions.Where(dd => dd.Name.StartsWith(displayDef?.Name));
if (relatedDisplays.Count() > 1)
{
// Get the display definition with the longest name
displayDef = relatedDisplays.Aggregate((first, second) => (first.Name.Length > second.Name.Length) ? first : second);
}

if (e.RightButton == MouseButtonState.Pressed)
{
switch (System.Windows.MessageBox.Show("Do you want to close this configuration window?", $"Close {Configuration?.DisplayName} in display {displayDef?.Name ?? "Not Specified"}", MessageBoxButton.YesNoCancel, MessageBoxImage.Question))
{
case MessageBoxResult.No:
case MessageBoxResult.Cancel:
case MessageBoxResult.None:
break;
case MessageBoxResult.OK:
case MessageBoxResult.Yes:
Close();
break;
}
}
else
{
var screen = GetScreen(this);
var clientLeft = mousePos.X - (displayDef?.Left ?? 0);
var clientTop = mousePos.Y - (displayDef?.Top ?? 0);
System.Windows.MessageBox.Show($"({mousePos.X}, {mousePos.Y}) ({clientLeft}, {clientTop}) in {displayDef?.ToReadableString() ?? "None"} on Screen {screen?.DeviceName ?? "None"}", $"{Configuration.Name}", MessageBoxButton.OK, MessageBoxImage.Information);
base.OnMouseDown(e);
}
}

#endregion Mouse events
Expand Down
9 changes: 5 additions & 4 deletions MFDMF-App/ConfigureApp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,12 @@ internal static IHost Configure(Action<IServiceCollection, IConfiguration> addti
var logFile = Path.Combine(appFolder, $"{Properties.Resources.BaseDataDirectory}Logs\\status");
loggerConfiguration.MinimumLevel.Warning();
loggerConfiguration.MinimumLevel.Override("Microsoft", LogEventLevel.Warning);
loggerConfiguration.MinimumLevel.Override("MFDMFApp", LogEventLevel.Warning);
loggerConfiguration.MinimumLevel.Override("MFDMF_Services", LogEventLevel.Warning);
loggerConfiguration.MinimumLevel.Override("MFDMF_Services.Configuration", LogEventLevel.Information);
loggerConfiguration.MinimumLevel.Override("MFDMFApp", LogEventLevel.Information);
loggerConfiguration.MinimumLevel.Override("MFDMF_Services.Configuration", LogEventLevel.Warning);
loggerConfiguration.MinimumLevel.Override("MFDMF_Services.Displays", LogEventLevel.Warning);
loggerConfiguration.MinimumLevel.Override("MFDMF_Services.ConfigurationProvider", LogEventLevel.Warning);
loggerConfiguration.Enrich.FromLogContext();
loggerConfiguration.WriteTo.RollingFile(logFile + "-{Date}.log", LogEventLevel.Information, outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level}] [{SourceContext}] [{Message}]{NewLine}{Exception}");
loggerConfiguration.WriteTo.RollingFile(logFile + "-{Date}.log", LogEventLevel.Verbose, outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level}] [{SourceContext}] [{Message}]{NewLine}{Exception}");
})
.Build();
}
Expand Down
26 changes: 22 additions & 4 deletions MFDMF-App/MFDMFApp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net5.0-windows</TargetFramework>
<TargetFramework>net5.0-windows10.0.17763.0</TargetFramework>
<RootNamespace>MFDMFApp</RootNamespace>
<UseWPF>true</UseWPF>
<UseWindowsForms>true</UseWindowsForms>
Expand All @@ -11,15 +11,18 @@
<Authors>Vyper Industries</Authors>
<Company>Vyper Industries</Company>
<Product>Multi-Function Display Management Application</Product>
<Copyright>© 2018-2021</Copyright>
<Copyright>© 2018-2022</Copyright>
<ApplicationIcon>mfd_xkl_icon.ico</ApplicationIcon>
<Platforms>AnyCPU;x64</Platforms>
<Version>3.0.3</Version>
<Version>3.1.0</Version>
<NeutralLanguage>en-US</NeutralLanguage>
<PackageProjectUrl>https://github.com/ScottyMac52/MFDMF</PackageProjectUrl>
<RepositoryUrl>https://github.com/ScottyMac52/MFDMF</RepositoryUrl>
<RepositoryType>GitHUb</RepositoryType>
<PackageTags>3.0.3</PackageTags>
<PackageTags>3.1</PackageTags>
<AssemblyVersion>3.1.0.0</AssemblyVersion>
<FileVersion>3.1.0.0</FileVersion>
<Nullable>enable</Nullable>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
Expand Down Expand Up @@ -74,8 +77,11 @@
<None Remove="Modules\Blue Warbirds\Spitfire.json" />
<None Remove="Modules\CombinedArms.json" />
<None Remove="Modules\Historical Flight\blank.json" />
<None Remove="Modules\Historical Flight\SW_Squadrons.json" />
<None Remove="Modules\LotATC\awacs.json" />
<None Remove="Modules\Non DCS\CTSProf.json" />
<None Remove="Modules\Non DCS\CTSProf2.json" />
<None Remove="Modules\Non DCS\CTSProfWindows.json" />
<None Remove="Modules\Non DCS\Elite.json" />
<None Remove="Modules\Non DCS\Il2.json" />
<None Remove="Modules\Non DCS\rgbSwitch.json" />
Expand Down Expand Up @@ -105,6 +111,12 @@
<Content Include="Modules\Blue Jets\T-45.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="Modules\Non DCS\CTSProf2.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="Modules\Non DCS\CTSProfWindows.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="Modules\Red Jets\Mig-29.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
Expand Down Expand Up @@ -452,5 +464,11 @@
</Content>
</ItemGroup>

<ItemGroup>
<Content Include="Modules\Historical Flight\SW_Squadrons.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>


</Project>
Loading

0 comments on commit 2c3ced7

Please sign in to comment.