diff --git a/template/framework/__PROJECT_NAME__/DevelopmentLaunch.cs b/template/framework/__PROJECT_NAME__/DevelopmentLaunch.cs new file mode 100644 index 0000000..ba309f5 --- /dev/null +++ b/template/framework/__PROJECT_NAME__/DevelopmentLaunch.cs @@ -0,0 +1,52 @@ +#if DEBUG +using System; +using System.IO; +using System.IO.Pipes; +using System.Linq; +using System.Security.Principal; +using System.Threading; +using System.Threading.Tasks; + +namespace __PROJECT_NAME__ +{ + internal static class DevelopmentLaunch + { + private const string Option = "--ns-dev-launch-v1"; + private const byte Ready = 0x01; + private const byte Commit = 0x02; + + internal static async Task AllowStartupAsync(string[] initialArgs, TimeSpan timeout) + { + int option = Array.IndexOf(initialArgs, Option); + if (option < 0) + return true; + + if (option != initialArgs.Length - 2 || Array.LastIndexOf(initialArgs, Option) != option) + return false; + + string token = initialArgs[option + 1]; + if (token.Length != 32 || !token.All(c => c is >= '0' and <= '9' or >= 'a' and <= 'f')) + return false; + + using var deadline = new CancellationTokenSource(timeout); + try + { + using var pipe = new NamedPipeClientStream(".", "NativeScript.DevLaunch.v1." + token, PipeDirection.InOut, + PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly, TokenImpersonationLevel.Identification); + // The STA entry point waits for this gate. Keep its continuations off that thread. + await pipe.ConnectAsync(deadline.Token).ConfigureAwait(false); + await pipe.WriteAsync(new byte[] { Ready }, deadline.Token).ConfigureAwait(false); + + var response = new byte[1]; + return await pipe.ReadAsync(response, deadline.Token).ConfigureAwait(false) == 1 + && response[0] == Commit && !deadline.IsCancellationRequested; + } + catch (Exception error) when (error is IOException or OperationCanceledException + or UnauthorizedAccessException) + { + return false; + } + } + } +} +#endif diff --git a/template/framework/__PROJECT_NAME__/Program.cs b/template/framework/__PROJECT_NAME__/Program.cs index b28b306..ea269ec 100644 --- a/template/framework/__PROJECT_NAME__/Program.cs +++ b/template/framework/__PROJECT_NAME__/Program.cs @@ -19,6 +19,13 @@ public static void Main(string[] args) { ComWrappersSupport.InitializeComWrappers(); +#if DEBUG + // Keep this on the path that stays in this process, after any activation redirection. + // Only initial Main arguments can acknowledge a development launch. + if (!DevelopmentLaunch.AllowStartupAsync(args, TimeSpan.FromSeconds(15)).GetAwaiter().GetResult()) + return; +#endif + Application.Start((_callbackParams) => { var dispatcherQueue = DispatcherQueue.GetForCurrentThread();