-
Notifications
You must be signed in to change notification settings - Fork 8.4k
/
Pane.cpp
3058 lines (2732 loc) · 119 KB
/
Pane.cpp
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "pch.h"
#include "Pane.h"
using namespace winrt::Windows::Foundation;
using namespace winrt::Windows::Graphics::Display;
using namespace winrt::Windows::UI;
using namespace winrt::Windows::UI::Xaml;
using namespace winrt::Windows::UI::Core;
using namespace winrt::Windows::UI::Xaml::Media;
using namespace winrt::Microsoft::Terminal::Settings::Model;
using namespace winrt::Microsoft::Terminal::Control;
using namespace winrt::Microsoft::Terminal::TerminalConnection;
using namespace winrt::TerminalApp;
static const int PaneBorderSize = 2;
static const int CombinedPaneBorderSize = 2 * PaneBorderSize;
// WARNING: Don't do this! This won't work
// Duration duration{ std::chrono::milliseconds{ 200 } };
// Instead, make a duration from a TimeSpan from the time in millis
//
// 200ms was chosen because it's quick enough that it doesn't break your
// flow, but not too quick to see
static const int AnimationDurationInMilliseconds = 200;
static const Duration AnimationDuration = DurationHelper::FromTimeSpan(winrt::Windows::Foundation::TimeSpan(std::chrono::milliseconds(AnimationDurationInMilliseconds)));
Pane::Pane(IPaneContent content, const bool lastFocused) :
_lastActive{ lastFocused }
{
_setPaneContent(std::move(content));
_root.Children().Append(_borderFirst);
const auto& control{ _content.GetRoot() };
_borderFirst.Child(control);
// Register an event with the control to have it inform us when it gains focus.
if (control)
{
_gotFocusRevoker = control.GotFocus(winrt::auto_revoke, { this, &Pane::_ContentGotFocusHandler });
_lostFocusRevoker = control.LostFocus(winrt::auto_revoke, { this, &Pane::_ContentLostFocusHandler });
}
// When our border is tapped, make sure to transfer focus to our control.
// LOAD-BEARING: This will NOT work if the border's BorderBrush is set to
// Colors::Transparent! The border won't get Tapped events, and they'll fall
// through to something else.
_borderFirst.Tapped({ this, &Pane::_borderTappedHandler });
_borderSecond.Tapped({ this, &Pane::_borderTappedHandler });
}
Pane::Pane(std::shared_ptr<Pane> first,
std::shared_ptr<Pane> second,
const SplitState splitState,
const float splitPosition,
const bool lastFocused) :
_firstChild{ first },
_secondChild{ second },
_splitState{ splitState },
_desiredSplitPosition{ splitPosition },
_lastActive{ lastFocused }
{
_CreateRowColDefinitions();
_borderFirst.Child(_firstChild->GetRootElement());
_borderSecond.Child(_secondChild->GetRootElement());
// Use the unfocused border color as the pane background, so an actual color
// appears behind panes as we animate them sliding in.
_root.Background(_themeResources.unfocusedBorderBrush);
_root.Children().Append(_borderFirst);
_root.Children().Append(_borderSecond);
_ApplySplitDefinitions();
// Register event handlers on our children to handle their Close events
_SetupChildCloseHandlers();
// When our border is tapped, make sure to transfer focus to our control.
// LOAD-BEARING: This will NOT work if the border's BorderBrush is set to
// Colors::Transparent! The border won't get Tapped events, and they'll fall
// through to something else.
_borderFirst.Tapped({ this, &Pane::_borderTappedHandler });
_borderSecond.Tapped({ this, &Pane::_borderTappedHandler });
}
// Extract the terminal settings from the current (leaf) pane's control
// to be used to create an equivalent control
INewContentArgs Pane::GetTerminalArgsForPane(BuildStartupKind kind) const
{
// Leaves are the only things that have controls
assert(_IsLeaf());
return _content.GetNewTerminalArgs(kind);
}
// Method Description:
// - Serializes the state of this tab as a series of commands that can be
// executed to recreate it.
// - This will always result in the right-most child being the focus
// after the commands finish executing.
// Arguments:
// - currentId: the id to use for the current/first pane
// - nextId: the id to use for a new pane if we split
// - asContent: We're serializing this set of actions as content actions for
// moving to other windows, so we need to make sure to include ContentId's
// in the final actions.
// - asMovePane: only used with asContent. When this is true, we're building
// these actions as a part of moving the pane to another window, but without
// the context of the hosting tab. In that case, we'll want to build a
// splitPane action even if we're just a single leaf, because there's no other
// parent to try and build an action for us.
// Return Value:
// - The state from building the startup actions, includes a vector of commands,
// the original root pane, the id of the focused pane, and the number of panes
// created.
Pane::BuildStartupState Pane::BuildStartupActions(uint32_t currentId, uint32_t nextId, BuildStartupKind kind)
{
// Normally, if we're a leaf, return an empt set of actions, because the
// parent pane will build the SplitPane action for us. If we're building
// actions for a movePane action though, we'll still need to include
// ourselves.
if (kind != BuildStartupKind::MovePane && _IsLeaf())
{
if (_lastActive)
{
// empty args, this is the first pane, currentId is
return { .args = {}, .firstPane = shared_from_this(), .focusedPaneId = currentId, .panesCreated = 0 };
}
return { .args = {}, .firstPane = shared_from_this(), .focusedPaneId = std::nullopt, .panesCreated = 0 };
}
auto buildSplitPane = [&](auto newPane) {
ActionAndArgs actionAndArgs;
actionAndArgs.Action(ShortcutAction::SplitPane);
const auto terminalArgs{ newPane->GetTerminalArgsForPane(kind) };
// When creating a pane the split size is the size of the new pane
// and not position.
const auto splitDirection = _splitState == SplitState::Horizontal ? SplitDirection::Down : SplitDirection::Right;
const auto splitSize = (kind != BuildStartupKind::None && _IsLeaf() ? 0.5f : 1.0f - _desiredSplitPosition);
SplitPaneArgs args{ SplitType::Manual, splitDirection, splitSize, terminalArgs };
actionAndArgs.Args(args);
return actionAndArgs;
};
if (kind != BuildStartupKind::None && _IsLeaf())
{
return {
.args = { buildSplitPane(shared_from_this()) },
.firstPane = shared_from_this(),
.focusedPaneId = currentId,
.panesCreated = 1
};
}
auto buildMoveFocus = [](auto direction) {
MoveFocusArgs args{ direction };
ActionAndArgs actionAndArgs{};
actionAndArgs.Action(ShortcutAction::MoveFocus);
actionAndArgs.Args(args);
return actionAndArgs;
};
// Handle simple case of a single split (a minor optimization for clarity)
// Here we just create the second child (by splitting) and return the first
// child for the parent to deal with.
if (_firstChild->_IsLeaf() && _secondChild->_IsLeaf())
{
auto actionAndArgs = buildSplitPane(_secondChild);
std::optional<uint32_t> focusedPaneId = std::nullopt;
if (_firstChild->_lastActive)
{
focusedPaneId = currentId;
}
else if (_secondChild->_lastActive)
{
focusedPaneId = nextId;
}
return {
.args = { actionAndArgs },
.firstPane = _firstChild,
.focusedPaneId = focusedPaneId,
.panesCreated = 1
};
}
// We now need to execute the commands for each side of the tree
// We've done one split, so the first-most child will have currentId, and the
// one after it will be incremented.
auto firstState = _firstChild->BuildStartupActions(currentId, nextId + 1, kind);
// the next id for the second branch depends on how many splits were in the
// first child.
auto secondState = _secondChild->BuildStartupActions(nextId, nextId + firstState.panesCreated + 1, kind);
std::vector<ActionAndArgs> actions{};
actions.reserve(firstState.args.size() + secondState.args.size() + 3);
// first we make our split
const auto newSplit = buildSplitPane(secondState.firstPane);
actions.emplace_back(std::move(newSplit));
if (firstState.args.size() > 0)
{
// Then move to the first child and execute any actions on the left branch
// then move back
actions.emplace_back(buildMoveFocus(FocusDirection::PreviousInOrder));
actions.insert(actions.end(), std::make_move_iterator(std::begin(firstState.args)), std::make_move_iterator(std::end(firstState.args)));
actions.emplace_back(buildMoveFocus(FocusDirection::NextInOrder));
}
// And if there are any commands to run on the right branch do so
if (secondState.args.size() > 0)
{
actions.insert(actions.end(), std::make_move_iterator(secondState.args.begin()), std::make_move_iterator(secondState.args.end()));
}
// if the tree is well-formed then f1.has_value and f2.has_value are
// mutually exclusive.
const auto focusedPaneId = firstState.focusedPaneId.has_value() ? firstState.focusedPaneId : secondState.focusedPaneId;
return {
.args = { actions },
.firstPane = firstState.firstPane,
.focusedPaneId = focusedPaneId,
.panesCreated = firstState.panesCreated + secondState.panesCreated + 1
};
}
// Method Description:
// - Adjust our child percentages to increase the size of one of our children
// and decrease the size of the other.
// - Adjusts the separation amount by 5%
// - Does nothing if the direction doesn't match our current split direction
// Arguments:
// - direction: the direction to move our separator. If it's down or right,
// we'll be increasing the size of the first of our children. Else, we'll be
// decreasing the size of our first child.
// Return Value:
// - false if we couldn't resize this pane in the given direction, else true.
bool Pane::_Resize(const ResizeDirection& direction)
{
if (!DirectionMatchesSplit(direction, _splitState))
{
return false;
}
auto amount = .05f;
if (direction == ResizeDirection::Right || direction == ResizeDirection::Down)
{
amount = -amount;
}
// Make sure we're not making a pane explode here by resizing it to 0 characters.
const auto changeWidth = _splitState == SplitState::Vertical;
const Size actualSize{ gsl::narrow_cast<float>(_root.ActualWidth()),
gsl::narrow_cast<float>(_root.ActualHeight()) };
// actualDimension is the size in DIPs of this pane in the direction we're
// resizing.
const auto actualDimension = changeWidth ? actualSize.Width : actualSize.Height;
_desiredSplitPosition = _ClampSplitPosition(changeWidth, _desiredSplitPosition - amount, actualDimension);
// Resize our columns to match the new percentages.
_CreateRowColDefinitions();
return true;
}
// Method Description:
// - Moves the separator between panes, as to resize each child on either size
// of the separator. Tries to move a separator in the given direction. The
// separator moved is the separator that's closest depth-wise to the
// currently focused pane, that's also in the correct direction to be moved.
// If there isn't such a separator, then this method returns false, as we
// couldn't handle the resize.
// Arguments:
// - direction: The direction to move the separator in.
// Return Value:
// - true if we or a child handled this resize request.
bool Pane::ResizePane(const ResizeDirection& direction)
{
// If we're a leaf, do nothing. We can't possibly have a descendant with a
// separator the correct direction.
if (_IsLeaf())
{
return false;
}
// Check if either our first or second child is the currently focused pane.
// If it is, and the requested resize direction matches our separator, then
// we're the pane that needs to adjust its separator.
// If our separator is the wrong direction, then we can't handle it.
const auto firstIsFocused = _firstChild->_lastActive;
const auto secondIsFocused = _secondChild->_lastActive;
if (firstIsFocused || secondIsFocused)
{
return _Resize(direction);
}
// If neither of our children were the focused pane, then recurse into
// our children and see if they can handle the resize.
// For each child, if it has a focused descendant, try having that child
// handle the resize.
// If the child wasn't able to handle the resize, it's possible that
// there were no descendants with a separator the correct direction. If
// our separator _is_ the correct direction, then we should be the pane
// to resize. Otherwise, just return false, as we couldn't handle it
// either.
if ((!_firstChild->_IsLeaf()) && _firstChild->_HasFocusedChild())
{
return _firstChild->ResizePane(direction) || _Resize(direction);
}
if ((!_secondChild->_IsLeaf()) && _secondChild->_HasFocusedChild())
{
return _secondChild->ResizePane(direction) || _Resize(direction);
}
return false;
}
// Method Description:
// - Attempt to navigate from the sourcePane according to direction.
// - If the direction is NextInOrder or PreviousInOrder, the next or previous
// leaf in the tree, respectively, will be returned.
// - If the direction is {Up, Down, Left, Right} then the visually-adjacent
// neighbor (if it exists) will be returned. If there are multiple options
// then the first-most leaf will be selected.
// Arguments:
// - sourcePane: the pane to navigate from
// - direction: which direction to go in
// - mruPanes: the list of most recently used panes, in order
// Return Value:
// - The result of navigating from source according to direction, which may be
// nullptr (i.e. no pane was found in that direction).
std::shared_ptr<Pane> Pane::NavigateDirection(const std::shared_ptr<Pane> sourcePane, const FocusDirection& direction, const std::vector<uint32_t>& mruPanes)
{
// Can't navigate anywhere if we are a leaf
if (_IsLeaf())
{
return nullptr;
}
if (direction == FocusDirection::None)
{
return nullptr;
}
// Check if moving up or down the tree
if (direction == FocusDirection::Parent)
{
if (const auto parent = _FindParentOfPane(sourcePane))
{
// Keep a reference to which child we came from
parent->_parentChildPath = sourcePane->weak_from_this();
return parent;
}
return nullptr;
}
if (direction == FocusDirection::Child)
{
if (!sourcePane->_IsLeaf())
{
auto child = sourcePane->_firstChild;
// If we've recorded path try to go back down it
if (const auto prevFocus = sourcePane->_parentChildPath.lock())
{
child = prevFocus;
}
// clean up references
sourcePane->_parentChildPath.reset();
return child;
}
return nullptr;
}
// Previous movement relies on the last used panes
if (direction == FocusDirection::Previous)
{
// If there is actually a previous pane.
if (mruPanes.size() > 1)
{
// This could return nullptr if the id is not actually in the tree.
return FindPane(mruPanes.at(1));
}
return nullptr;
}
// Check if we in-order traversal is requested
if (direction == FocusDirection::NextInOrder)
{
return NextPane(sourcePane);
}
if (direction == FocusDirection::PreviousInOrder)
{
return PreviousPane(sourcePane);
}
// Fixed movement
if (direction == FocusDirection::First)
{
// Just get the first leaf pane.
auto firstPane = _FindPane([](const auto& p) { return p->_IsLeaf(); });
// Don't need to do any movement if we are the source and target pane.
if (firstPane == sourcePane)
{
return nullptr;
}
return firstPane;
}
// We are left with directional traversal now
// If the focus direction does not match the split direction, the source pane
// and its neighbor must necessarily be contained within the same child.
if (!DirectionMatchesSplit(direction, _splitState))
{
if (const auto p = _firstChild->NavigateDirection(sourcePane, direction, mruPanes))
{
return p;
}
return _secondChild->NavigateDirection(sourcePane, direction, mruPanes);
}
// Since the direction is the same as our split, it is possible that we must
// move focus from one child to another child.
// We now must keep track of state while we recurse.
// If we have it, get the size of this pane.
const auto scaleX = _root.ActualWidth() > 0 ? gsl::narrow_cast<float>(_root.ActualWidth()) : 1.f;
const auto scaleY = _root.ActualHeight() > 0 ? gsl::narrow_cast<float>(_root.ActualHeight()) : 1.f;
const auto paneNeighborPair = _FindPaneAndNeighbor(sourcePane, direction, { 0, 0, scaleX, scaleY });
if (paneNeighborPair.source && paneNeighborPair.neighbor)
{
return paneNeighborPair.neighbor;
}
return nullptr;
}
// Method Description:
// - Attempts to find the succeeding pane of the provided pane.
// - NB: If targetPane is not a leaf, then this will return one of its children.
// Arguments:
// - targetPane: The pane to search for.
// Return Value:
// - The next pane in tree order after the target pane (if found)
std::shared_ptr<Pane> Pane::NextPane(const std::shared_ptr<Pane> targetPane)
{
// if we are a leaf pane there is no next pane.
if (_IsLeaf())
{
return nullptr;
}
std::shared_ptr<Pane> firstLeaf = nullptr;
std::shared_ptr<Pane> nextPane = nullptr;
auto foundTarget = false;
auto foundNext = WalkTree([&](const auto& pane) {
// If we are a parent pane we don't want to move to one of our children
if (foundTarget && targetPane->_HasChild(pane))
{
return false;
}
// In case the target pane is the last pane in the tree, keep a reference
// to the first leaf so we can wrap around.
if (firstLeaf == nullptr && pane->_IsLeaf())
{
firstLeaf = pane;
}
// If we've found the target pane already, get the next leaf pane.
if (foundTarget && pane->_IsLeaf())
{
nextPane = pane;
return true;
}
// Test if we're the target pane so we know to return the next pane.
if (pane == targetPane)
{
foundTarget = true;
}
return false;
});
// If we found the desired pane just return it
if (foundNext)
{
return nextPane;
}
// If we found the target pane, but not the next pane it means we were the
// last leaf in the tree.
if (foundTarget)
{
return firstLeaf;
}
return nullptr;
}
// Method Description:
// - Attempts to find the preceding pane of the provided pane.
// Arguments:
// - targetPane: The pane to search for.
// Return Value:
// - The previous pane in tree order before the target pane (if found)
std::shared_ptr<Pane> Pane::PreviousPane(const std::shared_ptr<Pane> targetPane)
{
// if we are a leaf pane there is no previous pane.
if (_IsLeaf())
{
return nullptr;
}
std::shared_ptr<Pane> lastLeaf = nullptr;
auto foundTarget = false;
WalkTree([&](auto pane) {
if (pane == targetPane)
{
foundTarget = true;
// If we were not the first leaf, then return the previous leaf.
// Otherwise keep walking the tree to get the last pane.
if (lastLeaf != nullptr)
{
return true;
}
}
if (pane->_IsLeaf())
{
lastLeaf = pane;
}
return false;
});
// If we found the target pane then lastLeaf will either be the preceding
// pane or the last pane in the tree if targetPane is the first leaf.
if (foundTarget)
{
return lastLeaf;
}
return nullptr;
}
// Method Description:
// - Attempts to find the parent pane of the provided pane.
// Arguments:
// - pane: The pane to search for.
// Return Value:
// - the parent of `pane` if pane is in this tree.
std::shared_ptr<Pane> Pane::_FindParentOfPane(const std::shared_ptr<Pane> pane)
{
return _FindPane([&](const auto& p) {
return p->_firstChild == pane || p->_secondChild == pane;
});
}
// Method Description:
// - Attempts to swap the location of the two given panes in the tree.
// Searches the tree starting at this pane to find the parent pane for each of
// the arguments, and if both parents are found, replaces the appropriate
// child in each.
// Arguments:
// - first: A pointer to the first pane to switch.
// - second: A pointer to the second pane to switch.
// Return Value:
// - true if a swap was performed.
bool Pane::SwapPanes(std::shared_ptr<Pane> first, std::shared_ptr<Pane> second)
{
// If there is nothing to swap, just return.
if (first == second || _IsLeaf())
{
return false;
}
// Similarly don't swap if we have a circular reference
if (first->_HasChild(second) || second->_HasChild(first))
{
return false;
}
// Recurse through the tree to find the parent panes of each pane that is
// being swapped.
auto firstParent = _FindParentOfPane(first);
auto secondParent = _FindParentOfPane(second);
// We should have found either no elements, or both elements.
// If we only found one parent then the pane SwapPane was called on did not
// contain both panes as leaves, as could happen if the tree was modified
// after the pointers were found but before we reached this function.
if (firstParent && secondParent)
{
// Before we swap anything get the borders for the parents so that
// it can be propagated to the swapped child.
firstParent->_borders = firstParent->_GetCommonBorders();
secondParent->_borders = secondParent->_GetCommonBorders();
// Replace the old child with new one, and revoke appropriate event
// handlers.
auto replaceChild = [](auto& parent, auto oldChild, auto newChild) {
// Revoke the old handlers
if (parent->_firstChild == oldChild)
{
parent->_firstChild->Closed(parent->_firstClosedToken);
parent->_firstChild = newChild;
}
else if (parent->_secondChild == oldChild)
{
parent->_secondChild->Closed(parent->_secondClosedToken);
parent->_secondChild = newChild;
}
// Clear now to ensure that we can add the child's grid to us later
parent->_root.Children().Clear();
parent->_borderFirst.Child(nullptr);
parent->_borderSecond.Child(nullptr);
};
// Make sure that the right event handlers are set, and the children
// are placed in the appropriate locations in the grid.
auto updateParent = [](auto& parent) {
// just always revoke the old helpers since we are making new ones.
parent->_firstChild->Closed(parent->_firstClosedToken);
parent->_secondChild->Closed(parent->_secondClosedToken);
parent->_SetupChildCloseHandlers();
parent->_root.Children().Clear();
parent->_borderFirst.Child(nullptr);
parent->_borderSecond.Child(nullptr);
parent->_borderFirst.Child(parent->_firstChild->GetRootElement());
parent->_borderSecond.Child(parent->_secondChild->GetRootElement());
parent->_root.Children().Append(parent->_borderFirst);
parent->_root.Children().Append(parent->_borderSecond);
// reset split definitions to clear any set row/column
parent->_root.ColumnDefinitions().Clear();
parent->_root.RowDefinitions().Clear();
parent->_CreateRowColDefinitions();
};
// If the firstParent and secondParent are the same, then we are just
// swapping the first child and second child of that parent.
if (firstParent == secondParent)
{
firstParent->_firstChild->Closed(firstParent->_firstClosedToken);
firstParent->_secondChild->Closed(firstParent->_secondClosedToken);
std::swap(firstParent->_firstChild, firstParent->_secondChild);
updateParent(firstParent);
firstParent->_ApplySplitDefinitions();
}
else
{
// Replace both children before updating display to ensure
// that the grid elements are not attached to multiple panes
replaceChild(firstParent, first, second);
replaceChild(secondParent, second, first);
updateParent(firstParent);
updateParent(secondParent);
// If one of the two parents is a child of the other we only want
// to apply the split definitions to the greatest parent to make
// sure that all panes get the correct borders. if this is not done
// and the ordering happens to be bad one parent's children will lose
// a border.
if (firstParent->_HasChild(secondParent))
{
firstParent->_ApplySplitDefinitions();
}
else if (secondParent->_HasChild(firstParent))
{
secondParent->_ApplySplitDefinitions();
}
else
{
firstParent->_ApplySplitDefinitions();
secondParent->_ApplySplitDefinitions();
}
}
// Refocus the last pane if there was a pane focused
if (const auto focus = first->GetActivePane())
{
focus->_Focus();
}
if (const auto focus = second->GetActivePane())
{
focus->_Focus();
}
return true;
}
return false;
}
// Method Description:
// - Given two panes' offsets, test whether the `direction` side of first is adjacent to second.
// Arguments:
// - firstOffset: The offset for the reference pane
// - secondOffset: the offset to test adjacency with.
// - direction: The direction to search in from the reference pane.
// Return Value:
// - true if the two panes are adjacent.
bool Pane::_IsAdjacent(const PanePoint firstOffset,
const PanePoint secondOffset,
const FocusDirection& direction) const
{
// Since float equality is tricky (arithmetic is non-associative, commutative),
// test if the two numbers are within an epsilon distance of each other.
auto floatEqual = [](float left, float right) {
return abs(left - right) < 1e-4F;
};
auto getXMax = [](PanePoint offset) {
return offset.x + offset.scaleX;
};
auto getYMax = [](PanePoint offset) {
return offset.y + offset.scaleY;
};
// When checking containment in a range, the range is half-closed, i.e. [x, x+w).
// If the direction is left test that the left side of the first element is
// next to the right side of the second element, and that the top left
// corner of the first element is within the second element's height
if (direction == FocusDirection::Left)
{
const auto sharesBorders = floatEqual(firstOffset.x, getXMax(secondOffset));
const auto withinHeight = (firstOffset.y >= secondOffset.y) && (firstOffset.y < getYMax(secondOffset));
return sharesBorders && withinHeight;
}
// If the direction is right test that the right side of the first element is
// next to the left side of the second element, and that the top left
// corner of the first element is within the second element's height
else if (direction == FocusDirection::Right)
{
const auto sharesBorders = floatEqual(getXMax(firstOffset), secondOffset.x);
const auto withinHeight = (firstOffset.y >= secondOffset.y) && (firstOffset.y < getYMax(secondOffset));
return sharesBorders && withinHeight;
}
// If the direction is up test that the top side of the first element is
// next to the bottom side of the second element, and that the top left
// corner of the first element is within the second element's width
else if (direction == FocusDirection::Up)
{
const auto sharesBorders = floatEqual(firstOffset.y, getYMax(secondOffset));
const auto withinWidth = (firstOffset.x >= secondOffset.x) && (firstOffset.x < getXMax(secondOffset));
return sharesBorders && withinWidth;
}
// If the direction is down test that the bottom side of the first element is
// next to the top side of the second element, and that the top left
// corner of the first element is within the second element's width
else if (direction == FocusDirection::Down)
{
const auto sharesBorders = floatEqual(getYMax(firstOffset), secondOffset.y);
const auto withinWidth = (firstOffset.x >= secondOffset.x) && (firstOffset.x < getXMax(secondOffset));
return sharesBorders && withinWidth;
}
return false;
}
// Method Description:
// - Gets the offsets for the two children of this parent pane
// - If real dimensions are not available, simulated ones based on the split size
// will be used instead.
// Arguments:
// - parentOffset the location and scale information of this pane.
// Return Value:
// - the two location/scale points for the children panes.
std::pair<Pane::PanePoint, Pane::PanePoint> Pane::_GetOffsetsForPane(const PanePoint parentOffset) const
{
assert(!_IsLeaf());
auto firstOffset = parentOffset;
auto secondOffset = parentOffset;
// Make up fake dimensions using an exponential layout. This is useful
// since we might need to navigate when there are panes not attached to
// the ui tree, such as initialization, command running, and zoom.
// Basically create the tree layout on the fly by partitioning [0,1].
// This could run into issues if the tree depth is >127 (or other
// degenerate splits) as a float's mantissa only has so many bits of
// precision.
if (_splitState == SplitState::Horizontal)
{
secondOffset.y += _desiredSplitPosition * parentOffset.scaleY;
firstOffset.scaleY *= _desiredSplitPosition;
secondOffset.scaleY *= (1 - _desiredSplitPosition);
}
else
{
secondOffset.x += _desiredSplitPosition * parentOffset.scaleX;
firstOffset.scaleX *= _desiredSplitPosition;
secondOffset.scaleX *= (1 - _desiredSplitPosition);
}
return { firstOffset, secondOffset };
}
// Method Description:
// - Given the source pane, and its relative position in the tree, attempt to
// find its visual neighbor within the current pane's tree.
// The neighbor, if it exists, will be a leaf pane.
// Arguments:
// - direction: The direction to search in from the source pane.
// - searchResult: the source pane and its relative position.
// - sourceIsSecondSide: If the source pane is on the "second" side (down/right of split)
// relative to the branch being searched
// - offset: the offset of the current pane
// Return Value:
// - A tuple of Panes, the first being the focused pane if found, and the second
// being the adjacent pane if it exists, and a bool that represents if the move
// goes out of bounds.
Pane::PaneNeighborSearch Pane::_FindNeighborForPane(const FocusDirection& direction,
PaneNeighborSearch searchResult,
const bool sourceIsSecondSide,
const Pane::PanePoint offset)
{
// Test if the move will go out of boundaries. E.g. if the focus is already
// on the second child of some pane and it attempts to move right, there
// can't possibly be a neighbor to be found in the first child.
if ((sourceIsSecondSide && (direction == FocusDirection::Right || direction == FocusDirection::Down)) ||
(!sourceIsSecondSide && (direction == FocusDirection::Left || direction == FocusDirection::Up)))
{
return searchResult;
}
// If we are a leaf node test if we adjacent to the focus node
if (_IsLeaf())
{
if (_IsAdjacent(searchResult.sourceOffset, offset, direction))
{
searchResult.neighbor = shared_from_this();
}
return searchResult;
}
auto [firstOffset, secondOffset] = _GetOffsetsForPane(offset);
auto sourceNeighborSearch = _firstChild->_FindNeighborForPane(direction, searchResult, sourceIsSecondSide, firstOffset);
if (sourceNeighborSearch.neighbor)
{
return sourceNeighborSearch;
}
return _secondChild->_FindNeighborForPane(direction, searchResult, sourceIsSecondSide, secondOffset);
}
// Method Description:
// - Searches the tree to find the source pane, and if it exists, the
// visually adjacent pane by direction.
// Arguments:
// - sourcePane: The pane to find the neighbor of.
// - direction: The direction to search in from the focused pane.
// - offset: The offset, with the top-left corner being (0,0), that the current pane is relative to the root.
// Return Value:
// - The (partial) search result. If the search was successful, the pane and its neighbor will be returned.
// Otherwise, the neighbor will be null and the focus will be null/non-null if it was found.
Pane::PaneNeighborSearch Pane::_FindPaneAndNeighbor(const std::shared_ptr<Pane> sourcePane, const FocusDirection& direction, const Pane::PanePoint offset)
{
// If we are the source pane, return ourselves
if (this == sourcePane.get())
{
return { shared_from_this(), nullptr, offset };
}
if (_IsLeaf())
{
return { nullptr, nullptr, offset };
}
auto [firstOffset, secondOffset] = _GetOffsetsForPane(offset);
auto sourceNeighborSearch = _firstChild->_FindPaneAndNeighbor(sourcePane, direction, firstOffset);
// If we have both the focus element and its neighbor, we are done
if (sourceNeighborSearch.source && sourceNeighborSearch.neighbor)
{
return sourceNeighborSearch;
}
// if we only found the focus, then we search the second branch for the
// neighbor.
if (sourceNeighborSearch.source)
{
// If we can possibly have both sides of a direction, check if the sibling has the neighbor
if (DirectionMatchesSplit(direction, _splitState))
{
return _secondChild->_FindNeighborForPane(direction, sourceNeighborSearch, false, secondOffset);
}
return sourceNeighborSearch;
}
// If we didn't find the focus at all, we need to search the second branch
// for the focus (and possibly its neighbor).
sourceNeighborSearch = _secondChild->_FindPaneAndNeighbor(sourcePane, direction, secondOffset);
// We found both so we are done.
if (sourceNeighborSearch.source && sourceNeighborSearch.neighbor)
{
return sourceNeighborSearch;
}
// We only found the focus, which means that its neighbor might be in the
// first branch.
if (sourceNeighborSearch.source)
{
// If we can possibly have both sides of a direction, check if the sibling has the neighbor
if (DirectionMatchesSplit(direction, _splitState))
{
return _firstChild->_FindNeighborForPane(direction, sourceNeighborSearch, true, firstOffset);
}
return sourceNeighborSearch;
}
return { nullptr, nullptr, offset };
}
// Method Description:
// - Returns true if the connection state of this pane is closed.
// Arguments:
// - <none>
// Return Value:
// - true if the connection state of this Pane is closed.
bool Pane::IsConnectionClosed() const
{
if (const auto& control{ GetTerminalControl() })
{
return control.ConnectionState() >= ConnectionState::Closed;
}
return false;
}
// Event Description:
// - Called when our control gains focus. We'll use this to trigger our GotFocus
// callback. The tab that's hosting us should have registered a callback which
// can be used to mark us as active.
// Arguments:
// - <unused>
// Return Value:
// - <none>
void Pane::_ContentGotFocusHandler(const winrt::Windows::Foundation::IInspectable& sender,
const RoutedEventArgs& /* args */)
{
auto f = FocusState::Programmatic;
if (const auto o = sender.try_as<winrt::Windows::UI::Xaml::Controls::Control>())
{
f = o.FocusState();
}
GotFocus.raise(shared_from_this(), f);
}
// Event Description:
// - Called when our control loses focus. We'll use this to trigger our LostFocus
// callback. The tab that's hosting us should have registered a callback which
// can be used to update its own internal focus state
void Pane::_ContentLostFocusHandler(const winrt::Windows::Foundation::IInspectable& /* sender */,
const RoutedEventArgs& /* args */)
{
LostFocus.raise(shared_from_this());
}
// Method Description:
// - Fire our Closed event to tell our parent that we should be removed.
// Arguments:
// - <none>
// Return Value:
// - <none>
void Pane::Close()
{
_setPaneContent(nullptr);
// Fire our Closed event to tell our parent that we should be removed.
Closed.raise(nullptr, nullptr);
}
// Method Description:
// - Prepare this pane to be removed from the UI hierarchy by closing all controls
// and connections beneath it.
void Pane::Shutdown()
{
if (_IsLeaf())
{
_setPaneContent(nullptr);