Files
crosslangdevstudio/ViewModels/NewProjectDialogViewModel.cs
2025-08-31 00:25:32 -05:00

120 lines
3.2 KiB
C#

using System;
using System.Collections.ObjectModel;
using System.IO;
using Avalonia.Markup.Xaml.Templates;
using Avalonia.Media;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using CrossLangDevStudio.Messages;
using CrossLangDevStudio.Views;
namespace CrossLangDevStudio.ViewModels;
public partial class NewProjectDialogViewModel : ViewModelBase
{
public ObservableCollection<CrossLangTemplate> CrossLangTemplates { get; set; } = new ObservableCollection<CrossLangTemplate>();
bool updated = false;
string _name = "";
public string Name
{
get
{
return _name;
}
set
{
updated = true;
SetProperty(ref _name, value, nameof(Name));
}
}
private void SelectProjectType(string name)
{
if (!updated)
{
var newName = name.Replace(" ", "");
int i;
for (i = 1; i < int.MaxValue; i++)
{
string name2 = $"{name}{i}";
if (!Directory.Exists(Path.Combine(ParentDirectory, name2)))
{
Name = name2;
updated = false;
break;
}
}
}
}
[ObservableProperty]
private string _parentDirectory = CrossLangShell.Settings.ProjectDirectory;
CrossLangTemplate? _template = null;
public CrossLangTemplate? SelectedTemplate
{
get
{
return _template;
}
set
{
SetProperty(ref _template, value, nameof(SelectedTemplate));
if (value is not null)
{
SelectProjectType(value.Name);
}
}
}
public NewProjectDialogViewModel()
{
foreach (var item in Directory.EnumerateFiles(Path.Combine(CrossLangShell.CrossLangConfigDirectory, "Templates"), "*.crvm"))
{
CrossLangFile file = new CrossLangFile();
try
{
file.Load(item);
CrossLangTemplates.Add(new CrossLangTemplate(Path.GetFileNameWithoutExtension(item), file));
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
[RelayCommand]
private void OK()
{
if (_template is not null && !string.IsNullOrWhiteSpace(Name) && !string.IsNullOrWhiteSpace(ParentDirectory))
{
var path = Path.Combine(ParentDirectory, Name);
Directory.CreateDirectory(path);
if (CrossLangShell.CreateProject(_template.TemplateName, path))
{
WeakReferenceMessenger.Default.Send(new NewProjectCloseMessage(path));
}
}
}
[RelayCommand]
private void Cancel()
{
WeakReferenceMessenger.Default.Send(new NewProjectCloseMessage(null));
}
}
public partial class CrossLangTemplate(string name,CrossLangFile file) : ObservableObject
{
[ObservableProperty]
private string _name = file.GetTemplatePrettyName();
[ObservableProperty]
private IImage _icon = file.GetIcon(64);
public string TemplateName = name;
}