-
Notifications
You must be signed in to change notification settings - Fork 13
/
App.axaml.cs
253 lines (216 loc) · 9.76 KB
/
App.axaml.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Input.Platform;
using Avalonia.Markup.Xaml;
using Avalonia.Threading;
using Serilog;
using Serilog.Events;
using Atomex.Client.Desktop.Services;
using Atomex.Client.Desktop.ViewModels;
using Atomex.Client.Desktop.Views;
using Atomex.Common.Configuration;
using Atomex.Core;
using Atomex.MarketData;
using Atomex.MarketData.Abstract;
using Atomex.MarketData.Bitfinex;
using Atomex.MarketData.TezTools;
using Atomex.Services;
namespace Atomex.Client.Desktop
{
public class App : Application
{
public static DialogService DialogService;
public static TemplateService TemplateService;
public static IClipboard? Clipboard;
public static NotificationsService NotificationsService;
public static ILoggerFactory LoggerFactory;
public static MainWindowViewModel MainWindowViewModel;
public static Action<string> ConnectTezosDapp;
private SingleInstanceLoopbackService _singleInstanceLoopbackService;
public override void Initialize()
{
AvaloniaXamlLoader.Load(this);
}
public override void OnFrameworkInitializationCompleted()
{
// set invariant culture by default
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
// configure loggers
ConfigureLoggers();
// MacUpdater.CheckForMacOsDeepLinks();
UrlsOpened += (sender, args) =>
{
if (args.Urls.Length == 0) return;
MainWindowViewModel.StartupData = args.Urls[0];
Log.Information("Setting startup data from URLOpened {Url}", args.Urls[0]);
};
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
if (SingleInstanceLoopbackService.TrySendArgsToOtherInstance(desktop.Args, LoggerFactory.CreateLogger<SingleInstanceLoopbackService>()))
{
// arguments passed successfully to another application instance, exit
Environment.Exit(0);
return;
}
TemplateService = new TemplateService();
Clipboard = AvaloniaLocator.Current.GetService<IClipboard>();
var currenciesProvider = new CurrenciesProvider(CurrenciesConfigurationString);
var symbolsProvider = new SymbolsProvider(SymbolsConfiguration);
var quotesProvider = new MultiSourceQuotesProvider(
log: LoggerFactory.CreateLogger<MultiSourceQuotesProvider>());
// init Atomex client app
AtomexApp = new AtomexApp(logger: LoggerFactory.CreateLogger("AtomexApp"))
.UseCurrenciesProvider(currenciesProvider)
.UseSymbolsProvider(symbolsProvider)
.UseCurrenciesUpdater(new CurrenciesUpdater(currenciesProvider))
.UseSymbolsUpdater(new SymbolsUpdater(symbolsProvider))
.UseQuotesProvider(quotesProvider);
quotesProvider.ConfigureOnStart = provider =>
{
if (AtomexApp?.Account?.Network == Network.MainNet)
{
var bitfinexQuotesProvider = new BitfinexQuotesProvider(
currencies: AtomexApp.CurrenciesProvider
.GetCurrencies(Network.MainNet)
.GetOrderedPreset()
.Select(c => c.Name),
baseCurrency: QuotesProvider.Usd,
log: LoggerFactory.CreateLogger<BitfinexQuotesProvider>());
var tezToolsQuotesProvider = new TezToolsQuotesProvider(
log: LoggerFactory.CreateLogger<TezToolsQuotesProvider>());
provider.AddProviders(bitfinexQuotesProvider, tezToolsQuotesProvider);
}
};
var mainWindow = new MainWindow();
DialogService = new DialogService();
NotificationsService = new NotificationsService(AtomexApp, mainWindow.NotificationManager);
MainWindowViewModel = new MainWindowViewModel(AtomexApp, mainWindow);
mainWindow.DataContext = MainWindowViewModel;
desktop.Exit += OnExit;
if (desktop.Args.Length != 0)
{
MainWindowViewModel.StartupData = desktop.Args[0];
Log.Information("Setting startup data from start args {Data}", desktop.Args[0]);
}
desktop.MainWindow = mainWindow;
AtomexApp.Start();
_singleInstanceLoopbackService = new SingleInstanceLoopbackService();
_singleInstanceLoopbackService.RunInBackground((receivedText) =>
{
MainWindowViewModel.StartupData = receivedText;
Log.Information("Received startup data from socket {Data}", receivedText);
_ = Dispatcher.UIThread.InvokeAsync(() => { desktop.MainWindow.Activate(); });
});
}
base.OnFrameworkInitializationCompleted();
}
void OnExit(object? sender, ControlledApplicationLifetimeExitEventArgs e)
{
Log.Information("Application shutdown");
try
{
AtomexApp.Stop();
Environment.Exit(0);
}
catch (Exception)
{
Log.Error("Error stopping Atomex in OnExit");
}
}
public static IAtomexApp AtomexApp { get; private set; }
public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
#if DEBUG
.AddJsonFile("config.debug.json")
#else
.AddJsonFile("config.json")
#endif
.Build();
private static Assembly CoreAssembly { get; } = AppDomain.CurrentDomain
.GetAssemblies()
.FirstOrDefault(a => a.GetName().Name == "Atomex.Client.Core") ?? throw new Exception("Can't find core library assembly");
private static string CurrenciesConfigurationString
{
get
{
const string resourceName = "currencies.json";
var resourceNames = CoreAssembly.GetManifestResourceNames();
var fullFileName = resourceNames.FirstOrDefault(n => n.EndsWith(resourceName));
var stream = CoreAssembly.GetManifestResourceStream(fullFileName!);
using StreamReader reader = new(stream!);
return reader.ReadToEnd();
}
}
private static IConfiguration SymbolsConfiguration { get; } = new ConfigurationBuilder()
.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
.AddEmbeddedJsonFile(CoreAssembly, "symbols.json")
.Build();
public static void OpenBrowser(string url)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
// If no associated application/json MimeType is found xdg-open opens retrun error
// but it tries to open it anyway using the console editor (nano, vim, other..)
ShellExec($"xdg-open {url}", waitForExit: false);
}
else
{
using var process = Process.Start(new ProcessStartInfo
{
FileName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? url : "open",
Arguments = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? $"{url}" : "",
CreateNoWindow = true,
UseShellExecute = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
});
}
}
private static void ShellExec(string cmd, bool waitForExit = true)
{
var escapedArgs = cmd.Replace("\"", "\\\"");
using var process = Process.Start(
new ProcessStartInfo
{
FileName = "/bin/bash",
Arguments = $"-c \"{escapedArgs}\"",
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden
}
);
if (waitForExit)
process?.WaitForExit();
}
private void ConfigureLoggers()
{
// todo: remove Serilog static logger and use Serilog only as provider for Microsoft.Extensions.Logging
// init Serilog static logger
Log.Logger = new LoggerConfiguration()
#if DEBUG
.ReadFrom.Configuration(Configuration)
#else
.WriteTo.Sentry(o =>
{
o.Dsn = "https://[email protected]/3";
// Debug and higher are stored as breadcrumbs (default is Information)
o.MinimumBreadcrumbLevel = LogEventLevel.Information;
// Warning and higher is sent as event (default is Error)
o.MinimumEventLevel = LogEventLevel.Error;
})
#endif
.CreateLogger();
// init Microsoft.Extensions.Logging logger factory
LoggerFactory = new LoggerFactory()
.AddSerilog();
}
}
}