Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 97 additions & 17 deletions src/DynamoCoreWpf/Controls/StartPage.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Dynamo.Configuration;
using Dynamo.Logging;
using Dynamo.UI.Prompts;
using Dynamo.Utilities;
using Dynamo.ViewModels;
using Dynamo.Wpf.Properties;
Expand All @@ -16,6 +17,7 @@
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Threading.Tasks;
using static Dynamo.Wpf.Interfaces.ResourceNames;
using NotificationObject = Dynamo.Core.NotificationObject;

Expand Down Expand Up @@ -224,36 +226,34 @@ internal StartPageViewModel(DynamoViewModel dynamoViewModel, bool isFirstRun)


private void LoadTemplates()
{
foreach (var templateItem in BuildTemplateListItems())
{
this.TemplateFiles.Add(templateItem);
}
}

private List<StartPageListItem> BuildTemplateListItems()
{
// Retrieve the current Temlates location from Dynamo properties
var templatesDirectory = DynamoViewModel.Model.PathManager.TemplatesDirectory;
var templateItems = new List<StartPageListItem>();

if (Directory.Exists(templatesDirectory))
{
var rootDynPaths = new List<string>();
string[] filePaths = Directory.GetFiles(templatesDirectory, "*.dyn"); // This could change if we move to *dyt

// We only collect the files in the root
if (filePaths.Length != 0)
{
foreach (string path in filePaths)
{
rootDynPaths.Add(path);
}
}

// Make comment on legacy use of StartPage.xaml.cs
if (rootDynPaths.Any())
foreach (var filePath in filePaths)
{
foreach (var filePath in rootDynPaths)
{
AddTemplateListItemFromPath(filePath);
}
templateItems.Add(CreateTemplateListItemFromPath(filePath));
}
}

return templateItems;
}

private void AddTemplateListItemFromPath(string filePath)
private StartPageListItem CreateTemplateListItemFromPath(string filePath)
{
var extension = Path.GetExtension(filePath).ToUpper();
// If not extension specified and code reach here, this means this is still a valid file
Expand All @@ -276,7 +276,29 @@ private void AddTemplateListItemFromPath(string filePath)
ClickAction = StartPageListItem.Action.FilePath,
};

this.TemplateFiles.Add(templateItem);
return templateItem;
}

internal void RefreshTemplateFiles()
{
TemplateFiles.Clear();
LoadTemplates();
}
Comment on lines +282 to +286

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Worth a look, but it may be a minor issue and the solution could be complex. So investigate and address the concern before resolving the conversation

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed with a smaller async refresh. The template file scan and metadata creation now happen off the UI path, and TemplateFiles is updated after the async work completes


internal async Task RefreshTemplateFilesAsync()
{
var templateItems = await Task.Run(BuildTemplateListItems);

TemplateFiles.Clear();
foreach (var templateItem in templateItems)
{
TemplateFiles.Add(templateItem);
}
}

internal void RefreshRecentFiles()
{
RefreshRecentFileList(DynamoViewModel.RecentFiles, true);
}

internal void WalkDirectoryTree(System.IO.DirectoryInfo root, SampleFileEntry rootProperty)
Expand Down Expand Up @@ -654,6 +676,11 @@ private void HandleRegularCommand(StartPageListItem item)
private void HandleFilePath(StartPageListItem item)
{
var path = item.ContextData;
if (HandleMissingFilePath(path))
{
return;
}

// Listed templates: use the same open path as the template file-picker (ShowOpenTemplateDialog),
// i.e. open as a new graph from the file contents, not as the saved template path on disk.
object openArg = IsTemplateFilePath(path)
Expand All @@ -671,6 +698,59 @@ private bool IsTemplateFilePath(string path)
string.Equals(template.ContextData, path, StringComparison.OrdinalIgnoreCase));
}

internal bool HandleMissingFilePath(string path, bool showWarning = true)
{
if (File.Exists(path))
{
return false;
}

if (showWarning)
{
DynamoMessageBox.Show(
DynamoViewModel.Owner,
string.Format(Resources.MessageHomeFileMissing.Replace("\\n", Environment.NewLine), path),
Resources.MessageErrorOpeningFileGeneral,
MessageBoxButton.OK,
MessageBoxImage.Warning);
}

RemoveMissingFilePath(path);

return true;
}

private void RemoveMissingFilePath(string path)
{
RemoveMissingFilePath(RecentFiles, path);
RemoveMissingFilePath(TemplateFiles, path);
RemoveMissingFilePath(DynamoViewModel.RecentFiles, path);
}

private static void RemoveMissingFilePath(ObservableCollection<StartPageListItem> files, string path)
{
var missingFiles = files
.Where(file => string.Equals(file.ContextData, path, StringComparison.OrdinalIgnoreCase))
.ToList();

foreach (var missingFile in missingFiles)
{
files.Remove(missingFile);
}
}

private static void RemoveMissingFilePath(ObservableCollection<string> files, string path)
{
var missingFiles = files
.Where(file => string.Equals(file, path, StringComparison.OrdinalIgnoreCase))
.ToList();

foreach (var missingFile in missingFiles)
{
files.Remove(missingFile);
}
}

private void HandleExternalUrl(StartPageListItem item)
{
System.Diagnostics.Process.Start(new ProcessStartInfo(item.ContextData) { UseShellExecute = true });
Expand Down
9 changes: 9 additions & 0 deletions src/DynamoCoreWpf/Properties/Resources.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions src/DynamoCoreWpf/Properties/Resources.en-US.resx
Original file line number Diff line number Diff line change
Expand Up @@ -4183,6 +4183,9 @@ To make this file into a new template, save it to a different folder, then move
<data name="MessageErrorOpeningInvalidPath" xml:space="preserve">
<value>Invalid file path provided. In case the file is archived, please make sure to extract it before opening.\n{0}</value>
</data>
<data name="MessageHomeFileMissing" xml:space="preserve">
<value>This file is no longer available. It may have been moved, renamed, or deleted.\n{0}</value>
</data>
<data name="GroupContextMenuFreezeGroup" xml:space="preserve">
<value>Freeze Group</value>
</data>
Expand Down
3 changes: 3 additions & 0 deletions src/DynamoCoreWpf/Properties/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -4174,6 +4174,9 @@ To make this file into a new template, save it to a different folder, then move
<data name="MessageErrorOpeningInvalidPath" xml:space="preserve">
<value>Invalid file path provided. In case the file is archived, please make sure to extract it before opening.\n{0}</value>
</data>
<data name="MessageHomeFileMissing" xml:space="preserve">
<value>This file is no longer available. It may have been moved, renamed, or deleted.\n{0}</value>
</data>
<data name="GroupContextMenuFreezeGroup" xml:space="preserve">
<value>Freeze Group</value>
</data>
Expand Down
71 changes: 53 additions & 18 deletions src/DynamoCoreWpf/Views/HomePage/HomePage.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -124,11 +124,28 @@ private void OnDataContextChanged(object sender, DependencyPropertyChangedEventA
}
}

private void DynamoViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
private async void DynamoViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if(e.PropertyName == nameof(startPage.DynamoViewModel.ShowStartPage) && dynWebView?.CoreWebView2 != null)
{
dynWebView.CoreWebView2.ExecuteScriptAsync(@$"window.setShowStartPageChanged('{startPage.DynamoViewModel.ShowStartPage}')");
try
{
if (startPage.DynamoViewModel.ShowStartPage)
{
await startPage.RefreshTemplateFilesAsync();
startPage.RefreshRecentFiles();

await SendTemplateData();
await SendRecentGraphsData();
}

await dynWebView.CoreWebView2.ExecuteScriptAsync(@$"window.setShowStartPageChanged('{startPage.DynamoViewModel.ShowStartPage}')");
}
catch (Exception ex)
{
startPage?.DynamoViewModel?.Model?.Logger?.Log("Failed to update Dynamo Home visibility state.");
startPage?.DynamoViewModel?.Model?.Logger?.Log(ex);
}
}
}
Comment on lines +127 to 150

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a valid concern that should be addressed.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed. I wrapped the awaited Home refresh and WebView update work in DynamoViewModel_PropertyChanged in a try/catch and log any exception through Dynamo’s logger, so failures from SendTemplateData, SendRecentGraphsData, or ExecuteScriptAsync won’t surface as unhandled UI-thread exceptions.


Expand Down Expand Up @@ -338,11 +355,8 @@ private async Task SendSamplesData()
/// </summary>
private async Task SendTemplateData()
{
var items = startPage.TemplateFiles?.DistinctBy(x => x.ContextData).ToList();
if (items != null && items.Any())
{
await LoadTemplates(items);
}
var items = startPage.TemplateFiles?.DistinctBy(x => x.ContextData).ToList() ?? new List<StartPageListItem>();
await LoadTemplates(items);
}

private async Task SendRecentGraphsData()
Expand All @@ -361,14 +375,12 @@ private async Task SendRecentGraphsData()
}

// Load recent files
var recentFiles = startPage.RecentFiles?.DistinctBy(x => x.ContextData).ToList();
if (recentFiles != null && recentFiles.Any())
{
await LoadGraphs(recentFiles);
}
var recentFiles = startPage.RecentFiles?.DistinctBy(x => x.ContextData).ToList() ?? new List<StartPageListItem>();
await LoadGraphs(recentFiles);

if (startPage.DynamoViewModel != null && startPage.DynamoViewModel.RecentFiles != null)
{
startPage.DynamoViewModel.RecentFiles.CollectionChanged -= RecentFiles_CollectionChanged;
startPage.DynamoViewModel.RecentFiles.CollectionChanged += RecentFiles_CollectionChanged;
}
}
Expand Down Expand Up @@ -534,6 +546,11 @@ private void ShowPackagesGuidedTour()

#region Relay Commands
internal void OpenFile(string path)
{
_ = OpenFileAsync(path);
}

private async Task OpenFileAsync(string path)
{
if (String.IsNullOrEmpty(path)) return;
if (DynamoModel.IsTestMode)
Expand All @@ -542,13 +559,31 @@ internal void OpenFile(string path)
return;
}

var dvm = this.startPage.DynamoViewModel;
var openArg = IsListedHomePageTemplate(path)
? (object)Tuple.Create(path, false, true)
: path;
if (dvm.OpenCommand.CanExecute(openArg))
try
{
if (startPage.HandleMissingFilePath(path))
{
var recentFiles = startPage.RecentFiles?.DistinctBy(x => x.ContextData).ToList() ?? new List<StartPageListItem>();
var templateFiles = startPage.TemplateFiles?.DistinctBy(x => x.ContextData).ToList() ?? new List<StartPageListItem>();

await LoadGraphs(recentFiles);
await LoadTemplates(templateFiles);
return;
}

var dvm = this.startPage.DynamoViewModel;
var openArg = IsListedHomePageTemplate(path)
? (object)Tuple.Create(path, false, true)
: path;
if (dvm.OpenCommand.CanExecute(openArg))
{
dvm.OpenCommand.Execute(openArg);
}
}
catch (Exception ex)
{
dvm.OpenCommand.Execute(openArg);
startPage?.DynamoViewModel?.Model?.Logger?.Log("Failed to open file from Dynamo Home.");
startPage?.DynamoViewModel?.Model?.Logger?.Log(ex);
}
}

Expand Down
26 changes: 26 additions & 0 deletions test/DynamoCoreWpfTests/HomePageTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Dynamo.Controls;
Expand Down Expand Up @@ -84,6 +85,31 @@ public void HomePage_NewSettingsAreAddedCorrectly()
Assert.AreEqual(preferences.HomePageSettings.Count, 2);
}

[Test]
public void HandleMissingFilePathRemovesPathFromAuthoritativeRecentFiles()
{
// Arrange
var missingPath = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.dyn");
var vm = View.DataContext as DynamoViewModel;
var startPage = new StartPageViewModel(vm, true);
startPage.RecentFiles.Add(new StartPageListItem(missingPath) { ContextData = missingPath });
vm.RecentFiles.Add(missingPath);

Assert.IsFalse(File.Exists(missingPath));
Assert.IsTrue(vm.RecentFiles.Contains(missingPath));
Assert.IsTrue(vm.Model.PreferenceSettings.RecentFiles.Contains(missingPath));

// Act
var wasMissing = startPage.HandleMissingFilePath(missingPath, false);

// Assert
Assert.IsTrue(wasMissing);
Assert.IsFalse(startPage.RecentFiles.Any(file =>
string.Equals(file.ContextData, missingPath, StringComparison.OrdinalIgnoreCase)));
Assert.IsFalse(vm.RecentFiles.Contains(missingPath));
Assert.IsFalse(vm.Model.PreferenceSettings.RecentFiles.Contains(missingPath));
}

#endregion

#region integration tests
Expand Down
Loading