Skip to content

Commit

Permalink
Aktualizacja - ustawienia
Browse files Browse the repository at this point in the history
Sporo zmian dotyczących wczytywania tablic
  • Loading branch information
mateusz-kierepka-hl committed Oct 10, 2024
1 parent 43364ab commit 2906c0e
Show file tree
Hide file tree
Showing 12 changed files with 457 additions and 183 deletions.
4 changes: 2 additions & 2 deletions ChatAAC/App.axaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ private void OpenConfigWindow()
{
var configWindow = new ConfigWindow()
{
DataContext = new ConfigViewModel()
DataContext = ConfigViewModel.Instance
};
var mainWindow = (Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)
?.MainWindow;
Expand All @@ -52,7 +52,7 @@ private void OpenAboutWindow()
{
DataContext = new AboutViewModel()
};
var mainWindow = (Application.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)
var mainWindow = (Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)
?.MainWindow;
if (mainWindow != null)
aboutWindow.ShowDialog(mainWindow);
Expand Down
31 changes: 31 additions & 0 deletions ChatAAC/Converters/StringConverterAllowNumber.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using System;
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace ChatAAC.Converters;

public class StringConverterAllowNumber : JsonConverter<string>
{
public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return reader.TokenType switch
{
// Obsługa wartości null
JsonTokenType.Null => null,
// Obsługa ciągów znaków
JsonTokenType.String => reader.GetString(),
// Obsługa liczb
JsonTokenType.Number => reader.GetDouble().ToString(CultureInfo.InvariantCulture),
// Obsługa wartości logicznych
JsonTokenType.True or JsonTokenType.False => reader.GetBoolean().ToString(),
_ => throw new JsonException(
$"Nieoczekiwany typ tokenu {reader.TokenType} podczas parsowania ciągu znaków.")
};
}

public override void Write(Utf8JsonWriter writer, string? value, JsonSerializerOptions options)
{
writer.WriteStringValue(value);
}
}
21 changes: 21 additions & 0 deletions ChatAAC/Converters/StringNotEmptyToBoolConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using Avalonia.Data.Converters;
using System;
using System.Globalization;

namespace ChatAAC.Converters
{
public class StringNotEmptyToBoolConverter : IValueConverter
{
public static StringNotEmptyToBoolConverter Instance { get; } = new StringNotEmptyToBoolConverter();

public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
return !string.IsNullOrEmpty(value as string);
}

public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
17 changes: 17 additions & 0 deletions ChatAAC/Models/ConfigData.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System.Collections.Generic;

namespace ChatAAC.Models;

public class ConfigData
{
public string OllamaAddress { get; set; } = string.Empty;
public string SelectedModel { get; set; } = string.Empty;
public bool ShowSex { get; set; }
public bool ShowViolence { get; set; }
public bool ShowAac { get; set; }
public bool ShowSchematic { get; set; }
public string? SelectedLanguage { get; set; }
public int LoadedIconsCount { get; set; }
public string DefaultBoardPath { get; set; } = string.Empty;
public List<string> BoardPaths { get; set; } = new();
}
4 changes: 1 addition & 3 deletions ChatAAC/Models/Obf/Button.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@ namespace ChatAAC.Models.Obf;
// Class for Button
public class Button
{
[JsonPropertyName("id")]
[JsonConverter(typeof(IntFromStringConverter))]
public int? Id { get; set; }
[JsonPropertyName("id")] public string Id { get; set; } = string.Empty;

[JsonPropertyName("label")] public string Label { get; set; } = string.Empty;

Expand Down
3 changes: 2 additions & 1 deletion ChatAAC/Models/Obf/Grid.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;

Expand All @@ -9,5 +10,5 @@ public class Grid

[JsonPropertyName("columns")] public int Columns { get; set; }

[JsonPropertyName("order")] public List<List<int?>> Order { get; set; } = new();
[JsonPropertyName("order")] public string?[][] Order { get; set; } = [];
}
94 changes: 65 additions & 29 deletions ChatAAC/Models/Obf/ObfLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@ public static partial class ObfLoader
{
PropertyNameCaseInsensitive = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
Converters = { new IntFromStringConverter() }
Converters =
{
new StringConverterAllowNumber(),
new IntFromStringConverter()
}
};

public static string ObfCacheDirectory { get; } = Path.Combine(
Expand Down Expand Up @@ -59,19 +63,19 @@ public static partial class ObfLoader
return null;
}


// Pobierz katalog bazowy oryginalnego pliku OBF
var obfBaseDirectory = Path.GetDirectoryName(filePath) ?? string.Empty;

// Przetwarzaj obrazy w pliku OBF, przekazując katalog bazowy
await ProcessImagesAsync(obfFile, obfBaseDirectory);


foreach (var button in obfFile.Buttons)
{
// Find the corresponding image
// Znajdź odpowiadający obraz
button.Image = obfFile.Images.Find(image => image.Id == button.ImageId);
if (button.Image is null)
if (button.Image == null)
{
Console.WriteLine($"Brak obrazu dla przycisku o ID: {button.Id}");
}
Expand Down Expand Up @@ -124,16 +128,16 @@ private static async Task ProcessImagesAsync(ObfFile obfFile, string obfBaseDire
}

// Próba zapisania obrazu z różnych źródeł
if (!await SaveImageFromDataAsync(image, image.ImagePath))
{
if (!await SaveImageFromUrlAsync(image, image.ImagePath))
{
if (!await SaveImageFromPathAsync(image, image.ImagePath, obfBaseDirectory))
{
LogError($"Nie udało się zapisać obrazu: {image.Id}");
}
}
}
if (!string.IsNullOrEmpty(image.Data) || !string.IsNullOrWhiteSpace(image.DataUrl))
if (await SaveImageFromDataAsync(image, image.ImagePath))
continue;

if (!string.IsNullOrEmpty(image.Url))
if (await SaveImageFromUrlAsync(image, image.ImagePath))
continue;

if (await SaveImageFromPathAsync(image, image.ImagePath, obfBaseDirectory)) continue;
LogError($"Nie udało się zapisać obrazu: {image.Id}");
}
}

Expand All @@ -152,12 +156,23 @@ private static string GenerateImageFileName(Image image)
/// </summary>
private static async Task<bool> SaveImageFromDataAsync(Image image, string destinationPath)
{
if (string.IsNullOrEmpty(image.Data))
return false;
var data = image.Data;

if (!(string.IsNullOrEmpty(image.DataUrl)))
{
var response = await HttpClient.GetAsync(image.DataUrl);
if (response.IsSuccessStatusCode)
{
data = await response.Content.ReadAsStringAsync();
Log($"Downloaded image data from URL: {destinationPath}");
}
}

if (string.IsNullOrEmpty(data)) return false;

try
{
var base64Data = ExtractBase64Data(image.Data);
var base64Data = ExtractBase64Data(data);
var imageBytes = Convert.FromBase64String(base64Data);
await File.WriteAllBytesAsync(destinationPath, imageBytes);
Log($"Saved image from Base64 data: {destinationPath}");
Expand Down Expand Up @@ -188,11 +203,9 @@ private static async Task<bool> SaveImageFromUrlAsync(Image image, string destin
Log($"Downloaded and saved image from URL: {destinationPath}");
return true;
}
else
{
LogError($"Failed to download image from URL: {image.Url}. Status code: {response.StatusCode}");
return false;
}

LogError($"Failed to download image from URL: {image.Url}. Status code: {response.StatusCode}");
return false;
}
catch (Exception ex)
{
Expand All @@ -202,7 +215,7 @@ private static async Task<bool> SaveImageFromUrlAsync(Image image, string destin
}

/// <summary>
/// Attempts to save the image from a file path, using only the filename.
/// Próbuje zapisać obraz z podanej ścieżki, używając tylko nazwy pliku.
/// </summary>
private static async Task<bool> SaveImageFromPathAsync(Image image, string destinationPath,
string obfBaseDirectory)
Expand All @@ -227,9 +240,12 @@ private static async Task<bool> SaveImageFromPathAsync(Image image, string desti
return false;
}

if (File.Exists(fullImagePath))
// Sprawdź asynchronicznie, czy plik istnieje
bool fileExists = await Task.Run(() => File.Exists(fullImagePath));
if (fileExists)
{
File.Copy(fullImagePath, destinationPath);
// Skopiuj plik asynchronicznie
await CopyFileAsync(fullImagePath, destinationPath);
Log($"Skopiowano obraz z {fullImagePath} do {destinationPath}");
return true;
}
Expand All @@ -246,9 +262,10 @@ private static async Task<bool> SaveImageFromPathAsync(Image image, string desti

foreach (var path in potentialPaths)
{
if (File.Exists(path))
bool exists = await Task.Run(() => File.Exists(path));
if (exists)
{
File.Copy(path, destinationPath);
await CopyFileAsync(path, destinationPath);
Log($"Skopiowano obraz z {path} do {destinationPath}");
return true;
}
Expand All @@ -264,7 +281,25 @@ private static async Task<bool> SaveImageFromPathAsync(Image image, string desti
return false;
}
}


private static async Task CopyFileAsync(string sourceFilePath, string destinationFilePath)
{
const int bufferSize = 81920; // Domyślny rozmiar bufora

// Upewnij się, że katalog docelowy istnieje
var destinationDirectory = Path.GetDirectoryName(destinationFilePath);
if (!string.IsNullOrEmpty(destinationDirectory) && !Directory.Exists(destinationDirectory))
{
Directory.CreateDirectory(destinationDirectory);
}

await using var sourceStream = new FileStream(sourceFilePath, FileMode.Open, FileAccess.Read, FileShare.Read,
bufferSize, useAsync: true);
await using var destinationStream = new FileStream(destinationFilePath, FileMode.Create, FileAccess.Write,
FileShare.None, bufferSize, useAsync: true);
await sourceStream.CopyToAsync(destinationStream);
}

private static string SanitizeImagePath(string imagePath)
{
// Zamień backslashes na slashe
Expand All @@ -280,6 +315,7 @@ private static string SanitizeImagePath(string imagePath)
// Pomijamy niebezpieczne segmenty
continue;
}

sanitizedSegments.Add(segment);
}

Expand Down
Loading

0 comments on commit 2906c0e

Please sign in to comment.