Skip to content

Commit

Permalink
Merge pull request #32 from zadjii-msft/dev/crutkas/moreCleanup
Browse files Browse the repository at this point in the history
Bookmarks so it can serialize / deserialize via objects
  • Loading branch information
crutkas authored Sep 4, 2024
2 parents b5a4829 + 6de494d commit 8d65662
Show file tree
Hide file tree
Showing 11 changed files with 143 additions and 155 deletions.
179 changes: 84 additions & 95 deletions src/modules/cmdpal/src/WindowsCommandPalette/BookmarkActions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Diagnostics.CodeAnalysis;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using Microsoft.Bot.AdaptiveExpressions.Core;
using Microsoft.Windows.CommandPalette.Extensions;
using Microsoft.Windows.CommandPalette.Extensions.Helpers;
using Windows.Foundation;
using Windows.System;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace Run.Bookmarks;

Expand All @@ -21,8 +21,8 @@ internal sealed class OpenInTerminalAction : InvokableCommand

public OpenInTerminalAction(string folder)
{
this.Name = "Open in Terminal";
this._folder = folder;
Name = "Open in Terminal";
_folder = folder;
}

public override ICommandResult Invoke()
Expand All @@ -34,7 +34,7 @@ public override ICommandResult Invoke()
{
FileName = "wt.exe",
Arguments = $"-d \"{_folder}\"",
UseShellExecute = true
UseShellExecute = true,
};
System.Diagnostics.Process.Start(startInfo);
}
Expand All @@ -47,11 +47,16 @@ public override ICommandResult Invoke()
}
}

internal sealed class BookmarkData
public class BookmarkData
{
internal string name = string.Empty;
internal string bookmark = string.Empty;
internal string type = string.Empty;
public string Name = string.Empty;
public string Bookmark = string.Empty;
public string Type = string.Empty;
}

public sealed class Bookmarks
{
public List<BookmarkData> Data { get; set; } = [];
}

[JsonSourceGenerationOptions(WriteIndented = true)]
Expand Down Expand Up @@ -149,61 +154,48 @@ public override ActionResult SubmitForm(string payload)
bookmarkType = "web";
}

var formData = new BookmarkData()
{
Name = formName.ToString(),
Bookmark = formBookmark.ToString(),
Type = bookmarkType,
};

// Construct a new json blob with the name and url
var json = string.Empty;
var jsonPath = BookmarksActionProvider.StateJsonPath();
Bookmarks data;

// if the file exists, load it and append the new item
if (File.Exists(BookmarksActionProvider.StateJsonPath()))
if (File.Exists(jsonPath))
{
var state = File.ReadAllText(BookmarksActionProvider.StateJsonPath());
var jsonState = JsonNode.Parse(state);
var items = jsonState?["items"]?.AsArray();

if (items != null)
{
// var items = jsonState["items"];
var newItem = new JsonObject();
newItem["name"] = formName;
newItem["bookmark"] = formBookmark;
var formData = new BookmarkData()
{
name = formName.ToString(),
bookmark = formBookmark.ToString(),
type = bookmarkType,
};

items.Add(JsonSerializer.SerializeToNode(formData, typeof(BookmarkData), SourceGenerationContext.Default));
var jsonStringReading = File.ReadAllText(jsonPath);

json = jsonState?.ToString();
}
data = JsonSerializer.Deserialize<Bookmarks>(jsonStringReading);
}
else
{
json = $$"""
{
"items": [
{
"name": "{{formName}}",
"type": "{{bookmarkType}}",
"bookmark": "{{formBookmark}}",
"hasPlaceholder":"{{hasPlaceholder}}"
}
]
}
""";
data = new Bookmarks();
}

File.WriteAllText(BookmarksActionProvider.StateJsonPath(), json);
data.Data.Add(formData);
var options = new JsonSerializerOptions()
{
IncludeFields = true,
};
var jsonString = JsonSerializer.Serialize<Bookmarks>(data, options);

File.WriteAllText(BookmarksActionProvider.StateJsonPath(), jsonString);
AddedAction?.Invoke(this, null);
return ActionResult.GoHome();
}
}

internal sealed class AddBookmarkPage : Microsoft.Windows.CommandPalette.Extensions.Helpers.FormPage
internal sealed class AddBookmarkPage : FormPage
{
private readonly AddBookmarkForm _addBookmark = new();

internal event TypedEventHandler<object, object?>? AddedAction {
internal event TypedEventHandler<object, object?>? AddedAction
{
add => _addBookmark.AddedAction += value;
remove => _addBookmark.AddedAction -= value;
}
Expand All @@ -217,23 +209,25 @@ public AddBookmarkPage()
}
}

internal sealed class BookmarkPlaceholderForm: Microsoft.Windows.CommandPalette.Extensions.Helpers.Form
internal sealed class BookmarkPlaceholderForm : Microsoft.Windows.CommandPalette.Extensions.Helpers.Form
{
private List<string> placeholderNames { get; init; }
private readonly List<string> _placeholderNames;

private readonly string _Bookmark = string.Empty;
private readonly string _bookmark = string.Empty;

// TODO pass in an array of placeholders
public BookmarkPlaceholderForm(string name, string url, string type) {
_Bookmark = url;
public BookmarkPlaceholderForm(string name, string url, string type)
{
_bookmark = url;
Regex r = new Regex(Regex.Escape("{") + "(.*?)" + Regex.Escape("}"));
MatchCollection matches = r.Matches(url);
placeholderNames = matches.Select(m => m.Groups[1].Value).ToList();
_placeholderNames = matches.Select(m => m.Groups[1].Value).ToList();
}

public override string TemplateJson()
{
var inputs = placeholderNames.Select(p => {
var inputs = _placeholderNames.Select(p =>
{
return $$"""
{
"type": "Input.Text",
Expand Down Expand Up @@ -276,7 +270,7 @@ public override string TemplateJson()

public override ActionResult SubmitForm(string payload)
{
var target = _Bookmark;
var target = _bookmark;

// parse the submitted JSON and then open the link
var formInput = JsonNode.Parse(payload);
Expand Down Expand Up @@ -314,7 +308,7 @@ public override ActionResult SubmitForm(string payload)
}
}

internal sealed class BookmarkPlaceholderPage : Microsoft.Windows.CommandPalette.Extensions.Helpers.FormPage
internal sealed class BookmarkPlaceholderPage : FormPage
{
private readonly IForm _bookmarkPlaceholder;

Expand All @@ -330,11 +324,11 @@ public BookmarkPlaceholderPage(string name, string url, string type)

public class UrlAction : InvokableCommand
{
private bool _containsPlaceholder => _url.Contains('{') && _url.Contains('}');
private bool IsContainsPlaceholder => _url.Contains('{') && _url.Contains('}');

public string Type { get; }

public string Url { get; }
public string Url { get; }

private readonly string _url;

Expand Down Expand Up @@ -428,12 +422,12 @@ public class BookmarksActionProvider : ICommandProvider

public BookmarksActionProvider()
{
_addNewCommand.AddedAction += _addNewCommand_AddedAction;
_addNewCommand.AddedAction += AddNewCommand_AddedAction;
}

private void _addNewCommand_AddedAction(object sender, object? args)
private void AddNewCommand_AddedAction(object sender, object? args)
{
_addNewCommand.AddedAction += _addNewCommand_AddedAction;
_addNewCommand.AddedAction += AddNewCommand_AddedAction;
_commands.Clear();
}

Expand All @@ -447,42 +441,37 @@ private void LoadCommands()
collected.Add(_addNewCommand);
try
{
// Open state.json from the disk and read it
var state = File.ReadAllText(BookmarksActionProvider.StateJsonPath());

// Parse the JSON
var json = JsonNode.Parse(state);
var jsonObject = json?.AsObject();
if (jsonObject == null)
{
return;
}

if (!jsonObject.ContainsKey("items"))
{
return;
}

var itemsJson = jsonObject["items"]?.AsArray();
if (itemsJson == null)
var jsonFile = StateJsonPath();
if (File.Exists(jsonFile))
{
return;
}
// Open state.json from the disk and read it
var jsonString = File.ReadAllText(jsonFile);
var options = new JsonSerializerOptions()
{
IncludeFields = true,
};
var data = JsonSerializer.Deserialize<Bookmarks>(jsonString, options);

foreach (var item in itemsJson)
{
var nameToken = item?["name"];
var urlToken = item?["bookmark"];
var typeToken = item?["type"];
if (nameToken == null || urlToken == null || typeToken == null)
if (data != null)
{
continue;
var items = data?.Data;
foreach (var item in items)
{
var nameToken = item.Name;
var urlToken = item.Bookmark;
var typeToken = item.Type;

if (nameToken == null || urlToken == null || typeToken == null)
{
continue;
}

var name = nameToken.ToString();
var url = urlToken.ToString();
var type = typeToken.ToString();
collected.Add((url.Contains('{') && url.Contains('}')) ? new BookmarkPlaceholderPage(name, url, type) : new UrlAction(name, url, type));
}
}

var name = nameToken.ToString();
var url = urlToken.ToString();
var type = typeToken.ToString();
collected.Add((url.Contains('{') && url.Contains('}')) ? new BookmarkPlaceholderPage(name, url, type) : new UrlAction(name, url, type));
}
}
catch (Exception ex)
Expand Down Expand Up @@ -515,11 +504,11 @@ public IListItem[] TopLevelCommands()
}

// listItem.Subtitle = "Bookmark";
if (action is AddBookmarkPage) { }
else
if (action is not AddBookmarkPage)
{
listItem.Tags = [
new Tag() {
new Tag()
{
Text = "Bookmark",

// Icon = new("🔗"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ await Task.Run(() =>
{
try
{
appManager.ActivateApplication(amuid, /*queryArguments*/ "", noFlags, out var unusedPid);
appManager.ActivateApplication(amuid, /*queryArguments*/ string.Empty, noFlags, out var unusedPid);
}
catch (System.Exception)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,17 @@ namespace WindowsCommandPalette.BuiltinCommands.AllApps;

internal sealed class AppItem
{
public string Name { get; set; } = "";
public string Subtitle { get; set; } = "";
public string IcoPath { get; set; } = "";
public string ExePath { get; set; } = "";
public string DirPath { get; set; } = "";
public string UserModelId { get; set; } = "";
public string Name { get; set; } = string.Empty;

public string Subtitle { get; set; } = string.Empty;

public string IcoPath { get; set; } = string.Empty;

public string ExePath { get; set; } = string.Empty;

public string DirPath { get; set; } = string.Empty;

public string UserModelId { get; set; } = string.Empty;

public AppItem()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@ namespace WindowsCommandPalette.BuiltinCommands.AllApps;

internal sealed class AppListItem : ListItem
{
private readonly AppItem app;
public AppListItem(AppItem app) : base(new AppAction(app))
private readonly AppItem _app;

public AppListItem(AppItem app)
: base(new AppAction(app))
{
this.app = app;
this._app = app;
this.Title = app.Name;
this.Subtitle = app.Subtitle;
this.Details = new Details() { Title = this.Title, HeroImage = this.Command.Icon, Body = "### App" };
Expand All @@ -21,7 +23,7 @@ public AppListItem(AppItem app) : base(new AppAction(app))
{
// Win32 exe or other non UWP app
this._MoreCommands = [
new CommandContextItem(new OpenPathAction(app.DirPath){ Name = "Open location", Icon=new("\ue838") })
new CommandContextItem(new OpenPathAction(app.DirPath) { Name = "Open location", Icon=new("\ue838") })
];
}
else
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,23 +25,9 @@ public IEnumerable<IPackage> FindPackagesForCurrentUser()
{
var pkgs = _packageManager.FindPackagesForUser(user.Value);

return pkgs.Select(TryGetWrapperFromPackage).Where(package => package != null);
return pkgs.Select(PackageWrapper.GetWrapperFromPackage).Where(package => package != null);
}

return Enumerable.Empty<IPackage>();
}

private static PackageWrapper TryGetWrapperFromPackage(Package package)
{
try
{
return PackageWrapper.GetWrapperFromPackage(package);
}
catch (Exception )
{
// Log.Error(e.Message, typeof(PackageManagerWrapper));
}

return null;
}
}
Loading

0 comments on commit 8d65662

Please sign in to comment.