Skip to content

Commit

Permalink
Merge pull request #25 from J0nnyI/library
Browse files Browse the repository at this point in the history
Library
  • Loading branch information
J0nnyI authored Jan 25, 2022
2 parents 4314e1c + a541743 commit 8580f89
Show file tree
Hide file tree
Showing 76 changed files with 1,788 additions and 707 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@ namespace TableTopCrucible.Core.Helper
/// <summary>
/// executes the given action when disposed
/// </summary>
public class ActOnDispose : IDisposable
public class ActOnLifecycle : IDisposable
{
private readonly Action _onDispose;

public ActOnDispose(Action onCreate, Action onDispose)
public ActOnLifecycle(Action onCreate, Action onDispose)
{
onCreate();
onCreate?.Invoke();
_onDispose = onDispose;
}

Expand Down
5 changes: 4 additions & 1 deletion Core/TableTopCrucible.Core.Helper/IEnumerableHelper.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using DynamicData;
Expand Down Expand Up @@ -33,5 +34,7 @@ public static StringCollection ToStringCollection(this IEnumerable<string> list)

public static bool None<T>(this IEnumerable<T> list)
=> !list.Any();
public static bool None<T>(this IEnumerable<T> list, Func<T,bool> selector)
=> !list.Any(selector);
}
}
5 changes: 5 additions & 0 deletions Core/TableTopCrucible.Core.Helper/SettingsHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,17 @@ public static class SettingsHelper
public static TimeSpan AnimationDuration => TimeSpan.FromMilliseconds(200);

public static int ThreadCount => 2;
public static ushort SimultaneousThumbnailWindows => 3;

public static TimeSpan PipelineBufferTime => TimeSpan.FromSeconds(5);

// the last n jobs will stay in memory, everything else will be removed
public static int DoneJobLimit => 5;
public static Size ThumbnailSize = new(200, 200);
public static double ThumbnailHeight => ThumbnailSize.Height;
public static double ThumbnailWidth=> ThumbnailSize.Width;
public static bool GenerateThumbnailOnSync => false;
public static int MaxTagCountInDropDown = 30;

/// <summary>
/// the autoSave (subject) is buffered by this duration to prevent excessive writing
Expand Down
12 changes: 12 additions & 0 deletions Core/TableTopCrucible.Core.Helper/SourceCacheHelper.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;

using DynamicData;

using TableTopCrucible.Core.Helper.Exceptions;

namespace TableTopCrucible.Core.Helper
Expand Down Expand Up @@ -97,5 +100,14 @@ public static void RemoveWhere<TObject, TId>(
public static IObservable<TObject> WatchFirstOrDefault<TObject, TKey>(
this IObservable<IChangeSet<TObject, TKey>> cache)
=> cache.ToCollection().Select(col => col.FirstOrDefault());

public static void RemoveWhere<TObject>(this ISourceList<TObject> list, Func<TObject, bool> selector)
=> list.Edit(updater => updater.RemoveMany(updater.Where(selector)));
public static IEnumerable<TObject> RemoveWhere<TObject>(this IList<TObject> list, Func<TObject, bool> selector)
{
var items = list.Where(selector).ToArray();
list.Remove(items);
return items;
}
}
}
10 changes: 9 additions & 1 deletion Core/TableTopCrucible.Core.ValueTypes/BareFileName.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,15 @@ namespace TableTopCrucible.Core.ValueTypes
/// </summary>
public class BareFileName : ValueType<string, BareFileName>
{
public static BareFileName TimeSuffix => (BareFileName)$"_{DateTime.Now:yyyyMMdd_HHmmssss}";
private static readonly Random random = new(DateTime.Now.GetHashCode());
public static BareFileName TimeSuffix
{
get
{
lock (random)
return (BareFileName)$"_{DateTime.Now:yyyyMMdd_HHmmssss}_${random.NextDouble()}";
}
}

public static BareFileName operator +(BareFileName bareFileA, BareFileName bareFileB) =>
From(bareFileA.Value + bareFileB.Value);
Expand Down
7 changes: 6 additions & 1 deletion Core/TableTopCrucible.Core.ValueTypes/FileHashKey.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Linq;
using System.Security.Cryptography;

namespace TableTopCrucible.Core.ValueTypes
Expand All @@ -18,7 +19,11 @@ public static FileHashKey Create<TFilePath>(FilePath<TFilePath> file, HashAlgori
return res;
}

private static readonly string _separator = "_";
public static FileHashKey From(FileSize fileSize, FileHash hash)
=> From(fileSize.Value + "_" + BitConverter.ToString(hash.Value).Replace("-", ""));
=> From(fileSize.Value + _separator + BitConverter.ToString(hash.Value).Replace("-", ""));

public FileSize GetFileSizeComponent()
=> (FileSize)int.Parse(Value.Split(_separator).First());
}
}
41 changes: 20 additions & 21 deletions Core/TableTopCrucible.Core.ValueTypes/FilePath.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,15 @@
using TableTopCrucible.Core.Helper;
using TableTopCrucible.Core.ValueTypes.Exceptions;

using JsonSerializer = System.Text.Json.JsonSerializer;

namespace TableTopCrucible.Core.ValueTypes
{
public class FilePath<TThis> : ValueType<string, TThis> where TThis : FilePath<TThis>, new()
{
protected override void Validate(string value)
{
base.Validate(value);
if (!Path.HasExtension(value))
throw new InvalidValueException($"the filepath '{value}' does not contain an extension");
//if (!Path.HasExtension(value))
// throw new InvalidValueException($"the filepath '{value}' does not contain an extension");
if (!Path.IsPathRooted(value))
throw new InvalidValueException($"the filepath '{value}' is incomplete (i.e. missing a drive letter)");
}
Expand Down Expand Up @@ -52,8 +50,24 @@ public void TryDelete()
}

public string ReadAllText() => FileSystemHelper.File.ReadAllText(Value);
public T ReadAllJson<T>() => JsonSerializer.Deserialize<T>(ReadAllText());
public void WriteAllJson(object data) => WriteAllText(JsonConvert.SerializeObject(data));

public T ReadAllJson<T>()
{
using var s = OpenRead();
using var sr = new StreamReader(s);
using JsonReader reader = new JsonTextReader(sr);
var serializer = JsonSerializer.CreateDefault();
return serializer.Deserialize<T>(reader);
}

public void WriteAllJson(object data)
{
using var s = OpenWrite();
using var sr = new StreamWriter(s);
using JsonWriter writer= new JsonTextWriter(sr);
var serializer = JsonSerializer.CreateDefault();
serializer.Serialize(writer,data);
}

public bool Exists() => FileSystemHelper.File.Exists(Value);

Expand All @@ -80,21 +94,6 @@ public void WriteAllText(string text)
throw new FileWriteFailedException(ex);
}
}
public void WriteObject(object data, bool createDirectory = true)
{
GetDirectoryPath().Create();
string text;
try
{
text = JsonSerializer.Serialize(data);
}
catch (Exception ex)
{
throw new SerializationFailedException(ex);
}

WriteAllText(text);
}

public BareFileName GetFilenameWithoutExtension() =>
BareFileName.From(FileSystemHelper.Path.GetFileNameWithoutExtension(Value));
Expand Down
10 changes: 6 additions & 4 deletions Core/TableTopCrucible.Core.ValueTypes/ModelFilePath.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using System.IO;
using System.Windows.Media.Media3D;

using HelixToolkit.Wpf;

using TableTopCrucible.Core.ValueTypes.Exceptions;

namespace TableTopCrucible.Core.ValueTypes
Expand All @@ -22,10 +24,10 @@ public static ModelFilePath From(FilePath path)
public FilePath ToFilePath()
=> FilePath.From(Value);

public Model3DGroup Load()
=> new ModelImporter().Load(Value);
public Model3DGroup Load(bool freeze)
=> new ModelImporter() { DefaultMaterial = Materials.LightGray }.Load(Value, null, true);

public ModelVisual3D LoadVisual()
=> new() { Content = Load() };
public ModelVisual3D LoadVisual(bool freeze)
=> new() { Content = Load(freeze) };
}
}
55 changes: 54 additions & 1 deletion Core/TableTopCrucible.Core.ValueTypes/Tag.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
using TableTopCrucible.Core.ValueTypes.Exceptions;
using System;
using System.Linq;
using DynamicData;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using TableTopCrucible.Core.ValueTypes.Exceptions;

namespace TableTopCrucible.Core.ValueTypes
{
Expand All @@ -11,4 +16,52 @@ protected override void Validate(string value)
throw new InvalidValueException("a tag must not be empty");
}
}

public class TagSourceListConverter : JsonConverter<SourceList<Tag>>
{
public override bool CanRead => true;
public override bool CanWrite => true;

public override void WriteJson(JsonWriter writer, SourceList<Tag>? value, JsonSerializer serializer)
{
if (value is null)
return;

var token = JToken.FromObject(value.Items.Select(tag=>tag.Value));

if (token.Type != JTokenType.Object)
token.WriteTo(writer);
else
{
var property = (JProperty)token;
property.AddRange(value.Items.Select(tag => new JValue(tag.Value)));
property.WriteTo(writer);
}
}

public override SourceList<Tag>? ReadJson(JsonReader reader, Type objectType, SourceList<Tag>? existingValue,
bool hasExistingValue,
JsonSerializer serializer)
{
if (objectType != typeof(SourceList<Tag>))
return new();


var obj = JArray.Load(reader);
var tags = obj
.Values<string>()
.Select(tag => (Tag)tag);

if (existingValue is null)
{
var res = new SourceList<Tag>();
res.AddRange(tags);
return res;
}

existingValue.Clear();
existingValue.AddRange(tags);
return existingValue;
}
}
}
17 changes: 16 additions & 1 deletion Core/TableTopCrucible.Core.Wpf.Engine/EngineStarter.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using System.Linq;
using System;
using System.Linq;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using ReactiveUI;
using Splat;
using Splat.Microsoft.Extensions.DependencyInjection;
Expand All @@ -16,6 +18,7 @@ public static class EngineStarter
{
public static void InitializeEngine()
{
initializeJson();
initializeHost();
initializeWpf();
//Application.Current.Startup +=
Expand Down Expand Up @@ -53,5 +56,17 @@ private static void initializeWpf()
.ToList()
.ForEach(Locator.CurrentMutable.RegisterViewsForViewModels);
}

private static void initializeJson()
{
var converters =AssemblyHelper
.GetSolutionClassesOfType<JsonConverter>()
.Select(t => Activator.CreateInstance(t) as JsonConverter)
.ToList();
JsonConvert.DefaultSettings = () => new()
{
Converters = converters
};
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public SimpleNotification()
v => v.Content.Text),
this.WhenAnyValue(
v => v.ViewModel.Content,
c => string.IsNullOrWhiteSpace(c.Value)
c => string.IsNullOrWhiteSpace(c?.Value)
? Visibility.Collapsed
: Visibility.Visible)
.BindTo(this, v => v.Content.Visibility),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;

namespace TableTopCrucible.Core.Wpf.Helper.Converter
{
/// <summary>
/// valid parameters: h(false => hidden) + i(invert result)
/// </summary>
public class BoolVisibilityConverter:IValueConverter
{
public static IValueConverter Instance = new BoolVisibilityConverter();

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var notVisible = Visibility.Collapsed;
var invert = false;
if (parameter is string strPar)
{
if (strPar.ToLower().Contains("i"))
invert = true;
if (strPar.ToLower().Contains("h"))
notVisible = Visibility.Hidden;
}

return value is bool boolVal && (boolVal ^ invert)
? Visibility.Visible
: notVisible;
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
=> value is Visibility.Visible;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace TableTopCrucible.Core.Wpf.Helper
{
public static class VisualTreeNavigationHelper
{

public static T GetByType<T>(this UIElementCollection collection)
where T : FrameworkElement
{
foreach (var child in collection)
{
if (child is T element)
return element;
}

return null;
}
}
}
Loading

0 comments on commit 8580f89

Please sign in to comment.