-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMainWindow.xaml.cs
185 lines (158 loc) · 7.03 KB
/
MainWindow.xaml.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
using MahApps.Metro.Controls;
using Serilog;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Input;
using Path = System.IO.Path;
namespace SSHMan
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : MetroWindow
{
private readonly HostModel model = new HostModel();
private bool keepOpen = true;
private readonly Dictionary<Guid, Thread> threads = new Dictionary<Guid, Thread>();
private readonly ConcurrentBag<Guid> deadThreads = new ConcurrentBag<Guid>();
public static readonly ManualResetEventSlim ShutdownSignal = new ManualResetEventSlim(false);
public MainWindow()
{
this.InitializeComponent();
this.sshMenu.DataContext = model;
}
private void LauncherToggleToggled(object sender, RoutedEventArgs e)
{
if (sender is ToggleSwitch toggleSwitch)
{
keepOpen = toggleSwitch.IsOn;
}
}
private void LaunchSSHSession(string target, Guid workId)
{
Log.Information("Connecting to {host}", target);
var wtpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Microsoft", "WindowsApps", "wt.exe");
Log.Information("Executing client script...");
using var proc = new Process()
{
StartInfo = new ProcessStartInfo()
{
FileName = wtpath,
ArgumentList = { "new-tab", "-p", "Remote", "pwsh.exe", "-NoLogo", "-NonInteractive", "-File", App.ScriptPath, workId.ToString() },
UseShellExecute = false,
RedirectStandardError = true,
StandardErrorEncoding = Encoding.Unicode,
},
EnableRaisingEvents = true,
};
proc.Exited += this.Proc_Exited;
proc.ErrorDataReceived += this.Proc_ErrorDataReceived;
var success = proc.Start();
Debug.Assert(success);
Log.Debug("Thread ({thread}) initialized and running", Thread.CurrentThread.ManagedThreadId);
proc.WaitForExit();
Log.Debug("Process for thread ({thread}) exited", Thread.CurrentThread.ManagedThreadId);
}
private void Proc_ErrorDataReceived(object sender, DataReceivedEventArgs e) => Log.Error("SSH Error: {error}", e.Data);
private void Proc_Exited(object sender, EventArgs e)
{
if (sender is Process handle)
{
if (handle.ExitCode != 0)
{
var err = handle.StandardError.ReadToEnd();
_ = MessageBox.Show(err, "Connection failed", MessageBoxButton.OK, MessageBoxImage.Error);
}
var workId = new Guid(handle.StartInfo.ArgumentList.Last());
Log.Debug("Thread with work id {id} died and was added to the queue", workId);
deadThreads.Add(workId);
}
}
private void Connect_Click(object sender, RoutedEventArgs e)
{
var host = this.sshMenu.SelectedItem as SSHHostEntry;
Connect(host);
}
private void Connect(SSHHostEntry host)
{
var workId = Guid.NewGuid();
var msghandle = PwshIPC.Message(host.Name, exitAfterDelivery: !keepOpen, workId);
var thread = new Thread(() => this.LaunchSSHSession(host.Name, workId));
thread.Start();
Log.Debug("Thread ({id}) started with work id: {workid}", thread.ManagedThreadId, workId);
threads[workId] = thread;
if (!keepOpen)
{
ShutdownSignal.Wait();
Application.Current.Shutdown();
}
}
private void ConfigClick(object sender, RoutedEventArgs e)
{
var localsshdir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".ssh");
var localsshcfg = Path.Combine(localsshdir, "config");
App.EnsureDirectory(localsshdir);
if (!File.Exists(localsshcfg))
{
File.WriteAllText(localsshcfg, Encoding.UTF8.GetString(Scripts.ssh));
}
using var proc = new Process() { StartInfo = new ProcessStartInfo() { FileName = "notepad", ArgumentList = { localsshcfg }, LoadUserProfile = true, UseShellExecute = true } };
_ = proc.Start();
proc.WaitForExit();
model.Clear();
model.Update();
}
private void SettingsBntClick(object sender, RoutedEventArgs e) => this.settingsFlyout.IsOpen = !this.settingsFlyout.IsOpen;
private void MetroWindow_Closed(object sender, EventArgs e)
{
ShutdownSignal.Set();
Log.Debug("Found {count} dead threads. Beginning with cleanup", deadThreads.Count);
foreach (var corpse in deadThreads)
{
if (threads[corpse].ThreadState == System.Threading.ThreadState.Unstarted) continue;
Log.Debug("\t > .. joining Thread {id}", threads[corpse].ManagedThreadId);
var success = threads[corpse].Join(TimeSpan.FromSeconds(3));
if (!success)
{
Log.Error("Thread (id) stopped responding and will be terminated", threads[corpse].ManagedThreadId);
threads[corpse].Abort();
}
}
ShutdownSignal.Dispose();
}
private void SSHMenu_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
var host = this.sshMenu.SelectedItem as SSHHostEntry;
Connect(host);
}
private void ExportProfiles_Click(object sender, RoutedEventArgs e)
{
var (stableExists, stableJson) = SSHToProfileConverter.GenerateSettings(App.WtSettings);
var (previewExists, previewJson) = SSHToProfileConverter.GenerateSettings(App.WtPreviewSettings);
var backupPaths = new List<string>();
if (stableExists)
{
backupPaths.Add(App.BackupFile(App.WtSettings, "stable-"));
File.WriteAllText(App.WtSettings, stableJson);
}
if (previewExists)
{
backupPaths.Add(App.BackupFile(App.WtPreviewSettings, "preview-"));
File.WriteAllText(App.WtPreviewSettings, previewJson);
}
var message = "Successfully exported all know SSH hosts into Windows Terminal profiles.\nA backup from your old config(s) can be found here:";
foreach (var path in backupPaths)
{
message += $"\n\n - {path}";
}
MessageBox.Show(message, "Profiles exported", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
}