forked from microsoft/terminal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTerminalContainer.cs
495 lines (423 loc) · 19.7 KB
/
TerminalContainer.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
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
// <copyright file="TerminalContainer.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
// </copyright>
namespace Microsoft.Terminal.Wpf
{
using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Automation.Peers;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Threading;
/// <summary>
/// The container class that hosts the native hwnd terminal.
/// </summary>
/// <remarks>
/// This class is only left public since xaml cannot work with internal classes.
/// </remarks>
public class TerminalContainer : HwndHost
{
private ITerminalConnection connection;
private IntPtr hwnd;
private IntPtr terminal;
private DispatcherTimer blinkTimer;
private NativeMethods.ScrollCallback scrollCallback;
private NativeMethods.WriteCallback writeCallback;
/// <summary>
/// Initializes a new instance of the <see cref="TerminalContainer"/> class.
/// </summary>
public TerminalContainer()
{
this.MessageHook += this.TerminalContainer_MessageHook;
this.GotFocus += this.TerminalContainer_GotFocus;
this.Focusable = true;
var blinkTime = NativeMethods.GetCaretBlinkTime();
if (blinkTime == uint.MaxValue)
{
return;
}
this.blinkTimer = new DispatcherTimer();
this.blinkTimer.Interval = TimeSpan.FromMilliseconds(blinkTime);
this.blinkTimer.Tick += (_, __) =>
{
if (this.terminal != IntPtr.Zero)
{
NativeMethods.TerminalBlinkCursor(this.terminal);
}
};
}
/// <summary>
/// Event that is fired when the terminal buffer scrolls from text output.
/// </summary>
internal event EventHandler<(int viewTop, int viewHeight, int bufferSize)> TerminalScrolled;
/// <summary>
/// Event that is fired when the user engages in a mouse scroll over the terminal hwnd.
/// </summary>
internal event EventHandler<int> UserScrolled;
/// <summary>
/// Gets or sets a value indicating whether if the renderer should automatically resize to fill the control
/// on user action.
/// </summary>
internal bool AutoResize { get; set; } = true;
/// <summary>
/// Gets or sets the size of the parent user control that hosts the terminal hwnd.
/// </summary>
/// <remarks>Control size is in device independent units, but for simplicity all sizes should be scaled.</remarks>
internal Size TerminalControlSize { get; set; }
/// <summary>
/// Gets or sets the size of the terminal renderer.
/// </summary>
internal Size TerminalRendererSize { get; set; }
/// <summary>
/// Gets the current character rows available to the terminal.
/// </summary>
internal int Rows { get; private set; }
/// <summary>
/// Gets the current character columns available to the terminal.
/// </summary>
internal int Columns { get; private set; }
/// <summary>
/// Gets the window handle of the terminal.
/// </summary>
internal IntPtr Hwnd => this.hwnd;
/// <summary>
/// Sets the connection to the terminal backend.
/// </summary>
internal ITerminalConnection Connection
{
private get
{
return this.connection;
}
set
{
if (this.connection != null)
{
this.connection.TerminalOutput -= this.Connection_TerminalOutput;
}
this.Connection_TerminalOutput(this, new TerminalOutputEventArgs("\x001bc\x1b]104\x1b\\")); // reset console/clear screen - https://github.com/microsoft/terminal/pull/15062#issuecomment-1505654110
var wasNull = this.connection == null;
this.connection = value;
if (this.connection != null)
{
if (wasNull)
{
this.Connection_TerminalOutput(this, new TerminalOutputEventArgs("\x1b[?25h")); // show cursor
}
this.connection.TerminalOutput += this.Connection_TerminalOutput;
this.connection.Start();
}
else
{
this.Connection_TerminalOutput(this, new TerminalOutputEventArgs("\x1b[?25l")); // hide cursor
}
}
}
/// <summary>
/// Manually invoke a scroll of the terminal buffer.
/// </summary>
/// <param name="viewTop">The top line to show in the terminal.</param>
internal void UserScroll(int viewTop)
{
NativeMethods.TerminalUserScroll(this.terminal, viewTop);
}
/// <summary>
/// Sets the theme for the terminal. This includes font family, size, color, as well as background and foreground colors.
/// </summary>
/// <param name="theme">The color theme for the terminal to use.</param>
/// <param name="fontFamily">The font family to use in the terminal.</param>
/// <param name="fontSize">The font size to use in the terminal.</param>
internal void SetTheme(TerminalTheme theme, string fontFamily, short fontSize)
{
var dpiScale = VisualTreeHelper.GetDpi(this);
NativeMethods.TerminalSetTheme(this.terminal, theme, fontFamily, fontSize, (int)dpiScale.PixelsPerInchX);
// Validate before resizing that we have a non-zero size.
if (!this.RenderSize.IsEmpty && !this.TerminalControlSize.IsEmpty
&& this.TerminalControlSize.Width != 0 && this.TerminalControlSize.Height != 0)
{
this.Resize(this.TerminalControlSize);
}
}
/// <summary>
/// Gets the selected text from the terminal renderer and clears the selection.
/// </summary>
/// <returns>The selected text, empty if no text is selected.</returns>
internal string GetSelectedText()
{
if (NativeMethods.TerminalIsSelectionActive(this.terminal))
{
return NativeMethods.TerminalGetSelection(this.terminal);
}
return string.Empty;
}
/// <summary>
/// Triggers a resize of the terminal with the given size, redrawing the rendered text.
/// </summary>
/// <param name="renderSize">Size of the rendering window.</param>
internal void Resize(Size renderSize)
{
if (renderSize.Width == 0 || renderSize.Height == 0)
{
throw new ArgumentException("Terminal column or row count cannot be 0.", nameof(renderSize));
}
NativeMethods.TerminalTriggerResize(
this.terminal,
(int)renderSize.Width,
(int)renderSize.Height,
out NativeMethods.TilSize dimensions);
this.Rows = dimensions.Y;
this.Columns = dimensions.X;
this.TerminalRendererSize = renderSize;
this.Connection?.Resize((uint)dimensions.Y, (uint)dimensions.X);
}
/// <summary>
/// Resizes the terminal using row and column count as the new size.
/// </summary>
/// <param name="rows">Number of rows to show.</param>
/// <param name="columns">Number of columns to show.</param>
internal void Resize(uint rows, uint columns)
{
if (rows == 0)
{
throw new ArgumentException("Terminal row count cannot be 0.", nameof(rows));
}
if (columns == 0)
{
throw new ArgumentException("Terminal column count cannot be 0.", nameof(columns));
}
NativeMethods.TilSize dimensions = new NativeMethods.TilSize
{
X = (int)columns,
Y = (int)rows,
};
NativeMethods.TerminalTriggerResizeWithDimension(this.terminal, dimensions, out var dimensionsInPixels);
this.Columns = dimensions.X;
this.Rows = dimensions.Y;
this.TerminalRendererSize = new Size
{
Width = dimensionsInPixels.X,
Height = dimensionsInPixels.Y,
};
this.Connection?.Resize((uint)dimensions.Y, (uint)dimensions.X);
}
/// <summary>
/// Calculates the rows and columns that would fit in the given size.
/// </summary>
/// <param name="size">DPI scaled size.</param>
/// <returns>Amount of rows and columns that would fit the given size.</returns>
internal (int columns, int rows) CalculateRowsAndColumns(Size size)
{
NativeMethods.TerminalCalculateResize(this.terminal, (int)size.Width, (int)size.Height, out NativeMethods.TilSize dimensions);
return (dimensions.X, dimensions.Y);
}
/// <summary>
/// Triggers the terminal resize event if more space is available in the terminal control.
/// </summary>
internal void RaiseResizedIfDrawSpaceIncreased()
{
var (columns, rows) = this.CalculateRowsAndColumns(this.TerminalControlSize);
if (this.Columns < columns || this.Rows < rows)
{
this.connection?.Resize((uint)rows, (uint)columns);
}
}
/// <summary>
/// WPF's HwndHost likes to mark the WM_GETOBJECT message as handled to
/// force the usage of the WPF automation peer. We explicitly mark it as
/// not handled and don't return an automation peer in "OnCreateAutomationPeer" below.
/// This forces the message to go down to the HwndTerminal where we return terminal's UiaProvider.
/// </summary>
/// <inheritdoc/>
protected override IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == (int)NativeMethods.WindowMessage.WM_GETOBJECT)
{
handled = false;
return IntPtr.Zero;
}
return base.WndProc(hwnd, msg, wParam, lParam, ref handled);
}
/// <inheritdoc/>
protected override AutomationPeer OnCreateAutomationPeer()
{
return null;
}
/// <inheritdoc/>
protected override void OnDpiChanged(DpiScale oldDpi, DpiScale newDpi)
{
if (this.terminal != IntPtr.Zero)
{
NativeMethods.TerminalDpiChanged(this.terminal, (int)(NativeMethods.USER_DEFAULT_SCREEN_DPI * newDpi.DpiScaleX));
}
}
/// <inheritdoc/>
protected override HandleRef BuildWindowCore(HandleRef hwndParent)
{
var dpiScale = VisualTreeHelper.GetDpi(this);
NativeMethods.CreateTerminal(hwndParent.Handle, out this.hwnd, out this.terminal);
this.scrollCallback = this.OnScroll;
this.writeCallback = this.OnWrite;
NativeMethods.TerminalRegisterScrollCallback(this.terminal, this.scrollCallback);
NativeMethods.TerminalRegisterWriteCallback(this.terminal, this.writeCallback);
// If the saved DPI scale isn't the default scale, we push it to the terminal.
if (dpiScale.PixelsPerInchX != NativeMethods.USER_DEFAULT_SCREEN_DPI)
{
NativeMethods.TerminalDpiChanged(this.terminal, (int)dpiScale.PixelsPerInchX);
}
if (NativeMethods.GetFocus() == this.hwnd)
{
this.blinkTimer?.Start();
}
else
{
NativeMethods.TerminalSetCursorVisible(this.terminal, false);
}
return new HandleRef(this, this.hwnd);
}
/// <inheritdoc/>
protected override void DestroyWindowCore(HandleRef hwnd)
{
NativeMethods.DestroyTerminal(this.terminal);
this.terminal = IntPtr.Zero;
}
private static void UnpackKeyMessage(IntPtr wParam, IntPtr lParam, out ushort vkey, out ushort scanCode, out ushort flags)
{
ulong scanCodeAndFlags = ((ulong)lParam >> 16) & 0xFFFF;
scanCode = (ushort)(scanCodeAndFlags & 0x00FFu);
flags = (ushort)(scanCodeAndFlags & 0xFF00u);
vkey = (ushort)wParam;
}
private static void UnpackCharMessage(IntPtr wParam, IntPtr lParam, out char character, out ushort scanCode, out ushort flags)
{
UnpackKeyMessage(wParam, lParam, out ushort vKey, out scanCode, out flags);
character = (char)vKey;
}
private void TerminalContainer_GotFocus(object sender, RoutedEventArgs e)
{
e.Handled = true;
NativeMethods.SetFocus(this.hwnd);
}
private IntPtr TerminalContainer_MessageHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (hwnd == this.hwnd)
{
switch ((NativeMethods.WindowMessage)msg)
{
case NativeMethods.WindowMessage.WM_SETFOCUS:
NativeMethods.TerminalSetFocus(this.terminal);
this.blinkTimer?.Start();
break;
case NativeMethods.WindowMessage.WM_KILLFOCUS:
NativeMethods.TerminalKillFocus(this.terminal);
this.blinkTimer?.Stop();
NativeMethods.TerminalSetCursorVisible(this.terminal, false);
break;
case NativeMethods.WindowMessage.WM_MOUSEACTIVATE:
this.Focus();
NativeMethods.SetFocus(this.hwnd);
break;
case NativeMethods.WindowMessage.WM_SYSKEYDOWN: // fallthrough
case NativeMethods.WindowMessage.WM_KEYDOWN:
{
// WM_KEYDOWN lParam layout documentation: https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-keydown
NativeMethods.TerminalSetCursorVisible(this.terminal, true);
UnpackKeyMessage(wParam, lParam, out ushort vkey, out ushort scanCode, out ushort flags);
NativeMethods.TerminalSendKeyEvent(this.terminal, vkey, scanCode, flags, true);
this.blinkTimer?.Start();
break;
}
case NativeMethods.WindowMessage.WM_SYSKEYUP: // fallthrough
case NativeMethods.WindowMessage.WM_KEYUP:
{
// WM_KEYUP lParam layout documentation: https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-keyup
UnpackKeyMessage(wParam, lParam, out ushort vkey, out ushort scanCode, out ushort flags);
NativeMethods.TerminalSendKeyEvent(this.terminal, (ushort)wParam, scanCode, flags, false);
break;
}
case NativeMethods.WindowMessage.WM_CHAR:
{
// WM_CHAR lParam layout documentation: https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-char
UnpackCharMessage(wParam, lParam, out char character, out ushort scanCode, out ushort flags);
NativeMethods.TerminalSendCharEvent(this.terminal, character, scanCode, flags);
break;
}
case NativeMethods.WindowMessage.WM_WINDOWPOSCHANGED:
var windowpos = (NativeMethods.WINDOWPOS)Marshal.PtrToStructure(lParam, typeof(NativeMethods.WINDOWPOS));
if (((NativeMethods.SetWindowPosFlags)windowpos.flags).HasFlag(NativeMethods.SetWindowPosFlags.SWP_NOSIZE)
|| (windowpos.cx == 0 && windowpos.cy == 0))
{
break;
}
NativeMethods.TilSize dimensions;
if (this.AutoResize)
{
NativeMethods.TerminalTriggerResize(this.terminal, windowpos.cx, windowpos.cy, out dimensions);
this.Columns = dimensions.X;
this.Rows = dimensions.Y;
this.TerminalRendererSize = new Size
{
Width = windowpos.cx,
Height = windowpos.cy,
};
}
else
{
// Calculate the new columns and rows that fit the total control size and alert the control to redraw the margins.
NativeMethods.TerminalCalculateResize(this.terminal, (int)this.TerminalControlSize.Width, (int)this.TerminalControlSize.Height, out dimensions);
}
this.Connection?.Resize((uint)dimensions.Y, (uint)dimensions.X);
break;
case NativeMethods.WindowMessage.WM_MOUSEWHEEL:
var delta = (short)(((long)wParam) >> 16);
this.UserScrolled?.Invoke(this, delta);
break;
}
}
return IntPtr.Zero;
}
private void LeftClickHandler(int lParam)
{
var altPressed = NativeMethods.GetKeyState((int)NativeMethods.VirtualKey.VK_MENU) < 0;
var x = lParam & 0xffff;
var y = lParam >> 16;
var cursorPosition = new NativeMethods.TilPoint
{
X = x,
Y = y,
};
NativeMethods.TerminalStartSelection(this.terminal, cursorPosition, altPressed);
}
private void MouseMoveHandler(int wParam, int lParam)
{
if ((wParam & 0x0001) == 1)
{
var x = lParam & 0xffff;
var y = lParam >> 16;
var cursorPosition = new NativeMethods.TilPoint
{
X = x,
Y = y,
};
NativeMethods.TerminalMoveSelection(this.terminal, cursorPosition);
}
}
private void Connection_TerminalOutput(object sender, TerminalOutputEventArgs e)
{
if (this.terminal == IntPtr.Zero || string.IsNullOrEmpty(e.Data))
{
return;
}
NativeMethods.TerminalSendOutput(this.terminal, e.Data);
}
private void OnScroll(int viewTop, int viewHeight, int bufferSize)
{
this.TerminalScrolled?.Invoke(this, (viewTop, viewHeight, bufferSize));
}
private void OnWrite(string data)
{
this.Connection?.WriteInput(data);
}
}
}