-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathEasyTerminalControl.cs
More file actions
275 lines (239 loc) · 11.4 KB
/
EasyTerminalControl.cs
File metadata and controls
275 lines (239 loc) · 11.4 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
using System;
using System.ComponentModel;
using System.Threading.Tasks;
#if WPF
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
#else
using System.Drawing;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.Terminal.WinUI3;
using FontFamily = Microsoft.UI.Xaml.Media.FontFamily;
using Microsoft.UI.Xaml.Input;
#endif
using EasyWindowsTerminalControl.Internals;
using Microsoft.Terminal.Wpf;
using System.Diagnostics;
namespace EasyWindowsTerminalControl {
public class EasyTerminalControl : UserControl {
/// <summary>
/// Converts Color to COLOREF, note that COLOREF does not support alpha channels so it is ignored
/// </summary>
/// <param name="color"></param>
/// <returns></returns>
public static uint ColorToVal(Color color) => BitConverter.ToUInt32(new byte[] { color.R, color.G, color.B, 0 }, 0);
public EasyTerminalControl() {
InitializeComponent();
SetKBCaptureOptions();
#if WPF
#else
this.RegisterPropertyChangedCallback(UIElement.VisibilityProperty, OnVisibleChanged);
#endif
}
#if WPF
#else
private void OnVisibleChanged(DependencyObject sender, DependencyProperty dp) {
if (Terminal != null)
Terminal.Visibility = Visibility;
}
#endif
[Flags]
[System.ComponentModel.TypeConverter(typeof(System.ComponentModel.EnumConverter))]
public enum INPUT_CAPTURE { None = 1 << 0, TabKey = 1 << 1, DirectionKeys = 1 << 2 };
private static void InputCaptureChanged(DependencyObject target, DependencyPropertyChangedEventArgs e) {
var cntrl = target as EasyTerminalControl;
cntrl.SetKBCaptureOptions();
}
private void SetKBCaptureOptions() {
#if WPF
KeyboardNavigation.SetTabNavigation(this, InputCapture.HasFlag(INPUT_CAPTURE.TabKey) ? KeyboardNavigationMode.Contained : KeyboardNavigationMode.Continue);
KeyboardNavigation.SetDirectionalNavigation(this, InputCapture.HasFlag(INPUT_CAPTURE.DirectionKeys) ? KeyboardNavigationMode.Contained : KeyboardNavigationMode.Continue);
#endif
}
/// <summary>
/// Helper property for setting KeyboardNavigation.Set*Navigation commands to prevent arrow keys or tabs from causing us to leave the control (aka pass through to conpty)
/// </summary>
public INPUT_CAPTURE InputCapture {
get => (INPUT_CAPTURE)GetValue(InputCaptureProperty);
set => SetValue(InputCaptureProperty, value);
}
[Description("Write only, sets the terminal theme"), Category("Common")]
public TerminalTheme? Theme { set => SetTheme(_Theme = value); private get => _Theme; }
private TerminalTheme? _Theme;
private void SetTheme(TerminalTheme? v) { if (v != null) Terminal?.SetTheme(v.Value, FontFamilyWhenSettingTheme.Source, (short)FontSizeWhenSettingTheme); }
[Description("Write only, When true user cannot give input through the Terminal UI (can still write to the Term from code behind using Term.WriteToTerm)"), Category("Common")]
public bool? IsReadOnly { set => SetReadOnly(_IsReadOnly = value); private get => _IsReadOnly; }
private bool? _IsReadOnly;
private void SetReadOnly(bool? v) { if (v != null) ConPTYTerm?.SetReadOnly(v.Value, false); }//no cursor auto update if user wants that they can use the separate dependency property for the cursor visibility
[Description("Write only, if the type cursor shows on the Terminal UI"), Category("Common")]
public bool? IsCursorVisible { set => SetCursor(_IsCursorVisible = value); private get => _IsCursorVisible; }
private bool? _IsCursorVisible;
private void SetCursor(bool? v) { if (v != null) ConPTYTerm?.SetCursorVisibility(v.Value); }
[Description("Direct access to the UI terminal control itself that handles rendering")]
public TerminalControl Terminal {
#if WPF
get => (TerminalControl)GetValue(TerminalPropertyKey.DependencyProperty);
set => SetValue(TerminalPropertyKey, value);
#else
get => (TerminalControl)GetValue(TerminalProperty);
set => SetValue(TerminalProperty, value);
#endif
}
private static void OnTermChanged(DependencyObject target, DependencyPropertyChangedEventArgs e) {
var cntrl = (target as EasyTerminalControl);
var newTerm = e.NewValue as TermPTY;
if (newTerm != null) {
if (cntrl.Terminal.IsLoaded)
cntrl.Terminal_Loaded(cntrl.Terminal, null);
if (newTerm.TermProcIsStarted)
cntrl.Term_TermReady(newTerm, null);
else
newTerm.TermReady += cntrl.Term_TermReady;
}
}
/// <summary>
/// Update the Term if you want to set to an existing
/// </summary>
[Description("The backend TermPTY connection allows changing the application the control is connected to")]
public TermPTY ConPTYTerm {
get => (TermPTY)GetValue(ConPTYTermProperty);
set => SetValue(ConPTYTermProperty, value);
}
public TermPTY DisconnectConPTYTerm() {
if (Terminal != null)
Terminal.Connection = null;
if (ConPTYTerm != null)
ConPTYTerm.TermReady -= Term_TermReady;
var ret = ConPTYTerm;
ConPTYTerm = null;
return ret;
}
public string StartupCommandLine {
get => (string)GetValue(StartupCommandLineProperty);
set => SetValue(StartupCommandLineProperty, value);
}
public string WorkingDirectory {
get => (string)GetValue(WorkingDirectoryProperty);
set => SetValue(WorkingDirectoryProperty, value);
}
public bool LogConPTYOutput {
get => (bool)GetValue(LogConPTYOutputProperty);
set => SetValue(LogConPTYOutputProperty, value);
}
/// <summary>
/// Sets if the GUI Terminal control communicates to ConPTY using extended key events (handles certain control sequences better)
/// https://github.com/microsoft/terminal/blob/main/doc/specs/%234999%20-%20Improved%20keyboard%20handling%20in%20Conpty.md
/// </summary>
public bool Win32InputMode {
get => (bool)GetValue(Win32InputModeProperty);
set => SetValue(Win32InputModeProperty, value);
}
public FontFamily FontFamilyWhenSettingTheme {
get => (FontFamily)GetValue(FontFamilyWhenSettingThemeProperty);
set => SetValue(FontFamilyWhenSettingThemeProperty, value);
}
public int FontSizeWhenSettingTheme {
get => (int)GetValue(FontSizeWhenSettingThemeProperty);
set => SetValue(FontSizeWhenSettingThemeProperty, value);
}
private void InitializeComponent() {
Terminal = new();
ConPTYTerm = new();
Terminal.AutoResize = true;
Terminal.Loaded += Terminal_Loaded;
var grid = new Grid() { };
grid.Children.Add(Terminal);
this.Content = grid;
#if WPF
Focusable = true;
Terminal.Focusable = true;
this.GotFocus += (_, _) => Terminal.Focus();
#else
this.GotFocus += (_, _) => Terminal.Focus(FocusState.Pointer);
IsTabStop = true;
//FocusManager.GotFocus += (o,e) => Debug.WriteLine($"FocusManager: {e.NewFocusedElement}");
#endif
}
#if WPF
void MainThreadRun(Action action) => Dispatcher.Invoke(action);
#else
async void MainThreadRun(Action action) => await UWPHelpers.Enqueue(this.DispatcherQueue, action);
#endif
private void Term_TermReady(object sender, EventArgs e) {
MainThreadRun(() => {
Terminal.Connection = ConPTYTerm;
ConPTYTerm.Win32DirectInputMode(Win32InputMode);
ConPTYTerm.Resize(Terminal.Columns, Terminal.Rows);//fix the size being partially off on first load
});
}
/// <summary>
/// Restarts the command we are running in a brand new term and disposes of the old one
/// </summary>
/// <param name="useTerm">Optional term to use, note if useTerm.TermProcIsStarted this function will not do verry much</param>
/// <param name="disposeOld">True if the old term should be killed off</param>
public async Task RestartTerm(TermPTY useTerm = null, bool disposeOld = true) {
var oldTerm = ConPTYTerm;
DisconnectConPTYTerm();
if (disposeOld) {
try {
oldTerm?.CloseStdinToApp();
} catch { }
try {
oldTerm?.StopExternalTermOnly();
} catch { }
}
ConPTYTerm = useTerm ?? new TermPTY(); //setting the term to a new value will automatically initalize everyhting
}
private void StartTerm(int column_width, int row_height) {
if (ConPTYTerm?.TermProcIsStarted != false)
return;
MainThreadRun(() => {
var cmd = StartupCommandLine;//thread safety for dp
var term = ConPTYTerm;
var logOutput = LogConPTYOutput;
var workingDir = WorkingDirectory;
//If the directory does not exist, set it to null (default behavior).
if (workingDir != null && !System.IO.Directory.Exists(workingDir)) {
workingDir = null;
}
Task.Run(() => term.Start(cmd, column_width, row_height, logOutput, null, workingDir));
});
}
private async void Terminal_Loaded(object sender, RoutedEventArgs e) {
await TermInit();
//Terminal.Focus();
}
private async Task TermInit() {
StartTerm(Terminal.Columns, Terminal.Rows);
SetTheme(Theme);
SetCursor(IsCursorVisible);
SetReadOnly(IsReadOnly);
await Task.Delay(1000);
SetCursor(IsCursorVisible);
}
#region Depdendency Properties
public static readonly DependencyProperty InputCaptureProperty = DependencyProperty.Register(nameof(InputCapture), typeof(INPUT_CAPTURE), typeof(EasyTerminalControl), new
PropertyMetadata(INPUT_CAPTURE.TabKey | INPUT_CAPTURE.DirectionKeys, InputCaptureChanged));
public static readonly DependencyProperty ThemeProperty = PropHelper.GenerateWriteOnlyProperty((c) => c.Theme);
#if WPF
protected static readonly DependencyPropertyKey TerminalPropertyKey = DependencyProperty.RegisterReadOnly(nameof(Terminal), typeof(TerminalControl), typeof(EasyTerminalControl), new PropertyMetadata());
public static readonly DependencyProperty TerminalProperty = TerminalPropertyKey.DependencyProperty;
#else
public static readonly DependencyProperty TerminalProperty = DependencyProperty.Register(nameof(Terminal), typeof(TerminalControl), typeof(EasyTerminalControl), new PropertyMetadata(null));
#endif
public static readonly DependencyProperty ConPTYTermProperty = DependencyProperty.Register(nameof(ConPTYTerm), typeof(TermPTY), typeof(EasyTerminalControl), new(null, OnTermChanged));
public static readonly DependencyProperty StartupCommandLineProperty = DependencyProperty.Register(nameof(StartupCommandLine), typeof(string), typeof(EasyTerminalControl), new PropertyMetadata("powershell.exe"));
public static readonly DependencyProperty WorkingDirectoryProperty = DependencyProperty.Register(nameof(WorkingDirectory), typeof(string), typeof(EasyTerminalControl), new PropertyMetadata(null));
public static readonly DependencyProperty LogConPTYOutputProperty = DependencyProperty.Register(nameof(LogConPTYOutput), typeof(bool), typeof(EasyTerminalControl), new PropertyMetadata(false));
public static readonly DependencyProperty Win32InputModeProperty = DependencyProperty.Register(nameof(Win32InputMode), typeof(bool), typeof(EasyTerminalControl), new PropertyMetadata(true));
public static readonly DependencyProperty IsReadOnlyProperty = PropHelper.GenerateWriteOnlyProperty((c) => c.IsReadOnly);
public static readonly DependencyProperty IsCursorVisibleProperty = PropHelper.GenerateWriteOnlyProperty((c) => c.IsCursorVisible);
public static readonly DependencyProperty FontFamilyWhenSettingThemeProperty = DependencyProperty.Register(nameof(FontFamilyWhenSettingTheme), typeof(FontFamily), typeof(EasyTerminalControl), new PropertyMetadata(new FontFamily("Cascadia Code")));
public static readonly DependencyProperty FontSizeWhenSettingThemeProperty = DependencyProperty.Register(nameof(FontSizeWhenSettingTheme), typeof(int), typeof(EasyTerminalControl), new PropertyMetadata(12));
private class PropHelper : DepPropHelper<EasyTerminalControl> { }
#endregion
}
}