Skip to content
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

Dependency Injection Code Quality #3276

Open
wants to merge 8 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 7 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
Expand Up @@ -7,7 +7,6 @@
using System.Linq;
using System.Windows;
using System.Windows.Forms;
using Flow.Launcher.Core.Resource;
using CommunityToolkit.Mvvm.DependencyInjection;

namespace Flow.Launcher.Core.ExternalPlugins.Environments
Expand Down Expand Up @@ -55,14 +54,14 @@ internal IEnumerable<PluginPair> Setup()
}

var noRuntimeMessage = string.Format(
InternationalizationManager.Instance.GetTranslation("runtimePluginInstalledChooseRuntimePrompt"),
API.GetTranslation("runtimePluginInstalledChooseRuntimePrompt"),
Language,
EnvName,
Environment.NewLine
);
if (API.ShowMsgBox(noRuntimeMessage, string.Empty, MessageBoxButton.YesNo) == MessageBoxResult.No)
{
var msg = string.Format(InternationalizationManager.Instance.GetTranslation("runtimePluginChooseRuntimeExecutable"), EnvName);
var msg = string.Format(API.GetTranslation("runtimePluginChooseRuntimeExecutable"), EnvName);
string selectedFile;

selectedFile = GetFileFromDialog(msg, FileDialogFilter);
Expand All @@ -85,7 +84,7 @@ internal IEnumerable<PluginPair> Setup()
}
else
{
API.ShowMsgBox(string.Format(InternationalizationManager.Instance.GetTranslation("runtimePluginUnableToSetExecutablePath"), Language));
API.ShowMsgBox(string.Format(API.GetTranslation("runtimePluginUnableToSetExecutablePath"), Language));
Log.Error("PluginsLoader",
$"Not able to successfully set {EnvName} path, setting's plugin executable path variable is still an empty string.",
$"{Language}Environment");
Expand Down
31 changes: 16 additions & 15 deletions Flow.Launcher.Core/Plugin/PluginManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public static class PluginManager
public static List<PluginPair> AllPlugins { get; private set; }
public static readonly HashSet<PluginPair> GlobalPlugins = new();
public static readonly Dictionary<string, PluginPair> NonGlobalPlugins = new();

// We should not initialize API in static constructor because it will create another API instance
private static IPublicAPI api = null;
private static IPublicAPI API => api ??= Ioc.Default.GetRequiredService<IPublicAPI>();
Expand Down Expand Up @@ -65,7 +65,7 @@ public static void Save()
savable?.Save();
}

API.SavePluginSettings();
_api.SavePluginSettings();
}

public static async ValueTask DisposePluginsAsync()
Expand Down Expand Up @@ -170,7 +170,7 @@ public static async Task InitializePluginsAsync()
try
{
var milliseconds = await Stopwatch.DebugAsync($"|PluginManager.InitializePlugins|Init method time cost for <{pair.Metadata.Name}>",
() => pair.Plugin.InitAsync(new PluginInitContext(pair.Metadata, API)));
() => pair.Plugin.InitAsync(new PluginInitContext(pair.Metadata, _api)));

pair.Metadata.InitTime += milliseconds;
Log.Info(
Expand Down Expand Up @@ -205,16 +205,17 @@ public static async Task InitializePluginsAsync()
}
}

InternationalizationManager.Instance.AddPluginLanguageDirectories(GetPluginsForInterface<IPluginI18n>());
InternationalizationManager.Instance.ChangeLanguage(Ioc.Default.GetRequiredService<Settings>().Language);
var translater = Ioc.Default.GetRequiredService<Internationalization>();
translater.AddPluginLanguageDirectories(GetPluginsForInterface<IPluginI18n>());
translater.ChangeLanguage(Ioc.Default.GetRequiredService<Settings>().Language);

if (failedPlugins.Any())
{
var failed = string.Join(",", failedPlugins.Select(x => x.Metadata.Name));
API.ShowMsg(
API.GetTranslation("failedToInitializePluginsTitle"),
_api.ShowMsg(
_api.GetTranslation("failedToInitializePluginsTitle"),
string.Format(
API.GetTranslation("failedToInitializePluginsMessage"),
_api.GetTranslation("failedToInitializePluginsMessage"),
failed
),
"",
Expand Down Expand Up @@ -521,7 +522,7 @@ internal static void InstallPlugin(UserPlugin plugin, string zipFilePath, bool c

var newPluginPath = Path.Combine(installDirectory, folderName);

FilesFolders.CopyAll(pluginFolderPath, newPluginPath, (s) => API.ShowMsgBox(s));
FilesFolders.CopyAll(pluginFolderPath, newPluginPath, (s) => _api.ShowMsgBox(s));

try
{
Expand Down Expand Up @@ -556,8 +557,8 @@ internal static void UninstallPlugin(PluginMetadata plugin, bool removePluginFro

// if user want to remove the plugin settings, we cannot call save method for the plugin json storage instance of this plugin
// so we need to remove it from the api instance
var method = API.GetType().GetMethod("RemovePluginSettings");
var pluginJsonStorage = method?.Invoke(API, new object[] { assemblyName });
var method = _api.GetType().GetMethod("RemovePluginSettings");
var pluginJsonStorage = method?.Invoke(_api, new object[] { assemblyName });

// if there exists a json storage for current plugin, we need to delete the directory path
if (pluginJsonStorage != null)
Expand All @@ -570,8 +571,8 @@ internal static void UninstallPlugin(PluginMetadata plugin, bool removePluginFro
catch (Exception e)
{
Log.Exception($"|PluginManager.UninstallPlugin|Failed to delete plugin json folder for {plugin.Name}", e);
API.ShowMsg(API.GetTranslation("failedToRemovePluginSettingsTitle"),
string.Format(API.GetTranslation("failedToRemovePluginSettingsMessage"), plugin.Name));
_api.ShowMsg(_api.GetTranslation("failedToRemovePluginSettingsTitle"),
string.Format(_api.GetTranslation("failedToRemovePluginSettingsMessage"), plugin.Name));
}
}
}
Expand All @@ -587,8 +588,8 @@ internal static void UninstallPlugin(PluginMetadata plugin, bool removePluginFro
catch (Exception e)
{
Log.Exception($"|PluginManager.UninstallPlugin|Failed to delete plugin json folder for {plugin.Name}", e);
API.ShowMsg(API.GetTranslation("failedToRemovePluginSettingsTitle"),
string.Format(API.GetTranslation("failedToRemovePluginSettingsMessage"), plugin.Name));
_api.ShowMsg(_api.GetTranslation("failedToRemovePluginSettingsTitle"),
string.Format(_api.GetTranslation("failedToRemovePluginSettingsMessage"), plugin.Name));
}
}
}
Expand Down
12 changes: 0 additions & 12 deletions Flow.Launcher.Core/Resource/InternationalizationManager.cs

This file was deleted.

7 changes: 4 additions & 3 deletions Flow.Launcher.Core/Resource/LocalizedDescriptionAttribute.cs
Original file line number Diff line number Diff line change
@@ -1,23 +1,24 @@
using System.ComponentModel;
using CommunityToolkit.Mvvm.DependencyInjection;
using Flow.Launcher.Plugin;

namespace Flow.Launcher.Core.Resource
{
public class LocalizedDescriptionAttribute : DescriptionAttribute
{
private readonly Internationalization _translator;
private static readonly IPublicAPI _api = Ioc.Default.GetRequiredService<IPublicAPI>();
private readonly string _resourceKey;

public LocalizedDescriptionAttribute(string resourceKey)
{
_translator = InternationalizationManager.Instance;
_resourceKey = resourceKey;
}

public override string Description
{
get
{
string description = _translator.GetTranslation(_resourceKey);
string description = _api.GetTranslation(_resourceKey);
return string.IsNullOrWhiteSpace(description) ?
string.Format("[[{0}]]", _resourceKey) : description;
}
Expand Down
5 changes: 2 additions & 3 deletions Flow.Launcher.Core/Resource/Theme.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
using Flow.Launcher.Infrastructure;
using Flow.Launcher.Infrastructure.Logger;
using Flow.Launcher.Infrastructure.UserSettings;
using CommunityToolkit.Mvvm.DependencyInjection;
using Flow.Launcher.Plugin;

namespace Flow.Launcher.Core.Resource
Expand Down Expand Up @@ -115,7 +114,7 @@ public bool ChangeTheme(string theme)
Log.Error($"|Theme.ChangeTheme|Theme <{theme}> path can't be found");
if (theme != defaultTheme)
{
_api.ShowMsgBox(string.Format(InternationalizationManager.Instance.GetTranslation("theme_load_failure_path_not_exists"), theme));
_api.ShowMsgBox(string.Format(_api.GetTranslation("theme_load_failure_path_not_exists"), theme));
ChangeTheme(defaultTheme);
}
return false;
Expand All @@ -125,7 +124,7 @@ public bool ChangeTheme(string theme)
Log.Error($"|Theme.ChangeTheme|Theme <{theme}> fail to parse");
if (theme != defaultTheme)
{
_api.ShowMsgBox(string.Format(InternationalizationManager.Instance.GetTranslation("theme_load_failure_parse_error"), theme));
_api.ShowMsgBox(string.Format(_api.GetTranslation("theme_load_failure_parse_error"), theme));
ChangeTheme(defaultTheme);
}
return false;
Expand Down
12 changes: 0 additions & 12 deletions Flow.Launcher.Core/Resource/ThemeManager.cs

This file was deleted.

10 changes: 7 additions & 3 deletions Flow.Launcher.Core/Resource/TranslationConverter.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
using System;
using System.Globalization;
using System.Windows.Data;
using CommunityToolkit.Mvvm.DependencyInjection;
using Flow.Launcher.Plugin;

namespace Flow.Launcher.Core.Resource
{
public class TranslationConverter : IValueConverter
{
private static readonly IPublicAPI _api = Ioc.Default.GetRequiredService<IPublicAPI>();

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var key = value.ToString();
if (String.IsNullOrEmpty(key))
if (string.IsNullOrEmpty(key))
return key;
return InternationalizationManager.Instance.GetTranslation(key);
return _api.GetTranslation(key);
}

public object ConvertBack(object value, System.Type targetType, object parameter, CultureInfo culture) => throw new System.InvalidOperationException();
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new InvalidOperationException();
}
}
4 changes: 1 addition & 3 deletions Flow.Launcher.Core/Updater.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
using System.Windows;
using JetBrains.Annotations;
using Squirrel;
using Flow.Launcher.Core.Resource;
using Flow.Launcher.Plugin.SharedCommands;
using Flow.Launcher.Infrastructure;
using Flow.Launcher.Infrastructure.Http;
Expand Down Expand Up @@ -146,8 +145,7 @@ private async Task<UpdateManager> GitHubUpdateManagerAsync(string repository)

public string NewVersionTips(string version)
{
var translator = InternationalizationManager.Instance;
var tips = string.Format(translator.GetTranslation("newVersionTips"), version);
var tips = string.Format(_api.GetTranslation("newVersionTips"), version);

return tips;
}
Expand Down
5 changes: 1 addition & 4 deletions Flow.Launcher/ActionKeywords.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
using System.Windows;
using Flow.Launcher.Core.Resource;
using Flow.Launcher.Plugin;
using Flow.Launcher.ViewModel;
using Flow.Launcher.Core;

namespace Flow.Launcher
{
public partial class ActionKeywords
{
private readonly PluginPair plugin;
private readonly Internationalization translater = InternationalizationManager.Instance;
private readonly PluginViewModel pluginViewModel;

public ActionKeywords(PluginViewModel pluginViewModel)
Expand Down Expand Up @@ -43,7 +40,7 @@ private void btnDone_OnClick(object sender, RoutedEventArgs _)
}
else
{
string msg = translater.GetTranslation("newActionKeywordsHasBeenAssigned");
string msg = App.API.GetTranslation("newActionKeywordsHasBeenAssigned");
App.API.ShowMsgBox(msg);
}
}
Expand Down
9 changes: 3 additions & 6 deletions Flow.Launcher/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,7 @@ await Stopwatch.NormalAsync("|App.OnStartup|Startup cost", async () =>

AbstractPluginEnvironment.PreStartPluginExecutablePathUpdate(_settings);

// TODO: Clean InternationalizationManager.Instance and InternationalizationManager.Instance.GetTranslation in future
InternationalizationManager.Instance.ChangeLanguage(_settings.Language);
Ioc.Default.GetRequiredService<Internationalization>().ChangeLanguage(_settings.Language);

PluginManager.LoadPlugins(_settings.PluginSettings);

Expand All @@ -145,8 +144,7 @@ await Stopwatch.NormalAsync("|App.OnStartup|Startup cost", async () =>
HotKeyMapper.Initialize();

// main windows needs initialized before theme change because of blur settings
// TODO: Clean ThemeManager.Instance in future
ThemeManager.Instance.ChangeTheme(_settings.Theme);
Ioc.Default.GetRequiredService<Theme>().ChangeTheme(_settings.Theme);

Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

Expand Down Expand Up @@ -183,8 +181,7 @@ private void AutoStartup()
// but if it fails (permissions, etc) then don't keep retrying
// this also gives the user a visual indication in the Settings widget
_settings.StartFlowLauncherOnSystemStartup = false;
Notification.Show(InternationalizationManager.Instance.GetTranslation("setAutoStartFailed"),
e.Message);
API.ShowMsg(API.GetTranslation("setAutoStartFailed"), e.Message);
}
}
}
Expand Down
3 changes: 1 addition & 2 deletions Flow.Launcher/Converters/TextConverter.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System;
using System.Globalization;
using System.Windows.Data;
using Flow.Launcher.Core.Resource;
using Flow.Launcher.ViewModel;

namespace Flow.Launcher.Converters;
Expand All @@ -23,7 +22,7 @@ public object Convert(object value, Type targetType, object parameter, CultureIn
if (translationKey is null)
return id;

return InternationalizationManager.Instance.GetTranslation(translationKey);
return App.API.GetTranslation(translationKey);
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new InvalidOperationException();
Expand Down
7 changes: 3 additions & 4 deletions Flow.Launcher/CustomQueryHotkeySetting.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using Flow.Launcher.Core.Resource;
using Flow.Launcher.Helper;
using Flow.Launcher.Helper;
using Flow.Launcher.Infrastructure.UserSettings;
using System.Collections.ObjectModel;
using System.Linq;
Expand Down Expand Up @@ -60,15 +59,15 @@ public void UpdateItem(CustomPluginHotkey item)
o.ActionKeyword == item.ActionKeyword && o.Hotkey == item.Hotkey);
if (updateCustomHotkey == null)
{
App.API.ShowMsgBox(InternationalizationManager.Instance.GetTranslation("invalidPluginHotkey"));
App.API.ShowMsgBox(App.API.GetTranslation("invalidPluginHotkey"));
Close();
return;
}

tbAction.Text = updateCustomHotkey.ActionKeyword;
HotkeyControl.SetHotkey(updateCustomHotkey.Hotkey, false);
update = true;
lblAdd.Text = InternationalizationManager.Instance.GetTranslation("update");
lblAdd.Text = App.API.GetTranslation("update");
}

private void BtnTestActionKeyword_OnClick(object sender, RoutedEventArgs e)
Expand Down
15 changes: 6 additions & 9 deletions Flow.Launcher/CustomShortcutSetting.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
using Flow.Launcher.Core.Resource;
using System;
using System.Windows;
using System.Windows;
using System.Windows.Input;
using Flow.Launcher.SettingPages.ViewModels;
using Flow.Launcher.Core;

namespace Flow.Launcher
{
public partial class CustomShortcutSetting : Window
{
private readonly SettingsPaneHotkeyViewModel _hotkeyVm;
public string Key { get; set; } = String.Empty;
public string Value { get; set; } = String.Empty;
public string Key { get; set; } = string.Empty;
public string Value { get; set; } = string.Empty;
private string originalKey { get; } = null;
private string originalValue { get; } = null;
private bool update { get; } = false;
Expand Down Expand Up @@ -41,15 +38,15 @@ private void BtnCancel_OnClick(object sender, RoutedEventArgs e)

private void BtnAdd_OnClick(object sender, RoutedEventArgs e)
{
if (String.IsNullOrEmpty(Key) || String.IsNullOrEmpty(Value))
if (string.IsNullOrEmpty(Key) || string.IsNullOrEmpty(Value))
{
App.API.ShowMsgBox(InternationalizationManager.Instance.GetTranslation("emptyShortcut"));
App.API.ShowMsgBox(App.API.GetTranslation("emptyShortcut"));
return;
}
// Check if key is modified or adding a new one
if (((update && originalKey != Key) || !update) && _hotkeyVm.DoesShortcutExist(Key))
{
App.API.ShowMsgBox(InternationalizationManager.Instance.GetTranslation("duplicateShortcut"));
App.API.ShowMsgBox(App.API.GetTranslation("duplicateShortcut"));
return;
}
DialogResult = !update || originalKey != Key || originalValue != Value;
Expand Down
Loading
Loading