Repository navigation
Expand file tree
/
Copy pathISessionManager.cs
More file actions
86 lines (73 loc) · 3.12 KB
/
Copy pathISessionManager.cs
File metadata and controls
86 lines (73 loc) · 3.12 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
using System;
using System.Diagnostics;
namespace GitCredentialManager
{
public interface ISessionManager
{
/// <summary>
/// Determine if the current session has access to a desktop/can display UI.
/// </summary>
/// <returns>True if the session can display UI, false otherwise.</returns>
bool IsDesktopSession { get; }
/// <summary>
/// Determine if the current session has access to a web browser.
/// </summary>
/// <returns>True if the session can display a web browser, false otherwise.</returns>
bool IsWebBrowserAvailable { get; }
/// <summary>
/// Open the system web browser to the specified URL.
/// </summary>
/// <param name="uri"><see cref="Uri"/> to open the browser at.</param>
/// <exception cref="InvalidOperationException">Thrown if <see cref="IsWebBrowserAvailable"/> is false.</exception>
void OpenBrowser(Uri uri);
}
public static class SessionManagerExtensions
{
public static void OpenBrowser(this ISessionManager sm, string url)
{
if (!Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
{
throw new ArgumentException($"Not a valid URI: '{url}'");
}
sm.OpenBrowser(uri);
}
}
public abstract class SessionManager : ISessionManager
{
protected ITrace Trace { get; }
protected IEnvironment Environment { get; }
protected IFileSystem FileSystem { get; }
protected SessionManager(ITrace trace, IEnvironment env, IFileSystem fs)
{
EnsureArgument.NotNull(trace, nameof(trace));
EnsureArgument.NotNull(env, nameof(env));
EnsureArgument.NotNull(fs, nameof(fs));
Trace = trace;
Environment = env;
FileSystem = fs;
}
public abstract bool IsDesktopSession { get; }
public virtual bool IsWebBrowserAvailable => IsDesktopSession;
public void OpenBrowser(Uri uri)
{
if (!uri.Scheme.Equals(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) &&
!uri.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException("Can only open HTTP/HTTPS URIs", nameof(uri));
}
// Important! Use AbsoluteUri to ensure that the URL is properly
// escaped (e.g. spaces are converted to %20).
// The 'shell execute' handler on some operating systems (e.g. macOS)
// will try to validate the URL handed to it and if it sees any
// unescaped characters it will decide that the rest of the query
// parameters also need esacaping leading to double escaping!
OpenBrowserInternal(uri.AbsoluteUri);
}
protected virtual void OpenBrowserInternal(string url)
{
Trace.WriteLine("Opening browser using framework shell-execute: " + url);
var psi = new ProcessStartInfo(url) { UseShellExecute = true };
Process.Start(psi);
}
}
}