Skip to content

Commit 3ef2c4e

Browse files
committed
Use Main.Context for code quality
1 parent 54b35d1 commit 3ef2c4e

12 files changed

+63
-91
lines changed

Plugins/Flow.Launcher.Plugin.BrowserBookmark/Main.cs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,8 @@ public void Init(PluginInitContext context)
3737

3838
var tempPath = SetupTempDirectory();
3939

40-
_bookmarkLoader = new BookmarkLoaderService(Context, _settings, tempPath);
41-
_faviconService = new FaviconService(Context, _settings, tempPath);
40+
_bookmarkLoader = new BookmarkLoaderService(_settings, tempPath);
41+
_faviconService = new FaviconService(_settings, tempPath);
4242
_bookmarkWatcher = new BookmarkWatcherService();
4343
_bookmarkWatcher.OnBookmarkFileChanged += OnBookmarkFileChanged;
4444

@@ -89,7 +89,7 @@ public List<Result> Query(Query query)
8989
return bookmarks.Select(b => CreateResult(b, 0)).ToList();
9090
}
9191

92-
private Result CreateResult(Bookmark bookmark, int score) => new()
92+
private static Result CreateResult(Bookmark bookmark, int score) => new()
9393
{
9494
Title = bookmark.Name,
9595
SubTitle = bookmark.Url,
@@ -179,7 +179,7 @@ private async Task ReloadFirefoxBookmarksAsync()
179179
Context.API.LogInfo(nameof(Main), "Starting periodic reload of Firefox bookmarks.");
180180

181181
var firefoxLoaders = _bookmarkLoader.GetFirefoxBookmarkLoaders().ToList();
182-
if (!firefoxLoaders.Any())
182+
if (firefoxLoaders.Count == 0)
183183
{
184184
Context.API.LogInfo(nameof(Main), "No Firefox bookmark loaders enabled, skipping reload.");
185185
return;
@@ -210,7 +210,7 @@ private async Task ReloadFirefoxBookmarksAsync()
210210
var results = await Task.WhenAll(tasks);
211211
var successfulResults = results.Where(r => r.Success).ToList();
212212

213-
if (!successfulResults.Any())
213+
if (successfulResults.Count == 0)
214214
{
215215
Context.API.LogInfo(nameof(Main), "No Firefox bookmarks successfully reloaded.");
216216
return;

Plugins/Flow.Launcher.Plugin.BrowserBookmark/Services/BookmarkLoaderService.cs

Lines changed: 14 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,11 @@ namespace Flow.Launcher.Plugin.BrowserBookmark.Services;
1212

1313
public class BookmarkLoaderService
1414
{
15-
private readonly PluginInitContext _context;
1615
private readonly Settings _settings;
1716
private readonly string _tempPath;
1817

19-
public BookmarkLoaderService(PluginInitContext context, Settings settings, string tempPath)
18+
public BookmarkLoaderService(Settings settings, string tempPath)
2019
{
21-
_context = context;
2220
_settings = settings;
2321
_tempPath = tempPath;
2422
}
@@ -44,7 +42,7 @@ public BookmarkLoaderService(PluginInitContext context, Settings settings, strin
4442
}
4543
catch (Exception e)
4644
{
47-
_context.API.LogException(nameof(BookmarkLoaderService), $"Failed to load bookmarks from {loader.Name}.", e);
45+
Main.Context.API.LogException(nameof(BookmarkLoaderService), $"Failed to load bookmarks from {loader.Name}.", e);
4846
}
4947
});
5048

@@ -60,55 +58,52 @@ public IEnumerable<IBookmarkLoader> GetBookmarkLoaders(ConcurrentBag<string> dis
6058

6159
public IEnumerable<IBookmarkLoader> GetChromiumBookmarkLoaders(ConcurrentBag<string> discoveredBookmarkFiles)
6260
{
63-
var logAction = (string tag, string msg, Exception? ex) => _context.API.LogException(tag, msg, ex);
6461
var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
6562

6663
if (_settings.LoadChromeBookmark)
6764
{
6865
var path = Path.Combine(localAppData, @"Google\Chrome\User Data");
6966
if (Directory.Exists(path))
70-
yield return new ChromiumBookmarkLoader("Google Chrome", path, logAction, discoveredBookmarkFiles);
67+
yield return new ChromiumBookmarkLoader("Google Chrome", path, discoveredBookmarkFiles);
7168

7269
var canaryPath = Path.Combine(localAppData, @"Google\Chrome SxS\User Data");
7370
if (Directory.Exists(canaryPath))
74-
yield return new ChromiumBookmarkLoader("Google Chrome Canary", canaryPath, logAction, discoveredBookmarkFiles);
71+
yield return new ChromiumBookmarkLoader("Google Chrome Canary", canaryPath, discoveredBookmarkFiles);
7572
}
7673

7774
if (_settings.LoadEdgeBookmark)
7875
{
7976
var path = Path.Combine(localAppData, @"Microsoft\Edge\User Data");
8077
if (Directory.Exists(path))
81-
yield return new ChromiumBookmarkLoader("Microsoft Edge", path, logAction, discoveredBookmarkFiles);
78+
yield return new ChromiumBookmarkLoader("Microsoft Edge", path, discoveredBookmarkFiles);
8279

8380
var devPath = Path.Combine(localAppData, @"Microsoft\Edge Dev\User Data");
8481
if (Directory.Exists(devPath))
85-
yield return new ChromiumBookmarkLoader("Microsoft Edge Dev", devPath, logAction, discoveredBookmarkFiles);
82+
yield return new ChromiumBookmarkLoader("Microsoft Edge Dev", devPath, discoveredBookmarkFiles);
8683

8784
var canaryPath = Path.Combine(localAppData, @"Microsoft\Edge SxS\User Data");
8885
if (Directory.Exists(canaryPath))
89-
yield return new ChromiumBookmarkLoader("Microsoft Edge Canary", canaryPath, logAction, discoveredBookmarkFiles);
86+
yield return new ChromiumBookmarkLoader("Microsoft Edge Canary", canaryPath, discoveredBookmarkFiles);
9087
}
9188

9289
if (_settings.LoadChromiumBookmark)
9390
{
9491
var path = Path.Combine(localAppData, @"Chromium\User Data");
9592
if (Directory.Exists(path))
96-
yield return new ChromiumBookmarkLoader("Chromium", path, logAction, discoveredBookmarkFiles);
93+
yield return new ChromiumBookmarkLoader("Chromium", path, discoveredBookmarkFiles);
9794
}
9895

9996
foreach (var browser in _settings.CustomBrowsers.Where(b => b.BrowserType == BrowserType.Chromium))
10097
{
10198
if (string.IsNullOrEmpty(browser.Name) || string.IsNullOrEmpty(browser.DataDirectoryPath) || !Directory.Exists(browser.DataDirectoryPath))
10299
continue;
103100

104-
yield return new ChromiumBookmarkLoader(browser.Name, browser.DataDirectoryPath, logAction, discoveredBookmarkFiles);
101+
yield return new ChromiumBookmarkLoader(browser.Name, browser.DataDirectoryPath, discoveredBookmarkFiles);
105102
}
106103
}
107104

108105
public IEnumerable<IBookmarkLoader> GetFirefoxBookmarkLoaders()
109106
{
110-
var logAction = (string tag, string msg, Exception? ex) => _context.API.LogException(tag, msg, ex);
111-
112107
if (_settings.LoadFirefoxBookmark)
113108
{
114109
string? placesPath = null;
@@ -118,11 +113,11 @@ public IEnumerable<IBookmarkLoader> GetFirefoxBookmarkLoaders()
118113
}
119114
catch (Exception ex)
120115
{
121-
_context.API.LogException(nameof(BookmarkLoaderService), "Failed to find Firefox profile", ex);
116+
Main.Context.API.LogException(nameof(BookmarkLoaderService), "Failed to find Firefox profile", ex);
122117
}
123118
if (!string.IsNullOrEmpty(placesPath))
124119
{
125-
yield return new FirefoxBookmarkLoader("Firefox", placesPath, _tempPath, logAction);
120+
yield return new FirefoxBookmarkLoader("Firefox", placesPath, _tempPath);
126121
}
127122

128123
string? msixPlacesPath = null;
@@ -132,11 +127,11 @@ public IEnumerable<IBookmarkLoader> GetFirefoxBookmarkLoaders()
132127
}
133128
catch (Exception ex)
134129
{
135-
_context.API.LogException(nameof(BookmarkLoaderService), "Failed to find Firefox MSIX package", ex);
130+
Main.Context.API.LogException(nameof(BookmarkLoaderService), "Failed to find Firefox MSIX package", ex);
136131
}
137132
if (!string.IsNullOrEmpty(msixPlacesPath))
138133
{
139-
yield return new FirefoxBookmarkLoader("Firefox (Store)", msixPlacesPath, _tempPath, logAction);
134+
yield return new FirefoxBookmarkLoader("Firefox (Store)", msixPlacesPath, _tempPath);
140135
}
141136
}
142137

@@ -151,7 +146,6 @@ public IEnumerable<IBookmarkLoader> GetFirefoxBookmarkLoaders()
151146

152147
private IBookmarkLoader CreateCustomFirefoxLoader(string name, string dataDirectoryPath)
153148
{
154-
var logAction = (string tag, string msg, Exception? ex) => _context.API.LogException(tag, msg, ex);
155149
// Custom Firefox paths might point to the root profile dir (e.g. ...\Mozilla\Firefox)
156150
var placesPath = FirefoxProfileFinder.GetPlacesPathFromProfileDir(dataDirectoryPath);
157151
if (string.IsNullOrEmpty(placesPath))
@@ -161,6 +155,6 @@ private IBookmarkLoader CreateCustomFirefoxLoader(string name, string dataDirect
161155
}
162156

163157
// Do not add Firefox places.sqlite to the watcher as it's updated constantly for history.
164-
return new FirefoxBookmarkLoader(name, placesPath, _tempPath, logAction);
158+
return new FirefoxBookmarkLoader(name, placesPath, _tempPath);
165159
}
166160
}

Plugins/Flow.Launcher.Plugin.BrowserBookmark/Services/BookmarkWatcherService.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ public class BookmarkWatcherService : IDisposable
1010
public event Action OnBookmarkFileChanged;
1111

1212
// Timer to debounce file change events
13-
private Timer _debounceTimer;
14-
private readonly object _lock = new();
13+
private readonly Timer _debounceTimer;
14+
private readonly Lock _lock = new();
1515
private volatile bool _disposed;
1616

1717
public BookmarkWatcherService()

Plugins/Flow.Launcher.Plugin.BrowserBookmark/Services/BrowserDetector.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ public static class BrowserDetector
1111
public static IEnumerable<string> GetChromiumProfileDirectories(string basePath)
1212
{
1313
if (!Directory.Exists(basePath))
14-
return Enumerable.Empty<string>();
14+
return [];
1515

1616
var profileDirs = Directory.EnumerateDirectories(basePath, "Profile *").ToList();
1717

Plugins/Flow.Launcher.Plugin.BrowserBookmark/Services/ChromiumBookmarkLoader.cs

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,16 +14,14 @@ public class ChromiumBookmarkLoader : IBookmarkLoader
1414
{
1515
private readonly string _browserName;
1616
private readonly string _browserDataPath;
17-
private readonly Action<string, string, Exception?> _logException;
1817
private readonly ConcurrentBag<string> _discoveredFiles;
1918

2019
public string Name => _browserName;
2120

22-
public ChromiumBookmarkLoader(string browserName, string browserDataPath, Action<string, string, Exception?> logException, ConcurrentBag<string> discoveredFiles)
21+
public ChromiumBookmarkLoader(string browserName, string browserDataPath, ConcurrentBag<string> discoveredFiles)
2322
{
2423
_browserName = browserName;
2524
_browserDataPath = browserDataPath;
26-
_logException = logException;
2725
_discoveredFiles = discoveredFiles;
2826
}
2927

@@ -57,19 +55,19 @@ public async IAsyncEnumerable<Bookmark> GetBookmarksAsync([EnumeratorCancellatio
5755
}
5856
catch (IOException ex)
5957
{
60-
_logException(nameof(ChromiumBookmarkLoader), $"IO error reading {_browserName} bookmarks: {bookmarkPath}", ex);
58+
Main.Context.API.LogException(nameof(ChromiumBookmarkLoader), $"IO error reading {_browserName} bookmarks: {bookmarkPath}", ex);
6159
}
6260
catch (UnauthorizedAccessException ex)
6361
{
64-
_logException(nameof(ChromiumBookmarkLoader), $"Unauthorized to read {_browserName} bookmarks: {bookmarkPath}", ex);
62+
Main.Context.API.LogException(nameof(ChromiumBookmarkLoader), $"Unauthorized to read {_browserName} bookmarks: {bookmarkPath}", ex);
6563
}
6664
catch (JsonException ex)
6765
{
68-
_logException(nameof(ChromiumBookmarkLoader), $"Failed to parse bookmarks file for {_browserName}: {bookmarkPath}", ex);
66+
Main.Context.API.LogException(nameof(ChromiumBookmarkLoader), $"Failed to parse bookmarks file for {_browserName}: {bookmarkPath}", ex);
6967
}
7068
catch (Exception ex)
7169
{
72-
_logException(nameof(ChromiumBookmarkLoader), $"Unexpected error loading {_browserName} bookmarks: {bookmarkPath}", ex);
70+
Main.Context.API.LogException(nameof(ChromiumBookmarkLoader), $"Unexpected error loading {_browserName} bookmarks: {bookmarkPath}", ex);
7371
}
7472

7573
foreach (var bookmark in bookmarks)
@@ -124,7 +122,7 @@ private void EnumerateFolderBookmark(JsonElement folderElement, ICollection<Book
124122
}
125123
else
126124
{
127-
_logException(nameof(ChromiumBookmarkLoader), "type property not found in bookmark node.", null);
125+
Main.Context.API.LogException(nameof(ChromiumBookmarkLoader), "type property not found in bookmark node.", null);
128126
}
129127
}
130128
}

Plugins/Flow.Launcher.Plugin.BrowserBookmark/Services/FaviconService.cs

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ namespace Flow.Launcher.Plugin.BrowserBookmark.Services;
1818

1919
public partial class FaviconService : IDisposable
2020
{
21-
private readonly PluginInitContext _context;
2221
private readonly Settings _settings;
2322
private readonly string _faviconCacheDir;
2423
private readonly LocalFaviconExtractor _localExtractor;
@@ -33,24 +32,23 @@ public partial class FaviconService : IDisposable
3332
private record struct FetchResult(byte[]? PngData, int Size);
3433
private static readonly TimeSpan FailedFaviconCooldown = TimeSpan.FromHours(24);
3534

36-
public FaviconService(PluginInitContext context, Settings settings, string tempPath)
35+
public FaviconService(Settings settings, string tempPath)
3736
{
38-
_context = context;
3937
_settings = settings;
4038

41-
_faviconCacheDir = Path.Combine(context.CurrentPluginMetadata.PluginCacheDirectoryPath, "FaviconCache");
39+
_faviconCacheDir = Path.Combine(Main.Context.CurrentPluginMetadata.PluginCacheDirectoryPath, "FaviconCache");
4240
Directory.CreateDirectory(_faviconCacheDir);
4341

44-
var failsDir = Path.Combine(context.CurrentPluginMetadata.PluginCacheDirectoryPath, "FaviconFails");
42+
var failsDir = Path.Combine(Main.Context.CurrentPluginMetadata.PluginCacheDirectoryPath, "FaviconFails");
4543
Directory.CreateDirectory(failsDir);
4644
_failsFilePath = Path.Combine(failsDir, "FaviconFails.json");
4745

4846
LoadFailedFetches();
4947

50-
_localExtractor = new LocalFaviconExtractor(context, tempPath);
51-
_webClient = new FaviconWebClient(context);
52-
_htmlParser = new HtmlFaviconParser(context);
53-
_imageConverter = new ImageConverter(context);
48+
_localExtractor = new LocalFaviconExtractor(tempPath);
49+
_webClient = new FaviconWebClient();
50+
_htmlParser = new HtmlFaviconParser();
51+
_imageConverter = new ImageConverter();
5452
}
5553

5654
private void LoadFailedFetches()
@@ -68,7 +66,7 @@ private void LoadFailedFetches()
6866
}
6967
catch (Exception ex)
7068
{
71-
_context.API.LogException(nameof(FaviconService), $"Failed to load failed favicons file from {_failsFilePath}", ex);
69+
Main.Context.API.LogException(nameof(FaviconService), $"Failed to load failed favicons file from {_failsFilePath}", ex);
7270
}
7371
}
7472

@@ -86,7 +84,7 @@ private async Task SaveFailedFetchesAsync()
8684
catch (ObjectDisposedException) { /* Swallow if disposing */ }
8785
catch (Exception ex)
8886
{
89-
_context.API.LogException(nameof(FaviconService), $"Failed to save failed favicons file to {_failsFilePath}", ex);
87+
Main.Context.API.LogException(nameof(FaviconService), $"Failed to save failed favicons file to {_failsFilePath}", ex);
9088
}
9189
finally
9290
{
@@ -172,7 +170,7 @@ await Parallel.ForEachAsync(bookmarks, options, async (bookmark, token) =>
172170
if (_failedFetches.TryGetValue(authority, out var lastAttemptTime) &&
173171
(DateTime.UtcNow - lastAttemptTime < FailedFaviconCooldown))
174172
{
175-
_context.API.LogDebug(nameof(FaviconService),
173+
Main.Context.API.LogDebug(nameof(FaviconService),
176174
$"Skipping favicon fetch for {authority} due to recent failure (cooldown active).");
177175
return null;
178176
}
@@ -249,7 +247,7 @@ private static string GetCachePath(string url, string cacheDir)
249247
}
250248
if (File.Exists(cachePath))
251249
{
252-
_context.API.LogDebug(nameof(FaviconService), $"Favicon for {urlString} cached successfully.");
250+
Main.Context.API.LogDebug(nameof(FaviconService), $"Favicon for {urlString} cached successfully.");
253251
if (_failedFetches.TryRemove(urlString, out _))
254252
{
255253
_ = SaveFailedFetchesAsync();
@@ -259,11 +257,11 @@ private static string GetCachePath(string url, string cacheDir)
259257
// Do not treat as success; let finally record failure if needed.
260258
}
261259

262-
_context.API.LogDebug(nameof(FaviconService), $"No suitable favicon found for {urlString} after all tasks.");
260+
Main.Context.API.LogDebug(nameof(FaviconService), $"No suitable favicon found for {urlString} after all tasks.");
263261
}
264262
catch (Exception ex)
265263
{
266-
_context.API.LogException(nameof(FaviconService), $"Error in favicon fetch for {urlString}", ex);
264+
Main.Context.API.LogException(nameof(FaviconService), $"Error in favicon fetch for {urlString}", ex);
267265
fetchAttempted = true;
268266
}
269267
finally

Plugins/Flow.Launcher.Plugin.BrowserBookmark/Services/FaviconWebClient.cs

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#nullable enable
1+
#nullable enable
22
using System;
33
using System.IO;
44
using System.Net;
@@ -13,12 +13,10 @@ namespace Flow.Launcher.Plugin.BrowserBookmark.Services;
1313
public class FaviconWebClient : IDisposable
1414
{
1515
private readonly HttpClient _httpClient;
16-
private readonly PluginInitContext _context;
1716
private const int MaxFaviconBytes = 250 * 1024;
1817

19-
public FaviconWebClient(PluginInitContext context)
18+
public FaviconWebClient()
2019
{
21-
_context = context;
2220
var handler = new HttpClientHandler
2321
{
2422
AllowAutoRedirect = true,
@@ -62,12 +60,12 @@ public FaviconWebClient(PluginInitContext context)
6260
}
6361
catch (TaskCanceledException) when (!token.IsCancellationRequested)
6462
{
65-
_context.API.LogWarn(nameof(FaviconWebClient), $"HttpClient timed out fetching HTML for {pageUri}.");
63+
Main.Context.API.LogWarn(nameof(FaviconWebClient), $"HttpClient timed out fetching HTML for {pageUri}.");
6664
}
6765
catch (OperationCanceledException) { /* Expected if another task cancels this one */ }
6866
catch (Exception ex)
6967
{
70-
_context.API.LogException(nameof(FaviconWebClient), $"Failed to fetch or parse HTML head for {pageUri}", ex);
68+
Main.Context.API.LogException(nameof(FaviconWebClient), $"Failed to fetch or parse HTML head for {pageUri}", ex);
7169
}
7270
return null;
7371
}
@@ -108,16 +106,16 @@ public FaviconWebClient(PluginInitContext context)
108106
}
109107
catch (HttpRequestException ex) when (ex.InnerException is SocketException { SocketErrorCode: SocketError.HostNotFound })
110108
{
111-
_context.API.LogDebug(nameof(FaviconWebClient), $"Favicon host not found for URI: {faviconUri}");
109+
Main.Context.API.LogDebug(nameof(FaviconWebClient), $"Favicon host not found for URI: {faviconUri}");
112110
}
113111
catch (TaskCanceledException) when (!token.IsCancellationRequested)
114112
{
115-
_context.API.LogWarn(nameof(FaviconWebClient), $"HttpClient timed out for {faviconUri}.");
113+
Main.Context.API.LogWarn(nameof(FaviconWebClient), $"HttpClient timed out for {faviconUri}.");
116114
}
117115
catch (OperationCanceledException) { /* Expected if another task cancels this one */ }
118116
catch (Exception ex)
119117
{
120-
_context.API.LogException(nameof(FaviconWebClient), $"Favicon fetch failed for {faviconUri}", ex);
118+
Main.Context.API.LogException(nameof(FaviconWebClient), $"Favicon fetch failed for {faviconUri}", ex);
121119
}
122120
return null;
123121
}

0 commit comments

Comments
 (0)