Skip to content

refactor #59

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 14 commits into
base: main
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
@@ -1,44 +1,31 @@
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading;
using Microsoft.Win32;

namespace WebSearchShortcut.Browsers;

public static class BrowserDiscovery
{
private static readonly object _loadLock = new();
private static bool _isLoaded;
private static List<BrowserInfo> _cachedBrowsers = [];
private static Lazy<BrowserInfo[]> _installedBrowsersCache = CreateInstalledBrowsersCache();
private static Lazy<BrowserInfo[]> CreateInstalledBrowsersCache() =>
new(LoadInstalledBrowsers, LazyThreadSafetyMode.ExecutionAndPublication);
public static IReadOnlyCollection<BrowserInfo> GetAllInstalledBrowsers() => _installedBrowsersCache.Value;

public static List<BrowserInfo> GetAllInstalledBrowsers()
public static void Reload(bool warm = false)
{
if (_isLoaded) return _cachedBrowsers;
var newCache = CreateInstalledBrowsersCache();

lock (_loadLock)
{
if (!_isLoaded)
{
_cachedBrowsers = LoadInstalledBrowsers();
_isLoaded = true;
}
}
Interlocked.Exchange(ref _installedBrowsersCache, newCache);

return _cachedBrowsers;
}

public static void Reload()
{
lock (_loadLock)
{
_cachedBrowsers = LoadInstalledBrowsers();
_isLoaded = true;
}
if (warm)
_ = newCache.Value;
}

private static List<BrowserInfo> LoadInstalledBrowsers()
private static BrowserInfo[] LoadInstalledBrowsers()
{
List<string> progIds = GetAssociatedProgIds();
string[] progIds = GetAssociatedProgIds();
List<BrowserInfo> result = [];

foreach (var progId in progIds)
Expand All @@ -56,9 +43,9 @@ private static List<BrowserInfo> LoadInstalledBrowsers()
return [.. result.OrderBy(b => b.Name, StringComparer.OrdinalIgnoreCase)];
}

private static List<string> GetAssociatedProgIds()
private static string[] GetAssociatedProgIds()
{
HashSet<string> progIdSet = new HashSet<string>();
HashSet<string> progIdSet = [];

progIdSet.UnionWith(ScanProgIdsFromRegistry(
Registry.LocalMachine,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,34 +3,34 @@

namespace WebSearchShortcut.Browsers;

public class BrowserExecutionInfo
internal sealed class BrowserExecutionInfo
{
public string? Path { get; }
public string? ArgumentsPattern { get; }

public BrowserExecutionInfo(WebSearchShortcutItem item)
public BrowserExecutionInfo(WebSearchShortcutDataEntry shortcut)
{
DefaultBrowserProvider.UpdateIfTimePassed();

Path = !string.IsNullOrWhiteSpace(item.BrowserPath)
? item.BrowserPath
Path = !string.IsNullOrWhiteSpace(shortcut.BrowserPath)
? shortcut.BrowserPath
: DefaultBrowserProvider.Path;

string? trimmedArgs;

if (!string.IsNullOrWhiteSpace(item.BrowserArgs))
if (!string.IsNullOrWhiteSpace(shortcut.BrowserArgs))
{
trimmedArgs = item.BrowserArgs.Trim();
trimmedArgs = shortcut.BrowserArgs.Trim();
}
else if (string.IsNullOrWhiteSpace(item.BrowserPath))
else if (string.IsNullOrWhiteSpace(shortcut.BrowserPath))
{
trimmedArgs = DefaultBrowserProvider.ArgumentsPattern;
}
else
{
trimmedArgs = BrowserDiscovery
.GetAllInstalledBrowsers()
.FirstOrDefault(b => string.Equals(b.Path, item.BrowserPath, StringComparison.OrdinalIgnoreCase))
.FirstOrDefault(b => string.Equals(b.Path, shortcut.BrowserPath, StringComparison.OrdinalIgnoreCase))
?.ArgumentsPattern.Trim();
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
namespace WebSearchShortcut.Browsers;

public record BrowserInfo(string Id, string Name, string Path, string ArgumentsPattern);
public sealed record BrowserInfo(string Id, string Name, string Path, string ArgumentsPattern);
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
// See the LICENSE file in the project root for more information.

using System;
using System.Text;
using System.Threading;
using Microsoft.Win32;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,37 +1,31 @@
using Microsoft.CommandPalette.Extensions.Toolkit;
using WebSearchShortcut.Properties;
using WebSearchShortcut.Browsers;
using WebSearchShortcut.Helpers;
using WebSearchShortcut.Properties;

namespace WebSearchShortcut.Commands;

internal sealed partial class OpenHomePageCommand : InvokableCommand
{
// private readonly SettingsManager _settingsManager;
public WebSearchShortcutItem Item;
private readonly WebSearchShortcutDataEntry _shortcut;
private readonly BrowserExecutionInfo _browserInfo;

internal OpenHomePageCommand(WebSearchShortcutItem item)
internal OpenHomePageCommand(WebSearchShortcutDataEntry shortcut)
{
Icon = new IconInfo("\uE721");
Name = StringFormatter.Format(Resources.OpenHomePageCommand_Name, new() { ["engine"] = item.Name });
Item = item;
// Icon = IconHelpers.FromRelativePath("Assets\\WebSearch.png");
// Name = Properties.Resources.open_in_default_browser;
// _settingsManager = settingsManager;
Name = StringFormatter.Format(Resources.OpenHomePage_NameTemplate, new() { ["engine"] = shortcut.Name });
Icon = Icons.Search;
_shortcut = shortcut;
_browserInfo = new BrowserExecutionInfo(shortcut);
}

public override CommandResult Invoke()
{
if (!HomePageLauncher.OpenHomePageWithBrowser(Item))
if (!ShellHelpers.OpenCommandInShell(_browserInfo.Path, _browserInfo.ArgumentsPattern, WebSearchShortcutDataEntry.GetHomePageUrl(_shortcut)))
{
// TODO GH# 138 --> actually display feedback from the extension somewhere.
return CommandResult.KeepOpen();
}

// if (_settingsManager.ShowHistory != Resources.history_none)
// {
// _settingsManager.SaveHistory(new HistoryItem(Arguments, DateTime.Now));
// }

return CommandResult.Dismiss();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,24 @@ namespace WebSearchShortcut.Commands;

internal sealed partial class SearchWebCommand : InvokableCommand
{
private readonly string _query;
private readonly WebSearchShortcutDataEntry _shortcut;
private readonly BrowserExecutionInfo _browserInfo;
// private readonly SettingsManager _settingsManager;
public string Arguments { get; internal set; } = string.Empty;
public WebSearchShortcutItem Item;
private readonly BrowserExecutionInfo BrowserInfo;

internal SearchWebCommand(string arguments, WebSearchShortcutItem item)
public SearchWebCommand(WebSearchShortcutDataEntry shortcut, string query)
{
Arguments = arguments;
BrowserInfo = new BrowserExecutionInfo(item);
Icon = new IconInfo("\uE721");
Name = StringFormatter.Format(Resources.SearchWebCommand_Name, new() { ["engine"] = item.Name, ["query"] = arguments });
Item = item;
// Icon = IconHelpers.FromRelativePath("Assets\\WebSearch.png");
// Name = Properties.Resources.open_in_default_browser;
Name = StringFormatter.Format(Resources.SearchQuery_NameTemplate, new() { ["engine"] = shortcut.Name, ["query"] = query });
Icon = Icons.Search;
_query = query;
_shortcut = shortcut;
_browserInfo = new BrowserExecutionInfo(shortcut);
// _settingsManager = settingsManager;
}

public override CommandResult Invoke()
{
if (!ShellHelpers.OpenCommandInShell(BrowserInfo.Path, BrowserInfo.ArgumentsPattern, $"{WebSearchShortcutItem.GetSearchUrl(Item, Arguments)}"))
if (!ShellHelpers.OpenCommandInShell(_browserInfo.Path, _browserInfo.ArgumentsPattern, WebSearchShortcutDataEntry.GetSearchUrl(_shortcut, _query)))
{
// TODO GH# 138 --> actually display feedback from the extension somewhere.
return CommandResult.KeepOpen();
Expand Down
66 changes: 27 additions & 39 deletions CmdPalWebSearchShortcut/WebSearchShortcut/Forms/AddShortcutForm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,18 @@ namespace WebSearchShortcut;

internal sealed partial class AddShortcutForm : FormContent
{
internal event TypedEventHandler<object, WebSearchShortcutItem>? AddedCommand;
private readonly WebSearchShortcutDataEntry? _shortcut;

private readonly WebSearchShortcutItem? _item;

public AddShortcutForm(WebSearchShortcutItem? item)
public AddShortcutForm(WebSearchShortcutDataEntry? shortcut)
{
_item = item;
var name = _item?.Name ?? string.Empty;
var url = _item?.Url ?? string.Empty;
var suggestionProvider = _item?.SuggestionProvider ?? string.Empty;
var replaceWhitespace = _item?.ReplaceWhitespace ?? string.Empty;
var homePage = _item?.HomePage ?? string.Empty;
var browserPath = _item?.BrowserPath ?? string.Empty;
var browserArgs = _item?.BrowserArgs ?? string.Empty;
_shortcut = shortcut;
var name = shortcut?.Name ?? string.Empty;
var url = shortcut?.Url ?? string.Empty;
var suggestionProvider = shortcut?.SuggestionProvider ?? string.Empty;
var replaceWhitespace = shortcut?.ReplaceWhitespace ?? string.Empty;
var homePage = shortcut?.HomePage ?? string.Empty;
var browserPath = shortcut?.BrowserPath ?? string.Empty;
var browserArgs = shortcut?.BrowserArgs ?? string.Empty;

TemplateJson = $$"""
{
Expand Down Expand Up @@ -59,10 +57,10 @@ public AddShortcutForm(WebSearchShortcutItem? item)
"title": {{JsonSerializer.Serialize(Resources.AddShortcutForm_SuggestionProviderNone, AppJsonSerializerContext.Default.String)}},
"value": ""
},
{{Suggestions.SuggestionProviders.Keys.Select(k => $$"""
{{SuggestionsRegistry.ProviderNames.Select(key => $$"""
{
"title": {{JsonSerializer.Serialize(k, AppJsonSerializerContext.Default.String)}},
"value": {{JsonSerializer.Serialize(k, AppJsonSerializerContext.Default.String)}}
"title": {{JsonSerializer.Serialize(key, AppJsonSerializerContext.Default.String)}},
"value": {{JsonSerializer.Serialize(key, AppJsonSerializerContext.Default.String)}}
}
""").Aggregate((a, b) => a + "," + b)}}
],
Expand Down Expand Up @@ -139,33 +137,23 @@ public AddShortcutForm(WebSearchShortcutItem? item)
""";
}

public override CommandResult SubmitForm(string payload)
{
var formInput = JsonNode.Parse(payload);
if (formInput == null)
{
return CommandResult.GoHome();
}
internal event TypedEventHandler<object, WebSearchShortcutDataEntry>? AddedCommand;

// get the name and url out of the values
var formName = formInput["name"] ?? string.Empty;
var formUrl = formInput["url"] ?? string.Empty;
var formSuggestionProvider = formInput["suggestionProvider"] ?? string.Empty;
var formReplaceWhitespace = formInput["replaceWhitespace"] ?? string.Empty;
var formHomePage = formInput["homePage"] ?? string.Empty;
var formBrowserPath = formInput["browserPath"] ?? string.Empty;
var formBrowserArgs = formInput["browserArgs"] ?? string.Empty;
public override CommandResult SubmitForm(string inputs)
{
var root = JsonNode.Parse(inputs);
if (root is null) return CommandResult.GoHome();

var updated = _item ?? new WebSearchShortcutItem();
updated.Name = formName.ToString();
updated.Url = formUrl.ToString();
updated.SuggestionProvider = formSuggestionProvider.ToString();
updated.ReplaceWhitespace = formReplaceWhitespace.ToString();
updated.HomePage = formHomePage.ToString();
updated.BrowserPath = formBrowserPath.ToString();
updated.BrowserArgs = formBrowserArgs.ToString();
var shortcut = _shortcut ?? new WebSearchShortcutDataEntry();
shortcut.Name = root["name"]?.GetValue<string>() ?? string.Empty;
shortcut.Url = root["url"]?.GetValue<string>() ?? string.Empty;
shortcut.SuggestionProvider = root["suggestionProvider"]?.GetValue<string>() ?? string.Empty;
shortcut.ReplaceWhitespace = root["replaceWhitespace"]?.GetValue<string>() ?? string.Empty;
shortcut.HomePage = root["homePage"]?.GetValue<string>() ?? string.Empty;
shortcut.BrowserPath = root["browserPath"]?.GetValue<string>() ?? string.Empty;
shortcut.BrowserArgs = root["browserArgs"]?.GetValue<string>() ?? string.Empty;

AddedCommand?.Invoke(this, updated);
AddedCommand?.Invoke(this, shortcut);
return CommandResult.GoHome();
}
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

namespace WebSearchShortcut.Helpers;

internal static class JsonPrettyFormatter
public static class JsonPrettyFormatter
{
private static readonly JsonWriterOptions PrettyWriterOptions = new()
{
Expand All @@ -18,11 +18,15 @@ internal static class JsonPrettyFormatter
public static string ToPrettyJson<T>(T obj, JsonTypeInfo<T> typeInfo)
{
byte[] utf8Json = JsonSerializer.SerializeToUtf8Bytes(obj, typeInfo);

using JsonDocument doc = JsonDocument.Parse(utf8Json);

using var output = new MemoryStream();
using var writer = new Utf8JsonWriter(output, PrettyWriterOptions);

doc.RootElement.WriteTo(writer);
writer.Flush();

return Encoding.UTF8.GetString(output.ToArray());
}
}
2 changes: 1 addition & 1 deletion CmdPalWebSearchShortcut/WebSearchShortcut/JSONContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ namespace WebSearchShortcut;

[JsonSourceGenerationOptions(IncludeFields = true)]
[JsonSerializable(typeof(Storage))]
[JsonSerializable(typeof(WebSearchShortcutItem))]
[JsonSerializable(typeof(WebSearchShortcutDataEntry))]
internal partial class AppJsonSerializerContext : JsonSerializerContext
{
}
Loading