-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.xaml.cs
More file actions
315 lines (278 loc) · 11.9 KB
/
App.xaml.cs
File metadata and controls
315 lines (278 loc) · 11.9 KB
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
using System.Diagnostics.CodeAnalysis;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace DotPilot;
public partial class App : Application
{
private const string StartupLogPrefix = "[DotPilot.Startup]";
private const string ConstructorMarker = "App constructor initialized.";
private const string OnLaunchedStartedMarker = "OnLaunched started.";
private const string BuilderCreatedMarker = "Uno host builder created.";
private const string NavigateStartedMarker = "Navigating to shell.";
private const string NavigateCompletedMarker = "Shell navigation completed.";
private const string DotPilotCategoryName = "DotPilot";
#if !__WASM__
private const string CenterMethodName = "Center";
private const string WindowStartupLocationPropertyName = "WindowStartupLocation";
private const string CenterScreenValueName = "CenterScreen";
private const string ScreenWidthPropertyName = "ScreenWidthInRawPixels";
private const string ScreenHeightPropertyName = "ScreenHeightInRawPixels";
private const string WidthPropertyName = "Width";
private const string HeightPropertyName = "Height";
private const string PositionPropertyName = "Position";
private const string XPropertyName = "X";
private const string YPropertyName = "Y";
#endif
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
InitializeComponent();
WriteStartupMarker(ConstructorMarker);
}
protected Window? MainWindow { get; private set; }
internal static Window? DesktopWindow { get; private set; }
protected IHost? Host { get; private set; }
internal IServiceProvider? Services => Host?.Services;
internal event EventHandler? ServicesReady;
[SuppressMessage("Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "Uno.Extensions APIs are used in a way that is safe for trimming in this template context.")]
protected override async void OnLaunched(LaunchActivatedEventArgs args)
{
try
{
WriteStartupMarker(OnLaunchedStartedMarker);
var builder = this.CreateBuilder(args)
// Add navigation support for toolkit controls such as TabBar and NavigationView
.UseToolkitNavigation()
.Configure(host => host
#if DEBUG
// Switch to Development environment when running in DEBUG
.UseEnvironment(Environments.Development)
#endif
.UseLogging(configure: (context, logBuilder) =>
{
// Configure log levels for different categories of logging
logBuilder
.SetMinimumLevel(
context.HostingEnvironment.IsDevelopment() ?
LogLevel.Information :
LogLevel.Warning)
.AddFilter(DotPilotCategoryName, LogLevel.Information)
// Default filters for core Uno Platform namespaces
.CoreLogLevel(LogLevel.Warning);
#if !__WASM__
logBuilder.AddConsole();
#endif
// Uno Platform namespace filter groups
// Uncomment individual methods to see more detailed logging
//// Generic Xaml events
//logBuilder.XamlLogLevel(LogLevel.Debug);
//// Layout specific messages
//logBuilder.XamlLayoutLogLevel(LogLevel.Debug);
//// Storage messages
//logBuilder.StorageLogLevel(LogLevel.Debug);
//// Binding related messages
//logBuilder.XamlBindingLogLevel(LogLevel.Debug);
//// Binder memory references tracking
//logBuilder.BinderMemoryReferenceLogLevel(LogLevel.Debug);
//// DevServer and HotReload related
//logBuilder.HotReloadCoreLogLevel(LogLevel.Information);
//// Debug JS interop
//logBuilder.WebAssemblyLogLevel(LogLevel.Debug);
}, enableUnoLogging: true)
.UseConfiguration(configure: configBuilder =>
configBuilder
.EmbeddedSource<App>()
.Section<AppConfig>()
)
// Enable localization (see appsettings.json for supported languages)
.UseLocalization()
.ConfigureServices((context, services) =>
{
Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions
.AddSingleton(services, TimeProvider.System);
services.AddAgentSessions();
services.AddPresentationModels();
})
.UseNavigation(RegisterRoutes)
);
WriteStartupMarker(BuilderCreatedMarker);
MainWindow = builder.Window;
DesktopWindow = MainWindow;
#if DEBUG
#if !__WASM__
MainWindow.UseStudio();
#endif
#endif
MainWindow.SetWindowIcon();
WriteStartupMarker(NavigateStartedMarker);
Host = await builder.NavigateAsync<Shell>();
WriteStartupMarker(NavigateCompletedMarker);
ServicesReady?.Invoke(this, EventArgs.Empty);
#if !__WASM__
CenterDesktopWindow(MainWindow);
#endif
}
catch (Exception exception)
{
WriteStartupError(exception);
throw;
}
}
private static void WriteStartupMarker(string message)
{
var formattedMessage = $"{StartupLogPrefix} {message}";
Console.WriteLine(formattedMessage);
BrowserConsoleDiagnostics.Info(formattedMessage);
}
private static void WriteStartupError(Exception exception)
{
ArgumentNullException.ThrowIfNull(exception);
var formattedMessage = $"{StartupLogPrefix} ERROR {exception}";
Console.Error.WriteLine(formattedMessage);
BrowserConsoleDiagnostics.Error(formattedMessage);
}
#if !__WASM__
private static void CenterDesktopWindow(Window window)
{
if (!(OperatingSystem.IsWindows() || OperatingSystem.IsMacOS() || OperatingSystem.IsLinux()))
{
return;
}
var nativeWindow = Uno.UI.Xaml.WindowHelper.GetNativeWindow(window);
if (nativeWindow is null)
{
return;
}
if (TryInvokeCenter(nativeWindow) || TrySetCenteredStartupLocation(nativeWindow))
{
return;
}
_ = TryCenterWithRawScreenMetrics(nativeWindow);
}
private static bool TryInvokeCenter(object nativeWindow)
{
var centerMethod = nativeWindow
.GetType()
.GetMethod(
CenterMethodName,
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
if (centerMethod is null || centerMethod.GetParameters().Length != 0)
{
return false;
}
centerMethod.Invoke(nativeWindow, []);
return true;
}
private static bool TrySetCenteredStartupLocation(object nativeWindow)
{
var startupLocationProperty = nativeWindow
.GetType()
.GetProperty(
WindowStartupLocationPropertyName,
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
if (startupLocationProperty?.CanWrite != true || !startupLocationProperty.PropertyType.IsEnum)
{
return false;
}
var centerValue = Enum.GetNames(startupLocationProperty.PropertyType)
.FirstOrDefault(name => string.Equals(name, CenterScreenValueName, StringComparison.Ordinal));
if (centerValue is null)
{
return false;
}
startupLocationProperty.SetValue(nativeWindow, Enum.Parse(startupLocationProperty.PropertyType, centerValue));
return true;
}
private static bool TryCenterWithRawScreenMetrics(object nativeWindow)
{
if (!TryGetNumericPropertyValue(nativeWindow, ScreenWidthPropertyName, out var screenWidth) ||
!TryGetNumericPropertyValue(nativeWindow, ScreenHeightPropertyName, out var screenHeight) ||
!TryGetNumericPropertyValue(nativeWindow, WidthPropertyName, out var width) ||
!TryGetNumericPropertyValue(nativeWindow, HeightPropertyName, out var height))
{
return false;
}
var positionProperty = nativeWindow
.GetType()
.GetProperty(
PositionPropertyName,
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
if (positionProperty?.CanWrite != true)
{
return false;
}
var positionValue = positionProperty.GetValue(nativeWindow) ?? Activator.CreateInstance(positionProperty.PropertyType);
if (positionValue is null)
{
return false;
}
var targetX = Math.Max(0, (screenWidth - width) / 2);
var targetY = Math.Max(0, (screenHeight - height) / 2);
if (!TrySetNumericPropertyValue(positionValue, XPropertyName, targetX) ||
!TrySetNumericPropertyValue(positionValue, YPropertyName, targetY))
{
return false;
}
positionProperty.SetValue(nativeWindow, positionValue);
return true;
}
private static bool TryGetNumericPropertyValue(object target, string propertyName, out int value)
{
var property = target
.GetType()
.GetProperty(
propertyName,
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
if (property is null)
{
value = 0;
return false;
}
var propertyValue = property.GetValue(target);
if (propertyValue is null)
{
value = 0;
return false;
}
value = Convert.ToInt32(propertyValue, System.Globalization.CultureInfo.InvariantCulture);
return true;
}
private static bool TrySetNumericPropertyValue(object target, string propertyName, int value)
{
var property = target
.GetType()
.GetProperty(
propertyName,
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
if (property?.CanWrite != true)
{
return false;
}
var convertedValue = Convert.ChangeType(value, property.PropertyType, System.Globalization.CultureInfo.InvariantCulture);
property.SetValue(target, convertedValue);
return true;
}
#endif
private static void RegisterRoutes(IViewRegistry views, IRouteRegistry routes)
{
views.Register(
new ViewMap(ViewModel: typeof(ShellViewModel)),
new ViewMap<ChatPage, ChatViewModel>(),
new ViewMap<AgentBuilderPage, AgentBuilderViewModel>(),
new ViewMap<SettingsPage, SettingsViewModel>()
);
routes.Register(
new RouteMap("", View: views.FindByViewModel<ShellViewModel>(),
Nested:
[
new ("Chat", View: views.FindByViewModel<ChatViewModel>(), IsDefault:true),
new ("Agents", View: views.FindByViewModel<AgentBuilderViewModel>()),
new ("Settings", View: views.FindByViewModel<SettingsViewModel>()),
]
)
);
}
}