forked from ElectronNET/Electron.NET
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathApp.cs
More file actions
1339 lines (1208 loc) · 64.2 KB
/
App.cs
File metadata and controls
1339 lines (1208 loc) · 64.2 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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using ElectronNET.API.Entities;
using ElectronNET.API.Extensions;
using System;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
// ReSharper disable InconsistentNaming
namespace ElectronNET.API
{
/// <summary>
/// Control your application's event lifecycle.
/// </summary>
public sealed class App : ApiBase
{
protected override SocketTaskEventNameTypes SocketTaskEventNameType => SocketTaskEventNameTypes.NoDashUpperFirst;
protected override SocketEventNameTypes SocketEventNameType => SocketEventNameTypes.DashedLower;
/// <summary>
/// Emitted when all windows have been closed.
/// <para/>
/// If you do not subscribe to this event and all windows are closed, the default behavior is to quit
/// the app; however, if you subscribe, you control whether the app quits or not.If the user pressed
/// Cmd + Q, or the developer called <see cref="Quit"/>, Electron will first try to close all the windows
/// and then emit the <see cref="WillQuit"/> event, and in this case the <see cref="WindowAllClosed"/> event
/// would not be emitted.
/// </summary>
public event Action WindowAllClosed
{
add
{
if (_windowAllClosed == null)
{
BridgeConnector.Socket.On("app-window-all-closed" + GetHashCode(), () =>
{
if (!Electron.WindowManager.IsQuitOnWindowAllClosed || RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
_windowAllClosed();
}
});
BridgeConnector.Socket.Emit("register-app-window-all-closed", GetHashCode());
}
_windowAllClosed += value;
}
remove
{
_windowAllClosed -= value;
if (_windowAllClosed == null)
BridgeConnector.Socket.Off("app-window-all-closed" + GetHashCode());
}
}
private event Action _windowAllClosed;
/// <summary>
/// Emitted before the application starts closing its windows.
/// <para/>
/// Note: If application quit was initiated by <see cref="AutoUpdater.QuitAndInstall"/> then <see cref="BeforeQuit"/>
/// is emitted after emitting close event on all windows and closing them.
/// <para/>
/// Note: On Windows, this event will not be emitted if the app is closed due to a shutdown/restart of the system or a user logout.
/// </summary>
public event Func<QuitEventArgs, Task> BeforeQuit
{
add
{
if (_beforeQuit == null)
{
BridgeConnector.Socket.On("app-before-quit" + GetHashCode(), async () =>
{
await this._beforeQuit(new QuitEventArgs()).ConfigureAwait(false);
if (_preventQuit)
{
_preventQuit = false;
}
else
{
if (_willQuit == null && _quitting == null)
{
Exit();
}
else if (_willQuit != null)
{
await this._willQuit(new QuitEventArgs()).ConfigureAwait(false);
if (_preventQuit)
{
_preventQuit = false;
}
else
{
if (_quitting == null)
{
Exit();
}
else
{
await this._quitting().ConfigureAwait(false);
Exit();
}
}
}
else if (_quitting != null)
{
await this._quitting().ConfigureAwait(false);
Exit();
}
}
});
BridgeConnector.Socket.Emit("register-app-before-quit", GetHashCode());
}
_beforeQuit += value;
}
remove
{
_beforeQuit -= value;
if (_beforeQuit == null)
BridgeConnector.Socket.Off("app-before-quit" + GetHashCode());
}
}
private event Func<QuitEventArgs, Task> _beforeQuit;
/// <summary>
/// Emitted when all windows have been closed and the application will quit.
/// <para/>
/// See the description of the <see cref="WindowAllClosed"/> event for the differences between the <see cref="WillQuit"/>
/// and <see cref="WindowAllClosed"/> events.
/// <para/>
/// Note: On Windows, this event will not be emitted if the app is closed due to a shutdown/restart of the system or a user logout.
/// </summary>
public event Func<QuitEventArgs, Task> WillQuit
{
add
{
if (_willQuit == null)
{
BridgeConnector.Socket.On("app-will-quit" + GetHashCode(), async () =>
{
await this._willQuit(new QuitEventArgs()).ConfigureAwait(false);
if (_preventQuit)
{
_preventQuit = false;
}
else
{
if (_quitting == null)
{
Exit();
}
else
{
await this._quitting().ConfigureAwait(false);
Exit();
}
}
});
BridgeConnector.Socket.Emit("register-app-will-quit", GetHashCode());
}
_willQuit += value;
}
remove
{
_willQuit -= value;
if (_willQuit == null)
BridgeConnector.Socket.Off("app-will-quit" + GetHashCode());
}
}
private event Func<QuitEventArgs, Task> _willQuit;
/// <summary>
/// Emitted when the application is quitting.
/// <para/>
/// Note: On Windows, this event will not be emitted if the app is closed due to a shutdown/restart of the system or a user logout.
/// </summary>
public event Func<Task> Quitting
{
add
{
if (_quitting == null)
{
BridgeConnector.Socket.On("app-will-quit" + GetHashCode() + "quitting", async () =>
{
if (_willQuit == null)
{
await this._quitting().ConfigureAwait(false);
Exit();
}
});
BridgeConnector.Socket.Emit("register-app-will-quit", GetHashCode() + "quitting");
}
_quitting += value;
}
remove
{
_quitting -= value;
if (_quitting == null)
BridgeConnector.Socket.Off("app-will-quit" + GetHashCode() + "quitting");
}
}
private event Func<Task> _quitting;
/// <summary>
/// Emitted when a <see cref="BrowserWindow"/> blurred.
/// </summary>
public event Action BrowserWindowBlur
{
add => AddEvent(value, GetHashCode());
remove => RemoveEvent(value, GetHashCode());
}
/// <summary>
/// Emitted when a <see cref="BrowserWindow"/> gets focused.
/// </summary>
public event Action BrowserWindowFocus
{
add => AddEvent(value, GetHashCode());
remove => RemoveEvent(value, GetHashCode());
}
/// <summary>
/// Emitted when a new <see cref="BrowserWindow"/> is created.
/// </summary>
public event Action BrowserWindowCreated
{
add => AddEvent(value, GetHashCode());
remove => RemoveEvent(value, GetHashCode());
}
/// <summary>
/// Emitted when a new <see cref="WebContents"/> is created.
/// </summary>
public event Action WebContentsCreated
{
add => AddEvent(value, GetHashCode());
remove => RemoveEvent(value, GetHashCode());
}
/// <summary>
/// Emitted when Chrome’s accessibility support changes. This event fires when assistive technologies, such as
/// screen readers, are enabled or disabled. See https://www.chromium.org/developers/design-documents/accessibility for more details.
/// </summary>
/// <returns><see langword="true"/> when Chrome's accessibility support is enabled, <see langword="false"/> otherwise.</returns>
[SupportedOSPlatform("macOS")]
[SupportedOSPlatform("Windows")]
public event Action<bool> AccessibilitySupportChanged
{
add => AddEvent(value, GetHashCode());
remove => RemoveEvent(value, GetHashCode());
}
/// <summary>
/// Emitted when the application has finished basic startup.
/// </summary>
public event Action Ready
{
add
{
if (IsReady)
{
value();
}
_ready += value;
}
remove
{
_ready -= value;
}
}
private event Action _ready;
/// <summary>
/// Application host fully started.
/// </summary>
public bool IsReady
{
get
{
return _isReady;
}
internal set
{
_isReady = value;
if (value)
{
_ready?.Invoke();
}
}
}
private bool _isReady = false;
/// <summary>
/// Emitted when a MacOS user wants to open a file with the application. The open-file event is usually emitted
/// when the application is already open and the OS wants to reuse the application to open the file.
/// open-file is also emitted when a file is dropped onto the dock and the application is not yet running.
/// <para/>
/// On Windows, you have to parse the arguments using App.CommandLine to get the filepath.
/// </summary>
[SupportedOSPlatform("macOS")]
public event Action<string> OpenFile
{
add => AddEvent(value, GetHashCode());
remove => RemoveEvent(value, GetHashCode());
}
/// <summary>
/// Emitted when a MacOS user wants to open a URL with the application. Your application's Info.plist file must
/// define the URL scheme within the CFBundleURLTypes key, and set NSPrincipalClass to AtomApplication.
/// </summary>
[SupportedOSPlatform("macOS")]
public event Action<string> OpenUrl
{
add => AddEvent(value, GetHashCode());
remove => RemoveEvent(value, GetHashCode());
}
/// <summary>
/// A <see cref="string"/> property that indicates the current application's name, which is the name in the
/// application's package.json file.
///
/// Usually the name field of package.json is a short lowercase name, according to the npm modules spec. You
/// should usually also specify a productName field, which is your application's full capitalized name, and
/// which will be preferred over name by Electron.
/// </summary>
public string Name
{
[Obsolete("Use the asynchronous version NameAsync instead")]
get
{
return NameAsync.Result;
}
set
{
BridgeConnector.Socket.Emit("appSetName", value);
}
}
/// <summary>
/// A <see cref="string"/> property that indicates the current application's name, which is the name in the
/// application's package.json file.
///
/// Usually the name field of package.json is a short lowercase name, according to the npm modules spec. You
/// should usually also specify a productName field, which is your application's full capitalized name, and
/// which will be preferred over name by Electron.
/// </summary>
public Task<string> NameAsync
{
get
{
return this.InvokeAsync<string>();
}
}
internal App()
{
CommandLine = new CommandLine();
}
internal static App Instance
{
get
{
if (_app == null)
{
lock (_syncRoot)
{
if (_app == null)
{
_app = new App();
}
}
}
return _app;
}
}
private static App _app;
private static object _syncRoot = new object();
/// <summary>
/// Try to close all windows. The <see cref="BeforeQuit"/> event will be emitted first. If all windows are successfully
/// closed, the <see cref="WillQuit"/> event will be emitted and by default the application will terminate. This method
/// guarantees that all beforeunload and unload event handlers are correctly executed. It is possible
/// that a window cancels the quitting by returning <see langword="false"/> in the beforeunload event handler.
/// </summary>
public void Quit()
{
this.CallMethod0();
}
/// <summary>
/// All windows will be closed immediately without asking user and the <see cref="BeforeQuit"/> and <see cref="WillQuit"/>
/// events will not be emitted.
/// </summary>
/// <param name="exitCode">Exits immediately with exitCode. exitCode defaults to 0.</param>
public void Exit(int exitCode = 0)
{
this.CallMethod1(exitCode);
}
public void DisposeSocket()
{
BridgeConnector.Socket.DisposeSocket();
}
/// <summary>
/// Relaunches the app when current instance exits. By default the new instance will use the same working directory
/// and command line arguments with current instance.
/// <para/>
/// Note that this method does not quit the app when executed, you have to call <see cref="Quit"/> or <see cref="Exit"/>
/// after calling <see cref="Relaunch()"/> to make the app restart.
/// <para/>
/// When <see cref="Relaunch()"/> is called for multiple times, multiple instances will be started after current instance
/// exited.
/// </summary>
public void Relaunch()
{
this.CallMethod0();
}
/// <summary>
/// Relaunches the app when current instance exits. By default the new instance will use the same working directory
/// and command line arguments with current instance. When <see cref="RelaunchOptions.Args"/> is specified, the
/// <see cref="RelaunchOptions.Args"/> will be passed as command line arguments instead. When <see cref="RelaunchOptions.ExecPath"/>
/// is specified, the <see cref="RelaunchOptions.ExecPath"/> will be executed for relaunch instead of current app.
/// <para/>
/// Note that this method does not quit the app when executed, you have to call <see cref="Quit"/> or <see cref="Exit"/>
/// after calling <see cref="Relaunch()"/> to make the app restart.
/// <para/>
/// When <see cref="Relaunch()"/> is called for multiple times, multiple instances will be started after current instance
/// exited.
/// </summary>
/// <param name="relaunchOptions">Options for the relaunch.</param>
public void Relaunch(RelaunchOptions relaunchOptions)
{
this.CallMethod1(relaunchOptions);
}
/// <summary>
/// On Linux, focuses on the first visible window. On macOS, makes the application the active app. On Windows, focuses
/// on the application's first window.
/// </summary>
public void Focus()
{
this.CallMethod0();
}
/// <summary>
/// On Linux, focuses on the first visible window. On macOS, makes the application the active app. On Windows, focuses
/// on the application's first window.
/// <para/>
/// You should seek to use the <see cref="FocusOptions.Steal"/> option as sparingly as possible.
/// </summary>
public void Focus(FocusOptions focusOptions)
{
this.CallMethod1(focusOptions);
}
/// <summary>
/// Hides all application windows without minimizing them.
/// </summary>
[SupportedOSPlatform("macOS")]
public void Hide()
{
this.CallMethod0();
}
/// <summary>
/// Shows application windows after they were hidden. Does not automatically focus them.
/// </summary>
[SupportedOSPlatform("macOS")]
public void Show()
{
this.CallMethod0();
}
/// <summary>
/// The current application directory.
/// </summary>
public async Task<string> GetAppPathAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
return await this.InvokeAsync<string>().ConfigureAwait(false);
}
/// <summary>
/// Sets or creates a directory your app's logs which can then be manipulated with <see cref="GetPathAsync"/>
/// or <see cref="SetPath"/>.
/// <para/>
/// Calling <see cref="SetAppLogsPath"/> without a path parameter will result in this directory being set to
/// ~/Library/Logs/YourAppName on macOS, and inside the userData directory on Linux and Windows.
/// </summary>
/// <param name="path">A custom path for your logs. Must be absolute.</param>
public void SetAppLogsPath(string path)
{
this.CallMethod1(path);
}
/// <summary>
/// The path to a special directory. If <see cref="GetPathAsync"/> is called without called
/// <see cref="SetAppLogsPath"/> being called first, a default directory will be created equivalent
/// to calling <see cref="SetAppLogsPath"/> without a path parameter.
/// </summary>
/// <param name="pathName">Special directory.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A path to a special directory or file associated with name.</returns>
public async Task<string> GetPathAsync(PathName pathName, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var taskCompletionSource = new TaskCompletionSource<string>();
using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled()))
{
BridgeConnector.Socket.Once<string>("appGetPathCompleted", taskCompletionSource.SetResult);
BridgeConnector.Socket.Emit("appGetPath", pathName);
return await taskCompletionSource.Task
.ConfigureAwait(false);
}
}
/// <summary>
/// Overrides the path to a special directory or file associated with name. If the path specifies a directory
/// that does not exist, an Error is thrown. In that case, the directory should be created with fs.mkdirSync or similar.
/// <para/>
/// You can only override paths of a name defined in <see cref="GetPathAsync"/>.
/// <para/>
/// By default, web pages' cookies and caches will be stored under the <see cref="PathName.UserData"/> directory. If you
/// want to change this location, you have to override the <see cref="PathName.UserData"/> path before the <see cref="Ready"/>
/// event of the <see cref="App"/> module is emitted.
/// <param name="name">Special directory.</param>
/// <param name="path">New path to a special directory.</param>
/// </summary>
public void SetPath(PathName name, string path)
{
this.CallMethod2(name, path);
}
/// <summary>
/// The version of the loaded application. If no version is found in the application’s package.json file,
/// the version of the current bundle or executable is returned.
/// </summary>
/// <returns>The version of the loaded application.</returns>
public async Task<string> GetVersionAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
return await this.InvokeAsync<string>().ConfigureAwait(false);
}
/// <summary>
/// The current application locale. Possible return values are documented <see href="https://www.electronjs.org/docs/api/locales">here</see>.
/// <para/>
/// Note: When distributing your packaged app, you have to also ship the locales folder.
/// <para/>
/// Note: On Windows, you have to call it after the <see cref="Ready"/> events gets emitted.
/// </summary>
/// <returns>The current application locale.</returns>
public async Task<string> GetLocaleAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
return await this.InvokeAsync<string>().ConfigureAwait(false);
}
/// <summary>
/// Adds path to the recent documents list. This list is managed by the OS. On Windows you can visit the
/// list from the task bar, and on macOS you can visit it from dock menu.
/// </summary>
/// <param name="path">Path to add.</param>
[SupportedOSPlatform("macOS")]
[SupportedOSPlatform("Windows")]
public void AddRecentDocument(string path)
{
this.CallMethod1(path);
}
/// <summary>
/// Clears the recent documents list.
/// </summary>
[SupportedOSPlatform("macOS")]
[SupportedOSPlatform("Windows")]
public void ClearRecentDocuments()
{
this.CallMethod0();
}
/// <summary>
/// Sets the current executable as the default handler for a protocol (aka URI scheme). It allows you to
/// integrate your app deeper into the operating system. Once registered, all links with your-protocol://
/// will be opened with the current executable. The whole link, including protocol, will be passed to your
/// application as a parameter.
/// <para/>
/// Note: On macOS, you can only register protocols that have been added to your app's info.plist, which
/// cannot be modified at runtime. However, you can change the file during build time via
/// <see href="https://www.electronforge.io/">Electron Forge</see>,
/// <see href="https://github.com/electron/electron-packager">Electron Packager</see>, or by editing info.plist
/// with a text editor. Please refer to
/// <see href="https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/TP40009249-102207-TPXREF115">Apple's documentation</see>
/// for details.
/// <para/>
/// Note: In a Windows Store environment (when packaged as an appx) this API will return true for all calls but
/// the registry key it sets won't be accessible by other applications. In order to register your Windows Store
/// application as a default protocol handler you <see href="https://docs.microsoft.com/en-us/uwp/schemas/appxpackage/uapmanifestschema/element-uap-protocol">must declare the protocol in your manifest</see>.
/// <para/>
/// The API uses the Windows Registry and LSSetDefaultHandlerForURLScheme internally.
/// </summary>
/// <param name="protocol">
/// The name of your protocol, without ://. For example, if you want your app to handle electron:// links,
/// call this method with electron as the parameter.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Whether the call succeeded.</returns>
public async Task<bool> SetAsDefaultProtocolClientAsync(string protocol, CancellationToken cancellationToken = default)
{
return await this.SetAsDefaultProtocolClientAsync(protocol, null, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Sets the current executable as the default handler for a protocol (aka URI scheme). It allows you to
/// integrate your app deeper into the operating system. Once registered, all links with your-protocol://
/// will be opened with the current executable. The whole link, including protocol, will be passed to your
/// application as a parameter.
/// <para/>
/// Note: On macOS, you can only register protocols that have been added to your app's info.plist, which
/// cannot be modified at runtime. However, you can change the file during build time via
/// <see href="https://www.electronforge.io/">Electron Forge</see>,
/// <see href="https://github.com/electron/electron-packager">Electron Packager</see>, or by editing info.plist
/// with a text editor. Please refer to
/// <see href="https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/TP40009249-102207-TPXREF115">Apple's documentation</see>
/// for details.
/// <para/>
/// Note: In a Windows Store environment (when packaged as an appx) this API will return true for all calls but
/// the registry key it sets won't be accessible by other applications. In order to register your Windows Store
/// application as a default protocol handler you <see href="https://docs.microsoft.com/en-us/uwp/schemas/appxpackage/uapmanifestschema/element-uap-protocol">must declare the protocol in your manifest</see>.
/// <para/>
/// The API uses the Windows Registry and LSSetDefaultHandlerForURLScheme internally.
/// </summary>
/// <param name="protocol">
/// The name of your protocol, without ://. For example, if you want your app to handle electron:// links,
/// call this method with electron as the parameter.</param>
/// <param name="path">The path to the Electron executable. Defaults to process.execPath</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Whether the call succeeded.</returns>
public async Task<bool> SetAsDefaultProtocolClientAsync(string protocol, string path, CancellationToken cancellationToken = default)
{
return await this.SetAsDefaultProtocolClientAsync(protocol, path, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Sets the current executable as the default handler for a protocol (aka URI scheme). It allows you to
/// integrate your app deeper into the operating system. Once registered, all links with your-protocol://
/// will be opened with the current executable. The whole link, including protocol, will be passed to your
/// application as a parameter.
/// <para/>
/// Note: On macOS, you can only register protocols that have been added to your app's info.plist, which
/// cannot be modified at runtime. However, you can change the file during build time via
/// <see href="https://www.electronforge.io/">Electron Forge</see>,
/// <see href="https://github.com/electron/electron-packager">Electron Packager</see>, or by editing info.plist
/// with a text editor. Please refer to
/// <see href="https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/TP40009249-102207-TPXREF115">Apple's documentation</see>
/// for details.
/// <para/>
/// Note: In a Windows Store environment (when packaged as an appx) this API will return true for all calls but
/// the registry key it sets won't be accessible by other applications. In order to register your Windows Store
/// application as a default protocol handler you <see href="https://docs.microsoft.com/en-us/uwp/schemas/appxpackage/uapmanifestschema/element-uap-protocol">must declare the protocol in your manifest</see>.
/// <para/>
/// The API uses the Windows Registry and LSSetDefaultHandlerForURLScheme internally.
/// </summary>
/// <param name="protocol">
/// The name of your protocol, without ://. For example, if you want your app to handle electron:// links,
/// call this method with electron as the parameter.</param>
/// <param name="path">The path to the Electron executable. Defaults to process.execPath</param>
/// <param name="args">Arguments passed to the executable. Defaults to an empty array.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Whether the call succeeded.</returns>
public async Task<bool> SetAsDefaultProtocolClientAsync(string protocol, string path, string[] args, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var taskCompletionSource = new TaskCompletionSource<bool>();
using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled()))
{
BridgeConnector.Socket.Once<bool>("appSetAsDefaultProtocolClientCompleted", taskCompletionSource.SetResult);
BridgeConnector.Socket.Emit("appSetAsDefaultProtocolClient", protocol, path, args);
return await taskCompletionSource.Task
.ConfigureAwait(false);
}
}
/// <summary>
/// This method checks if the current executable as the default handler for a protocol (aka URI scheme).
/// If so, it will remove the app as the default handler.
/// </summary>
/// <param name="protocol">The name of your protocol, without ://.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Whether the call succeeded.</returns>
[SupportedOSPlatform("macOS")]
[SupportedOSPlatform("Windows")]
public async Task<bool> RemoveAsDefaultProtocolClientAsync(string protocol, CancellationToken cancellationToken = default)
{
return await this.RemoveAsDefaultProtocolClientAsync(protocol, null, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// This method checks if the current executable as the default handler for a protocol (aka URI scheme).
/// If so, it will remove the app as the default handler.
/// </summary>
/// <param name="protocol">The name of your protocol, without ://.</param>
/// <param name="path">Defaults to process.execPath.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Whether the call succeeded.</returns>
[SupportedOSPlatform("macOS")]
[SupportedOSPlatform("Windows")]
public async Task<bool> RemoveAsDefaultProtocolClientAsync(string protocol, string path, CancellationToken cancellationToken = default)
{
return await this.RemoveAsDefaultProtocolClientAsync(protocol, path, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// This method checks if the current executable as the default handler for a protocol (aka URI scheme).
/// If so, it will remove the app as the default handler.
/// </summary>
/// <param name="protocol">The name of your protocol, without ://.</param>
/// <param name="path">Defaults to process.execPath.</param>
/// <param name="args">Defaults to an empty array.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Whether the call succeeded.</returns>
[SupportedOSPlatform("macOS")]
[SupportedOSPlatform("Windows")]
public async Task<bool> RemoveAsDefaultProtocolClientAsync(string protocol, string path, string[] args, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var taskCompletionSource = new TaskCompletionSource<bool>();
using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled()))
{
BridgeConnector.Socket.Once<bool>("appRemoveAsDefaultProtocolClientCompleted", taskCompletionSource.SetResult);
BridgeConnector.Socket.Emit("appRemoveAsDefaultProtocolClient", protocol, path, args);
return await taskCompletionSource.Task
.ConfigureAwait(false);
}
}
/// <summary>
/// This method checks if the current executable is the default handler for a protocol (aka URI scheme).
/// <para/>
/// Note: On macOS, you can use this method to check if the app has been registered as the default protocol
/// handler for a protocol. You can also verify this by checking ~/Library/Preferences/com.apple.LaunchServices.plist
/// on the macOS machine. Please refer to <see href="https://developer.apple.com/library/mac/documentation/Carbon/Reference/LaunchServicesReference/#//apple_ref/c/func/LSCopyDefaultHandlerForURLScheme">Apple's documentation</see>
/// for details.
/// <para/>
/// The API uses the Windows Registry and LSCopyDefaultHandlerForURLScheme internally.
/// </summary>
/// <param name="protocol">The name of your protocol, without ://.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Whether the current executable is the default handler for a protocol (aka URI scheme).</returns>
public async Task<bool> IsDefaultProtocolClientAsync(string protocol, CancellationToken cancellationToken = default)
{
return await this.IsDefaultProtocolClientAsync(protocol, null, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// This method checks if the current executable is the default handler for a protocol (aka URI scheme).
/// <para/>
/// Note: On macOS, you can use this method to check if the app has been registered as the default protocol
/// handler for a protocol. You can also verify this by checking ~/Library/Preferences/com.apple.LaunchServices.plist
/// on the macOS machine. Please refer to <see href="https://developer.apple.com/library/mac/documentation/Carbon/Reference/LaunchServicesReference/#//apple_ref/c/func/LSCopyDefaultHandlerForURLScheme">Apple's documentation</see>
/// for details.
/// <para/>
/// The API uses the Windows Registry and LSCopyDefaultHandlerForURLScheme internally.
/// </summary>
/// <param name="protocol">The name of your protocol, without ://.</param>
/// <param name="path">Defaults to process.execPath.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Whether the current executable is the default handler for a protocol (aka URI scheme).</returns>
public async Task<bool> IsDefaultProtocolClientAsync(string protocol, string path, CancellationToken cancellationToken = default)
{
return await this.IsDefaultProtocolClientAsync(protocol, path, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// This method checks if the current executable is the default handler for a protocol (aka URI scheme).
/// <para/>
/// Note: On macOS, you can use this method to check if the app has been registered as the default protocol
/// handler for a protocol. You can also verify this by checking ~/Library/Preferences/com.apple.LaunchServices.plist
/// on the macOS machine. Please refer to <see href="https://developer.apple.com/library/mac/documentation/Carbon/Reference/LaunchServicesReference/#//apple_ref/c/func/LSCopyDefaultHandlerForURLScheme">Apple's documentation</see>
/// for details.
/// <para/>
/// The API uses the Windows Registry and LSCopyDefaultHandlerForURLScheme internally.
/// </summary>
/// <param name="protocol">The name of your protocol, without ://.</param>
/// <param name="path">Defaults to process.execPath.</param>
/// <param name="args">Defaults to an empty array.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Whether the current executable is the default handler for a protocol (aka URI scheme).</returns>
public async Task<bool> IsDefaultProtocolClientAsync(string protocol, string path, string[] args, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var taskCompletionSource = new TaskCompletionSource<bool>();
using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled()))
{
BridgeConnector.Socket.Once<bool>("appIsDefaultProtocolClientCompleted", taskCompletionSource.SetResult);
BridgeConnector.Socket.Emit("appIsDefaultProtocolClient", protocol, path, args);
return await taskCompletionSource.Task
.ConfigureAwait(false);
}
}
/// <summary>
/// Adds tasks to the <see cref="UserTask"/> category of the JumpList on Windows.
/// <para/>
/// Note: If you'd like to customize the Jump List even more use <see cref="SetJumpList"/> instead.
/// </summary>
/// <param name="userTasks">Array of <see cref="UserTask"/> objects.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Whether the call succeeded.</returns>
[SupportedOSPlatform("Windows")]
public async Task<bool> SetUserTasksAsync(UserTask[] userTasks, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var taskCompletionSource = new TaskCompletionSource<bool>();
using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled()))
{
BridgeConnector.Socket.Once<bool>("appSetUserTasksCompleted", taskCompletionSource.SetResult);
BridgeConnector.Socket.Emit("appSetUserTasks", userTasks);
return await taskCompletionSource.Task
.ConfigureAwait(false);
}
}
/// <summary>
/// Jump List settings for the application.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Jump List settings.</returns>
[SupportedOSPlatform("Windows")]
public async Task<JumpListSettings> GetJumpListSettingsAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
return await this.InvokeAsync<JumpListSettings>().ConfigureAwait(false);
}
/// <summary>
/// Sets or removes a custom Jump List for the application. If categories is null the previously set custom
/// Jump List (if any) will be replaced by the standard Jump List for the app (managed by Windows).
/// <para/>
/// Note: If a <see cref="JumpListCategory"/> object has neither the <see cref="JumpListCategory.Type"/> nor
/// the <see cref="JumpListCategory.Name"/> property set then its <see cref="JumpListCategory.Type"/> is assumed
/// to be <see cref="JumpListCategoryType.tasks"/>. If the <see cref="JumpListCategory.Name"/> property is set but
/// the <see cref="JumpListCategory.Type"/> property is omitted then the <see cref="JumpListCategory.Type"/> is
/// assumed to be <see cref="JumpListCategoryType.custom"/>.
/// <para/>
/// Note: Users can remove items from custom categories, and Windows will not allow a removed item to be added
/// back into a custom category until after the next successful call to <see cref="SetJumpList"/>. Any attempt
/// to re-add a removed item to a custom category earlier than that will result in the entire custom category being
/// omitted from the Jump List. The list of removed items can be obtained using <see cref="GetJumpListSettingsAsync"/>.
/// </summary>
/// <param name="categories">Array of <see cref="JumpListCategory"/> objects.</param>
[SupportedOSPlatform("Windows")]
public void SetJumpList(JumpListCategory[] categories)
{
this.CallMethod1(categories);
}
/// <summary>
/// The return value of this method indicates whether or not this instance of your application successfully obtained
/// the lock. If it failed to obtain the lock, you can assume that another instance of your application is already
/// running with the lock and exit immediately.
/// <para/>
/// I.e.This method returns <see langword="true"/> if your process is the primary instance of your application and your
/// app should continue loading. It returns <see langword="false"/> if your process should immediately quit as it has
/// sent its parameters to another instance that has already acquired the lock.
/// <para/>
/// On macOS, the system enforces single instance automatically when users try to open a second instance of your app
/// in Finder, and the open-file and open-url events will be emitted for that.However when users start your app in
/// command line, the system's single instance mechanism will be bypassed, and you have to use this method to ensure
/// single instance.
/// </summary>
/// <param name="newInstanceOpened">Lambda with an array of the second instance’s command line arguments.
/// The second parameter is the working directory path.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>This method returns false if your process is the primary instance of the application and your app
/// should continue loading. And returns true if your process has sent its parameters to another instance, and
/// you should immediately quit.
/// </returns>
public async Task<bool> RequestSingleInstanceLockAsync(Action<string[], string> newInstanceOpened, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var taskCompletionSource = new TaskCompletionSource<bool>();
using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled()))
{
BridgeConnector.Socket.Once<bool>("appRequestSingleInstanceLockCompleted", taskCompletionSource.SetResult);
BridgeConnector.Socket.Off("secondInstance");
BridgeConnector.Socket.On<JsonElement>("secondInstance", (result) =>
{
var arr = result.EnumerateArray();
var e = arr.GetEnumerator();
e.MoveNext();
var args = e.Current.Deserialize<string[]>(JsonSerializerOptions.Default);
e.MoveNext();
var workingDirectory = e.Current.GetString();
newInstanceOpened(args, workingDirectory);
});
BridgeConnector.Socket.Emit("appRequestSingleInstanceLock");
return await taskCompletionSource.Task
.ConfigureAwait(false);
}
}
/// <summary>
/// Releases all locks that were created by makeSingleInstance. This will allow
/// multiple instances of the application to once again run side by side.
/// </summary>
public void ReleaseSingleInstanceLock()
{
this.CallMethod0();
}
/// <summary>
/// This method returns whether or not this instance of your app is currently holding the single instance lock.
/// You can request the lock with <see cref="RequestSingleInstanceLockAsync"/> and release with
/// <see cref="ReleaseSingleInstanceLock"/>.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
public async Task<bool> HasSingleInstanceLockAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
return await this.InvokeAsync<bool>().ConfigureAwait(false);
}
/// <summary>
/// Creates an NSUserActivity and sets it as the current activity. The activity is
/// eligible for <see href="https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/Handoff/HandoffFundamentals/HandoffFundamentals.html">Handoff</see>
/// to another device afterward.
/// </summary>
/// <param name="type">Uniquely identifies the activity. Maps to <see href="https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSUserActivity_Class/index.html#//apple_ref/occ/instp/NSUserActivity/activityType">NSUserActivity.activityType</see>.</param>
/// <param name="userInfo">App-specific state to store for use by another device.</param>
[SupportedOSPlatform("macOS")]
public void SetUserActivity(string type, object userInfo)
{
SetUserActivity(type, userInfo, null);
}
/// <summary>
/// Creates an NSUserActivity and sets it as the current activity. The activity is
/// eligible for <see href="https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/Handoff/HandoffFundamentals/HandoffFundamentals.html">Handoff</see>
/// to another device afterward.
/// </summary>
/// <param name="type">
/// Uniquely identifies the activity. Maps to <see href="https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSUserActivity_Class/index.html#//apple_ref/occ/instp/NSUserActivity/activityType">NSUserActivity.activityType</see>.
/// </param>
/// <param name="userInfo">App-specific state to store for use by another device.</param>
/// <param name="webpageUrl">
/// The webpage to load in a browser if no suitable app is installed on the resuming device. The scheme must be http or https.
/// </param>
[SupportedOSPlatform("macOS")]
public void SetUserActivity(string type, object userInfo, string webpageUrl)
{
this.CallMethod3(type, userInfo, webpageUrl);
}
/// <summary>
/// The type of the currently running activity.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>