add clang-format conf to the project, format the c++ code (#1141)

This commit is contained in:
adiviness 2019-06-11 13:27:09 -07:00 committed by GitHub
parent 6fc0978ddb
commit 9b92986b49
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
523 changed files with 11376 additions and 12481 deletions

93
.clang-format Normal file
View file

@ -0,0 +1,93 @@
AccessModifierOffset: -4
AlignAfterOpenBracket: Align
#AllowAllArgumentsOnNextLine: false
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
#AllowAllConstructorInitializersOnNextLine: false
AlignEscapedNewlines: Left
AlignOperands: true
AlignTrailingComments: false
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortFunctionsOnASingleLine: Inline
AllowShortCaseLabelsOnASingleLine: false
AllowShortIfStatementsOnASingleLine: false
#AllowShortLambdasOnASingleLine: Inline
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: Yes
BinPackArguments: false
BinPackParameters: false
BraceWrapping:
AfterClass: true
AfterControlStatement: true
AfterEnum: true
AfterFunction: true
AfterNamespace: true
AfterObjCDeclaration: true
AfterStruct: true
AfterUnion: true
AfterExternBlock: false
BeforeCatch: true
BeforeElse: true
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Custom
BreakBeforeTernaryOperators: false
BreakConstructorInitializers: AfterColon
BreakInheritanceList: AfterColon
ColumnLimit: 0
CommentPragmas: "suppress"
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: false
DerivePointerAlignment: false
FixNamespaceComments: false
IncludeBlocks: Regroup
IncludeCategories:
- Regex: '^.*(precomp|pch|stdafx)'
Priority: -1
- Regex: '^".*"'
Priority: 1
- Regex: '^<.*>'
Priority: 2
- Regex: '.*'
Priority: 3
IndentCaseLabels: false
IndentPPDirectives: None
IndentWidth: 4
IndentWrappedFunctionNames: false
KeepEmptyLinesAtTheStartOfBlocks: false
MacroBlockBegin: "BEGIN_TEST_METHOD_PROPERTIES|BEGIN_MODULE|BEGIN_TEST_CLASS|BEGIN_TEST_METHOD"
MacroBlockEnd: "END_TEST_METHOD_PROPERTIES|END_MODULE|END_TEST_CLASS|END_TEST_METHOD"
MaxEmptyLinesToKeep: 1
NamespaceIndentation: All
PointerAlignment: Left
ReflowComments: false
SortIncludes: false
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
#SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceBeforeRangeBasedForLoopColon: true
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInCStyleCastParentheses: false
SpacesInContainerLiterals: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Cpp11
TabWidth: 4
UseTab: Never

View file

@ -3,6 +3,8 @@
Openconsole can be built with Visual Studio or from the command line. There are build scripts for both cmd and powershell in /tools. Openconsole can be built with Visual Studio or from the command line. There are build scripts for both cmd and powershell in /tools.
When using Visual Studio, be sure to set up the path for code formatting. This can be done in Visual Studio by going to Tools > Options > Text Editor > C++ > Formatting and checking "Use custom clang-format.exe file" and choosing the clang-format.exe in the repository at /dep/llvm/clang-format.exe by clicking "browse" right under the check box.
## Building with cmd ## Building with cmd
The cmd scripts are set up to emulate a portion of the OS razzle build environment. razzle.cmd is the first script that should be run. bcz.cmd will build clean and bz.cmd should build incrementally. The cmd scripts are set up to emulate a portion of the OS razzle build environment. razzle.cmd is the first script that should be run. bcz.cmd will build clean and bz.cmd should build incrementally.
@ -11,6 +13,7 @@ There are also scripts for running the tests:
- `runut.cmd` - run the unit tests - `runut.cmd` - run the unit tests
- `runft.cmd` - run the feature tests - `runft.cmd` - run the feature tests
- `runuia.cmd` - run the UIA tests - `runuia.cmd` - run the UIA tests
- `runformat` - uses clang-format to format all c++ files to match our coding style.
## Build with Powershell ## Build with Powershell
@ -20,6 +23,7 @@ Openconsole.psm1 should be loaded with `Import-Module`. From there `Set-MsbuildD
- `Invoke-OpenConsoleTests` - runs the various tests. Will run the unit tests by default. - `Invoke-OpenConsoleTests` - runs the various tests. Will run the unit tests by default.
- `Start-OpenConsole` - starts Openconsole.exe from the output directory. x64 is run by default. - `Start-OpenConsole` - starts Openconsole.exe from the output directory. x64 is run by default.
- `Debug-OpenConsole` - starts Openconsole.exe and attaches it to the default debugger. x64 is run by default. - `Debug-OpenConsole` - starts Openconsole.exe and attaches it to the default debugger. x64 is run by default.
- `Invoke-CodeFormat` - uses clang-format to format all c++ files to match our coding style.
## Configuration Types ## Configuration Types

View file

@ -4,14 +4,14 @@
#include "precomp.h" #include "precomp.h"
#include "AttrRow.hpp" #include "AttrRow.hpp"
// Routine Description: // Routine Description:
// - constructor // - constructor
// Arguments: // Arguments:
// - cchRowWidth - the length of the default text attribute // - cchRowWidth - the length of the default text attribute
// - attr - the default text attribute // - attr - the default text attribute
// Return Value: // Return Value:
// - constructed object // - constructed object
// Note: will throw exception if unable to allocate memory for text attribute storage // Note: will throw exception if unable to allocate memory for text attribute storage
ATTR_ROW::ATTR_ROW(const UINT cchRowWidth, const TextAttribute attr) ATTR_ROW::ATTR_ROW(const UINT cchRowWidth, const TextAttribute attr)
{ {
_list.push_back(TextAttributeRun(cchRowWidth, attr)); _list.push_back(TextAttributeRun(cchRowWidth, attr));
@ -210,7 +210,6 @@ void ATTR_ROW::ReplaceLegacyAttrs(_In_ WORD wToBeReplacedAttr, _In_ WORD wReplac
ReplaceAttrs(ToBeReplaced, ReplaceWith); ReplaceAttrs(ToBeReplaced, ReplaceWith);
} }
// Method Description: // Method Description:
// - Replaces all runs in the row with the given toBeReplacedAttr with the new // - Replaces all runs in the row with the given toBeReplacedAttr with the new
// attribute replaceWith. // attribute replaceWith.
@ -230,7 +229,6 @@ void ATTR_ROW::ReplaceAttrs(const TextAttribute& toBeReplacedAttr, const TextAtt
} }
} }
// Routine Description: // Routine Description:
// - Takes a array of attribute runs, and inserts them into this row from startIndex to endIndex. // - Takes a array of attribute runs, and inserts them into this row from startIndex to endIndex.
// - For example, if the current row was was [{4, BLUE}], the merge string // - For example, if the current row was was [{4, BLUE}], the merge string
@ -245,11 +243,10 @@ void ATTR_ROW::ReplaceAttrs(const TextAttribute& toBeReplacedAttr, const TextAtt
// Return Value: // Return Value:
// - STATUS_NO_MEMORY if there wasn't enough memory to insert the runs // - STATUS_NO_MEMORY if there wasn't enough memory to insert the runs
// otherwise STATUS_SUCCESS if we were successful. // otherwise STATUS_SUCCESS if we were successful.
[[nodiscard]] [[nodiscard]] HRESULT ATTR_ROW::InsertAttrRuns(const std::basic_string_view<TextAttributeRun> newAttrs,
HRESULT ATTR_ROW::InsertAttrRuns(const std::basic_string_view<TextAttributeRun> newAttrs, const size_t iStart,
const size_t iStart, const size_t iEnd,
const size_t iEnd, const size_t cBufferWidth)
const size_t cBufferWidth)
{ {
// Definitions: // Definitions:
// Existing Run = The run length encoded color array we're already storing in memory before this was called. // Existing Run = The run length encoded color array we're already storing in memory before this was called.

View file

@ -47,11 +47,10 @@ public:
void Resize(const size_t newWidth); void Resize(const size_t newWidth);
[[nodiscard]] [[nodiscard]] HRESULT InsertAttrRuns(const std::basic_string_view<TextAttributeRun> newAttrs,
HRESULT InsertAttrRuns(const std::basic_string_view<TextAttributeRun> newAttrs, const size_t iStart,
const size_t iStart, const size_t iEnd,
const size_t iEnd, const size_t cBufferWidth);
const size_t cBufferWidth);
static std::vector<TextAttributeRun> PackAttrs(const std::vector<TextAttribute>& attrs); static std::vector<TextAttributeRun> PackAttrs(const std::vector<TextAttribute>& attrs);
@ -65,12 +64,10 @@ public:
friend class AttrRowIterator; friend class AttrRowIterator;
private: private:
std::vector<TextAttributeRun> _list; std::vector<TextAttributeRun> _list;
size_t _cchRowWidth; size_t _cchRowWidth;
#ifdef UNIT_TESTING #ifdef UNIT_TESTING
friend class AttrRowTests; friend class AttrRowTests;
#endif #endif
}; };

View file

@ -13,7 +13,6 @@ Author(s):
- Austin Diviness (AustDi) 04-Jun-2018 - Austin Diviness (AustDi) 04-Jun-2018
--*/ --*/
#pragma once #pragma once
#include "TextAttribute.hpp" #include "TextAttribute.hpp"
@ -55,7 +54,7 @@ private:
std::vector<TextAttributeRun>::const_iterator _run; std::vector<TextAttributeRun>::const_iterator _run;
const ATTR_ROW* _pAttrRow; const ATTR_ROW* _pAttrRow;
size_t _currentAttributeIndex; // index of TextAttribute within the current TextAttributeRun size_t _currentAttributeIndex; // index of TextAttribute within the current TextAttributeRun
void _increment(size_t count); void _increment(size_t count);
void _decrement(size_t count); void _decrement(size_t count);
void _setToEnd(); void _setToEnd();

View file

@ -101,8 +101,7 @@ void CharRow::Reset()
// - newSize - the new width of the character and attributes rows // - newSize - the new width of the character and attributes rows
// Return Value: // Return Value:
// - S_OK on success, otherwise relevant error code // - S_OK on success, otherwise relevant error code
[[nodiscard]] [[nodiscard]] HRESULT CharRow::Resize(const size_t newSize) noexcept
HRESULT CharRow::Resize(const size_t newSize) noexcept
{ {
try try
{ {
@ -263,7 +262,7 @@ std::wstring CharRow::GetTextRaw() const
{ {
std::wstring wstr; std::wstring wstr;
wstr.reserve(_data.size()); wstr.reserve(_data.size());
for (size_t i = 0; i < _data.size(); ++i) for (size_t i = 0; i < _data.size(); ++i)
{ {
auto glyph = GlyphAt(i); auto glyph = GlyphAt(i);
for (auto it = glyph.begin(); it != glyph.end(); ++it) for (auto it = glyph.begin(); it != glyph.end(); ++it)
@ -279,7 +278,7 @@ std::wstring CharRow::GetText() const
std::wstring wstr; std::wstring wstr;
wstr.reserve(_data.size()); wstr.reserve(_data.size());
for (size_t i = 0; i < _data.size(); ++i) for (size_t i = 0; i < _data.size(); ++i)
{ {
auto glyph = GlyphAt(i); auto glyph = GlyphAt(i);
if (!DbcsAttrAt(i).IsTrailing()) if (!DbcsAttrAt(i).IsTrailing())

View file

@ -54,8 +54,7 @@ public:
bool WasDoubleBytePadded() const noexcept; bool WasDoubleBytePadded() const noexcept;
size_t size() const noexcept; size_t size() const noexcept;
void Reset(); void Reset();
[[nodiscard]] [[nodiscard]] HRESULT Resize(const size_t newSize) noexcept;
HRESULT Resize(const size_t newSize) noexcept;
size_t MeasureLeft() const; size_t MeasureLeft() const;
size_t MeasureRight() const noexcept; size_t MeasureRight() const noexcept;
void ClearCell(const size_t column); void ClearCell(const size_t column);
@ -116,8 +115,7 @@ void OverwriteColumns(InputIt1 startChars, InputIt1 endChars, InputIt2 startAttr
endChars, endChars,
startAttrs, startAttrs,
outIt, outIt,
[](const wchar_t wch, const DbcsAttribute attr) [](const wchar_t wch, const DbcsAttribute attr) {
{ return CharRow::value_type{ wch, attr };
return CharRow::value_type{ wch, attr }; });
});
} }

View file

@ -5,7 +5,6 @@
#include "CharRowCell.hpp" #include "CharRowCell.hpp"
#include "unicode.hpp" #include "unicode.hpp"
// default glyph value, used for reseting the character data portion of a cell // default glyph value, used for reseting the character data portion of a cell
static constexpr wchar_t DefaultValue = UNICODE_SPACE; static constexpr wchar_t DefaultValue = UNICODE_SPACE;

View file

@ -18,14 +18,12 @@ Author(s):
#include "DbcsAttribute.hpp" #include "DbcsAttribute.hpp"
#if (defined(_M_IX86) || defined(_M_AMD64)) #if (defined(_M_IX86) || defined(_M_AMD64))
// currently CharRowCell's fields use 3 bytes of memory, leaving the 4th byte in unused. this leads // currently CharRowCell's fields use 3 bytes of memory, leaving the 4th byte in unused. this leads
// to a rather large amount of useless memory allocated. so instead, pack CharRowCell by bytes instead of words. // to a rather large amount of useless memory allocated. so instead, pack CharRowCell by bytes instead of words.
#pragma pack(push, 1) #pragma pack(push, 1)
#endif #endif
class CharRowCell final class CharRowCell final
{ {
public: public:
@ -44,6 +42,7 @@ public:
const wchar_t& Char() const noexcept; const wchar_t& Char() const noexcept;
friend constexpr bool operator==(const CharRowCell& a, const CharRowCell& b) noexcept; friend constexpr bool operator==(const CharRowCell& a, const CharRowCell& b) noexcept;
private: private:
wchar_t _wch; wchar_t _wch;
DbcsAttribute _attr; DbcsAttribute _attr;

View file

@ -5,7 +5,6 @@
#include "UnicodeStorage.hpp" #include "UnicodeStorage.hpp"
#include "CharRow.hpp" #include "CharRow.hpp"
// Routine Description: // Routine Description:
// - assignment operator. will store extended glyph data in a separate storage location // - assignment operator. will store extended glyph data in a separate storage location
// Arguments: // Arguments:
@ -96,7 +95,6 @@ CharRowCellReference::const_iterator CharRowCellReference::end() const
{ {
if (_cellData().DbcsAttr().IsGlyphStored()) if (_cellData().DbcsAttr().IsGlyphStored())
{ {
const auto& chars = _parent.GetUnicodeStorage().GetText(_parent.GetStorageKey(_index)); const auto& chars = _parent.GetUnicodeStorage().GetText(_parent.GetStorageKey(_index));
return chars.data() + chars.size(); return chars.data() + chars.size();
} }

View file

@ -23,7 +23,6 @@ class CharRow;
class CharRowCellReference final class CharRowCellReference final
{ {
public: public:
using const_iterator = const wchar_t*; using const_iterator = const wchar_t*;
CharRowCellReference(CharRow& parent, const size_t index) : CharRowCellReference(CharRow& parent, const size_t index) :
@ -45,7 +44,6 @@ public:
const_iterator begin() const; const_iterator begin() const;
const_iterator end() const; const_iterator end() const;
friend bool operator==(const CharRowCellReference& ref, const std::vector<wchar_t>& glyph); friend bool operator==(const CharRowCellReference& ref, const std::vector<wchar_t>& glyph);
friend bool operator==(const std::vector<wchar_t>& glyph, const CharRowCellReference& ref); friend bool operator==(const std::vector<wchar_t>& glyph, const CharRowCellReference& ref);

View file

@ -139,5 +139,6 @@ constexpr bool operator==(const DbcsAttribute& a, const DbcsAttribute& b) noexce
return a._attribute == b._attribute; return a._attribute == b._attribute;
} }
static_assert(sizeof(DbcsAttribute) == sizeof(BYTE), "DbcsAttribute should be one byte big. if this changes then it needs" static_assert(sizeof(DbcsAttribute) == sizeof(BYTE), "DbcsAttribute should be one byte big. if this changes then it needs "
" either an implicit conversion to a BYTE or an update to all places that assume it's a byte big"); "either an implicit conversion to a BYTE or an update to all places "
"that assume it's a byte big");

View file

@ -17,7 +17,6 @@ OutputCell::OutputCell() :
_textAttribute{ InvalidTextAttribute }, _textAttribute{ InvalidTextAttribute },
_behavior{ TextAttributeBehavior::Stored } _behavior{ TextAttributeBehavior::Stored }
{ {
} }
OutputCell::OutputCell(const std::wstring_view charData, OutputCell::OutputCell(const std::wstring_view charData,

View file

@ -78,9 +78,9 @@ public:
} }
private: private:
// basic_string contains a small storage internally so we don't need // basic_string contains a small storage internally so we don't need
// to worry about heap allocation for short strings. // to worry about heap allocation for short strings.
std::wstring _text; std::wstring _text;
DbcsAttribute _dbcsAttribute; DbcsAttribute _dbcsAttribute;
TextAttribute _textAttribute; TextAttribute _textAttribute;
TextAttributeBehavior _behavior; TextAttributeBehavior _behavior;

View file

@ -26,7 +26,6 @@ OutputCellIterator::OutputCellIterator(const wchar_t& wch, const size_t fillLimi
_distance(0), _distance(0),
_fillLimit(fillLimit) _fillLimit(fillLimit)
{ {
} }
// Routine Description: // Routine Description:
@ -43,7 +42,6 @@ OutputCellIterator::OutputCellIterator(const TextAttribute& attr, const size_t f
_distance(0), _distance(0),
_fillLimit(fillLimit) _fillLimit(fillLimit)
{ {
} }
// Routine Description: // Routine Description:
@ -61,7 +59,6 @@ OutputCellIterator::OutputCellIterator(const wchar_t& wch, const TextAttribute&
_distance(0), _distance(0),
_fillLimit(fillLimit) _fillLimit(fillLimit)
{ {
} }
// Routine Description: // Routine Description:
@ -78,7 +75,6 @@ OutputCellIterator::OutputCellIterator(const CHAR_INFO& charInfo, const size_t f
_distance(0), _distance(0),
_fillLimit(fillLimit) _fillLimit(fillLimit)
{ {
} }
// Routine Description: // Routine Description:
@ -94,7 +90,6 @@ OutputCellIterator::OutputCellIterator(const std::wstring_view utf16Text) :
_distance(0), _distance(0),
_fillLimit(0) _fillLimit(0)
{ {
} }
// Routine Description: // Routine Description:
@ -111,7 +106,6 @@ OutputCellIterator::OutputCellIterator(const std::wstring_view utf16Text, const
_pos(0), _pos(0),
_fillLimit(0) _fillLimit(0)
{ {
} }
// Routine Description: // Routine Description:
@ -131,7 +125,6 @@ OutputCellIterator::OutputCellIterator(const std::basic_string_view<WORD> legacy
_pos(0), _pos(0),
_fillLimit(0) _fillLimit(0)
{ {
} }
// Routine Description: // Routine Description:
@ -142,12 +135,11 @@ OutputCellIterator::OutputCellIterator(const std::basic_string_view<CHAR_INFO> c
_mode(Mode::CharInfo), _mode(Mode::CharInfo),
_currentView(s_GenerateView(charInfos.at(0))), _currentView(s_GenerateView(charInfos.at(0))),
_run(charInfos), _run(charInfos),
_attr(InvalidTextAttribute), _attr(InvalidTextAttribute),
_distance(0), _distance(0),
_pos(0), _pos(0),
_fillLimit(0) _fillLimit(0)
{ {
} }
// Routine Description: // Routine Description:
@ -163,7 +155,6 @@ OutputCellIterator::OutputCellIterator(const std::basic_string_view<OutputCell>
_pos(0), _pos(0),
_fillLimit(0) _fillLimit(0)
{ {
} }
// Routine Description: // Routine Description:

View file

@ -47,7 +47,7 @@ public:
OutputCellIterator& operator=(const OutputCellIterator& it) = default; OutputCellIterator& operator=(const OutputCellIterator& it) = default;
operator bool() const noexcept; operator bool() const noexcept;
ptrdiff_t GetCellDistance(OutputCellIterator other) const noexcept; ptrdiff_t GetCellDistance(OutputCellIterator other) const noexcept;
ptrdiff_t GetInputDistance(OutputCellIterator other) const noexcept; ptrdiff_t GetInputDistance(OutputCellIterator other) const noexcept;
friend ptrdiff_t operator-(OutputCellIterator one, OutputCellIterator two) = delete; friend ptrdiff_t operator-(OutputCellIterator one, OutputCellIterator two) = delete;
@ -59,12 +59,11 @@ public:
const OutputCellView* operator->() const; const OutputCellView* operator->() const;
private: private:
enum class Mode
enum class Mode {
{
// Loose mode is where we're given text and attributes in a raw sort of form // Loose mode is where we're given text and attributes in a raw sort of form
// like while data is being inserted from an API call. // like while data is being inserted from an API call.
Loose, Loose,
// Loose mode with only text is where we're given just text and we want // Loose mode with only text is where we're given just text and we want
// to use the attribute already in the buffer when writing // to use the attribute already in the buffer when writing
@ -90,10 +89,11 @@ private:
std::basic_string_view<WORD> _legacyAttrs; std::basic_string_view<WORD> _legacyAttrs;
std::variant< std::variant<
std::wstring_view, std::wstring_view,
std::basic_string_view<CHAR_INFO>, std::basic_string_view<CHAR_INFO>,
std::basic_string_view<OutputCell>, std::basic_string_view<OutputCell>,
std::monostate> _run; std::monostate>
_run;
TextAttribute _attr; TextAttribute _attr;

View file

@ -11,7 +11,6 @@ OutputCellRect::OutputCellRect() :
_rows(0), _rows(0),
_cols(0) _cols(0)
{ {
} }
// Routine Description: // Routine Description:
@ -57,7 +56,7 @@ OutputCellIterator OutputCellRect::GetRowIter(const size_t row) const
} }
// Routine Description: // Routine Description:
// - Internal helper to find the pointer to the specific row offset in the giant // - Internal helper to find the pointer to the specific row offset in the giant
// contiguous block of memory allocated for this rectangle. // contiguous block of memory allocated for this rectangle.
// Arguments: // Arguments:
// - row - The Y position or row index in the buffer. // - row - The Y position or row index in the buffer.
@ -69,7 +68,7 @@ OutputCell* OutputCellRect::_FindRowOffset(const size_t row)
} }
// Routine Description: // Routine Description:
// - Internal helper to find the pointer to the specific row offset in the giant // - Internal helper to find the pointer to the specific row offset in the giant
// contiguous block of memory allocated for this rectangle. // contiguous block of memory allocated for this rectangle.
// Arguments: // Arguments:
// - row - The Y position or row index in the buffer. // - row - The Y position or row index in the buffer.

View file

@ -40,7 +40,7 @@ public:
private: private:
std::vector<OutputCell> _storage; std::vector<OutputCell> _storage;
OutputCell* _FindRowOffset(const size_t row); OutputCell* _FindRowOffset(const size_t row);
const OutputCell* _FindRowOffset(const size_t row) const; const OutputCell* _FindRowOffset(const size_t row) const;

View file

@ -21,7 +21,6 @@ OutputCellView::OutputCellView(const std::wstring_view view,
_textAttr(textAttr), _textAttr(textAttr),
_behavior(behavior) _behavior(behavior)
{ {
} }
// Routine Description: // Routine Description:
@ -91,9 +90,9 @@ TextAttributeBehavior OutputCellView::TextAttrBehavior() const noexcept
bool OutputCellView::operator==(const OutputCellView& it) const noexcept bool OutputCellView::operator==(const OutputCellView& it) const noexcept
{ {
return _view == it._view && return _view == it._view &&
_dbcsAttr == it._dbcsAttr && _dbcsAttr == it._dbcsAttr &&
_textAttr == it._textAttr && _textAttr == it._textAttr &&
_behavior == it._behavior; _behavior == it._behavior;
} }
// Routine Description: // Routine Description:

View file

@ -25,7 +25,6 @@ Revision History:
class OutputCellView class OutputCellView
{ {
public: public:
OutputCellView(const std::wstring_view view, OutputCellView(const std::wstring_view view,
const DbcsAttribute dbcsAttr, const DbcsAttribute dbcsAttr,
const TextAttribute textAttr, const TextAttribute textAttr,

View file

@ -87,8 +87,7 @@ bool ROW::Reset(const TextAttribute Attr)
// - width - the new width, in cells // - width - the new width, in cells
// Return Value: // Return Value:
// - S_OK if successful, otherwise relevant error // - S_OK if successful, otherwise relevant error
[[nodiscard]] [[nodiscard]] HRESULT ROW::Resize(const size_t width)
HRESULT ROW::Resize(const size_t width)
{ {
RETURN_IF_FAILED(_charRow.Resize(width)); RETURN_IF_FAILED(_charRow.Resize(width));
try try
@ -151,11 +150,11 @@ const UnicodeStorage& ROW::GetUnicodeStorage() const
// - setWrap - set the wrap flags if we hit the end of the row while writing and there's still more data in the iterator. // - setWrap - set the wrap flags if we hit the end of the row while writing and there's still more data in the iterator.
// - limitRight - right inclusive column ID for the last write in this row. (optional, will just write to the end of row if nullopt) // - limitRight - right inclusive column ID for the last write in this row. (optional, will just write to the end of row if nullopt)
// Return Value: // Return Value:
// - iterator to first cell that was not written to this row. // - iterator to first cell that was not written to this row.
OutputCellIterator ROW::WriteCells(OutputCellIterator it, const size_t index, const bool setWrap, std::optional<size_t> limitRight) OutputCellIterator ROW::WriteCells(OutputCellIterator it, const size_t index, const bool setWrap, std::optional<size_t> limitRight)
{ {
THROW_HR_IF(E_INVALIDARG, index >= _charRow.size()); THROW_HR_IF(E_INVALIDARG, index >= _charRow.size());
THROW_HR_IF(E_INVALIDARG, limitRight.value_or(0) >= _charRow.size()); THROW_HR_IF(E_INVALIDARG, limitRight.value_or(0) >= _charRow.size());
size_t currentIndex = index; size_t currentIndex = index;
// If we're given a right-side column limit, use it. Otherwise, the write limit is the final column index available in the char row. // If we're given a right-side column limit, use it. Otherwise, the write limit is the final column index available in the char row.

View file

@ -46,8 +46,7 @@ public:
void SetId(const SHORT id) noexcept; void SetId(const SHORT id) noexcept;
bool Reset(const TextAttribute Attr); bool Reset(const TextAttribute Attr);
[[nodiscard]] [[nodiscard]] HRESULT Resize(const size_t width);
HRESULT Resize(const size_t width);
void ClearColumn(const size_t column); void ClearColumn(const size_t column);
std::wstring GetText() const; std::wstring GetText() const;

View file

@ -16,7 +16,6 @@ RowCellIterator::RowCellIterator(const ROW& row, const size_t start, const size_
_pos(start), _pos(start),
_view(s_GenerateView(row, start)) _view(s_GenerateView(row, start))
{ {
} }
RowCellIterator::operator bool() const noexcept RowCellIterator::operator bool() const noexcept
@ -29,9 +28,9 @@ RowCellIterator::operator bool() const noexcept
bool RowCellIterator::operator==(const RowCellIterator& it) const noexcept bool RowCellIterator::operator==(const RowCellIterator& it) const noexcept
{ {
return _row == it._row && return _row == it._row &&
_start == it._start && _start == it._start &&
_length == it._length && _length == it._length &&
_pos == it._pos; _pos == it._pos;
} }
bool RowCellIterator::operator!=(const RowCellIterator& it) const noexcept bool RowCellIterator::operator!=(const RowCellIterator& it) const noexcept
{ {

View file

@ -164,7 +164,8 @@ private:
#ifdef UNIT_TESTING #ifdef UNIT_TESTING
friend class TextBufferTests; friend class TextBufferTests;
friend class TextAttributeTests; friend class TextAttributeTests;
template<typename TextAttribute> friend class WEX::TestExecution::VerifyOutputTraits; template<typename TextAttribute>
friend class WEX::TestExecution::VerifyOutputTraits;
#endif #endif
}; };
@ -210,13 +211,15 @@ constexpr bool operator!=(const WORD& legacyAttr, const TextAttribute& attr) noe
#ifdef UNIT_TESTING #ifdef UNIT_TESTING
#define LOG_ATTR(attr) (Log::Comment(NoThrowString().Format(\ #define LOG_ATTR(attr) (Log::Comment(NoThrowString().Format( \
L#attr L"=%s", VerifyOutputTraits<TextAttribute>::ToString(attr).GetBuffer()))) L#attr L"=%s", VerifyOutputTraits<TextAttribute>::ToString(attr).GetBuffer())))
namespace WEX { namespace WEX
namespace TestExecution { {
namespace TestExecution
{
template<> template<>
class VerifyOutputTraits < TextAttribute > class VerifyOutputTraits<TextAttribute>
{ {
public: public:
static WEX::Common::NoThrowString ToString(const TextAttribute& attr) static WEX::Common::NoThrowString ToString(const TextAttribute& attr)
@ -226,8 +229,7 @@ namespace WEX {
VerifyOutputTraits<TextColor>::ToString(attr._foreground).GetBuffer(), VerifyOutputTraits<TextColor>::ToString(attr._foreground).GetBuffer(),
VerifyOutputTraits<TextColor>::ToString(attr._background).GetBuffer(), VerifyOutputTraits<TextColor>::ToString(attr._background).GetBuffer(),
attr.IsBold(), attr.IsBold(),
attr._wAttrLegacy attr._wAttrLegacy);
);
} }
}; };
} }

View file

@ -86,7 +86,6 @@ COLORREF TextColor::GetColor(std::basic_string_view<COLORREF> colorTable,
return colorTable[i + 8]; return colorTable[i + 8];
} }
} }
} }
return defaultColor; return defaultColor;

View file

@ -49,7 +49,6 @@ enum class ColorType : BYTE
struct TextColor struct TextColor
{ {
public: public:
constexpr TextColor() noexcept : constexpr TextColor() noexcept :
_meta{ ColorType::IsDefault }, _meta{ ColorType::IsDefault },
_red{ 0 }, _red{ 0 },
@ -105,7 +104,6 @@ public:
return _index; return _index;
} }
private: private:
ColorType _meta : 2; ColorType _meta : 2;
union union
@ -119,7 +117,8 @@ private:
#ifdef UNIT_TESTING #ifdef UNIT_TESTING
friend class TextBufferTests; friend class TextBufferTests;
template<typename TextColor> friend class WEX::TestExecution::VerifyOutputTraits; template<typename TextColor>
friend class WEX::TestExecution::VerifyOutputTraits;
#endif #endif
}; };
@ -140,10 +139,12 @@ bool constexpr operator!=(const TextColor& a, const TextColor& b) noexcept
#ifdef UNIT_TESTING #ifdef UNIT_TESTING
namespace WEX { namespace WEX
namespace TestExecution { {
namespace TestExecution
{
template<> template<>
class VerifyOutputTraits < TextColor > class VerifyOutputTraits<TextColor>
{ {
public: public:
static WEX::Common::NoThrowString ToString(const TextColor& color) static WEX::Common::NoThrowString ToString(const TextColor& color)
@ -166,4 +167,4 @@ namespace WEX {
} }
#endif #endif
static_assert(sizeof(TextColor) <= 4*sizeof(BYTE), "We should only need 4B for an entire TextColor. Any more than that is just waste"); static_assert(sizeof(TextColor) <= 4 * sizeof(BYTE), "We should only need 4B for an entire TextColor. Any more than that is just waste");

View file

@ -21,10 +21,9 @@ Author(s):
// std::unordered_map needs help to know how to hash a COORD // std::unordered_map needs help to know how to hash a COORD
namespace std namespace std
{ {
template <> template<>
struct hash<COORD> struct hash<COORD>
{ {
// Routine Description: // Routine Description:
// - hashes a coord. coord will be hashed by storing the x and y values consecutively in the lower // - hashes a coord. coord will be hashed by storing the x and y values consecutively in the lower
// bits of a size_t. // bits of a size_t.

View file

@ -267,25 +267,25 @@ void Cursor::CopyProperties(const Cursor& OtherCursor)
// We shouldn't copy the position as it will be already rearranged by the resize operation. // We shouldn't copy the position as it will be already rearranged by the resize operation.
//_cPosition = pOtherCursor->_cPosition; //_cPosition = pOtherCursor->_cPosition;
_fHasMoved = OtherCursor._fHasMoved; _fHasMoved = OtherCursor._fHasMoved;
_fIsVisible = OtherCursor._fIsVisible; _fIsVisible = OtherCursor._fIsVisible;
_fIsOn = OtherCursor._fIsOn; _fIsOn = OtherCursor._fIsOn;
_fIsDouble = OtherCursor._fIsDouble; _fIsDouble = OtherCursor._fIsDouble;
_fBlinkingAllowed = OtherCursor._fBlinkingAllowed; _fBlinkingAllowed = OtherCursor._fBlinkingAllowed;
_fDelay = OtherCursor._fDelay; _fDelay = OtherCursor._fDelay;
_fIsConversionArea = OtherCursor._fIsConversionArea; _fIsConversionArea = OtherCursor._fIsConversionArea;
// A resize operation should invalidate the delayed end of line status, so do not copy. // A resize operation should invalidate the delayed end of line status, so do not copy.
//_fDelayedEolWrap = OtherCursor._fDelayedEolWrap; //_fDelayedEolWrap = OtherCursor._fDelayedEolWrap;
//_coordDelayedAt = OtherCursor._coordDelayedAt; //_coordDelayedAt = OtherCursor._coordDelayedAt;
_fDeferCursorRedraw = OtherCursor._fDeferCursorRedraw; _fDeferCursorRedraw = OtherCursor._fDeferCursorRedraw;
_fHaveDeferredCursorRedraw = OtherCursor._fHaveDeferredCursorRedraw; _fHaveDeferredCursorRedraw = OtherCursor._fHaveDeferredCursorRedraw;
// Size will be handled seperately in the resize operation. // Size will be handled seperately in the resize operation.
//_ulSize = OtherCursor._ulSize; //_ulSize = OtherCursor._ulSize;
_cursorType = OtherCursor._cursorType; _cursorType = OtherCursor._cursorType;
_color = OtherCursor._color; _color = OtherCursor._color;
} }
void Cursor::DelayEOLWrap(const COORD coordDelayedAt) void Cursor::DelayEOLWrap(const COORD coordDelayedAt)
@ -296,7 +296,7 @@ void Cursor::DelayEOLWrap(const COORD coordDelayedAt)
void Cursor::ResetDelayEOLWrap() void Cursor::ResetDelayEOLWrap()
{ {
_coordDelayedAt = {0}; _coordDelayedAt = { 0 };
_fDelayedEolWrap = false; _fDelayedEolWrap = false;
} }

View file

@ -20,13 +20,12 @@ Revision History:
#include "../inc/conattrs.hpp" #include "../inc/conattrs.hpp"
// the following values are used to create the textmode cursor. // the following values are used to create the textmode cursor.
#define CURSOR_SMALL_SIZE 25 // large enough to be one pixel on a six pixel font #define CURSOR_SMALL_SIZE 25 // large enough to be one pixel on a six pixel font
class TextBuffer; class TextBuffer;
class Cursor final class Cursor final
{ {
public: public:
static const unsigned int s_InvertCursorColor = INVALID_COLOR; static const unsigned int s_InvertCursorColor = INVALID_COLOR;
Cursor(const ULONG ulSize, TextBuffer& parentBuffer); Cursor(const ULONG ulSize, TextBuffer& parentBuffer);
@ -94,19 +93,19 @@ private:
// NOTE: If you are adding a property here, go add it to CopyProperties. // NOTE: If you are adding a property here, go add it to CopyProperties.
COORD _cPosition; // current position on screen (in screen buffer coords). COORD _cPosition; // current position on screen (in screen buffer coords).
bool _fHasMoved; bool _fHasMoved;
bool _fIsVisible; // whether cursor is visible (set only through the API) bool _fIsVisible; // whether cursor is visible (set only through the API)
bool _fIsOn; // whether blinking cursor is on or not bool _fIsOn; // whether blinking cursor is on or not
bool _fIsDouble; // whether the cursor size should be doubled bool _fIsDouble; // whether the cursor size should be doubled
bool _fBlinkingAllowed; //Whether or not the cursor is allowed to blink at all. only set through VT (^[[?12h/l) bool _fBlinkingAllowed; //Whether or not the cursor is allowed to blink at all. only set through VT (^[[?12h/l)
bool _fDelay; // don't blink scursor on next timer message bool _fDelay; // don't blink scursor on next timer message
bool _fIsConversionArea; // is attached to a conversion area so it doesn't actually need to display the cursor. bool _fIsConversionArea; // is attached to a conversion area so it doesn't actually need to display the cursor.
bool _fIsPopupShown; // if a popup is being shown, turn off, stop blinking. bool _fIsPopupShown; // if a popup is being shown, turn off, stop blinking.
bool _fDelayedEolWrap; // don't wrap at EOL till the next char comes in. bool _fDelayedEolWrap; // don't wrap at EOL till the next char comes in.
COORD _coordDelayedAt; // coordinate the EOL wrap was delayed at. COORD _coordDelayedAt; // coordinate the EOL wrap was delayed at.
bool _fDeferCursorRedraw; // whether we should defer redrawing the cursor or not bool _fDeferCursorRedraw; // whether we should defer redrawing the cursor or not
bool _fHaveDeferredCursorRedraw; // have we been asked to redraw the cursor while it was being deferred? bool _fHaveDeferredCursorRedraw; // have we been asked to redraw the cursor while it was being deferred?

View file

@ -17,6 +17,8 @@ Abstract:
#pragma once #pragma once
// clang-format off
// This includes support libraries from the CRT, STL, WIL, and GSL // This includes support libraries from the CRT, STL, WIL, and GSL
#include "LibraryIncludes.h" #include "LibraryIncludes.h"
@ -33,3 +35,5 @@ Abstract:
#include "..\inc\operators.hpp" #include "..\inc\operators.hpp"
#include "..\inc\unicode.hpp" #include "..\inc\unicode.hpp"
#pragma warning(pop) #pragma warning(pop)
// clang-format on

View file

@ -748,8 +748,7 @@ const Cursor& TextBuffer::GetCursor() const
return _cursor; return _cursor;
} }
[[nodiscard]] [[nodiscard]] TextAttribute TextBuffer::GetCurrentAttributes() const noexcept
TextAttribute TextBuffer::GetCurrentAttributes() const noexcept
{ {
return _currentAttributes; return _currentAttributes;
} }
@ -779,8 +778,7 @@ void TextBuffer::Reset()
// - newSize - new size of screen. // - newSize - new size of screen.
// Return Value: // Return Value:
// - Success if successful. Invalid parameter if screen buffer size is unexpected. No memory if allocation failed. // - Success if successful. Invalid parameter if screen buffer size is unexpected. No memory if allocation failed.
[[nodiscard]] [[nodiscard]] NTSTATUS TextBuffer::ResizeTraditional(const COORD newSize) noexcept
NTSTATUS TextBuffer::ResizeTraditional(const COORD newSize) noexcept
{ {
RETURN_HR_IF(E_INVALIDARG, newSize.X < 0 || newSize.Y < 0); RETURN_HR_IF(E_INVALIDARG, newSize.X < 0 || newSize.Y < 0);
@ -822,7 +820,6 @@ NTSTATUS TextBuffer::ResizeTraditional(const COORD newSize) noexcept
// Also take advantage of the row ID refresh loop to resize the rows in the X dimension // Also take advantage of the row ID refresh loop to resize the rows in the X dimension
// and cleanup the UnicodeStorage characters that might fall outside the resized buffer. // and cleanup the UnicodeStorage characters that might fall outside the resized buffer.
_RefreshRowIDs(newSize.X); _RefreshRowIDs(newSize.X);
} }
CATCH_RETURN(); CATCH_RETURN();
@ -1012,7 +1009,7 @@ const TextBuffer::TextAndColor TextBuffer::GetTextForClipboard(const bool lineSe
// always apply \r\n for box selection // always apply \r\n for box selection
if (!lineSelection || !GetRowByOffset(iRow).GetCharRow().WasWrapForced()) if (!lineSelection || !GetRowByOffset(iRow).GetCharRow().WasWrapForced())
{ {
COLORREF const Blackness = RGB(0x00, 0x00, 0x00); // cant see CR/LF so just use black FG & BK COLORREF const Blackness = RGB(0x00, 0x00, 0x00); // cant see CR/LF so just use black FG & BK
selectionText.push_back(UNICODE_CARRIAGERETURN); selectionText.push_back(UNICODE_CARRIAGERETURN);
selectionText.push_back(UNICODE_LINEFEED); selectionText.push_back(UNICODE_LINEFEED);

View file

@ -117,15 +117,13 @@ public:
UINT TotalRowCount() const; UINT TotalRowCount() const;
[[nodiscard]] [[nodiscard]] TextAttribute GetCurrentAttributes() const noexcept;
TextAttribute GetCurrentAttributes() const noexcept;
void SetCurrentAttributes(const TextAttribute currentAttributes) noexcept; void SetCurrentAttributes(const TextAttribute currentAttributes) noexcept;
void Reset(); void Reset();
[[nodiscard]] [[nodiscard]] HRESULT ResizeTraditional(const COORD newSize) noexcept;
HRESULT ResizeTraditional(const COORD newSize) noexcept;
const UnicodeStorage& GetUnicodeStorage() const; const UnicodeStorage& GetUnicodeStorage() const;
UnicodeStorage& GetUnicodeStorage(); UnicodeStorage& GetUnicodeStorage();
@ -147,7 +145,6 @@ public:
std::function<COLORREF(TextAttribute&)> GetBackgroundColor) const; std::function<COLORREF(TextAttribute&)> GetBackgroundColor) const;
private: private:
std::deque<ROW> _storage; std::deque<ROW> _storage;
Cursor _cursor; Cursor _cursor;

View file

@ -68,11 +68,11 @@ TextBufferCellIterator::operator bool() const noexcept
bool TextBufferCellIterator::operator==(const TextBufferCellIterator& it) const noexcept bool TextBufferCellIterator::operator==(const TextBufferCellIterator& it) const noexcept
{ {
return _pos == it._pos && return _pos == it._pos &&
&_buffer == &it._buffer && &_buffer == &it._buffer &&
_exceeded == it._exceeded && _exceeded == it._exceeded &&
_bounds == it._bounds && _bounds == it._bounds &&
_pRow == it._pRow && _pRow == it._pRow &&
_attrIter == it._attrIter; _attrIter == it._attrIter;
} }
// Routine Description: // Routine Description:

View file

@ -50,7 +50,6 @@ public:
const OutputCellView* operator->() const noexcept; const OutputCellView* operator->() const noexcept;
protected: protected:
void _SetPos(const COORD newPos); void _SetPos(const COORD newPos);
void _GenerateView(); void _GenerateView();
static const ROW* s_GetRow(const TextBuffer& buffer, const COORD pos); static const ROW* s_GetRow(const TextBuffer& buffer, const COORD pos);
@ -70,4 +69,3 @@ protected:
friend class ApiRoutinesTests; friend class ApiRoutinesTests;
#endif #endif
}; };

View file

@ -38,4 +38,3 @@ const std::wstring_view* TextBufferTextIterator::operator->() const
{ {
return &_view.Chars(); return &_view.Chars();
} }

View file

@ -28,7 +28,6 @@ public:
const std::wstring_view* operator->() const; const std::wstring_view* operator->() const;
protected: protected:
#if UNIT_TESTING #if UNIT_TESTING
friend class TextBufferIteratorTests; friend class TextBufferIteratorTests;
#endif #endif

View file

@ -72,8 +72,7 @@ void TextAttributeTests::TestRoundtripLegacy()
void TextAttributeTests::TestRoundtripMetaBits() void TextAttributeTests::TestRoundtripMetaBits()
{ {
WORD metaFlags[] = WORD metaFlags[] = {
{
COMMON_LVB_GRID_HORIZONTAL, COMMON_LVB_GRID_HORIZONTAL,
COMMON_LVB_GRID_LVERTICAL, COMMON_LVB_GRID_LVERTICAL,
COMMON_LVB_GRID_RVERTICAL, COMMON_LVB_GRID_RVERTICAL,
@ -102,7 +101,7 @@ void TextAttributeTests::TestRoundtripExhaustive()
// each takes a lot longer than checking. // each takes a lot longer than checking.
// Only VERIFY if the comparison actually fails to speed up the test. // Only VERIFY if the comparison actually fails to speed up the test.
Log::Comment(L"This test will check each possible legacy attribute to make " Log::Comment(L"This test will check each possible legacy attribute to make "
"sure it roundtrips through the creation of a text attribute."); "sure it roundtrips through the creation of a text attribute.");
Log::Comment(L"It will only log if it fails."); Log::Comment(L"It will only log if it fails.");
for (WORD wLegacy = 0; wLegacy < allAttrs; wLegacy++) for (WORD wLegacy = 0; wLegacy < allAttrs; wLegacy++)
{ {
@ -123,8 +122,7 @@ void TextAttributeTests::TestRoundtripExhaustive()
if (!(isLegacy && areEqual)) if (!(isLegacy && areEqual))
{ {
Log::Comment(NoThrowString().Format( Log::Comment(NoThrowString().Format(
L"Failed on wLegacy=0x%x", wLegacy L"Failed on wLegacy=0x%x", wLegacy));
));
VERIFY_IS_TRUE(attr.IsLegacy()); VERIFY_IS_TRUE(attr.IsLegacy());
VERIFY_ARE_EQUAL(wLegacy, attr.GetLegacyAttributes()); VERIFY_ARE_EQUAL(wLegacy, attr.GetLegacyAttributes());
} }

View file

@ -199,7 +199,6 @@ void TextColorTests::TestChangeColor()
color = rgbColor.GetColor(view, _defaultBg, true); color = rgbColor.GetColor(view, _defaultBg, true);
VERIFY_ARE_EQUAL(_colorTable[15], color); VERIFY_ARE_EQUAL(_colorTable[15], color);
rgbColor.SetIndex(15); rgbColor.SetIndex(15);
color = rgbColor.GetColor(view, _defaultFg, false); color = rgbColor.GetColor(view, _defaultFg, false);
VERIFY_ARE_EQUAL(_colorTable[15], color); VERIFY_ARE_EQUAL(_colorTable[15], color);

View file

@ -15,7 +15,6 @@ class UnicodeStorageTests
{ {
TEST_CLASS(UnicodeStorageTests); TEST_CLASS(UnicodeStorageTests);
TEST_METHOD(CanOverwriteEmoji) TEST_METHOD(CanOverwriteEmoji)
{ {
UnicodeStorage storage; UnicodeStorage storage;

View file

@ -17,6 +17,8 @@ Abstract:
#pragma once #pragma once
// clang-format off
// This includes support libraries from the CRT, STL, WIL, and GSL // This includes support libraries from the CRT, STL, WIL, and GSL
#include "LibraryIncludes.h" #include "LibraryIncludes.h"
@ -35,3 +37,5 @@ Abstract:
#include "..\inc\operators.hpp" #include "..\inc\operators.hpp"
#include "..\inc\unicode.hpp" #include "..\inc\unicode.hpp"
#pragma warning(pop) #pragma warning(pop)
// clang-format on

View file

@ -10,10 +10,10 @@
namespace xaml = ::winrt::Windows::UI::Xaml; namespace xaml = ::winrt::Windows::UI::Xaml;
extern "C" { extern "C" {
WINBASEAPI HMODULE WINAPI LoadLibraryExW(_In_ LPCWSTR lpLibFileName, _Reserved_ HANDLE hFile, _In_ DWORD dwFlags); WINBASEAPI HMODULE WINAPI LoadLibraryExW(_In_ LPCWSTR lpLibFileName, _Reserved_ HANDLE hFile, _In_ DWORD dwFlags);
WINBASEAPI HMODULE WINAPI GetModuleHandleW(_In_opt_ LPCWSTR lpModuleName); WINBASEAPI HMODULE WINAPI GetModuleHandleW(_In_opt_ LPCWSTR lpModuleName);
WINUSERAPI BOOL WINAPI PeekMessageW(_Out_ LPMSG lpMsg, _In_opt_ HWND hWnd, _In_ UINT wMsgFilterMin, _In_ UINT wMsgFilterMax, _In_ UINT wRemoveMsg); WINUSERAPI BOOL WINAPI PeekMessageW(_Out_ LPMSG lpMsg, _In_opt_ HWND hWnd, _In_ UINT wMsgFilterMin, _In_ UINT wMsgFilterMax, _In_ UINT wRemoveMsg);
WINUSERAPI LRESULT WINAPI DispatchMessageW(_In_ CONST MSG* lpMsg); WINUSERAPI LRESULT WINAPI DispatchMessageW(_In_ CONST MSG* lpMsg);
} }
namespace winrt::Microsoft::UI::Xaml::Markup::implementation namespace winrt::Microsoft::UI::Xaml::Markup::implementation

View file

@ -39,6 +39,7 @@ namespace winrt::Microsoft::UI::Xaml::Markup::factory_implementation
public: public:
XamlApplication(); XamlApplication();
~XamlApplication(); ~XamlApplication();
private: private:
std::vector<HMODULE> m_preloadInstances; std::vector<HMODULE> m_preloadInstances;
}; };

View file

@ -19,4 +19,3 @@
#include <unknwn.h> #include <unknwn.h>
#include <winrt/Windows.Foundation.h> #include <winrt/Windows.Foundation.h>

View file

@ -36,7 +36,6 @@ namespace winrt
namespace winrt::TerminalApp::implementation namespace winrt::TerminalApp::implementation
{ {
App::App() : App::App() :
App(winrt::TerminalApp::XamlMetaDataProvider()) App(winrt::TerminalApp::XamlMetaDataProvider())
{ {
@ -44,8 +43,8 @@ namespace winrt::TerminalApp::implementation
App::App(Windows::UI::Xaml::Markup::IXamlMetadataProvider const& parentProvider) : App::App(Windows::UI::Xaml::Markup::IXamlMetadataProvider const& parentProvider) :
base_type(parentProvider), base_type(parentProvider),
_settings{ }, _settings{},
_tabs{ }, _tabs{},
_loadedInitialSettings{ false }, _loadedInitialSettings{ false },
_settingsLoadedResult{ S_OK }, _settingsLoadedResult{ S_OK },
_dialogLock{} _dialogLock{}
@ -138,7 +137,7 @@ namespace winrt::TerminalApp::implementation
_newTabButton.HorizontalAlignment(HorizontalAlignment::Left); _newTabButton.HorizontalAlignment(HorizontalAlignment::Left);
// When the new tab button is clicked, open the default profile // When the new tab button is clicked, open the default profile
_newTabButton.Click([this](auto&&, auto&&){ _newTabButton.Click([this](auto&&, auto&&) {
this->_OpenNewTab(std::nullopt); this->_OpenNewTab(std::nullopt);
}); });
@ -263,7 +262,6 @@ namespace winrt::TerminalApp::implementation
return TermControl::GetProposedDimensions(settings, dpi); return TermControl::GetProposedDimensions(settings, dpi);
} }
bool App::GetShowTabsInTitlebar() bool App::GetShowTabsInTitlebar()
{ {
if (!_loadedInitialSettings) if (!_loadedInitialSettings)
@ -322,7 +320,7 @@ namespace winrt::TerminalApp::implementation
profileMenuItem.FontWeight(FontWeights::Bold()); profileMenuItem.FontWeight(FontWeights::Bold());
} }
profileMenuItem.Click([this, profileIndex](auto&&, auto&&){ profileMenuItem.Click([this, profileIndex](auto&&, auto&&) {
this->_OpenNewTab({ profileIndex }); this->_OpenNewTab({ profileIndex });
}); });
newTabFlyout.Items().Append(profileMenuItem); newTabFlyout.Items().Append(profileMenuItem);
@ -391,7 +389,7 @@ namespace winrt::TerminalApp::implementation
// Return Value: // Return Value:
// - <none> // - <none>
void App::_SettingsButtonOnClick(const IInspectable&, void App::_SettingsButtonOnClick(const IInspectable&,
const RoutedEventArgs&) const RoutedEventArgs&)
{ {
LaunchSettings(); LaunchSettings();
} }
@ -440,8 +438,7 @@ namespace winrt::TerminalApp::implementation
// `CascadiaSettings::LoadAll` for details. // `CascadiaSettings::LoadAll` for details.
// Return Value: // Return Value:
// - S_OK if we successfully parsed the settings, otherwise an appropriate HRESULT. // - S_OK if we successfully parsed the settings, otherwise an appropriate HRESULT.
[[nodiscard]] [[nodiscard]] HRESULT App::_TryLoadSettings(const bool saveOnLoad) noexcept
HRESULT App::_TryLoadSettings(const bool saveOnLoad) noexcept
{ {
HRESULT hr = E_FAIL; HRESULT hr = E_FAIL;
@ -514,32 +511,33 @@ namespace winrt::TerminalApp::implementation
std::filesystem::path fileParser = localPathCopy.c_str(); std::filesystem::path fileParser = localPathCopy.c_str();
const auto folder = fileParser.parent_path(); const auto folder = fileParser.parent_path();
_reader.create(folder.c_str(), false, wil::FolderChangeEvents::All, _reader.create(folder.c_str(),
[this](wil::FolderChangeEvent event, PCWSTR fileModified) false,
{ wil::FolderChangeEvents::All,
// We want file modifications, AND when files are renamed to be [this](wil::FolderChangeEvent event, PCWSTR fileModified) {
// profiles.json. This second case will oftentimes happen with text // We want file modifications, AND when files are renamed to be
// editors, who will write a temp file, then rename it to be the // profiles.json. This second case will oftentimes happen with text
// actual file you wrote. So listen for that too. // editors, who will write a temp file, then rename it to be the
if (!(event == wil::FolderChangeEvent::Modified || // actual file you wrote. So listen for that too.
event == wil::FolderChangeEvent::RenameNewName)) if (!(event == wil::FolderChangeEvent::Modified ||
{ event == wil::FolderChangeEvent::RenameNewName))
return; {
} return;
}
const auto localPathCopy = CascadiaSettings::GetSettingsPath(); const auto localPathCopy = CascadiaSettings::GetSettingsPath();
std::filesystem::path settingsParser = localPathCopy.c_str(); std::filesystem::path settingsParser = localPathCopy.c_str();
std::filesystem::path modifiedParser = fileModified; std::filesystem::path modifiedParser = fileModified;
// Getting basename (filename.ext) // Getting basename (filename.ext)
const auto settingsBasename = settingsParser.filename(); const auto settingsBasename = settingsParser.filename();
const auto modifiedBasename = modifiedParser.filename(); const auto modifiedBasename = modifiedParser.filename();
if (settingsBasename == modifiedBasename) if (settingsBasename == modifiedBasename)
{ {
this->_ReloadSettings(); this->_ReloadSettings();
} }
}); });
} }
// Method Description: // Method Description:
@ -574,12 +572,12 @@ namespace winrt::TerminalApp::implementation
// Refresh UI elements // Refresh UI elements
auto profiles = _settings->GetProfiles(); auto profiles = _settings->GetProfiles();
for (auto &profile : profiles) for (auto& profile : profiles)
{ {
const GUID profileGuid = profile.GetGuid(); const GUID profileGuid = profile.GetGuid();
TerminalSettings settings = _settings->MakeSettings(profileGuid); TerminalSettings settings = _settings->MakeSettings(profileGuid);
for (auto &tab : _tabs) for (auto& tab : _tabs)
{ {
// Attempt to reload the settings of any panes with this profile // Attempt to reload the settings of any panes with this profile
tab->UpdateSettings(settings, profileGuid); tab->UpdateSettings(settings, profileGuid);
@ -600,7 +598,6 @@ namespace winrt::TerminalApp::implementation
// profile, which might have changed // profile, which might have changed
_CreateNewTabFlyout(); _CreateNewTabFlyout();
}); });
} }
// Method Description: // Method Description:
@ -673,7 +670,7 @@ namespace winrt::TerminalApp::implementation
// GH#1117: This is a workaround because _tabView.SelectedIndex(tabIndex) // GH#1117: This is a workaround because _tabView.SelectedIndex(tabIndex)
// sometimes set focus to an incorrect tab after removing some tabs // sometimes set focus to an incorrect tab after removing some tabs
auto tab = _tabs.at(tabIndex); auto tab = _tabs.at(tabIndex);
_tabView.Dispatcher().RunAsync(CoreDispatcherPriority::Normal, [tab, this](){ _tabView.Dispatcher().RunAsync(CoreDispatcherPriority::Normal, [tab, this]() {
auto tabViewItem = tab->GetTabViewItem(); auto tabViewItem = tab->GetTabViewItem();
_tabView.SelectedItem(tabViewItem); _tabView.SelectedItem(tabViewItem);
}); });
@ -789,7 +786,7 @@ namespace winrt::TerminalApp::implementation
// Don't capture a strong ref to the tab. If the tab is removed as this // Don't capture a strong ref to the tab. If the tab is removed as this
// is called, we don't really care anymore about handling the event. // is called, we don't really care anymore about handling the event.
std::weak_ptr<Tab> weakTabPtr = hostingTab; std::weak_ptr<Tab> weakTabPtr = hostingTab;
term.TitleChanged([this, weakTabPtr](auto newTitle){ term.TitleChanged([this, weakTabPtr](auto newTitle) {
auto tab = weakTabPtr.lock(); auto tab = weakTabPtr.lock();
if (!tab) if (!tab)
{ {
@ -801,8 +798,7 @@ namespace winrt::TerminalApp::implementation
_UpdateTitle(tab); _UpdateTitle(tab);
}); });
term.GetControl().GotFocus([this, weakTabPtr](auto&&, auto&&) term.GetControl().GotFocus([this, weakTabPtr](auto&&, auto&&) {
{
auto tab = weakTabPtr.lock(); auto tab = weakTabPtr.lock();
if (!tab) if (!tab)
{ {
@ -850,7 +846,7 @@ namespace winrt::TerminalApp::implementation
tabViewItem.PointerPressed({ this, &App::_OnTabClick }); tabViewItem.PointerPressed({ this, &App::_OnTabClick });
// When the tab is closed, remove it from our list of tabs. // When the tab is closed, remove it from our list of tabs.
newTab->Closed([tabViewItem, this](){ newTab->Closed([tabViewItem, this]() {
_tabView.Dispatcher().RunAsync(CoreDispatcherPriority::Normal, [tabViewItem, this]() { _tabView.Dispatcher().RunAsync(CoreDispatcherPriority::Normal, [tabViewItem, this]() {
_RemoveTabViewItem(tabViewItem); _RemoveTabViewItem(tabViewItem);
}); });
@ -945,8 +941,7 @@ namespace winrt::TerminalApp::implementation
// we clamp the values to the range [0, tabCount) while still supporting moving // we clamp the values to the range [0, tabCount) while still supporting moving
// leftward from 0 to tabCount - 1. // leftward from 0 to tabCount - 1.
_SetFocusedTabIndex( _SetFocusedTabIndex(
static_cast<int>((tabCount + focusedTabIndex + (bMoveRight ? 1 : -1)) % tabCount) static_cast<int>((tabCount + focusedTabIndex + (bMoveRight ? 1 : -1)) % tabCount));
);
} }
// Method Description: // Method Description:

View file

@ -18,9 +18,8 @@
namespace winrt::TerminalApp::implementation namespace winrt::TerminalApp::implementation
{ {
// We dont use AppT as it does not provide access to protected constructors // We dont use AppT as it does not provide access to protected constructors
template <typename D, typename... I> template<typename D, typename... I>
using AppT_Override = App_base<D, I...>; using AppT_Override = App_base<D, I...>;
struct App : AppT_Override<App> struct App : AppT_Override<App>
@ -75,8 +74,7 @@ namespace winrt::TerminalApp::implementation
fire_and_forget _ShowOkDialog(const winrt::hstring& titleKey, const winrt::hstring& contentKey); fire_and_forget _ShowOkDialog(const winrt::hstring& titleKey, const winrt::hstring& contentKey);
[[nodiscard]] [[nodiscard]] HRESULT _TryLoadSettings(const bool saveOnLoad) noexcept;
HRESULT _TryLoadSettings(const bool saveOnLoad) noexcept;
void _LoadSettings(); void _LoadSettings();
void _OpenSettings(); void _OpenSettings();
@ -92,7 +90,6 @@ namespace winrt::TerminalApp::implementation
void _UpdateTabIcon(std::shared_ptr<Tab> tab); void _UpdateTabIcon(std::shared_ptr<Tab> tab);
void _UpdateTitle(std::shared_ptr<Tab> tab); void _UpdateTitle(std::shared_ptr<Tab> tab);
void _RegisterTerminalEvents(Microsoft::Terminal::TerminalControl::TermControl term, std::shared_ptr<Tab> hostingTab); void _RegisterTerminalEvents(Microsoft::Terminal::TerminalControl::TermControl term, std::shared_ptr<Tab> hostingTab);
void _CreateNewTabFromSettings(GUID profileGuid, winrt::Microsoft::Terminal::Settings::TerminalSettings settings); void _CreateNewTabFromSettings(GUID profileGuid, winrt::Microsoft::Terminal::Settings::TerminalSettings settings);

View file

@ -23,7 +23,10 @@ namespace winrt::TerminalApp::implementation
{ {
for (auto& kv : _keyShortcuts) for (auto& kv : _keyShortcuts)
{ {
if (kv.second == action) return kv.first; if (kv.second == action)
{
return kv.first;
}
} }
return { nullptr }; return { nullptr };
} }
@ -43,114 +46,114 @@ namespace winrt::TerminalApp::implementation
{ {
switch (action) switch (action)
{ {
case ShortcutAction::CopyText: case ShortcutAction::CopyText:
_CopyTextHandlers(); _CopyTextHandlers();
return true; return true;
case ShortcutAction::PasteText: case ShortcutAction::PasteText:
_PasteTextHandlers(); _PasteTextHandlers();
return true; return true;
case ShortcutAction::NewTab: case ShortcutAction::NewTab:
_NewTabHandlers(); _NewTabHandlers();
return true; return true;
case ShortcutAction::OpenSettings: case ShortcutAction::OpenSettings:
_OpenSettingsHandlers(); _OpenSettingsHandlers();
return true; return true;
case ShortcutAction::NewTabProfile0: case ShortcutAction::NewTabProfile0:
_NewTabWithProfileHandlers(0); _NewTabWithProfileHandlers(0);
return true; return true;
case ShortcutAction::NewTabProfile1: case ShortcutAction::NewTabProfile1:
_NewTabWithProfileHandlers(1); _NewTabWithProfileHandlers(1);
return true; return true;
case ShortcutAction::NewTabProfile2: case ShortcutAction::NewTabProfile2:
_NewTabWithProfileHandlers(2); _NewTabWithProfileHandlers(2);
return true; return true;
case ShortcutAction::NewTabProfile3: case ShortcutAction::NewTabProfile3:
_NewTabWithProfileHandlers(3); _NewTabWithProfileHandlers(3);
return true; return true;
case ShortcutAction::NewTabProfile4: case ShortcutAction::NewTabProfile4:
_NewTabWithProfileHandlers(4); _NewTabWithProfileHandlers(4);
return true; return true;
case ShortcutAction::NewTabProfile5: case ShortcutAction::NewTabProfile5:
_NewTabWithProfileHandlers(5); _NewTabWithProfileHandlers(5);
return true; return true;
case ShortcutAction::NewTabProfile6: case ShortcutAction::NewTabProfile6:
_NewTabWithProfileHandlers(6); _NewTabWithProfileHandlers(6);
return true; return true;
case ShortcutAction::NewTabProfile7: case ShortcutAction::NewTabProfile7:
_NewTabWithProfileHandlers(7); _NewTabWithProfileHandlers(7);
return true; return true;
case ShortcutAction::NewTabProfile8: case ShortcutAction::NewTabProfile8:
_NewTabWithProfileHandlers(8); _NewTabWithProfileHandlers(8);
return true; return true;
case ShortcutAction::NewWindow: case ShortcutAction::NewWindow:
_NewWindowHandlers(); _NewWindowHandlers();
return true; return true;
case ShortcutAction::CloseWindow: case ShortcutAction::CloseWindow:
_CloseWindowHandlers(); _CloseWindowHandlers();
return true; return true;
case ShortcutAction::CloseTab: case ShortcutAction::CloseTab:
_CloseTabHandlers(); _CloseTabHandlers();
return true; return true;
case ShortcutAction::ScrollUp: case ShortcutAction::ScrollUp:
_ScrollUpHandlers(); _ScrollUpHandlers();
return true; return true;
case ShortcutAction::ScrollDown: case ShortcutAction::ScrollDown:
_ScrollDownHandlers(); _ScrollDownHandlers();
return true; return true;
case ShortcutAction::ScrollUpPage: case ShortcutAction::ScrollUpPage:
_ScrollUpPageHandlers(); _ScrollUpPageHandlers();
return true; return true;
case ShortcutAction::ScrollDownPage: case ShortcutAction::ScrollDownPage:
_ScrollDownPageHandlers(); _ScrollDownPageHandlers();
return true; return true;
case ShortcutAction::NextTab: case ShortcutAction::NextTab:
_NextTabHandlers(); _NextTabHandlers();
return true; return true;
case ShortcutAction::PrevTab: case ShortcutAction::PrevTab:
_PrevTabHandlers(); _PrevTabHandlers();
return true; return true;
case ShortcutAction::SplitVertical: case ShortcutAction::SplitVertical:
_SplitVerticalHandlers(); _SplitVerticalHandlers();
return true; return true;
case ShortcutAction::SplitHorizontal: case ShortcutAction::SplitHorizontal:
_SplitHorizontalHandlers(); _SplitHorizontalHandlers();
return true; return true;
case ShortcutAction::SwitchToTab0: case ShortcutAction::SwitchToTab0:
_SwitchToTabHandlers(0); _SwitchToTabHandlers(0);
return true; return true;
case ShortcutAction::SwitchToTab1: case ShortcutAction::SwitchToTab1:
_SwitchToTabHandlers(1); _SwitchToTabHandlers(1);
return true; return true;
case ShortcutAction::SwitchToTab2: case ShortcutAction::SwitchToTab2:
_SwitchToTabHandlers(2); _SwitchToTabHandlers(2);
return true; return true;
case ShortcutAction::SwitchToTab3: case ShortcutAction::SwitchToTab3:
_SwitchToTabHandlers(3); _SwitchToTabHandlers(3);
return true; return true;
case ShortcutAction::SwitchToTab4: case ShortcutAction::SwitchToTab4:
_SwitchToTabHandlers(4); _SwitchToTabHandlers(4);
return true; return true;
case ShortcutAction::SwitchToTab5: case ShortcutAction::SwitchToTab5:
_SwitchToTabHandlers(5); _SwitchToTabHandlers(5);
return true; return true;
case ShortcutAction::SwitchToTab6: case ShortcutAction::SwitchToTab6:
_SwitchToTabHandlers(6); _SwitchToTabHandlers(6);
return true; return true;
case ShortcutAction::SwitchToTab7: case ShortcutAction::SwitchToTab7:
_SwitchToTabHandlers(7); _SwitchToTabHandlers(7);
return true; return true;
case ShortcutAction::SwitchToTab8: case ShortcutAction::SwitchToTab8:
_SwitchToTabHandlers(8); _SwitchToTabHandlers(8);
return true; return true;
default: default:
return false; return false;
} }
return false; return false;
} }
@ -208,6 +211,7 @@ namespace winrt::TerminalApp::implementation
} }
// -------------------------------- Events --------------------------------- // -------------------------------- Events ---------------------------------
// clang-format off
DEFINE_EVENT(AppKeyBindings, CopyText, _CopyTextHandlers, TerminalApp::CopyTextEventArgs); DEFINE_EVENT(AppKeyBindings, CopyText, _CopyTextHandlers, TerminalApp::CopyTextEventArgs);
DEFINE_EVENT(AppKeyBindings, PasteText, _PasteTextHandlers, TerminalApp::PasteTextEventArgs); DEFINE_EVENT(AppKeyBindings, PasteText, _PasteTextHandlers, TerminalApp::PasteTextEventArgs);
DEFINE_EVENT(AppKeyBindings, NewTab, _NewTabHandlers, TerminalApp::NewTabEventArgs); DEFINE_EVENT(AppKeyBindings, NewTab, _NewTabHandlers, TerminalApp::NewTabEventArgs);
@ -227,4 +231,5 @@ namespace winrt::TerminalApp::implementation
DEFINE_EVENT(AppKeyBindings, ScrollUpPage, _ScrollUpPageHandlers, TerminalApp::ScrollUpPageEventArgs); DEFINE_EVENT(AppKeyBindings, ScrollUpPage, _ScrollUpPageHandlers, TerminalApp::ScrollUpPageEventArgs);
DEFINE_EVENT(AppKeyBindings, ScrollDownPage, _ScrollDownPageHandlers, TerminalApp::ScrollDownPageEventArgs); DEFINE_EVENT(AppKeyBindings, ScrollDownPage, _ScrollDownPageHandlers, TerminalApp::ScrollDownPageEventArgs);
DEFINE_EVENT(AppKeyBindings, OpenSettings, _OpenSettingsHandlers, TerminalApp::OpenSettingsEventArgs); DEFINE_EVENT(AppKeyBindings, OpenSettings, _OpenSettingsHandlers, TerminalApp::OpenSettingsEventArgs);
// clang-format on
} }

View file

@ -39,6 +39,7 @@ namespace winrt::TerminalApp::implementation
static Windows::System::VirtualKeyModifiers ConvertVKModifiers(winrt::Microsoft::Terminal::Settings::KeyModifiers modifiers); static Windows::System::VirtualKeyModifiers ConvertVKModifiers(winrt::Microsoft::Terminal::Settings::KeyModifiers modifiers);
static winrt::hstring FormatOverrideShortcutText(winrt::Microsoft::Terminal::Settings::KeyModifiers modifiers); static winrt::hstring FormatOverrideShortcutText(winrt::Microsoft::Terminal::Settings::KeyModifiers modifiers);
// clang-format off
DECLARE_EVENT(CopyText, _CopyTextHandlers, TerminalApp::CopyTextEventArgs); DECLARE_EVENT(CopyText, _CopyTextHandlers, TerminalApp::CopyTextEventArgs);
DECLARE_EVENT(PasteText, _PasteTextHandlers, TerminalApp::PasteTextEventArgs); DECLARE_EVENT(PasteText, _PasteTextHandlers, TerminalApp::PasteTextEventArgs);
DECLARE_EVENT(NewTab, _NewTabHandlers, TerminalApp::NewTabEventArgs); DECLARE_EVENT(NewTab, _NewTabHandlers, TerminalApp::NewTabEventArgs);
@ -58,11 +59,11 @@ namespace winrt::TerminalApp::implementation
DECLARE_EVENT(ScrollUpPage, _ScrollUpPageHandlers, TerminalApp::ScrollUpPageEventArgs); DECLARE_EVENT(ScrollUpPage, _ScrollUpPageHandlers, TerminalApp::ScrollUpPageEventArgs);
DECLARE_EVENT(ScrollDownPage, _ScrollDownPageHandlers, TerminalApp::ScrollDownPageEventArgs); DECLARE_EVENT(ScrollDownPage, _ScrollDownPageHandlers, TerminalApp::ScrollDownPageEventArgs);
DECLARE_EVENT(OpenSettings, _OpenSettingsHandlers, TerminalApp::OpenSettingsEventArgs); DECLARE_EVENT(OpenSettings, _OpenSettingsHandlers, TerminalApp::OpenSettingsEventArgs);
// clang-format on
private: private:
std::unordered_map<winrt::Microsoft::Terminal::Settings::KeyChord, TerminalApp::ShortcutAction, KeyChordHash, KeyChordEquality> _keyShortcuts; std::unordered_map<winrt::Microsoft::Terminal::Settings::KeyChord, TerminalApp::ShortcutAction, KeyChordHash, KeyChordEquality> _keyShortcuts;
bool _DoAction(ShortcutAction action); bool _DoAction(ShortcutAction action);
}; };
} }

View file

@ -58,7 +58,7 @@ static constexpr std::string_view SplitVerticalKey{ "splitVertical" };
// the actual strings being pointed to. However, since both these strings and // the actual strings being pointed to. However, since both these strings and
// the map are all const for the lifetime of the app, we have nothing to worry // the map are all const for the lifetime of the app, we have nothing to worry
// about here. // about here.
static const std::map<std::string_view, ShortcutAction, std::less<>> commandNames { static const std::map<std::string_view, ShortcutAction, std::less<>> commandNames{
{ CopyTextKey, ShortcutAction::CopyText }, { CopyTextKey, ShortcutAction::CopyText },
{ PasteTextKey, ShortcutAction::PasteText }, { PasteTextKey, ShortcutAction::PasteText },
{ NewTabKey, ShortcutAction::NewTab }, { NewTabKey, ShortcutAction::NewTab },
@ -211,5 +211,4 @@ winrt::TerminalApp::AppKeyBindings AppKeyBindingsSerialization::FromJson(const J
} }
} }
return newBindings; return newBindings;
} }

View file

@ -18,8 +18,7 @@ using namespace Microsoft::Console;
// {2bde4a90-d05f-401c-9492-e40884ead1d8} // {2bde4a90-d05f-401c-9492-e40884ead1d8}
// uuidv5 properties: name format is UTF-16LE bytes // uuidv5 properties: name format is UTF-16LE bytes
static constexpr GUID TERMINAL_PROFILE_NAMESPACE_GUID = static constexpr GUID TERMINAL_PROFILE_NAMESPACE_GUID = { 0x2bde4a90, 0xd05f, 0x401c, { 0x94, 0x92, 0xe4, 0x8, 0x84, 0xea, 0xd1, 0xd8 } };
{ 0x2bde4a90, 0xd05f, 0x401c, { 0x94, 0x92, 0xe4, 0x8, 0x84, 0xea, 0xd1, 0xd8 } };
static constexpr std::wstring_view PACKAGED_PROFILE_ICON_PATH{ L"ms-appx:///ProfileIcons/" }; static constexpr std::wstring_view PACKAGED_PROFILE_ICON_PATH{ L"ms-appx:///ProfileIcons/" };
static constexpr std::wstring_view PACKAGED_PROFILE_ICON_EXTENSION{ L".png" }; static constexpr std::wstring_view PACKAGED_PROFILE_ICON_EXTENSION{ L".png" };
@ -29,19 +28,17 @@ CascadiaSettings::CascadiaSettings() :
_globals{}, _globals{},
_profiles{} _profiles{}
{ {
} }
CascadiaSettings::~CascadiaSettings() CascadiaSettings::~CascadiaSettings()
{ {
} }
ColorScheme _CreateCampbellScheme() ColorScheme _CreateCampbellScheme()
{ {
ColorScheme campbellScheme { L"Campbell", ColorScheme campbellScheme{ L"Campbell",
RGB(242, 242, 242), RGB(242, 242, 242),
RGB(12, 12, 12) }; RGB(12, 12, 12) };
auto& campbellTable = campbellScheme.GetTable(); auto& campbellTable = campbellScheme.GetTable();
auto campbellSpan = gsl::span<COLORREF>(&campbellTable[0], gsl::narrow<ptrdiff_t>(COLOR_TABLE_SIZE)); auto campbellSpan = gsl::span<COLORREF>(&campbellTable[0], gsl::narrow<ptrdiff_t>(COLOR_TABLE_SIZE));
Utils::InitializeCampbellColorTable(campbellSpan); Utils::InitializeCampbellColorTable(campbellSpan);
@ -50,6 +47,8 @@ ColorScheme _CreateCampbellScheme()
return campbellScheme; return campbellScheme;
} }
// clang-format off
ColorScheme _CreateOneHalfDarkScheme() ColorScheme _CreateOneHalfDarkScheme()
{ {
// First 8 dark colors per: https://github.com/sonph/onehalf/blob/master/putty/onehalf-dark.reg // First 8 dark colors per: https://github.com/sonph/onehalf/blob/master/putty/onehalf-dark.reg
@ -167,6 +166,8 @@ ColorScheme _CreateSolarizedLightScheme()
return solarizedLightScheme; return solarizedLightScheme;
} }
// clang-format on
// Method Description: // Method Description:
// - Create the set of schemes to use as the default schemes. Currently creates // - Create the set of schemes to use as the default schemes. Currently creates
// five default color schemes - Campbell (the new cmd color scheme), // five default color schemes - Campbell (the new cmd color scheme),
@ -250,23 +251,23 @@ void CascadiaSettings::_CreateDefaultKeybindings()
// TODO:MSFT:20700157 read our settings from some source, and configure // TODO:MSFT:20700157 read our settings from some source, and configure
// keychord,action pairings from that file // keychord,action pairings from that file
keyBindings.SetKeyBinding(ShortcutAction::NewTab, keyBindings.SetKeyBinding(ShortcutAction::NewTab,
KeyChord{ KeyModifiers::Ctrl, KeyChord{ KeyModifiers::Ctrl,
static_cast<int>('T') }); static_cast<int>('T') });
keyBindings.SetKeyBinding(ShortcutAction::CloseTab, keyBindings.SetKeyBinding(ShortcutAction::CloseTab,
KeyChord{ KeyModifiers::Ctrl, KeyChord{ KeyModifiers::Ctrl,
static_cast<int>('W') }); static_cast<int>('W') });
keyBindings.SetKeyBinding(ShortcutAction::OpenSettings, keyBindings.SetKeyBinding(ShortcutAction::OpenSettings,
KeyChord{ KeyModifiers::Ctrl, KeyChord{ KeyModifiers::Ctrl,
VK_OEM_COMMA }); VK_OEM_COMMA });
keyBindings.SetKeyBinding(ShortcutAction::NextTab, keyBindings.SetKeyBinding(ShortcutAction::NextTab,
KeyChord{ KeyModifiers::Ctrl, KeyChord{ KeyModifiers::Ctrl,
VK_TAB }); VK_TAB });
keyBindings.SetKeyBinding(ShortcutAction::PrevTab, keyBindings.SetKeyBinding(ShortcutAction::PrevTab,
KeyChord{ KeyModifiers::Ctrl | KeyModifiers::Shift, KeyChord{ KeyModifiers::Ctrl | KeyModifiers::Shift,
VK_TAB }); VK_TAB });
// Yes these are offset by one. // Yes these are offset by one.
// Ideally, you'd want C-S-1 to open the _first_ profile, which is index 0 // Ideally, you'd want C-S-1 to open the _first_ profile, which is index 0
@ -498,8 +499,16 @@ void CascadiaSettings::_AppendWslProfiles(std::vector<TerminalApp::Profile>& pro
std::wstring command(systemPath.get()); std::wstring command(systemPath.get());
command += L"\\wsl.exe --list"; command += L"\\wsl.exe --list";
THROW_IF_WIN32_BOOL_FALSE(CreateProcessW(nullptr, const_cast<LPWSTR>(command.c_str()), nullptr, nullptr, THROW_IF_WIN32_BOOL_FALSE(CreateProcessW(nullptr,
TRUE, CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi)); const_cast<LPWSTR>(command.c_str()),
nullptr,
nullptr,
TRUE,
CREATE_NO_WINDOW,
nullptr,
nullptr,
&si,
&pi));
switch (WaitForSingleObject(pi.hProcess, INFINITE)) switch (WaitForSingleObject(pi.hProcess, INFINITE))
{ {
case WAIT_OBJECT_0: case WAIT_OBJECT_0:
@ -524,9 +533,10 @@ void CascadiaSettings::_AppendWslProfiles(std::vector<TerminalApp::Profile>& pro
DWORD bytesAvailable; DWORD bytesAvailable;
THROW_IF_WIN32_BOOL_FALSE(PeekNamedPipe(readPipe.get(), nullptr, NULL, nullptr, &bytesAvailable, nullptr)); THROW_IF_WIN32_BOOL_FALSE(PeekNamedPipe(readPipe.get(), nullptr, NULL, nullptr, &bytesAvailable, nullptr));
std::wfstream pipe{ _wfdopen(_open_osfhandle((intptr_t)readPipe.get(), _O_WTEXT | _O_RDONLY), L"r") }; std::wfstream pipe{ _wfdopen(_open_osfhandle((intptr_t)readPipe.get(), _O_WTEXT | _O_RDONLY), L"r") };
//don't worry about the handle returned from wfdOpen, readPipe handle is already managed by wil and closing the file handle will cause an error. // don't worry about the handle returned from wfdOpen, readPipe handle is already managed by wil
// and closing the file handle will cause an error.
std::wstring wline; std::wstring wline;
std::getline(pipe, wline); //remove the header from the output. std::getline(pipe, wline); // remove the header from the output.
while (pipe.tellp() < bytesAvailable) while (pipe.tellp() < bytesAvailable)
{ {
std::getline(pipe, wline); std::getline(pipe, wline);
@ -571,7 +581,7 @@ std::wstring CascadiaSettings::ExpandEnvironmentVariableString(std::wstring_view
} while (requiredSize != result.size()); } while (requiredSize != result.size());
// Trim the terminating null character // Trim the terminating null character
result.resize(requiredSize-1); result.resize(requiredSize - 1);
return result; return result;
} }

View file

@ -20,7 +20,6 @@ Author(s):
#include "GlobalAppSettings.h" #include "GlobalAppSettings.h"
#include "Profile.h" #include "Profile.h"
namespace TerminalApp namespace TerminalApp
{ {
class CascadiaSettings; class CascadiaSettings;
@ -28,7 +27,6 @@ namespace TerminalApp
class TerminalApp::CascadiaSettings final class TerminalApp::CascadiaSettings final
{ {
public: public:
CascadiaSettings(); CascadiaSettings();
~CascadiaSettings(); ~CascadiaSettings();
@ -52,11 +50,11 @@ public:
const Profile* FindProfile(GUID profileGuid) const noexcept; const Profile* FindProfile(GUID profileGuid) const noexcept;
void CreateDefaults(); void CreateDefaults();
private: private:
GlobalAppSettings _globals; GlobalAppSettings _globals;
std::vector<Profile> _profiles; std::vector<Profile> _profiles;
void _CreateDefaultKeybindings(); void _CreateDefaultKeybindings();
void _CreateDefaultSchemes(); void _CreateDefaultSchemes();
void _CreateDefaultProfiles(); void _CreateDefaultProfiles();

View file

@ -17,7 +17,7 @@ using namespace winrt::Windows::Storage;
using namespace winrt::Windows::Storage::Streams; using namespace winrt::Windows::Storage::Streams;
using namespace ::Microsoft::Console; using namespace ::Microsoft::Console;
static constexpr std::wstring_view FILENAME { L"profiles.json" }; static constexpr std::wstring_view FILENAME{ L"profiles.json" };
static constexpr std::wstring_view SETTINGS_FOLDER_NAME{ L"\\Microsoft\\Windows Terminal\\" }; static constexpr std::wstring_view SETTINGS_FOLDER_NAME{ L"\\Microsoft\\Windows Terminal\\" };
static constexpr std::string_view ProfilesKey{ "profiles" }; static constexpr std::string_view ProfilesKey{ "profiles" };
@ -40,7 +40,8 @@ std::unique_ptr<CascadiaSettings> CascadiaSettings::LoadAll(const bool saveOnLoa
{ {
std::unique_ptr<CascadiaSettings> resultPtr; std::unique_ptr<CascadiaSettings> resultPtr;
std::optional<std::string> fileData = _IsPackaged() ? std::optional<std::string> fileData = _IsPackaged() ?
_LoadAsPackagedApp() : _LoadAsUnpackagedApp(); _LoadAsPackagedApp() :
_LoadAsUnpackagedApp();
const bool foundFile = fileData.has_value(); const bool foundFile = fileData.has_value();
if (foundFile) if (foundFile)
@ -340,7 +341,6 @@ std::optional<std::string> CascadiaSettings::_LoadAsPackagedApp()
return { resultString }; return { resultString };
} }
// Method Description: // Method Description:
// - Reads the content in UTF-8 enconding of our settings file using the Win32 APIs // - Reads the content in UTF-8 enconding of our settings file using the Win32 APIs
// Arguments: // Arguments:

View file

@ -17,8 +17,7 @@ static constexpr std::string_view NameKey{ "name" };
static constexpr std::string_view TableKey{ "colors" }; static constexpr std::string_view TableKey{ "colors" };
static constexpr std::string_view ForegroundKey{ "foreground" }; static constexpr std::string_view ForegroundKey{ "foreground" };
static constexpr std::string_view BackgroundKey{ "background" }; static constexpr std::string_view BackgroundKey{ "background" };
static constexpr std::array<std::string_view, 16> TableColors = static constexpr std::array<std::string_view, 16> TableColors = {
{
"black", "black",
"red", "red",
"green", "green",
@ -39,25 +38,22 @@ static constexpr std::array<std::string_view, 16> TableColors =
ColorScheme::ColorScheme() : ColorScheme::ColorScheme() :
_schemeName{ L"" }, _schemeName{ L"" },
_table{ }, _table{},
_defaultForeground{ RGB(242, 242, 242) }, _defaultForeground{ RGB(242, 242, 242) },
_defaultBackground{ RGB(12, 12, 12) } _defaultBackground{ RGB(12, 12, 12) }
{ {
} }
ColorScheme::ColorScheme(std::wstring name, COLORREF defaultFg, COLORREF defaultBg) : ColorScheme::ColorScheme(std::wstring name, COLORREF defaultFg, COLORREF defaultBg) :
_schemeName{ name }, _schemeName{ name },
_table{ }, _table{},
_defaultForeground{ defaultFg }, _defaultForeground{ defaultFg },
_defaultBackground{ defaultBg } _defaultBackground{ defaultBg }
{ {
} }
ColorScheme::~ColorScheme() ColorScheme::~ColorScheme()
{ {
} }
// Method Description: // Method Description:
@ -157,7 +153,6 @@ ColorScheme ColorScheme::FromJson(const Json::Value& json)
return result; return result;
} }
std::wstring_view ColorScheme::GetName() const noexcept std::wstring_view ColorScheme::GetName() const noexcept
{ {
return { _schemeName }; return { _schemeName };

View file

@ -27,7 +27,6 @@ namespace TerminalApp
class TerminalApp::ColorScheme class TerminalApp::ColorScheme
{ {
public: public:
ColorScheme(); ColorScheme();
ColorScheme(std::wstring name, COLORREF defaultFg, COLORREF defaultBg); ColorScheme(std::wstring name, COLORREF defaultFg, COLORREF defaultBg);

View file

@ -39,12 +39,10 @@ GlobalAppSettings::GlobalAppSettings() :
_showTabsInTitlebar{ true }, _showTabsInTitlebar{ true },
_requestedTheme{ ElementTheme::Default } _requestedTheme{ ElementTheme::Default }
{ {
} }
GlobalAppSettings::~GlobalAppSettings() GlobalAppSettings::~GlobalAppSettings()
{ {
} }
const std::vector<ColorScheme>& GlobalAppSettings::GetColorSchemes() const noexcept const std::vector<ColorScheme>& GlobalAppSettings::GetColorSchemes() const noexcept
@ -52,7 +50,6 @@ const std::vector<ColorScheme>& GlobalAppSettings::GetColorSchemes() const noexc
return _colorSchemes; return _colorSchemes;
} }
std::vector<ColorScheme>& GlobalAppSettings::GetColorSchemes() noexcept std::vector<ColorScheme>& GlobalAppSettings::GetColorSchemes() noexcept
{ {
return _colorSchemes; return _colorSchemes;
@ -207,7 +204,6 @@ GlobalAppSettings GlobalAppSettings::FromJson(const Json::Value& json)
return result; return result;
} }
// Method Description: // Method Description:
// - Helper function for converting a user-specified cursor style corresponding // - Helper function for converting a user-specified cursor style corresponding
// CursorStyle enum value // CursorStyle enum value
@ -240,11 +236,11 @@ std::wstring_view GlobalAppSettings::_SerializeTheme(const ElementTheme theme) n
{ {
switch (theme) switch (theme)
{ {
case ElementTheme::Light: case ElementTheme::Light:
return LightThemeValue; return LightThemeValue;
case ElementTheme::Dark: case ElementTheme::Dark:
return DarkThemeValue; return DarkThemeValue;
default: default:
return SystemThemeValue; return SystemThemeValue;
} }
} }

View file

@ -24,7 +24,6 @@ namespace TerminalApp
class TerminalApp::GlobalAppSettings final class TerminalApp::GlobalAppSettings final
{ {
public: public:
GlobalAppSettings(); GlobalAppSettings();
~GlobalAppSettings(); ~GlobalAppSettings();
@ -73,5 +72,4 @@ private:
static winrt::Windows::UI::Xaml::ElementTheme _ParseTheme(const std::wstring& themeString) noexcept; static winrt::Windows::UI::Xaml::ElementTheme _ParseTheme(const std::wstring& themeString) noexcept;
static std::wstring_view _SerializeTheme(const winrt::Windows::UI::Xaml::ElementTheme theme) noexcept; static std::wstring_view _SerializeTheme(const winrt::Windows::UI::Xaml::ElementTheme theme) noexcept;
}; };

View file

@ -12,6 +12,7 @@ static constexpr std::wstring_view ALT_KEY{ L"alt" };
static constexpr int MAX_CHORD_PARTS = 4; static constexpr int MAX_CHORD_PARTS = 4;
// clang-format off
static const std::unordered_map<int32_t, std::wstring_view> vkeyNamePairs { static const std::unordered_map<int32_t, std::wstring_view> vkeyNamePairs {
{ VK_BACK , L"backspace"}, { VK_BACK , L"backspace"},
{ VK_TAB , L"tab"}, { VK_TAB , L"tab"},
@ -83,6 +84,7 @@ static const std::unordered_map<int32_t, std::wstring_view> vkeyNamePairs {
// #define VK_OEM_6 0xDD // ']}' for US // #define VK_OEM_6 0xDD // ']}' for US
// #define VK_OEM_7 0xDE // ''"' for US // #define VK_OEM_7 0xDE // ''"' for US
}; };
// clang-format on
// Function Description: // Function Description:
// - Deserializes the given string into a new KeyChord instance. If this // - Deserializes the given string into a new KeyChord instance. If this
@ -104,7 +106,7 @@ winrt::Microsoft::Terminal::Settings::KeyChord KeyChordSerialization::FromString
std::vector<std::wstring> parts; std::vector<std::wstring> parts;
std::wstringstream wss(wstr); std::wstringstream wss(wstr);
while(std::getline(wss, temp, L'+')) while (std::getline(wss, temp, L'+'))
{ {
parts.push_back(temp); parts.push_back(temp);

View file

@ -376,7 +376,6 @@ void Pane::_CloseChild(const bool closeFirst)
_root.Children().Append(_separatorRoot); _root.Children().Append(_separatorRoot);
_root.Children().Append(_secondChild->GetRootElement()); _root.Children().Append(_secondChild->GetRootElement());
// If the closed child was focused, transfer the focus to it's first sibling. // If the closed child was focused, transfer the focus to it's first sibling.
if (closedChild->_lastFocused) if (closedChild->_lastFocused)
{ {
@ -398,14 +397,14 @@ void Pane::_CloseChild(const bool closeFirst)
// - <none> // - <none>
void Pane::_SetupChildCloseHandlers() void Pane::_SetupChildCloseHandlers()
{ {
_firstClosedToken = _firstChild->Closed([this](){ _firstClosedToken = _firstChild->Closed([this]() {
_root.Dispatcher().RunAsync(CoreDispatcherPriority::Normal, [=](){ _root.Dispatcher().RunAsync(CoreDispatcherPriority::Normal, [=]() {
_CloseChild(true); _CloseChild(true);
}); });
}); });
_secondClosedToken = _secondChild->Closed([this](){ _secondClosedToken = _secondChild->Closed([this]() {
_root.Dispatcher().RunAsync(CoreDispatcherPriority::Normal, [=](){ _root.Dispatcher().RunAsync(CoreDispatcherPriority::Normal, [=]() {
_CloseChild(false); _CloseChild(false);
}); });
}); });
@ -468,7 +467,6 @@ void Pane::_ApplySplitDefinitions()
Controls::Grid::SetColumn(_firstChild->GetRootElement(), 0); Controls::Grid::SetColumn(_firstChild->GetRootElement(), 0);
Controls::Grid::SetColumn(_separatorRoot, 1); Controls::Grid::SetColumn(_separatorRoot, 1);
Controls::Grid::SetColumn(_secondChild->GetRootElement(), 2); Controls::Grid::SetColumn(_secondChild->GetRootElement(), 2);
} }
else if (_splitState == SplitState::Horizontal) else if (_splitState == SplitState::Horizontal)
{ {
@ -478,7 +476,6 @@ void Pane::_ApplySplitDefinitions()
} }
} }
// Method Description: // Method Description:
// - Vertically split the focused pane in our tree of panes, and place the given // - Vertically split the focused pane in our tree of panes, and place the given
// TermControl into the newly created pane. If we're the focused pane, then // TermControl into the newly created pane. If we're the focused pane, then

View file

@ -18,16 +18,13 @@
// Author: // Author:
// - Mike Griese (zadjii-msft) 16-May-2019 // - Mike Griese (zadjii-msft) 16-May-2019
#pragma once #pragma once
#include <winrt/Microsoft.Terminal.TerminalControl.h> #include <winrt/Microsoft.Terminal.TerminalControl.h>
#include "../../cascadia/inc/cppwinrt_utils.h" #include "../../cascadia/inc/cppwinrt_utils.h"
class Pane : public std::enable_shared_from_this<Pane> class Pane : public std::enable_shared_from_this<Pane>
{ {
public: public:
enum class SplitState : int enum class SplitState : int
{ {
None = 0, None = 0,

View file

@ -63,13 +63,13 @@ Profile::Profile() :
{ {
} }
Profile::Profile(const winrt::guid& guid): Profile::Profile(const winrt::guid& guid) :
_guid(guid), _guid(guid),
_name{ L"Default" }, _name{ L"Default" },
_schemeName{}, _schemeName{},
_defaultForeground{ }, _defaultForeground{},
_defaultBackground{ }, _defaultBackground{},
_colorTable{}, _colorTable{},
_historySize{ DEFAULT_HISTORY_SIZE }, _historySize{ DEFAULT_HISTORY_SIZE },
_snapOnInput{ true }, _snapOnInput{ true },
@ -78,24 +78,23 @@ Profile::Profile(const winrt::guid& guid):
_cursorHeight{ DEFAULT_CURSOR_HEIGHT }, _cursorHeight{ DEFAULT_CURSOR_HEIGHT },
_commandline{ L"cmd.exe" }, _commandline{ L"cmd.exe" },
_startingDirectory{ }, _startingDirectory{},
_fontFace{ DEFAULT_FONT_FACE }, _fontFace{ DEFAULT_FONT_FACE },
_fontSize{ DEFAULT_FONT_SIZE }, _fontSize{ DEFAULT_FONT_SIZE },
_acrylicTransparency{ 0.5 }, _acrylicTransparency{ 0.5 },
_useAcrylic{ false }, _useAcrylic{ false },
_scrollbarState{ }, _scrollbarState{},
_closeOnExit{ true }, _closeOnExit{ true },
_padding{ DEFAULT_PADDING }, _padding{ DEFAULT_PADDING },
_icon{ }, _icon{},
_backgroundImage{ }, _backgroundImage{},
_backgroundImageOpacity{ }, _backgroundImageOpacity{},
_backgroundImageStretchMode{ } _backgroundImageStretchMode{}
{ {
} }
Profile::~Profile() Profile::~Profile()
{ {
} }
GUID Profile::GetGuid() const noexcept GUID Profile::GetGuid() const noexcept
@ -494,8 +493,8 @@ void Profile::SetIconPath(std::wstring_view path) noexcept
std::wstring_view Profile::GetIconPath() const noexcept std::wstring_view Profile::GetIconPath() const noexcept
{ {
return HasIcon() ? return HasIcon() ?
std::wstring_view{ _icon.value().c_str(), _icon.value().size() } : std::wstring_view{ _icon.value().c_str(), _icon.value().size() } :
std::wstring_view{ L"", 0 }; std::wstring_view{ L"", 0 };
} }
// Method Description: // Method Description:
@ -661,16 +660,16 @@ std::wstring_view Profile::_SerializeCursorStyle(const CursorStyle cursorShape)
{ {
switch (cursorShape) switch (cursorShape)
{ {
case CursorStyle::Underscore: case CursorStyle::Underscore:
return CursorShapeUnderscore; return CursorShapeUnderscore;
case CursorStyle::FilledBox: case CursorStyle::FilledBox:
return CursorShapeFilledbox; return CursorShapeFilledbox;
case CursorStyle::EmptyBox: case CursorStyle::EmptyBox:
return CursorShapeEmptybox; return CursorShapeEmptybox;
case CursorStyle::Vintage: case CursorStyle::Vintage:
return CursorShapeVintage; return CursorShapeVintage;
default: default:
case CursorStyle::Bar: case CursorStyle::Bar:
return CursorShapeBar; return CursorShapeBar;
} }
} }

View file

@ -23,7 +23,6 @@ namespace TerminalApp
class TerminalApp::Profile final class TerminalApp::Profile final
{ {
public: public:
Profile(const winrt::guid& guid); Profile(const winrt::guid& guid);
Profile(); Profile();
@ -55,7 +54,6 @@ public:
bool GetCloseOnExit() const noexcept; bool GetCloseOnExit() const noexcept;
private: private:
static std::wstring EvaluateStartingDirectory(const std::wstring& directory); static std::wstring EvaluateStartingDirectory(const std::wstring& directory);
static winrt::Microsoft::Terminal::Settings::ScrollbarState ParseScrollbarState(const std::wstring& scrollbarState); static winrt::Microsoft::Terminal::Settings::ScrollbarState ParseScrollbarState(const std::wstring& scrollbarState);

View file

@ -165,7 +165,7 @@ void Tab::SetTabText(const winrt::hstring& text)
{ {
// Copy the hstring, so we don't capture a dead reference // Copy the hstring, so we don't capture a dead reference
winrt::hstring textCopy{ text }; winrt::hstring textCopy{ text };
_tabViewItem.Dispatcher().RunAsync(CoreDispatcherPriority::Normal, [text = std::move(textCopy), this](){ _tabViewItem.Dispatcher().RunAsync(CoreDispatcherPriority::Normal, [text = std::move(textCopy), this]() {
_tabViewItem.Header(text); _tabViewItem.Header(text);
}); });
} }
@ -181,7 +181,7 @@ void Tab::SetTabText(const winrt::hstring& text)
void Tab::Scroll(const int delta) void Tab::Scroll(const int delta)
{ {
auto control = GetFocusedTerminalControl(); auto control = GetFocusedTerminalControl();
control.GetControl().Dispatcher().RunAsync(CoreDispatcherPriority::Normal, [control, delta](){ control.GetControl().Dispatcher().RunAsync(CoreDispatcherPriority::Normal, [control, delta]() {
const auto currentOffset = control.GetScrollOffset(); const auto currentOffset = control.GetScrollOffset();
control.KeyboardScrollViewport(currentOffset + delta); control.KeyboardScrollViewport(currentOffset + delta);
}); });

View file

@ -7,7 +7,6 @@
class Tab class Tab
{ {
public: public:
Tab(const GUID& profile, const winrt::Microsoft::Terminal::TerminalControl::TermControl& control); Tab(const GUID& profile, const winrt::Microsoft::Terminal::TerminalControl::TermControl& control);
@ -32,7 +31,6 @@ public:
DECLARE_EVENT(Closed, _closedHandlers, winrt::Microsoft::Terminal::TerminalControl::ConnectionClosedEventArgs); DECLARE_EVENT(Closed, _closedHandlers, winrt::Microsoft::Terminal::TerminalControl::ConnectionClosedEventArgs);
private: private:
std::shared_ptr<Pane> _rootPane{ nullptr }; std::shared_ptr<Pane> _rootPane{ nullptr };
bool _focused{ false }; bool _focused{ false };

View file

@ -8,7 +8,7 @@
// STARTF_USESTDHANDLES is only defined in WINAPI_PARTITION_DESKTOP // STARTF_USESTDHANDLES is only defined in WINAPI_PARTITION_DESKTOP
// We're just gonna manually define it for this prototyping code // We're just gonna manually define it for this prototyping code
#ifndef STARTF_USESTDHANDLES #ifndef STARTF_USESTDHANDLES
#define STARTF_USESTDHANDLES 0x00000100 #define STARTF_USESTDHANDLES 0x00000100
#endif #endif
#include "ConhostConnection.g.cpp" #include "ConhostConnection.g.cpp"
@ -135,8 +135,14 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation
void ConhostConnection::Close() void ConhostConnection::Close()
{ {
if (!_connected) return; if (!_connected)
if (_closing) return; {
return;
}
if (_closing)
{
return;
}
_closing = true; _closing = true;
// TODO: // TODO:
// terminate the output thread // terminate the output thread
@ -181,12 +187,14 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation
_disconnectHandlers(); _disconnectHandlers();
return (DWORD)-1; return (DWORD)-1;
} }
} }
if (dwRead == 0) continue; if (dwRead == 0)
{
continue;
}
// Convert buffer to hstring // Convert buffer to hstring
char* pchStr = (char*)(buffer); char* pchStr = (char*)(buffer);
std::string str{pchStr, dwRead}; std::string str{ pchStr, dwRead };
auto hstr = winrt::to_hstring(str); auto hstr = winrt::to_hstring(str);
// Pass the output to our registered event handlers // Pass the output to our registered event handlers

View file

@ -32,7 +32,7 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation
hstring _startingDirectory{}; hstring _startingDirectory{};
bool _connected{}; bool _connected{};
HANDLE _inPipe{ INVALID_HANDLE_VALUE }; // The pipe for writing input to HANDLE _inPipe{ INVALID_HANDLE_VALUE }; // The pipe for writing input to
HANDLE _outPipe{ INVALID_HANDLE_VALUE }; // The pipe for reading output from HANDLE _outPipe{ INVALID_HANDLE_VALUE }; // The pipe for reading output from
HANDLE _signalPipe{ INVALID_HANDLE_VALUE }; HANDLE _signalPipe{ INVALID_HANDLE_VALUE };
DWORD _outputThreadId{}; DWORD _outputThreadId{};

View file

@ -22,7 +22,6 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation
_commandline = commandline; _commandline = commandline;
_initialRows = initialRows; _initialRows = initialRows;
_initialCols = initialCols; _initialCols = initialCols;
} }
winrt::event_token ConptyConnection::TerminalOutput(TerminalConnection::TerminalOutputEventArgs const& handler) winrt::event_token ConptyConnection::TerminalOutput(TerminalConnection::TerminalOutputEventArgs const& handler)
@ -97,7 +96,6 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation
throw hresult_not_implemented(); throw hresult_not_implemented();
} }
// Function Description: // Function Description:
// - Sample function which combines the creation of some basic anonymous pipes // - Sample function which combines the creation of some basic anonymous pipes
// and passes them to CreatePseudoConsole. // and passes them to CreatePseudoConsole.
@ -112,7 +110,7 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation
_Out_ HANDLE* phOutput, _Out_ HANDLE* phOutput,
_Out_ HPCON* phPC) _Out_ HPCON* phPC)
{ {
if(phPC == NULL || phInput == NULL || phOutput == NULL) if (phPC == NULL || phInput == NULL || phOutput == NULL)
{ {
return E_INVALIDARG; return E_INVALIDARG;
} }
@ -180,7 +178,7 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation
{ {
bool fSuccess; bool fSuccess;
COORD dimensions{_initialCols, _initialRows}; COORD dimensions{ _initialCols, _initialRows };
THROW_IF_FAILED(_CreatePseudoConsoleAndHandles(dimensions, 0, &_inPipe, &_outPipe, &_hPC)); THROW_IF_FAILED(_CreatePseudoConsoleAndHandles(dimensions, 0, &_inPipe, &_outPipe, &_hPC));
STARTUPINFOEX siEx; STARTUPINFOEX siEx;
@ -195,33 +193,33 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation
THROW_IF_FAILED(_AttachPseudoConsole(_hPC, siEx.lpAttributeList)); THROW_IF_FAILED(_AttachPseudoConsole(_hPC, siEx.lpAttributeList));
std::wstring realCommand = _commandline.c_str();//winrt::to_string(_commandline); std::wstring realCommand = _commandline.c_str(); //winrt::to_string(_commandline);
if (realCommand == L""){ if (realCommand == L"")
{
realCommand = L"cmd.exe"; realCommand = L"cmd.exe";
} }
std::unique_ptr<wchar_t[]> mutableCommandline = std::make_unique<wchar_t[]>(realCommand.length() + 1); std::unique_ptr<wchar_t[]> mutableCommandline = std::make_unique<wchar_t[]>(realCommand.length() + 1);
THROW_IF_NULL_ALLOC(mutableCommandline); THROW_IF_NULL_ALLOC(mutableCommandline);
HRESULT hr = StringCchCopy(mutableCommandline.get(), realCommand.length()+1, realCommand.c_str()); HRESULT hr = StringCchCopy(mutableCommandline.get(), realCommand.length() + 1, realCommand.c_str());
THROW_IF_FAILED(hr); THROW_IF_FAILED(hr);
fSuccess = !!CreateProcessW( fSuccess = !!CreateProcessW(
nullptr, nullptr,
mutableCommandline.get(), mutableCommandline.get(),
nullptr, // lpProcessAttributes nullptr, // lpProcessAttributes
nullptr, // lpThreadAttributes nullptr, // lpThreadAttributes
true, // bInheritHandles true, // bInheritHandles
EXTENDED_STARTUPINFO_PRESENT, // dwCreationFlags EXTENDED_STARTUPINFO_PRESENT, // dwCreationFlags
nullptr, // lpEnvironment nullptr, // lpEnvironment
nullptr, // lpCurrentDirectory nullptr, // lpCurrentDirectory
&siEx.StartupInfo, // lpStartupInfo &siEx.StartupInfo, // lpStartupInfo
&_piClient // lpProcessInformation &_piClient // lpProcessInformation
); );
THROW_LAST_ERROR_IF(!fSuccess); THROW_LAST_ERROR_IF(!fSuccess);
DeleteProcThreadAttributeList(siEx.lpAttributeList); DeleteProcThreadAttributeList(siEx.lpAttributeList);
} }
DWORD WINAPI ConptyConnection::StaticOutputThreadProc(LPVOID lpParameter) DWORD WINAPI ConptyConnection::StaticOutputThreadProc(LPVOID lpParameter)
{ {
ConptyConnection* const pInstance = (ConptyConnection*)lpParameter; ConptyConnection* const pInstance = (ConptyConnection*)lpParameter;
@ -243,7 +241,7 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation
// Convert buffer to hstring // Convert buffer to hstring
char* pchStr = (char*)(buffer); char* pchStr = (char*)(buffer);
std::string str{pchStr, dwRead}; std::string str{ pchStr, dwRead };
auto hstr = winrt::to_hstring(str); auto hstr = winrt::to_hstring(str);
// Pass the output to our registered event handlers // Pass the output to our registered event handlers

View file

@ -32,7 +32,7 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation
hstring _commandline; hstring _commandline;
bool _connected; bool _connected;
HANDLE _inPipe; // The pipe for writing input to HANDLE _inPipe; // The pipe for writing input to
HANDLE _outPipe; // The pipe for reading output from HANDLE _outPipe; // The pipe for reading output from
HPCON _hPC; HPCON _hPC;
DWORD _outputThreadId; DWORD _outputThreadId;

View file

@ -32,7 +32,7 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation
void EchoConnection::TerminalDisconnected(winrt::event_token const& token) noexcept void EchoConnection::TerminalDisconnected(winrt::event_token const& token) noexcept
{ {
token; token;
} }
void EchoConnection::Start() void EchoConnection::Start()
{ {
@ -45,7 +45,7 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation
{ {
if (wch < 0x20) if (wch < 0x20)
{ {
prettyPrint << L"^" << (wchar_t)(wch+0x40); prettyPrint << L"^" << (wchar_t)(wch + 0x40);
} }
else if (wch == 0x7f) else if (wch == 0x7f)
{ {

View file

@ -21,7 +21,6 @@ using namespace winrt::Microsoft::Terminal::Settings;
namespace winrt::Microsoft::Terminal::TerminalControl::implementation namespace winrt::Microsoft::Terminal::TerminalControl::implementation
{ {
TermControl::TermControl() : TermControl::TermControl() :
TermControl(Settings::TerminalSettings{}) TermControl(Settings::TerminalSettings{})
{ {
@ -85,7 +84,7 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation
// Initialize the terminal only once the swapchainpanel is loaded - that // Initialize the terminal only once the swapchainpanel is loaded - that
// way, we'll be able to query the real pixel size it got on layout // way, we'll be able to query the real pixel size it got on layout
_loadedRevoker = swapChainPanel.Loaded(winrt::auto_revoke, [this] (auto /*s*/, auto /*e*/){ _loadedRevoker = swapChainPanel.Loaded(winrt::auto_revoke, [this](auto /*s*/, auto /*e*/) {
_InitializeTerminal(); _InitializeTerminal();
}); });
@ -115,7 +114,7 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation
// DON'T CALL _InitializeTerminal here - wait until the swap chain is loaded to do that. // DON'T CALL _InitializeTerminal here - wait until the swap chain is loaded to do that.
// Subscribe to the connection's disconnected event and call our connection closed handlers. // Subscribe to the connection's disconnected event and call our connection closed handlers.
_connection.TerminalDisconnected([=]() { _connection.TerminalDisconnected([=]() {
_connectionClosedHandlers(); _connectionClosedHandlers();
}); });
} }
@ -132,7 +131,7 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation
// Dispatch a call to the UI thread to apply the new settings to the // Dispatch a call to the UI thread to apply the new settings to the
// terminal. // terminal.
_root.Dispatcher().RunAsync(CoreDispatcherPriority::Normal,[this](){ _root.Dispatcher().RunAsync(CoreDispatcherPriority::Normal, [this]() {
// Update our control settings // Update our control settings
_ApplyUISettings(); _ApplyUISettings();
// Update the terminal core with its new Core settings // Update the terminal core with its new Core settings
@ -262,8 +261,9 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation
// set a new image source for the brush // set a new image source for the brush
auto imageSource = brush.ImageSource().try_as<Media::Imaging::BitmapImage>(); auto imageSource = brush.ImageSource().try_as<Media::Imaging::BitmapImage>();
if (imageSource == nullptr || imageSource.UriSource() == nullptr if (imageSource == nullptr ||
|| imageSource.UriSource().RawUri() != imageUri.RawUri()) imageSource.UriSource() == nullptr ||
imageSource.UriSource().RawUri() != imageUri.RawUri())
{ {
// Note that BitmapImage handles the image load asynchronously, // Note that BitmapImage handles the image load asynchronously,
// which is especially important since the image // which is especially important since the image
@ -376,8 +376,7 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation
} }
auto chain = _renderEngine->GetSwapChain(); auto chain = _renderEngine->GetSwapChain();
_swapChainPanel.Dispatcher().RunAsync(CoreDispatcherPriority::High, [=]() _swapChainPanel.Dispatcher().RunAsync(CoreDispatcherPriority::High, [=]() {
{
auto lock = _terminal->LockForWriting(); auto lock = _terminal->LockForWriting();
auto nativePanel = _swapChainPanel.as<ISwapChainPanelNative>(); auto nativePanel = _swapChainPanel.as<ISwapChainPanelNative>();
nativePanel->SetSwapChain(chain.Get()); nativePanel->SetSwapChain(chain.Get());
@ -391,7 +390,7 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation
return; return;
} }
const auto windowWidth = _swapChainPanel.ActualWidth(); // Width() and Height() are NaN? const auto windowWidth = _swapChainPanel.ActualWidth(); // Width() and Height() are NaN?
const auto windowHeight = _swapChainPanel.ActualHeight(); const auto windowHeight = _swapChainPanel.ActualHeight();
_terminal = std::make_unique<::Microsoft::Terminal::Core::Terminal>(); _terminal = std::make_unique<::Microsoft::Terminal::Core::Terminal>();
@ -457,8 +456,7 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation
_terminal->SetWriteInputCallback(inputFn); _terminal->SetWriteInputCallback(inputFn);
auto chain = _renderEngine->GetSwapChain(); auto chain = _renderEngine->GetSwapChain();
_swapChainPanel.Dispatcher().RunAsync(CoreDispatcherPriority::High, [this, chain]() _swapChainPanel.Dispatcher().RunAsync(CoreDispatcherPriority::High, [this, chain]() {
{
_terminal->LockConsole(); _terminal->LockConsole();
auto nativePanel = _swapChainPanel.as<ISwapChainPanelNative>(); auto nativePanel = _swapChainPanel.as<ISwapChainPanelNative>();
nativePanel->SetSwapChain(chain.Get()); nativePanel->SetSwapChain(chain.Get());
@ -518,8 +516,8 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation
// I don't believe there's a difference between KeyDown and // I don't believe there's a difference between KeyDown and
// PreviewKeyDown for our purposes // PreviewKeyDown for our purposes
// These two handlers _must_ be on _controlRoot, not _root. // These two handlers _must_ be on _controlRoot, not _root.
_controlRoot.PreviewKeyDown({this, &TermControl::_KeyDownHandler }); _controlRoot.PreviewKeyDown({ this, &TermControl::_KeyDownHandler });
_controlRoot.CharacterReceived({this, &TermControl::_CharacterHandler }); _controlRoot.CharacterReceived({ this, &TermControl::_CharacterHandler });
auto pfnTitleChanged = std::bind(&TermControl::_TerminalTitleChanged, this, std::placeholders::_1); auto pfnTitleChanged = std::bind(&TermControl::_TerminalTitleChanged, this, std::placeholders::_1);
_terminal->SetTitleChangedCallback(pfnTitleChanged); _terminal->SetTitleChangedCallback(pfnTitleChanged);
@ -560,7 +558,7 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation
} }
void TermControl::_CharacterHandler(winrt::Windows::Foundation::IInspectable const& /*sender*/, void TermControl::_CharacterHandler(winrt::Windows::Foundation::IInspectable const& /*sender*/,
Input::CharacterReceivedRoutedEventArgs const& e) Input::CharacterReceivedRoutedEventArgs const& e)
{ {
if (_closing) if (_closing)
{ {
@ -1008,7 +1006,6 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation
// TODO: MSFT:20895307 If the font doesn't exist, this doesn't // TODO: MSFT:20895307 If the font doesn't exist, this doesn't
// actually fail. We need a way to gracefully fallback. // actually fail. We need a way to gracefully fallback.
_renderer->TriggerFontChange(newDpi, _desiredFont, _actualFont); _renderer->TriggerFontChange(newDpi, _desiredFont, _actualFont);
} }
// Method Description: // Method Description:
@ -1147,7 +1144,8 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation
hstring TermControl::Title() hstring TermControl::Title()
{ {
if (!_initializedTerminal) return L""; if (!_initializedTerminal)
return L"";
hstring hstr(_terminal->GetConsoleTitle()); hstring hstr(_terminal->GetConsoleTitle());
return hstr; return hstr;
@ -1177,21 +1175,21 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation
_connection.TerminalOutput(_connectionOutputEventToken); _connection.TerminalOutput(_connectionOutputEventToken);
// Clear out the cursor timer, so it doesn't trigger again on us once we're destructed. // Clear out the cursor timer, so it doesn't trigger again on us once we're destructed.
if (auto localCursorTimer{std::exchange(_cursorTimer, std::nullopt)}) if (auto localCursorTimer{ std::exchange(_cursorTimer, std::nullopt) })
{ {
localCursorTimer->Stop(); localCursorTimer->Stop();
// cursorTimer timer, now stopped, is destroyed. // cursorTimer timer, now stopped, is destroyed.
} }
if (auto localConnection{std::exchange(_connection, nullptr)}) if (auto localConnection{ std::exchange(_connection, nullptr) })
{ {
localConnection.Close(); localConnection.Close();
// connection is destroyed. // connection is destroyed.
} }
if (auto localRenderEngine{std::exchange(_renderEngine, nullptr)}) if (auto localRenderEngine{ std::exchange(_renderEngine, nullptr) })
{ {
if (auto localRenderer{std::exchange(_renderer, nullptr)}) if (auto localRenderer{ std::exchange(_renderer, nullptr) })
{ {
localRenderer->TriggerTeardown(); localRenderer->TriggerTeardown();
// renderer is destroyed // renderer is destroyed
@ -1199,7 +1197,7 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation
// renderEngine is destroyed // renderEngine is destroyed
} }
if (auto localTerminal{std::exchange(_terminal, nullptr)}) if (auto localTerminal{ std::exchange(_terminal, nullptr) })
{ {
_initializedTerminal = false; _initializedTerminal = false;
// terminal is destroyed. // terminal is destroyed.
@ -1357,11 +1355,15 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation
switch (paddingPropIndex) switch (paddingPropIndex)
{ {
case 1: return ThicknessHelper::FromUniformLength(thicknessArr[0]); case 1:
case 2: return ThicknessHelper::FromLengths(thicknessArr[0], thicknessArr[1], thicknessArr[0], thicknessArr[1]); return ThicknessHelper::FromUniformLength(thicknessArr[0]);
// No case for paddingPropIndex = 3, since it's not a norm to provide just Left, Top & Right padding values leaving out Bottom case 2:
case 4: return ThicknessHelper::FromLengths(thicknessArr[0], thicknessArr[1], thicknessArr[2], thicknessArr[3]); return ThicknessHelper::FromLengths(thicknessArr[0], thicknessArr[1], thicknessArr[0], thicknessArr[1]);
default: return Thickness(); // No case for paddingPropIndex = 3, since it's not a norm to provide just Left, Top & Right padding values leaving out Bottom
case 4:
return ThicknessHelper::FromLengths(thicknessArr[0], thicknessArr[1], thicknessArr[2], thicknessArr[3]);
default:
return Thickness();
} }
} }
@ -1417,8 +1419,7 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation
const COORD TermControl::_GetTerminalPosition(winrt::Windows::Foundation::Point cursorPosition) const COORD TermControl::_GetTerminalPosition(winrt::Windows::Foundation::Point cursorPosition)
{ {
// Exclude padding from cursor position calculation // Exclude padding from cursor position calculation
COORD terminalPosition = COORD terminalPosition = {
{
static_cast<SHORT>(cursorPosition.X - _root.Padding().Left), static_cast<SHORT>(cursorPosition.X - _root.Padding().Left),
static_cast<SHORT>(cursorPosition.Y - _root.Padding().Top) static_cast<SHORT>(cursorPosition.Y - _root.Padding().Top)
}; };
@ -1434,13 +1435,15 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation
return terminalPosition; return terminalPosition;
} }
// clang-format off
// -------------------------------- WinRT Events --------------------------------- // -------------------------------- WinRT Events ---------------------------------
// Winrt events need a method for adding a callback to the event and removing the callback. // Winrt events need a method for adding a callback to the event and removing the callback.
// These macros will define them both for you. // These macros will define them both for you.
DEFINE_EVENT(TermControl, TitleChanged, _titleChangedHandlers, TerminalControl::TitleChangedEventArgs); DEFINE_EVENT(TermControl, TitleChanged, _titleChangedHandlers, TerminalControl::TitleChangedEventArgs);
DEFINE_EVENT(TermControl, ConnectionClosed, _connectionClosedHandlers, TerminalControl::ConnectionClosedEventArgs); DEFINE_EVENT(TermControl, ConnectionClosed, _connectionClosedHandlers, TerminalControl::ConnectionClosedEventArgs);
DEFINE_EVENT(TermControl, CopyToClipboard, _clipboardCopyHandlers, TerminalControl::CopyToClipboardEventArgs); DEFINE_EVENT(TermControl, CopyToClipboard, _clipboardCopyHandlers, TerminalControl::CopyToClipboardEventArgs);
DEFINE_EVENT(TermControl, ScrollPositionChanged, _scrollPositionChangedHandlers, TerminalControl::ScrollPositionChangedEventArgs); DEFINE_EVENT(TermControl, ScrollPositionChanged, _scrollPositionChangedHandlers, TerminalControl::ScrollPositionChangedEventArgs);
// clang-format on
DEFINE_EVENT_WITH_TYPED_EVENT_HANDLER(TermControl, PasteFromClipboard, _clipboardPasteHandlers, TerminalControl::TermControl, TerminalControl::PasteFromClipboardEventArgs); DEFINE_EVENT_WITH_TYPED_EVENT_HANDLER(TermControl, PasteFromClipboard, _clipboardPasteHandlers, TerminalControl::TermControl, TerminalControl::PasteFromClipboardEventArgs);
} }

View file

@ -18,7 +18,8 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation
public PasteFromClipboardEventArgsT<PasteFromClipboardEventArgs> public PasteFromClipboardEventArgsT<PasteFromClipboardEventArgs>
{ {
public: public:
PasteFromClipboardEventArgs(std::function<void(std::wstring)> clipboardDataHandler) : m_clipboardDataHandler(clipboardDataHandler) { } PasteFromClipboardEventArgs(std::function<void(std::wstring)> clipboardDataHandler) :
m_clipboardDataHandler(clipboardDataHandler) {}
void HandleClipboardData(hstring value) void HandleClipboardData(hstring value)
{ {
@ -53,6 +54,7 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation
static Windows::Foundation::Point GetProposedDimensions(Microsoft::Terminal::Settings::IControlSettings const& settings, const uint32_t dpi); static Windows::Foundation::Point GetProposedDimensions(Microsoft::Terminal::Settings::IControlSettings const& settings, const uint32_t dpi);
// clang-format off
// -------------------------------- WinRT Events --------------------------------- // -------------------------------- WinRT Events ---------------------------------
DECLARE_EVENT(TitleChanged, _titleChangedHandlers, TerminalControl::TitleChangedEventArgs); DECLARE_EVENT(TitleChanged, _titleChangedHandlers, TerminalControl::TitleChangedEventArgs);
DECLARE_EVENT(ConnectionClosed, _connectionClosedHandlers, TerminalControl::ConnectionClosedEventArgs); DECLARE_EVENT(ConnectionClosed, _connectionClosedHandlers, TerminalControl::ConnectionClosedEventArgs);
@ -60,6 +62,7 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation
DECLARE_EVENT(CopyToClipboard, _clipboardCopyHandlers, TerminalControl::CopyToClipboardEventArgs); DECLARE_EVENT(CopyToClipboard, _clipboardCopyHandlers, TerminalControl::CopyToClipboardEventArgs);
DECLARE_EVENT_WITH_TYPED_EVENT_HANDLER(PasteFromClipboard, _clipboardPasteHandlers, TerminalControl::TermControl, TerminalControl::PasteFromClipboardEventArgs); DECLARE_EVENT_WITH_TYPED_EVENT_HANDLER(PasteFromClipboard, _clipboardPasteHandlers, TerminalControl::TermControl, TerminalControl::PasteFromClipboardEventArgs);
// clang-format on
private: private:
TerminalConnection::ITerminalConnection _connection; TerminalConnection::ITerminalConnection _connection;

View file

@ -30,4 +30,3 @@
#include <winrt/Windows.ui.xaml.input.h> #include <winrt/Windows.ui.xaml.input.h>
#include <windows.ui.xaml.media.dxinterop.h> #include <windows.ui.xaml.media.dxinterop.h>

View file

@ -12,10 +12,8 @@ namespace Microsoft::Terminal::Core
virtual bool SendKeyEvent(const WORD vkey, const bool ctrlPressed, const bool altPressed, const bool shiftPressed) = 0; virtual bool SendKeyEvent(const WORD vkey, const bool ctrlPressed, const bool altPressed, const bool shiftPressed) = 0;
// void SendMouseEvent(uint row, uint col, KeyModifiers modifiers); // void SendMouseEvent(uint row, uint col, KeyModifiers modifiers);
[[nodiscard]] [[nodiscard]] virtual HRESULT UserResize(const COORD size) noexcept = 0;
virtual HRESULT UserResize(const COORD size) noexcept = 0;
virtual void UserScrollViewport(const int viewTop) = 0; virtual void UserScrollViewport(const int viewTop) = 0;
virtual int GetScrollOffset() = 0; virtual int GetScrollOffset() = 0;
}; };
} }

View file

@ -22,7 +22,7 @@ using namespace Microsoft::Console::VirtualTerminal;
static std::wstring _KeyEventsToText(std::deque<std::unique_ptr<IInputEvent>>& inEventsToWrite) static std::wstring _KeyEventsToText(std::deque<std::unique_ptr<IInputEvent>>& inEventsToWrite)
{ {
std::wstring wstr = L""; std::wstring wstr = L"";
for(auto& ev : inEventsToWrite) for (auto& ev : inEventsToWrite)
{ {
if (ev->EventType() == InputEventType::KeyEvent) if (ev->EventType() == InputEventType::KeyEvent)
{ {
@ -35,7 +35,7 @@ static std::wstring _KeyEventsToText(std::deque<std::unique_ptr<IInputEvent>>& i
} }
Terminal::Terminal() : Terminal::Terminal() :
_mutableViewport{Viewport::Empty()}, _mutableViewport{ Viewport::Empty() },
_title{ L"" }, _title{ L"" },
_colorTable{}, _colorTable{},
_defaultFg{ RGB(255, 255, 255) }, _defaultFg{ RGB(255, 255, 255) },
@ -46,13 +46,15 @@ Terminal::Terminal() :
_boxSelection{ false }, _boxSelection{ false },
_selectionActive{ false }, _selectionActive{ false },
_selectionAnchor{ 0, 0 }, _selectionAnchor{ 0, 0 },
_endSelectionPosition { 0, 0 } _endSelectionPosition{ 0, 0 }
{ {
_stateMachine = std::make_unique<StateMachine>(new OutputStateMachineEngine(new TerminalDispatch(*this))); _stateMachine = std::make_unique<StateMachine>(new OutputStateMachineEngine(new TerminalDispatch(*this)));
auto passAlongInput = [&](std::deque<std::unique_ptr<IInputEvent>>& inEventsToWrite) auto passAlongInput = [&](std::deque<std::unique_ptr<IInputEvent>>& inEventsToWrite) {
{ if (!_pfnWriteInput)
if(!_pfnWriteInput) return; {
return;
}
std::wstring wstr = _KeyEventsToText(inEventsToWrite); std::wstring wstr = _KeyEventsToText(inEventsToWrite);
_pfnWriteInput(wstr); _pfnWriteInput(wstr);
}; };
@ -64,10 +66,10 @@ Terminal::Terminal() :
void Terminal::Create(COORD viewportSize, SHORT scrollbackLines, IRenderTarget& renderTarget) void Terminal::Create(COORD viewportSize, SHORT scrollbackLines, IRenderTarget& renderTarget)
{ {
_mutableViewport = Viewport::FromDimensions({ 0,0 }, viewportSize); _mutableViewport = Viewport::FromDimensions({ 0, 0 }, viewportSize);
_scrollbackLines = scrollbackLines; _scrollbackLines = scrollbackLines;
const COORD bufferSize { viewportSize.X, const COORD bufferSize{ viewportSize.X,
Utils::ClampToShortMax(viewportSize.Y + scrollbackLines, 1) }; Utils::ClampToShortMax(viewportSize.Y + scrollbackLines, 1) };
const TextAttribute attr{}; const TextAttribute attr{};
const UINT cursorSize = 12; const UINT cursorSize = 12;
_buffer = std::make_unique<TextBuffer>(bufferSize, attr, cursorSize, renderTarget); _buffer = std::make_unique<TextBuffer>(bufferSize, attr, cursorSize, renderTarget);
@ -79,7 +81,7 @@ void Terminal::Create(COORD viewportSize, SHORT scrollbackLines, IRenderTarget&
// - settings: the set of CoreSettings we need to use to initialize the terminal // - settings: the set of CoreSettings we need to use to initialize the terminal
// - renderTarget: A render target the terminal can use for paint invalidation. // - renderTarget: A render target the terminal can use for paint invalidation.
void Terminal::CreateFromSettings(winrt::Microsoft::Terminal::Settings::ICoreSettings settings, void Terminal::CreateFromSettings(winrt::Microsoft::Terminal::Settings::ICoreSettings settings,
Microsoft::Console::Render::IRenderTarget& renderTarget) Microsoft::Console::Render::IRenderTarget& renderTarget)
{ {
const COORD viewportSize{ Utils::ClampToShortMax(settings.InitialCols(), 1), const COORD viewportSize{ Utils::ClampToShortMax(settings.InitialCols(), 1),
Utils::ClampToShortMax(settings.InitialRows(), 1) }; Utils::ClampToShortMax(settings.InitialRows(), 1) };
@ -102,22 +104,22 @@ void Terminal::UpdateSettings(winrt::Microsoft::Terminal::Settings::ICoreSetting
CursorType cursorShape = CursorType::VerticalBar; CursorType cursorShape = CursorType::VerticalBar;
switch (settings.CursorShape()) switch (settings.CursorShape())
{ {
case CursorStyle::Underscore: case CursorStyle::Underscore:
cursorShape = CursorType::Underscore; cursorShape = CursorType::Underscore;
break; break;
case CursorStyle::FilledBox: case CursorStyle::FilledBox:
cursorShape = CursorType::FullBox; cursorShape = CursorType::FullBox;
break; break;
case CursorStyle::EmptyBox: case CursorStyle::EmptyBox:
cursorShape = CursorType::EmptyBox; cursorShape = CursorType::EmptyBox;
break; break;
case CursorStyle::Vintage: case CursorStyle::Vintage:
cursorShape = CursorType::Legacy; cursorShape = CursorType::Legacy;
break; break;
default: default:
case CursorStyle::Bar: case CursorStyle::Bar:
cursorShape = CursorType::VerticalBar; cursorShape = CursorType::VerticalBar;
break; break;
} }
_buffer->GetCursor().SetStyle(settings.CursorHeight(), _buffer->GetCursor().SetStyle(settings.CursorHeight(),
@ -146,8 +148,7 @@ void Terminal::UpdateSettings(winrt::Microsoft::Terminal::Settings::ICoreSetting
// - S_OK if we successfully resized the terminal, S_FALSE if there was // - S_OK if we successfully resized the terminal, S_FALSE if there was
// nothing to do (the viewportSize is the same as our current size), or an // nothing to do (the viewportSize is the same as our current size), or an
// appropriate HRESULT for failing to resize. // appropriate HRESULT for failing to resize.
[[nodiscard]] [[nodiscard]] HRESULT Terminal::UserResize(const COORD viewportSize) noexcept
HRESULT Terminal::UserResize(const COORD viewportSize) noexcept
{ {
const auto oldDimensions = _mutableViewport.Dimensions(); const auto oldDimensions = _mutableViewport.Dimensions();
if (viewportSize == oldDimensions) if (viewportSize == oldDimensions)
@ -212,11 +213,10 @@ bool Terminal::SendKeyEvent(const WORD vkey,
_NotifyScrollEvent(); _NotifyScrollEvent();
} }
DWORD modifiers = 0 DWORD modifiers = 0 |
| (ctrlPressed? LEFT_CTRL_PRESSED : 0) (ctrlPressed ? LEFT_CTRL_PRESSED : 0) |
| (altPressed? LEFT_ALT_PRESSED : 0) (altPressed ? LEFT_ALT_PRESSED : 0) |
| (shiftPressed? SHIFT_PRESSED : 0) (shiftPressed ? SHIFT_PRESSED : 0);
;
// Alt key sequences _require_ the char to be in the keyevent. If alt is // Alt key sequences _require_ the char to be in the keyevent. If alt is
// pressed, manually get the character that's being typed, and put it in the // pressed, manually get the character that's being typed, and put it in the
@ -241,7 +241,7 @@ bool Terminal::SendKeyEvent(const WORD vkey,
const bool manuallyHandled = ch != UNICODE_NULL; const bool manuallyHandled = ch != UNICODE_NULL;
KeyEvent keyEv{ true, 0, vkey, 0, ch, modifiers}; KeyEvent keyEv{ true, 0, vkey, 0, ch, modifiers };
const bool translated = _terminalInput->HandleKey(&keyEv); const bool translated = _terminalInput->HandleKey(&keyEv);
return translated && manuallyHandled; return translated && manuallyHandled;
@ -252,8 +252,7 @@ bool Terminal::SendKeyEvent(const WORD vkey,
// Return Value: // Return Value:
// - a shared_lock which can be used to unlock the terminal. The shared_lock // - a shared_lock which can be used to unlock the terminal. The shared_lock
// will release this lock when it's destructed. // will release this lock when it's destructed.
[[nodiscard]] [[nodiscard]] std::shared_lock<std::shared_mutex> Terminal::LockForReading()
std::shared_lock<std::shared_mutex> Terminal::LockForReading()
{ {
return std::shared_lock<std::shared_mutex>(_readWriteLock); return std::shared_lock<std::shared_mutex>(_readWriteLock);
} }
@ -263,13 +262,11 @@ std::shared_lock<std::shared_mutex> Terminal::LockForReading()
// Return Value: // Return Value:
// - a unique_lock which can be used to unlock the terminal. The unique_lock // - a unique_lock which can be used to unlock the terminal. The unique_lock
// will release this lock when it's destructed. // will release this lock when it's destructed.
[[nodiscard]] [[nodiscard]] std::unique_lock<std::shared_mutex> Terminal::LockForWriting()
std::unique_lock<std::shared_mutex> Terminal::LockForWriting()
{ {
return std::unique_lock<std::shared_mutex>(_readWriteLock); return std::unique_lock<std::shared_mutex>(_readWriteLock);
} }
Viewport Terminal::_GetMutableViewport() const noexcept Viewport Terminal::_GetMutableViewport() const noexcept
{ {
return _mutableViewport; return _mutableViewport;
@ -345,7 +342,7 @@ void Terminal::_WriteBuffer(const std::wstring_view& stringView)
// This is not great but I need it demoable. Fix by making a buffer stream writer. // This is not great but I need it demoable. Fix by making a buffer stream writer.
if (wch >= 0xD800 && wch <= 0xDFFF) if (wch >= 0xD800 && wch <= 0xDFFF)
{ {
OutputCellIterator it{ stringView.substr(i, 2) , _buffer->GetCurrentAttributes() }; OutputCellIterator it{ stringView.substr(i, 2), _buffer->GetCurrentAttributes() };
const auto end = _buffer->Write(it); const auto end = _buffer->Write(it);
const auto cellDistance = end.GetCellDistance(it); const auto cellDistance = end.GetCellDistance(it);
i += cellDistance - 1; i += cellDistance - 1;
@ -353,7 +350,7 @@ void Terminal::_WriteBuffer(const std::wstring_view& stringView)
} }
else else
{ {
OutputCellIterator it{ stringView.substr(i, 1) , _buffer->GetCurrentAttributes() }; OutputCellIterator it{ stringView.substr(i, 1), _buffer->GetCurrentAttributes() };
const auto end = _buffer->Write(it); const auto end = _buffer->Write(it);
const auto cellDistance = end.GetCellDistance(it); const auto cellDistance = end.GetCellDistance(it);
proposedCursorPosition.X += gsl::narrow<SHORT>(cellDistance); proposedCursorPosition.X += gsl::narrow<SHORT>(cellDistance);
@ -364,7 +361,7 @@ void Terminal::_WriteBuffer(const std::wstring_view& stringView)
const auto newRows = proposedCursorPosition.Y - bufferSize.Height() + 1; const auto newRows = proposedCursorPosition.Y - bufferSize.Height() + 1;
if (newRows > 0) if (newRows > 0)
{ {
for(auto dy = 0; dy < newRows; dy++) for (auto dy = 0; dy < newRows; dy++)
{ {
_buffer->IncrementCircularBuffer(); _buffer->IncrementCircularBuffer();
proposedCursorPosition.Y--; proposedCursorPosition.Y--;
@ -384,7 +381,7 @@ void Terminal::_WriteBuffer(const std::wstring_view& stringView)
const auto newViewTop = std::max(0, cursorPosAfter.Y - (_mutableViewport.Height() - 1)); const auto newViewTop = std::max(0, cursorPosAfter.Y - (_mutableViewport.Height() - 1));
if (newViewTop != _mutableViewport.Top()) if (newViewTop != _mutableViewport.Top())
{ {
_mutableViewport = Viewport::FromDimensions({0, gsl::narrow<short>(newViewTop)}, _mutableViewport.Dimensions()); _mutableViewport = Viewport::FromDimensions({ 0, gsl::narrow<short>(newViewTop) }, _mutableViewport.Dimensions());
notifyScroll = true; notifyScroll = true;
} }
} }
@ -527,8 +524,12 @@ std::vector<SMALL_RECT> Terminal::_GetSelectionRects() const
const COORD endSelectionPositionWithOffset = { _endSelectionPosition.X, temp2 }; const COORD endSelectionPositionWithOffset = { _endSelectionPosition.X, temp2 };
// NOTE: (0,0) is top-left so vertical comparison is inverted // NOTE: (0,0) is top-left so vertical comparison is inverted
const COORD &higherCoord = (selectionAnchorWithOffset.Y <= endSelectionPositionWithOffset.Y) ? selectionAnchorWithOffset : endSelectionPositionWithOffset; const COORD& higherCoord = (selectionAnchorWithOffset.Y <= endSelectionPositionWithOffset.Y) ?
const COORD &lowerCoord = (selectionAnchorWithOffset.Y > endSelectionPositionWithOffset.Y) ? selectionAnchorWithOffset : endSelectionPositionWithOffset; selectionAnchorWithOffset :
endSelectionPositionWithOffset;
const COORD& lowerCoord = (selectionAnchorWithOffset.Y > endSelectionPositionWithOffset.Y) ?
selectionAnchorWithOffset :
endSelectionPositionWithOffset;
selectionArea.reserve(lowerCoord.Y - higherCoord.Y + 1); selectionArea.reserve(lowerCoord.Y - higherCoord.Y + 1);
for (auto row = higherCoord.Y; row <= lowerCoord.Y; row++) for (auto row = higherCoord.Y; row <= lowerCoord.Y; row++)
@ -568,8 +569,8 @@ void Terminal::SetBoxSelection(const bool isEnabled) noexcept
void Terminal::ClearSelection() noexcept void Terminal::ClearSelection() noexcept
{ {
_selectionActive = false; _selectionActive = false;
_selectionAnchor = {0, 0}; _selectionAnchor = { 0, 0 };
_endSelectionPosition = {0, 0}; _endSelectionPosition = { 0, 0 };
_selectionAnchor_YOffset = 0; _selectionAnchor_YOffset = 0;
_endSelectionPosition_YOffset = 0; _endSelectionPosition_YOffset = 0;

View file

@ -34,28 +34,26 @@ class Microsoft::Terminal::Core::Terminal final :
{ {
public: public:
Terminal(); Terminal();
virtual ~Terminal() {}; virtual ~Terminal(){};
void Create(COORD viewportSize, void Create(COORD viewportSize,
SHORT scrollbackLines, SHORT scrollbackLines,
Microsoft::Console::Render::IRenderTarget& renderTarget); Microsoft::Console::Render::IRenderTarget& renderTarget);
void CreateFromSettings(winrt::Microsoft::Terminal::Settings::ICoreSettings settings, void CreateFromSettings(winrt::Microsoft::Terminal::Settings::ICoreSettings settings,
Microsoft::Console::Render::IRenderTarget& renderTarget); Microsoft::Console::Render::IRenderTarget& renderTarget);
void UpdateSettings(winrt::Microsoft::Terminal::Settings::ICoreSettings settings); void UpdateSettings(winrt::Microsoft::Terminal::Settings::ICoreSettings settings);
// Write goes through the parser // Write goes through the parser
void Write(std::wstring_view stringView); void Write(std::wstring_view stringView);
[[nodiscard]] [[nodiscard]] std::shared_lock<std::shared_mutex> LockForReading();
std::shared_lock<std::shared_mutex> LockForReading(); [[nodiscard]] std::unique_lock<std::shared_mutex> LockForWriting();
[[nodiscard]]
std::unique_lock<std::shared_mutex> LockForWriting();
short GetBufferHeight() const noexcept; short GetBufferHeight() const noexcept;
#pragma region ITerminalApi #pragma region ITerminalApi
// These methods are defined in TerminalApi.cpp // These methods are defined in TerminalApi.cpp
bool PrintString(std::wstring_view stringView) override; bool PrintString(std::wstring_view stringView) override;
bool ExecuteChar(wchar_t wch) override; bool ExecuteChar(wchar_t wch) override;
@ -74,21 +72,20 @@ public:
bool SetCursorStyle(const ::Microsoft::Console::VirtualTerminal::DispatchTypes::CursorStyle cursorStyle) override; bool SetCursorStyle(const ::Microsoft::Console::VirtualTerminal::DispatchTypes::CursorStyle cursorStyle) override;
bool SetDefaultForeground(const COLORREF dwColor) override; bool SetDefaultForeground(const COLORREF dwColor) override;
bool SetDefaultBackground(const COLORREF dwColor) override; bool SetDefaultBackground(const COLORREF dwColor) override;
#pragma endregion #pragma endregion
#pragma region ITerminalInput #pragma region ITerminalInput
// These methods are defined in Terminal.cpp // These methods are defined in Terminal.cpp
bool SendKeyEvent(const WORD vkey, bool SendKeyEvent(const WORD vkey,
const bool ctrlPressed, const bool ctrlPressed,
const bool altPressed, const bool altPressed,
const bool shiftPressed) override; const bool shiftPressed) override;
[[nodiscard]] [[nodiscard]] HRESULT UserResize(const COORD viewportSize) noexcept override;
HRESULT UserResize(const COORD viewportSize) noexcept override;
void UserScrollViewport(const int viewTop) override; void UserScrollViewport(const int viewTop) override;
int GetScrollOffset() override; int GetScrollOffset() override;
#pragma endregion #pragma endregion
#pragma region IRenderData #pragma region IRenderData
// These methods are defined in TerminalRenderData.cpp // These methods are defined in TerminalRenderData.cpp
Microsoft::Console::Types::Viewport GetViewport() noexcept override; Microsoft::Console::Types::Viewport GetViewport() noexcept override;
const TextBuffer& GetTextBuffer() noexcept override; const TextBuffer& GetTextBuffer() noexcept override;
@ -110,7 +107,7 @@ public:
const std::wstring GetConsoleTitle() const noexcept override; const std::wstring GetConsoleTitle() const noexcept override;
void LockConsole() noexcept override; void LockConsole() noexcept override;
void UnlockConsole() noexcept override; void UnlockConsole() noexcept override;
#pragma endregion #pragma endregion
void SetWriteInputCallback(std::function<void(std::wstring&)> pfn) noexcept; void SetWriteInputCallback(std::function<void(std::wstring&)> pfn) noexcept;
void SetTitleChangedCallback(std::function<void(const std::wstring_view&)> pfn) noexcept; void SetTitleChangedCallback(std::function<void(const std::wstring_view&)> pfn) noexcept;
@ -120,7 +117,7 @@ public:
void SetCursorVisible(const bool isVisible) noexcept; void SetCursorVisible(const bool isVisible) noexcept;
bool IsCursorBlinkingAllowed() const noexcept; bool IsCursorBlinkingAllowed() const noexcept;
#pragma region TextSelection #pragma region TextSelection
const bool IsSelectionActive() const noexcept; const bool IsSelectionActive() const noexcept;
void SetSelectionAnchor(const COORD position); void SetSelectionAnchor(const COORD position);
void SetEndSelectionPosition(const COORD position); void SetEndSelectionPosition(const COORD position);
@ -128,9 +125,9 @@ public:
void ClearSelection() noexcept; void ClearSelection() noexcept;
const std::wstring RetrieveSelectedTextFromBuffer(bool trimTrailingWhitespace) const; const std::wstring RetrieveSelectedTextFromBuffer(bool trimTrailingWhitespace) const;
#pragma endregion #pragma endregion
private: private:
std::function<void(std::wstring&)> _pfnWriteInput; std::function<void(std::wstring&)> _pfnWriteInput;
std::function<void(const std::wstring_view&)> _pfnTitleChanged; std::function<void(const std::wstring_view&)> _pfnTitleChanged;
std::function<void(const int, const int, const int)> _pfnScrollPositionChanged; std::function<void(const int, const int, const int)> _pfnScrollPositionChanged;
@ -193,4 +190,3 @@ public:
std::vector<SMALL_RECT> _GetSelectionRects() const; std::vector<SMALL_RECT> _GetSelectionRects() const;
}; };

View file

@ -17,7 +17,7 @@ bool Terminal::PrintString(std::wstring_view stringView)
bool Terminal::ExecuteChar(wchar_t wch) bool Terminal::ExecuteChar(wchar_t wch)
{ {
std::wstring_view view{&wch, 1}; std::wstring_view view{ &wch, 1 };
_WriteBuffer(view); _WriteBuffer(view);
return true; return true;
} }
@ -106,7 +106,7 @@ bool Terminal::SetCursorPosition(short x, short y)
const auto viewOrigin = viewport.Origin(); const auto viewOrigin = viewport.Origin();
const short absoluteX = viewOrigin.X + x; const short absoluteX = viewOrigin.X + x;
const short absoluteY = viewOrigin.Y + y; const short absoluteY = viewOrigin.Y + y;
COORD newPos{absoluteX, absoluteY}; COORD newPos{ absoluteX, absoluteY };
viewport.Clamp(newPos); viewport.Clamp(newPos);
_buffer->GetCursor().SetPosition(newPos); _buffer->GetCursor().SetPosition(newPos);

View file

@ -13,7 +13,6 @@ using namespace ::Microsoft::Console::VirtualTerminal;
TerminalDispatch::TerminalDispatch(ITerminalApi& terminalApi) : TerminalDispatch::TerminalDispatch(ITerminalApi& terminalApi) :
_terminalApi{ terminalApi } _terminalApi{ terminalApi }
{ {
} }
void TerminalDispatch::Execute(const wchar_t wchControl) void TerminalDispatch::Execute(const wchar_t wchControl)
@ -26,7 +25,7 @@ void TerminalDispatch::Print(const wchar_t wchPrintable)
_terminalApi.PrintString({ &wchPrintable, 1 }); _terminalApi.PrintString({ &wchPrintable, 1 });
} }
void TerminalDispatch::PrintString(const wchar_t *const rgwch, const size_t cch) void TerminalDispatch::PrintString(const wchar_t* const rgwch, const size_t cch)
{ {
_terminalApi.PrintString({ rgwch, cch }); _terminalApi.PrintString({ rgwch, cch });
} }
@ -44,7 +43,7 @@ bool TerminalDispatch::CursorPosition(const unsigned int uiLine,
bool TerminalDispatch::CursorForward(const unsigned int uiDistance) bool TerminalDispatch::CursorForward(const unsigned int uiDistance)
{ {
const auto cursorPos = _terminalApi.GetCursorPosition(); const auto cursorPos = _terminalApi.GetCursorPosition();
const COORD newCursorPos { cursorPos.X + gsl::narrow<short>(uiDistance), cursorPos.Y }; const COORD newCursorPos{ cursorPos.X + gsl::narrow<short>(uiDistance), cursorPos.Y };
return _terminalApi.SetCursorPosition(newCursorPos.X, newCursorPos.Y); return _terminalApi.SetCursorPosition(newCursorPos.X, newCursorPos.Y);
} }

View file

@ -11,7 +11,7 @@ public:
virtual ~TerminalDispatch(){}; virtual ~TerminalDispatch(){};
virtual void Execute(const wchar_t wchControl) override; virtual void Execute(const wchar_t wchControl) override;
virtual void Print(const wchar_t wchPrintable) override; virtual void Print(const wchar_t wchPrintable) override;
virtual void PrintString(const wchar_t *const rgwch, const size_t cch) override; virtual void PrintString(const wchar_t* const rgwch, const size_t cch) override;
bool SetGraphicsRendition(const ::Microsoft::Console::VirtualTerminal::DispatchTypes::GraphicsOptions* const rgOptions, bool SetGraphicsRendition(const ::Microsoft::Console::VirtualTerminal::DispatchTypes::GraphicsOptions* const rgOptions,
const size_t cOptions) override; const size_t cOptions) override;
@ -43,5 +43,4 @@ private:
bool _SetBoldColorHelper(const ::Microsoft::Console::VirtualTerminal::DispatchTypes::GraphicsOptions option); bool _SetBoldColorHelper(const ::Microsoft::Console::VirtualTerminal::DispatchTypes::GraphicsOptions option);
bool _SetDefaultColorHelper(const ::Microsoft::Console::VirtualTerminal::DispatchTypes::GraphicsOptions option); bool _SetDefaultColorHelper(const ::Microsoft::Console::VirtualTerminal::DispatchTypes::GraphicsOptions option);
void _SetGraphicsOptionHelper(const ::Microsoft::Console::VirtualTerminal::DispatchTypes::GraphicsOptions opt); void _SetGraphicsOptionHelper(const ::Microsoft::Console::VirtualTerminal::DispatchTypes::GraphicsOptions opt);
}; };

View file

@ -6,6 +6,7 @@
using namespace ::Microsoft::Terminal::Core; using namespace ::Microsoft::Terminal::Core;
using namespace ::Microsoft::Console::VirtualTerminal; using namespace ::Microsoft::Console::VirtualTerminal;
// clang-format off
const BYTE RED_ATTR = 0x01; const BYTE RED_ATTR = 0x01;
const BYTE GREEN_ATTR = 0x02; const BYTE GREEN_ATTR = 0x02;
const BYTE BLUE_ATTR = 0x04; const BYTE BLUE_ATTR = 0x04;
@ -26,6 +27,7 @@ const BYTE BRIGHT_BLUE = BRIGHT_ATTR | BLUE_ATTR;
const BYTE BRIGHT_MAGENTA = BRIGHT_ATTR | RED_ATTR | BLUE_ATTR; const BYTE BRIGHT_MAGENTA = BRIGHT_ATTR | RED_ATTR | BLUE_ATTR;
const BYTE BRIGHT_CYAN = BRIGHT_ATTR | GREEN_ATTR | BLUE_ATTR; const BYTE BRIGHT_CYAN = BRIGHT_ATTR | GREEN_ATTR | BLUE_ATTR;
const BYTE BRIGHT_WHITE = BRIGHT_ATTR | RED_ATTR | GREEN_ATTR | BLUE_ATTR; const BYTE BRIGHT_WHITE = BRIGHT_ATTR | RED_ATTR | GREEN_ATTR | BLUE_ATTR;
// clang-format on
// Routine Description: // Routine Description:
// Returns true if the GraphicsOption represents an extended color option. // Returns true if the GraphicsOption represents an extended color option.
@ -78,8 +80,8 @@ bool TerminalDispatch::s_IsDefaultColorOption(const DispatchTypes::GraphicsOptio
// 3 - true, parsed an xterm index to a color // 3 - true, parsed an xterm index to a color
// 5 - true, parsed an RGB color. // 5 - true, parsed an RGB color.
bool TerminalDispatch::_SetRgbColorsHelper(_In_reads_(cOptions) const DispatchTypes::GraphicsOptions* const rgOptions, bool TerminalDispatch::_SetRgbColorsHelper(_In_reads_(cOptions) const DispatchTypes::GraphicsOptions* const rgOptions,
const size_t cOptions, const size_t cOptions,
_Out_ size_t* const pcOptionsConsumed) _Out_ size_t* const pcOptionsConsumed)
{ {
COLORREF color = 0; COLORREF color = 0;
bool isForeground = false; bool isForeground = false;
@ -105,9 +107,9 @@ bool TerminalDispatch::_SetRgbColorsHelper(_In_reads_(cOptions) const DispatchTy
{ {
*pcOptionsConsumed = 5; *pcOptionsConsumed = 5;
// ensure that each value fits in a byte // ensure that each value fits in a byte
unsigned int red = rgOptions[2] > 255? 255 : rgOptions[2]; unsigned int red = rgOptions[2] > 255 ? 255 : rgOptions[2];
unsigned int green = rgOptions[3] > 255? 255 : rgOptions[3]; unsigned int green = rgOptions[3] > 255 ? 255 : rgOptions[3];
unsigned int blue = rgOptions[4] > 255? 255 : rgOptions[4]; unsigned int blue = rgOptions[4] > 255 ? 255 : rgOptions[4];
color = RGB(red, green, blue); color = RGB(red, green, blue);
@ -120,8 +122,8 @@ bool TerminalDispatch::_SetRgbColorsHelper(_In_reads_(cOptions) const DispatchTy
{ {
unsigned int tableIndex = rgOptions[2]; unsigned int tableIndex = rgOptions[2];
fSuccess = isForeground ? fSuccess = isForeground ?
_terminalApi.SetTextForegroundIndex((BYTE)tableIndex) : _terminalApi.SetTextForegroundIndex((BYTE)tableIndex) :
_terminalApi.SetTextBackgroundIndex((BYTE)tableIndex); _terminalApi.SetTextBackgroundIndex((BYTE)tableIndex);
} }
} }
} }
@ -307,7 +309,7 @@ bool TerminalDispatch::SetGraphicsRendition(const DispatchTypes::GraphicsOptions
size_t cOptionsConsumed = 0; size_t cOptionsConsumed = 0;
// _SetRgbColorsHelper will call the appropriate ConApi function // _SetRgbColorsHelper will call the appropriate ConApi function
fSuccess = _SetRgbColorsHelper(&(rgOptions[i]), cOptions-i, &cOptionsConsumed); fSuccess = _SetRgbColorsHelper(&(rgOptions[i]), cOptions - i, &cOptionsConsumed);
i += (cOptionsConsumed - 1); // cOptionsConsumed includes the opt we're currently on. i += (cOptionsConsumed - 1); // cOptionsConsumed includes the opt we're currently on.
} }

View file

@ -128,14 +128,14 @@ const std::wstring Terminal::GetConsoleTitle() const noexcept
// operation. // operation.
// Callers should make sure to also call Terminal::UnlockConsole once // Callers should make sure to also call Terminal::UnlockConsole once
// they're done with any querying they need to do. // they're done with any querying they need to do.
void Terminal::LockConsole() noexcept void Terminal::LockConsole() noexcept
{ {
_readWriteLock.lock_shared(); _readWriteLock.lock_shared();
} }
// Method Description: // Method Description:
// - Unlocks the terminal after a call to Terminal::LockConsole. // - Unlocks the terminal after a call to Terminal::LockConsole.
void Terminal::UnlockConsole() noexcept void Terminal::UnlockConsole() noexcept
{ {
_readWriteLock.unlock_shared(); _readWriteLock.unlock_shared();
} }

View file

@ -32,7 +32,6 @@ namespace winrt::Microsoft::Terminal::Settings::implementation
_keyBindings{ nullptr }, _keyBindings{ nullptr },
_scrollbarState{ ScrollbarState::Visible } _scrollbarState{ ScrollbarState::Visible }
{ {
} }
uint32_t TerminalSettings::DefaultForeground() uint32_t TerminalSettings::DefaultForeground()

View file

@ -20,4 +20,3 @@
#include <unknwn.h> #include <unknwn.h>
#include <winrt/Windows.Foundation.h> #include <winrt/Windows.Foundation.h>

View file

@ -16,121 +16,117 @@ using namespace Microsoft::Terminal::Core;
namespace TerminalCoreUnitTests namespace TerminalCoreUnitTests
{ {
class MockTermSettings : public winrt::implements<MockTermSettings, ICoreSettings> class MockTermSettings : public winrt::implements<MockTermSettings, ICoreSettings>
{ {
public: public:
MockTermSettings(int32_t historySize, int32_t initialRows, int32_t initialCols) : MockTermSettings(int32_t historySize, int32_t initialRows, int32_t initialCols) :
_historySize(historySize), _historySize(historySize),
_initialRows(initialRows), _initialRows(initialRows),
_initialCols(initialCols) _initialCols(initialCols)
{ } {
}
// property getters - all implemented // property getters - all implemented
int32_t HistorySize() { return _historySize; } int32_t HistorySize() { return _historySize; }
int32_t InitialRows() { return _initialRows; } int32_t InitialRows() { return _initialRows; }
int32_t InitialCols() { return _initialCols; } int32_t InitialCols() { return _initialCols; }
uint32_t DefaultForeground() { return COLOR_WHITE; } uint32_t DefaultForeground() { return COLOR_WHITE; }
uint32_t DefaultBackground() { return COLOR_BLACK; } uint32_t DefaultBackground() { return COLOR_BLACK; }
bool SnapOnInput() { return false; } bool SnapOnInput() { return false; }
uint32_t CursorColor() { return COLOR_WHITE; } uint32_t CursorColor() { return COLOR_WHITE; }
CursorStyle CursorShape() const noexcept { return CursorStyle::Vintage; } CursorStyle CursorShape() const noexcept { return CursorStyle::Vintage; }
uint32_t CursorHeight() { return 42UL; } uint32_t CursorHeight() { return 42UL; }
// other implemented methods // other implemented methods
uint32_t GetColorTableEntry(int32_t) const { return 123; } uint32_t GetColorTableEntry(int32_t) const { return 123; }
// property setters - all unimplemented // property setters - all unimplemented
void HistorySize(int32_t) { } void HistorySize(int32_t) {}
void InitialRows(int32_t) { } void InitialRows(int32_t) {}
void InitialCols(int32_t) { } void InitialCols(int32_t) {}
void DefaultForeground(uint32_t) { } void DefaultForeground(uint32_t) {}
void DefaultBackground(uint32_t) { } void DefaultBackground(uint32_t) {}
void SnapOnInput(bool) { } void SnapOnInput(bool) {}
void CursorColor(uint32_t) { } void CursorColor(uint32_t) {}
void CursorShape(CursorStyle const&) noexcept { } void CursorShape(CursorStyle const&) noexcept {}
void CursorHeight(uint32_t) { } void CursorHeight(uint32_t) {}
// other unimplemented methods // other unimplemented methods
void SetColorTableEntry(int32_t /* index */, uint32_t /* value */) { } void SetColorTableEntry(int32_t /* index */, uint32_t /* value */) {}
private: private:
int32_t _historySize; int32_t _historySize;
int32_t _initialRows; int32_t _initialRows;
int32_t _initialCols; int32_t _initialCols;
}; };
#define WCS(x) WCSHELPER(x) #define WCS(x) WCSHELPER(x)
#define WCSHELPER(x) L#x #define WCSHELPER(x) L#x
class ScreenSizeLimitsTest class ScreenSizeLimitsTest
{
TEST_CLASS(ScreenSizeLimitsTest);
TEST_METHOD(ScreenWidthAndHeightAreClampedToBounds)
{ {
DummyRenderTarget emptyRenderTarget; TEST_CLASS(ScreenSizeLimitsTest);
// Negative values for initial visible row count or column count TEST_METHOD(ScreenWidthAndHeightAreClampedToBounds)
// are clamped to 1. Too-large positive values are clamped to SHRT_MAX. {
auto negativeColumnsSettings = winrt::make<MockTermSettings>(10000, 9999999, -1234); DummyRenderTarget emptyRenderTarget;
Terminal negativeColumnsTerminal;
negativeColumnsTerminal.CreateFromSettings(negativeColumnsSettings, emptyRenderTarget);
COORD actualDimensions = negativeColumnsTerminal.GetViewport().Dimensions();
VERIFY_ARE_EQUAL(actualDimensions.Y, SHRT_MAX, L"Row count clamped to SHRT_MAX == " WCS(SHRT_MAX));
VERIFY_ARE_EQUAL(actualDimensions.X, 1, L"Column count clamped to 1");
// Zero values are clamped to 1 as well. // Negative values for initial visible row count or column count
auto zeroRowsSettings = winrt::make<MockTermSettings>(10000, 0, 9999999); // are clamped to 1. Too-large positive values are clamped to SHRT_MAX.
Terminal zeroRowsTerminal; auto negativeColumnsSettings = winrt::make<MockTermSettings>(10000, 9999999, -1234);
zeroRowsTerminal.CreateFromSettings(zeroRowsSettings, emptyRenderTarget); Terminal negativeColumnsTerminal;
actualDimensions = zeroRowsTerminal.GetViewport().Dimensions(); negativeColumnsTerminal.CreateFromSettings(negativeColumnsSettings, emptyRenderTarget);
VERIFY_ARE_EQUAL(actualDimensions.Y, 1, L"Row count clamped to 1"); COORD actualDimensions = negativeColumnsTerminal.GetViewport().Dimensions();
VERIFY_ARE_EQUAL(actualDimensions.X, SHRT_MAX, L"Column count clamped to SHRT_MAX == " WCS(SHRT_MAX)); VERIFY_ARE_EQUAL(actualDimensions.Y, SHRT_MAX, L"Row count clamped to SHRT_MAX == " WCS(SHRT_MAX));
} VERIFY_ARE_EQUAL(actualDimensions.X, 1, L"Column count clamped to 1");
TEST_METHOD(ScrollbackHistorySizeIsClampedToBounds) // Zero values are clamped to 1 as well.
{ auto zeroRowsSettings = winrt::make<MockTermSettings>(10000, 0, 9999999);
// What is actually clamped is the number of rows in the internal history buffer, Terminal zeroRowsTerminal;
// which is the *sum* of the history size plus the number of rows zeroRowsTerminal.CreateFromSettings(zeroRowsSettings, emptyRenderTarget);
// actually visible on screen at the moment. actualDimensions = zeroRowsTerminal.GetViewport().Dimensions();
VERIFY_ARE_EQUAL(actualDimensions.Y, 1, L"Row count clamped to 1");
VERIFY_ARE_EQUAL(actualDimensions.X, SHRT_MAX, L"Column count clamped to SHRT_MAX == " WCS(SHRT_MAX));
}
const unsigned int visibleRowCount = 100; TEST_METHOD(ScrollbackHistorySizeIsClampedToBounds)
DummyRenderTarget emptyRenderTarget; {
// What is actually clamped is the number of rows in the internal history buffer,
// which is the *sum* of the history size plus the number of rows
// actually visible on screen at the moment.
// Zero history size is acceptable. const unsigned int visibleRowCount = 100;
auto noHistorySettings = winrt::make<MockTermSettings>(0, visibleRowCount, 100); DummyRenderTarget emptyRenderTarget;
Terminal noHistoryTerminal;
noHistoryTerminal.CreateFromSettings(noHistorySettings, emptyRenderTarget);
VERIFY_ARE_EQUAL(noHistoryTerminal.GetTextBuffer().TotalRowCount(), visibleRowCount,
L"History size of 0 is accepted");
// Negative history sizes are clamped to zero. // Zero history size is acceptable.
auto negativeHistorySizeSettings = winrt::make<MockTermSettings>(-100, visibleRowCount, 100); auto noHistorySettings = winrt::make<MockTermSettings>(0, visibleRowCount, 100);
Terminal negativeHistorySizeTerminal; Terminal noHistoryTerminal;
negativeHistorySizeTerminal.CreateFromSettings(negativeHistorySizeSettings, emptyRenderTarget); noHistoryTerminal.CreateFromSettings(noHistorySettings, emptyRenderTarget);
VERIFY_ARE_EQUAL(negativeHistorySizeTerminal.GetTextBuffer().TotalRowCount(), visibleRowCount, VERIFY_ARE_EQUAL(noHistoryTerminal.GetTextBuffer().TotalRowCount(), visibleRowCount, L"History size of 0 is accepted");
L"Negative history size is clamped to 0");
// History size + initial visible rows == SHRT_MAX is acceptable. // Negative history sizes are clamped to zero.
auto maxHistorySizeSettings = winrt::make<MockTermSettings>(SHRT_MAX - visibleRowCount, visibleRowCount, 100); auto negativeHistorySizeSettings = winrt::make<MockTermSettings>(-100, visibleRowCount, 100);
Terminal maxHistorySizeTerminal; Terminal negativeHistorySizeTerminal;
maxHistorySizeTerminal.CreateFromSettings(maxHistorySizeSettings, emptyRenderTarget); negativeHistorySizeTerminal.CreateFromSettings(negativeHistorySizeSettings, emptyRenderTarget);
VERIFY_ARE_EQUAL(maxHistorySizeTerminal.GetTextBuffer().TotalRowCount(), static_cast<unsigned int>(SHRT_MAX), VERIFY_ARE_EQUAL(negativeHistorySizeTerminal.GetTextBuffer().TotalRowCount(), visibleRowCount, L"Negative history size is clamped to 0");
L"History size == SHRT_MAX - initial row count is accepted");
// History size + initial visible rows == SHRT_MAX + 1 will be clamped slightly. // History size + initial visible rows == SHRT_MAX is acceptable.
auto justTooBigHistorySizeSettings = winrt::make<MockTermSettings>(SHRT_MAX - visibleRowCount + 1, visibleRowCount, 100); auto maxHistorySizeSettings = winrt::make<MockTermSettings>(SHRT_MAX - visibleRowCount, visibleRowCount, 100);
Terminal justTooBigHistorySizeTerminal; Terminal maxHistorySizeTerminal;
justTooBigHistorySizeTerminal.CreateFromSettings(justTooBigHistorySizeSettings, emptyRenderTarget); maxHistorySizeTerminal.CreateFromSettings(maxHistorySizeSettings, emptyRenderTarget);
VERIFY_ARE_EQUAL(justTooBigHistorySizeTerminal.GetTextBuffer().TotalRowCount(), static_cast<unsigned int>(SHRT_MAX), VERIFY_ARE_EQUAL(maxHistorySizeTerminal.GetTextBuffer().TotalRowCount(), static_cast<unsigned int>(SHRT_MAX), L"History size == SHRT_MAX - initial row count is accepted");
L"History size == 1 + SHRT_MAX - initial row count is clamped to SHRT_MAX - initial row count");
// Ridiculously large history sizes are also clamped. // History size + initial visible rows == SHRT_MAX + 1 will be clamped slightly.
auto farTooBigHistorySizeSettings = winrt::make<MockTermSettings>(99999999, visibleRowCount, 100); auto justTooBigHistorySizeSettings = winrt::make<MockTermSettings>(SHRT_MAX - visibleRowCount + 1, visibleRowCount, 100);
Terminal farTooBigHistorySizeTerminal; Terminal justTooBigHistorySizeTerminal;
farTooBigHistorySizeTerminal.CreateFromSettings(farTooBigHistorySizeSettings, emptyRenderTarget); justTooBigHistorySizeTerminal.CreateFromSettings(justTooBigHistorySizeSettings, emptyRenderTarget);
VERIFY_ARE_EQUAL(farTooBigHistorySizeTerminal.GetTextBuffer().TotalRowCount(), static_cast<unsigned int>(SHRT_MAX), VERIFY_ARE_EQUAL(justTooBigHistorySizeTerminal.GetTextBuffer().TotalRowCount(), static_cast<unsigned int>(SHRT_MAX), L"History size == 1 + SHRT_MAX - initial row count is clamped to SHRT_MAX - initial row count");
L"History size that is far too large is clamped to SHRT_MAX - initial row count");
} // Ridiculously large history sizes are also clamped.
}; auto farTooBigHistorySizeSettings = winrt::make<MockTermSettings>(99999999, visibleRowCount, 100);
Terminal farTooBigHistorySizeTerminal;
farTooBigHistorySizeTerminal.CreateFromSettings(farTooBigHistorySizeSettings, emptyRenderTarget);
VERIFY_ARE_EQUAL(farTooBigHistorySizeTerminal.GetTextBuffer().TotalRowCount(), static_cast<unsigned int>(SHRT_MAX), L"History size that is far too large is clamped to SHRT_MAX - initial row count");
}
};
} }

View file

@ -39,9 +39,9 @@ namespace TerminalCoreUnitTests
// Validate selection area // Validate selection area
VERIFY_ARE_EQUAL(selectionRects.size(), static_cast<size_t>(1)); VERIFY_ARE_EQUAL(selectionRects.size(), static_cast<size_t>(1));
auto selection = term.GetViewport().ConvertToOrigin(selectionRects.at(0)).ToInclusive(); auto selection = term.GetViewport().ConvertToOrigin(selectionRects.at(0)).ToInclusive();
VerifyCompareTraits<SMALL_RECT>::AreEqual({5, 10, 10, 5}, selection); VerifyCompareTraits<SMALL_RECT>::AreEqual({ 5, 10, 10, 5 }, selection);
} }
TEST_METHOD(SelectArea) TEST_METHOD(SelectArea)
@ -73,20 +73,20 @@ namespace TerminalCoreUnitTests
{ {
auto selection = viewport.ConvertToOrigin(selectionRect).ToInclusive(); auto selection = viewport.ConvertToOrigin(selectionRect).ToInclusive();
if (rowValue == 10) if (rowValue == 10)
{ {
// Verify top line // Verify top line
VerifyCompareTraits<SMALL_RECT>::AreEqual({5, 10, rightBoundary, 10}, selection); VerifyCompareTraits<SMALL_RECT>::AreEqual({ 5, 10, rightBoundary, 10 }, selection);
} }
else if (rowValue == 20) else if (rowValue == 20)
{ {
// Verify bottom line // Verify bottom line
VerifyCompareTraits<SMALL_RECT>::AreEqual({0, 20, 15, 20}, selection); VerifyCompareTraits<SMALL_RECT>::AreEqual({ 0, 20, 15, 20 }, selection);
} }
else else
{ {
// Verify other lines (full) // Verify other lines (full)
VerifyCompareTraits<SMALL_RECT>::AreEqual({0, rowValue, rightBoundary, rowValue}, selection); VerifyCompareTraits<SMALL_RECT>::AreEqual({ 0, rowValue, rightBoundary, rowValue }, selection);
} }
rowValue++; rowValue++;
@ -123,7 +123,7 @@ namespace TerminalCoreUnitTests
auto selection = viewport.ConvertToOrigin(selectionRect).ToInclusive(); auto selection = viewport.ConvertToOrigin(selectionRect).ToInclusive();
// Verify all lines // Verify all lines
VerifyCompareTraits<SMALL_RECT>::AreEqual({5, rowValue, 15, rowValue}, selection); VerifyCompareTraits<SMALL_RECT>::AreEqual({ 5, rowValue, 15, rowValue }, selection);
rowValue++; rowValue++;
} }
@ -135,7 +135,7 @@ namespace TerminalCoreUnitTests
DummyRenderTarget emptyRT; DummyRenderTarget emptyRT;
SHORT scrollbackLines = 5; SHORT scrollbackLines = 5;
term.Create({ 100, 100 }, scrollbackLines, emptyRT); term.Create({ 100, 100 }, scrollbackLines, emptyRT);
// Used for two things: // Used for two things:
// - click y-pos // - click y-pos
// - keep track of row we're verifying // - keep track of row we're verifying
@ -162,17 +162,17 @@ namespace TerminalCoreUnitTests
if (rowValue == 10) if (rowValue == 10)
{ {
// Verify top line // Verify top line
VerifyCompareTraits<SMALL_RECT>::AreEqual({5, 10, rightBoundary, 10}, selection); VerifyCompareTraits<SMALL_RECT>::AreEqual({ 5, 10, rightBoundary, 10 }, selection);
} }
else if (rowValue == 20) else if (rowValue == 20)
{ {
// Verify bottom line // Verify bottom line
VerifyCompareTraits<SMALL_RECT>::AreEqual({0, 20, 15, 20}, selection); VerifyCompareTraits<SMALL_RECT>::AreEqual({ 0, 20, 15, 20 }, selection);
} }
else else
{ {
// Verify other lines (full) // Verify other lines (full)
VerifyCompareTraits<SMALL_RECT>::AreEqual({0, rowValue, rightBoundary, rowValue}, selection); VerifyCompareTraits<SMALL_RECT>::AreEqual({ 0, rowValue, rightBoundary, rowValue }, selection);
} }
rowValue++; rowValue++;

View file

@ -102,7 +102,8 @@ void AppHost::AppTitleChanged(winrt::hstring newTitle)
// - <none> // - <none>
// Return Value: // Return Value:
// - <none> // - <none>
void AppHost::LastTabClosed() { void AppHost::LastTabClosed()
{
_window->Close(); _window->Close();
} }
@ -140,7 +141,8 @@ void AppHost::_HandleCreateWindow(const HWND hwnd, const RECT proposedRect)
// Create a RECT from our requested client size // Create a RECT from our requested client size
auto nonClient = Viewport::FromDimensions({ _currentWidth, auto nonClient = Viewport::FromDimensions({ _currentWidth,
_currentHeight }).ToRect(); _currentHeight })
.ToRect();
// Get the size of a window we'd need to host that client rect. This will // Get the size of a window we'd need to host that client rect. This will
// add the titlebar space. // add the titlebar space.
@ -166,11 +168,11 @@ void AppHost::_HandleCreateWindow(const HWND hwnd, const RECT proposedRect)
// size of our window, which will be at least close. // size of our window, which will be at least close.
LOG_LAST_ERROR(); LOG_LAST_ERROR();
nonClient = Viewport::FromDimensions({ _currentWidth, nonClient = Viewport::FromDimensions({ _currentWidth,
_currentHeight }).ToRect(); _currentHeight })
.ToRect();
} }
} }
const auto adjustedHeight = nonClient.bottom - nonClient.top; const auto adjustedHeight = nonClient.bottom - nonClient.top;
const auto adjustedWidth = nonClient.right - nonClient.left; const auto adjustedWidth = nonClient.right - nonClient.left;
@ -181,7 +183,8 @@ void AppHost::_HandleCreateWindow(const HWND hwnd, const RECT proposedRect)
const auto newPos = Viewport::FromDimensions(origin, dimensions); const auto newPos = Viewport::FromDimensions(origin, dimensions);
bool succeeded = SetWindowPos(hwnd, nullptr, bool succeeded = SetWindowPos(hwnd,
nullptr,
newPos.Left(), newPos.Left(),
newPos.Top(), newPos.Top(),
newPos.Width(), newPos.Width(),
@ -191,6 +194,4 @@ void AppHost::_HandleCreateWindow(const HWND hwnd, const RECT proposedRect)
// If we can't resize the window, that's really okay. We can just go on with // If we can't resize the window, that's really okay. We can just go on with
// the originally proposed window size. // the originally proposed window size.
LOG_LAST_ERROR_IF(!succeeded); LOG_LAST_ERROR_IF(!succeeded);
} }

View file

@ -4,26 +4,25 @@
#pragma once #pragma once
// Custom window messages // Custom window messages
#define CM_UPDATE_TITLE (WM_USER) #define CM_UPDATE_TITLE (WM_USER)
template <typename T> template<typename T>
class BaseWindow class BaseWindow
{ {
public: public:
virtual ~BaseWindow() = 0; virtual ~BaseWindow() = 0;
static T* GetThisFromHandle(HWND const window) noexcept static T* GetThisFromHandle(HWND const window) noexcept
{ {
return reinterpret_cast<T *>(GetWindowLongPtr(window, GWLP_USERDATA)); return reinterpret_cast<T*>(GetWindowLongPtr(window, GWLP_USERDATA));
} }
[[nodiscard]] [[nodiscard]] static LRESULT __stdcall WndProc(HWND const window, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept
static LRESULT __stdcall WndProc(HWND const window, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept
{ {
WINRT_ASSERT(window); WINRT_ASSERT(window);
if (WM_NCCREATE == message) if (WM_NCCREATE == message)
{ {
auto cs = reinterpret_cast<CREATESTRUCT *>(lparam); auto cs = reinterpret_cast<CREATESTRUCT*>(lparam);
T* that = static_cast<T*>(cs->lpCreateParams); T* that = static_cast<T*>(cs->lpCreateParams);
WINRT_ASSERT(that); WINRT_ASSERT(that);
WINRT_ASSERT(!that->_window); WINRT_ASSERT(!that->_window);
@ -41,10 +40,10 @@ public:
return DefWindowProc(window, message, wparam, lparam); return DefWindowProc(window, message, wparam, lparam);
} }
[[nodiscard]] [[nodiscard]] virtual LRESULT MessageHandler(UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept
virtual LRESULT MessageHandler(UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept
{ {
switch (message) { switch (message)
{
case WM_DPICHANGED: case WM_DPICHANGED:
{ {
return HandleDpiChange(_window, wparam, lparam); return HandleDpiChange(_window, wparam, lparam);
@ -100,8 +99,7 @@ public:
} }
// DPI Change handler. on WM_DPICHANGE resize the window // DPI Change handler. on WM_DPICHANGE resize the window
[[nodiscard]] [[nodiscard]] LRESULT HandleDpiChange(const HWND hWnd, const WPARAM wParam, const LPARAM lParam)
LRESULT HandleDpiChange(const HWND hWnd, const WPARAM wParam, const LPARAM lParam)
{ {
_inDpiChange = true; _inDpiChange = true;
const HWND hWndStatic = GetWindow(hWnd, GW_CHILD); const HWND hWndStatic = GetWindow(hWnd, GW_CHILD);
@ -112,9 +110,7 @@ public:
// Resize the window // Resize the window
auto lprcNewScale = reinterpret_cast<RECT*>(lParam); auto lprcNewScale = reinterpret_cast<RECT*>(lParam);
SetWindowPos(hWnd, nullptr, lprcNewScale->left, lprcNewScale->top, SetWindowPos(hWnd, nullptr, lprcNewScale->left, lprcNewScale->top, lprcNewScale->right - lprcNewScale->left, lprcNewScale->bottom - lprcNewScale->top, SWP_NOZORDER | SWP_NOACTIVATE);
lprcNewScale->right - lprcNewScale->left, lprcNewScale->bottom - lprcNewScale->top,
SWP_NOZORDER | SWP_NOACTIVATE);
_currentDpi = uDpi; _currentDpi = uDpi;
} }
@ -202,5 +198,7 @@ protected:
bool _minimized = false; bool _minimized = false;
}; };
template <typename T> template<typename T>
inline BaseWindow<T>::~BaseWindow() { } inline BaseWindow<T>::~BaseWindow()
{
}

View file

@ -49,13 +49,18 @@ void IslandWindow::MakeWindow() noexcept
// window, the system will give us a chance to set its size in WM_CREATE. // window, the system will give us a chance to set its size in WM_CREATE.
// WM_CREATE will be handled synchronously, before CreateWindow returns. // WM_CREATE will be handled synchronously, before CreateWindow returns.
WINRT_VERIFY(CreateWindow(wc.lpszClassName, WINRT_VERIFY(CreateWindow(wc.lpszClassName,
L"Windows Terminal", L"Windows Terminal",
WS_OVERLAPPEDWINDOW, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
nullptr, nullptr, wc.hInstance, this)); CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
nullptr,
nullptr,
wc.hInstance,
this));
WINRT_ASSERT(_window); WINRT_ASSERT(_window);
} }
// Method Description: // Method Description:
@ -144,11 +149,10 @@ void IslandWindow::OnSize()
} }
} }
[[nodiscard]] [[nodiscard]] LRESULT IslandWindow::MessageHandler(UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept
LRESULT IslandWindow::MessageHandler(UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept
{ {
switch (message) { switch (message)
{
case WM_CREATE: case WM_CREATE:
{ {
_HandleCreateWindow(wparam, lparam); _HandleCreateWindow(wparam, lparam);
@ -205,4 +209,3 @@ void IslandWindow::SetRootContent(winrt::Windows::UI::Xaml::UIElement content)
_rootGrid.Children().Clear(); _rootGrid.Children().Clear();
_rootGrid.Children().Append(content); _rootGrid.Children().Append(content);
} }

View file

@ -16,8 +16,7 @@ public:
void Close(); void Close();
virtual void OnSize(); virtual void OnSize();
[[nodiscard]] [[nodiscard]] virtual LRESULT MessageHandler(UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept override;
virtual LRESULT MessageHandler(UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept override;
void OnResize(const UINT width, const UINT height) override; void OnResize(const UINT width, const UINT height) override;
void OnMinimize() override; void OnMinimize() override;
void OnRestore() override; void OnRestore() override;

View file

@ -25,7 +25,7 @@ constexpr int RECT_HEIGHT(const RECT* const pRect)
} }
NonClientIslandWindow::NonClientIslandWindow() noexcept : NonClientIslandWindow::NonClientIslandWindow() noexcept :
IslandWindow{ }, IslandWindow{},
_nonClientInteropWindowHandle{ nullptr }, _nonClientInteropWindowHandle{ nullptr },
_nonClientRootGrid{ nullptr }, _nonClientRootGrid{ nullptr },
_nonClientSource{ nullptr }, _nonClientSource{ nullptr },
@ -71,7 +71,6 @@ void NonClientIslandWindow::SetNonClientContent(winrt::Windows::UI::Xaml::UIElem
_nonClientRootGrid.Children().Append(content); _nonClientRootGrid.Children().Append(content);
} }
// Method Description: // Method Description:
// - Set the height we expect to reserve for the non-client content. // - Set the height we expect to reserve for the non-client content.
// Arguments: // Arguments:
@ -104,7 +103,6 @@ Viewport NonClientIslandWindow::GetTitlebarContentArea() const noexcept
const auto titlebarHeight = titlebarContentHeight - (_titlebarMarginTop + _titlebarMarginBottom); const auto titlebarHeight = titlebarContentHeight - (_titlebarMarginTop + _titlebarMarginBottom);
COORD titlebarOrigin = { static_cast<short>(_windowMarginSides), COORD titlebarOrigin = { static_cast<short>(_windowMarginSides),
static_cast<short>(_titlebarMarginTop) }; static_cast<short>(_titlebarMarginTop) };
@ -172,7 +170,8 @@ void NonClientIslandWindow::OnSize()
auto titlebarArea = GetTitlebarContentArea(); auto titlebarArea = GetTitlebarContentArea();
// update the interop window size // update the interop window size
SetWindowPos(_interopWindowHandle, 0, SetWindowPos(_interopWindowHandle,
0,
clientArea.Left(), clientArea.Left(),
clientArea.Top(), clientArea.Top(),
clientArea.Width(), clientArea.Width(),
@ -188,7 +187,8 @@ void NonClientIslandWindow::OnSize()
} }
// update the interop window size // update the interop window size
SetWindowPos(_nonClientInteropWindowHandle, 0, SetWindowPos(_nonClientInteropWindowHandle,
0,
titlebarArea.Left(), titlebarArea.Left(),
titlebarArea.Top(), titlebarArea.Top(),
titlebarArea.Width(), titlebarArea.Width(),
@ -209,8 +209,7 @@ void NonClientIslandWindow::OnSize()
// NOTE: // NOTE:
// Largely taken from code on: // Largely taken from code on:
// https://docs.microsoft.com/en-us/windows/desktop/dwm/customframe // https://docs.microsoft.com/en-us/windows/desktop/dwm/customframe
[[nodiscard]] [[nodiscard]] LRESULT NonClientIslandWindow::HitTestNCA(POINT ptMouse) const noexcept
LRESULT NonClientIslandWindow::HitTestNCA(POINT ptMouse) const noexcept
{ {
// Get the window rectangle. // Get the window rectangle.
RECT rcWindow = BaseWindow::GetWindowRect(); RECT rcWindow = BaseWindow::GetWindowRect();
@ -249,13 +248,14 @@ LRESULT NonClientIslandWindow::HitTestNCA(POINT ptMouse) const noexcept
uCol = 2; // right side uCol = 2; // right side
} }
// clang-format off
// Hit test (HTTOPLEFT, ... HTBOTTOMRIGHT) // Hit test (HTTOPLEFT, ... HTBOTTOMRIGHT)
LRESULT hitTests[3][3] = LRESULT hitTests[3][3] = {
{ { HTTOPLEFT, fOnResizeBorder ? HTTOP : HTCAPTION, HTTOPRIGHT },
{ HTTOPLEFT, fOnResizeBorder ? HTTOP : HTCAPTION, HTTOPRIGHT }, { HTLEFT, HTNOWHERE, HTRIGHT },
{ HTLEFT, HTNOWHERE, HTRIGHT }, { HTBOTTOMLEFT, HTBOTTOM, HTBOTTOMRIGHT },
{ HTBOTTOMLEFT, HTBOTTOM, HTBOTTOMRIGHT },
}; };
// clang-format on
return hitTests[uRow][uCol]; return hitTests[uRow][uCol];
} }
@ -270,7 +270,7 @@ MARGINS NonClientIslandWindow::GetFrameMargins() const noexcept
{ {
const auto titlebarView = GetTitlebarContentArea(); const auto titlebarView = GetTitlebarContentArea();
MARGINS margins{0}; MARGINS margins{ 0 };
margins.cxLeftWidth = _windowMarginSides; margins.cxLeftWidth = _windowMarginSides;
margins.cxRightWidth = _windowMarginSides; margins.cxRightWidth = _windowMarginSides;
margins.cyBottomHeight = _windowMarginBottom; margins.cyBottomHeight = _windowMarginBottom;
@ -285,8 +285,7 @@ MARGINS NonClientIslandWindow::GetFrameMargins() const noexcept
// - <none> // - <none>
// Return Value: // Return Value:
// - the HRESULT returned by DwmExtendFrameIntoClientArea. // - the HRESULT returned by DwmExtendFrameIntoClientArea.
[[nodiscard]] [[nodiscard]] HRESULT NonClientIslandWindow::_UpdateFrameMargins() const noexcept
HRESULT NonClientIslandWindow::_UpdateFrameMargins() const noexcept
{ {
// Get the size of the borders we want to use. The sides and bottom will // Get the size of the borders we want to use. The sides and bottom will
// just be big enough for resizing, but the top will be as big as we need // just be big enough for resizing, but the top will be as big as we need
@ -314,8 +313,8 @@ HRESULT NonClientIslandWindow::_UpdateFrameMargins() const noexcept
// origin in pixels. Measures the outer edges of the potential window. // origin in pixels. Measures the outer edges of the potential window.
// NOTE: // NOTE:
// Heavily taken from WindowMetrics::GetMaxWindowRectInPixels in conhost. // Heavily taken from WindowMetrics::GetMaxWindowRectInPixels in conhost.
RECT NonClientIslandWindow::GetMaxWindowRectInPixels(const RECT * const prcSuggested, RECT NonClientIslandWindow::GetMaxWindowRectInPixels(const RECT* const prcSuggested,
_Out_opt_ UINT * pDpiSuggested) _Out_opt_ UINT* pDpiSuggested)
{ {
// prepare rectangle // prepare rectangle
RECT rc = *prcSuggested; RECT rc = *prcSuggested;
@ -389,10 +388,9 @@ RECT NonClientIslandWindow::GetMaxWindowRectInPixels(const RECT * const prcSugge
// Return Value: // Return Value:
// - The return value is the result of the message processing and depends on the // - The return value is the result of the message processing and depends on the
// message sent. // message sent.
[[nodiscard]] [[nodiscard]] LRESULT NonClientIslandWindow::MessageHandler(UINT const message,
LRESULT NonClientIslandWindow::MessageHandler(UINT const message, WPARAM const wParam,
WPARAM const wParam, LPARAM const lParam) noexcept
LPARAM const lParam) noexcept
{ {
LRESULT lRet = 0; LRESULT lRet = 0;
@ -417,11 +415,11 @@ LRESULT NonClientIslandWindow::MessageHandler(UINT const message,
if (wParam == TRUE && lParam) if (wParam == TRUE && lParam)
{ {
// Calculate new NCCALCSIZE_PARAMS based on custom NCA inset. // Calculate new NCCALCSIZE_PARAMS based on custom NCA inset.
NCCALCSIZE_PARAMS *pncsp = reinterpret_cast<NCCALCSIZE_PARAMS*>(lParam); NCCALCSIZE_PARAMS* pncsp = reinterpret_cast<NCCALCSIZE_PARAMS*>(lParam);
pncsp->rgrc[0].left = pncsp->rgrc[0].left + 0; pncsp->rgrc[0].left = pncsp->rgrc[0].left + 0;
pncsp->rgrc[0].top = pncsp->rgrc[0].top + 0; pncsp->rgrc[0].top = pncsp->rgrc[0].top + 0;
pncsp->rgrc[0].right = pncsp->rgrc[0].right - 0; pncsp->rgrc[0].right = pncsp->rgrc[0].right - 0;
pncsp->rgrc[0].bottom = pncsp->rgrc[0].bottom - 0; pncsp->rgrc[0].bottom = pncsp->rgrc[0].bottom - 0;
return 0; return 0;
@ -438,7 +436,7 @@ LRESULT NonClientIslandWindow::MessageHandler(UINT const message,
// Handle hit testing in the NCA if not handled by DwmDefWindowProc. // Handle hit testing in the NCA if not handled by DwmDefWindowProc.
if (lRet == 0) if (lRet == 0)
{ {
lRet = HitTestNCA({ GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)}); lRet = HitTestNCA({ GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) });
if (lRet != HTNOWHERE) if (lRet != HTNOWHERE)
{ {
@ -466,7 +464,6 @@ LRESULT NonClientIslandWindow::MessageHandler(UINT const message,
break; break;
} }
} }
} }
return IslandWindow::MessageHandler(message, wParam, lParam); return IslandWindow::MessageHandler(message, wParam, lParam);
@ -609,9 +606,9 @@ bool NonClientIslandWindow::_HandleWindowPosChanging(WINDOWPOS* const windowPos)
// change, so we're likely to shrink the window too much or worse yet, // change, so we're likely to shrink the window too much or worse yet,
// keep it from moving entirely. We'll get a WM_DPICHANGED, resize the // keep it from moving entirely. We'll get a WM_DPICHANGED, resize the
// window, and then process the restriction in a few window messages. // window, and then process the restriction in a few window messages.
if ( ((int)dpiOfMaximum == _currentDpi) && if (((int)dpiOfMaximum == _currentDpi) &&
( (suggestedWidth > maxWidth) || ((suggestedWidth > maxWidth) ||
(suggestedHeight > maxHeight) ) ) (suggestedHeight > maxHeight)))
{ {
auto offset = 0; auto offset = 0;
// Determine which side of the window to use for the offset // Determine which side of the window to use for the offset
@ -642,7 +639,7 @@ bool NonClientIslandWindow::_HandleWindowPosChanging(WINDOWPOS* const windowPos)
else else
{ {
// Clear our maximization state // Clear our maximization state
_maximizedMargins = {0}; _maximizedMargins = { 0 };
// Immediately after resoring down, don't update our frame margins. If // Immediately after resoring down, don't update our frame margins. If
// you do this here, then a small gap will appear between the titlebar // you do this here, then a small gap will appear between the titlebar

View file

@ -31,8 +31,7 @@ public:
virtual void OnSize() override; virtual void OnSize() override;
[[nodiscard]] [[nodiscard]] virtual LRESULT MessageHandler(UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept override;
virtual LRESULT MessageHandler(UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept override;
void SetNonClientContent(winrt::Windows::UI::Xaml::UIElement content); void SetNonClientContent(winrt::Windows::UI::Xaml::UIElement content);
@ -43,7 +42,6 @@ public:
void SetNonClientHeight(const int contentHeight) noexcept; void SetNonClientHeight(const int contentHeight) noexcept;
private: private:
winrt::Windows::UI::Xaml::Hosting::DesktopWindowXamlSource _nonClientSource; winrt::Windows::UI::Xaml::Hosting::DesktopWindowXamlSource _nonClientSource;
HWND _nonClientInteropWindowHandle; HWND _nonClientInteropWindowHandle;
@ -63,14 +61,12 @@ private:
MARGINS _maximizedMargins; MARGINS _maximizedMargins;
bool _isMaximized; bool _isMaximized;
[[nodiscard]] [[nodiscard]] LRESULT HitTestNCA(POINT ptMouse) const noexcept;
LRESULT HitTestNCA(POINT ptMouse) const noexcept;
[[nodiscard]] [[nodiscard]] HRESULT _UpdateFrameMargins() const noexcept;
HRESULT _UpdateFrameMargins() const noexcept;
void _HandleActivateWindow(); void _HandleActivateWindow();
bool _HandleWindowPosChanging(WINDOWPOS* const windowPos); bool _HandleWindowPosChanging(WINDOWPOS* const windowPos);
RECT GetMaxWindowRectInPixels(const RECT * const prcSuggested, _Out_opt_ UINT * pDpiSuggested); RECT GetMaxWindowRectInPixels(const RECT* const prcSuggested, _Out_opt_ UINT* pDpiSuggested);
}; };

View file

@ -6,9 +6,9 @@
// //
#ifdef APSTUDIO_INVOKED #ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS #ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 103 #define _APS_NEXT_RESOURCE_VALUE 103
#define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001 #define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101 #define _APS_NEXT_SYMED_VALUE 101
#endif #endif
#endif #endif

View file

@ -20,30 +20,32 @@ Revision History:
// This is a helper macro to make declaring events easier. // This is a helper macro to make declaring events easier.
// This will declare the event handler and the methods for adding and removing a // This will declare the event handler and the methods for adding and removing a
// handler callback from the event // handler callback from the event
#define DECLARE_EVENT(name, eventHandler, args) \ #define DECLARE_EVENT(name, eventHandler, args) \
public: \ public: \
winrt::event_token name(args const& handler); \ winrt::event_token name(args const& handler); \
void name(winrt::event_token const& token) noexcept; \ void name(winrt::event_token const& token) noexcept; \
private: \ \
private: \
winrt::event<args> eventHandler; winrt::event<args> eventHandler;
// This is a helper macro for defining the body of events. // This is a helper macro for defining the body of events.
// Winrt events need a method for adding a callback to the event and removing // Winrt events need a method for adding a callback to the event and removing
// the callback. This macro will define them both for you, because they // the callback. This macro will define them both for you, because they
// don't really vary from event to event. // don't really vary from event to event.
#define DEFINE_EVENT(className, name, eventHandler, args) \ #define DEFINE_EVENT(className, name, eventHandler, args) \
winrt::event_token className::name(args const& handler) { return eventHandler.add(handler); } \ winrt::event_token className::name(args const& handler) { return eventHandler.add(handler); } \
void className::name(winrt::event_token const& token) noexcept { eventHandler.remove(token); } void className::name(winrt::event_token const& token) noexcept { eventHandler.remove(token); }
// This is a helper macro to make declaring events easier. // This is a helper macro to make declaring events easier.
// This will declare the event handler and the methods for adding and removing a // This will declare the event handler and the methods for adding and removing a
// handler callback from the event. // handler callback from the event.
// Use this if you have a Windows.Foundation.TypedEventHandler // Use this if you have a Windows.Foundation.TypedEventHandler
#define DECLARE_EVENT_WITH_TYPED_EVENT_HANDLER(name, eventHandler, sender, args) \ #define DECLARE_EVENT_WITH_TYPED_EVENT_HANDLER(name, eventHandler, sender, args) \
public: \ public: \
winrt::event_token name(Windows::Foundation::TypedEventHandler<sender, args> const& handler); \ winrt::event_token name(Windows::Foundation::TypedEventHandler<sender, args> const& handler); \
void name(winrt::event_token const& token) noexcept; \ void name(winrt::event_token const& token) noexcept; \
private: \ \
private: \
winrt::event<Windows::Foundation::TypedEventHandler<sender, args>> eventHandler; winrt::event<Windows::Foundation::TypedEventHandler<sender, args>> eventHandler;
// This is a helper macro for defining the body of events. // This is a helper macro for defining the body of events.
@ -51,6 +53,6 @@ Revision History:
// the callback. This macro will define them both for you, because they // the callback. This macro will define them both for you, because they
// don't really vary from event to event. // don't really vary from event to event.
// Use this if you have a Windows.Foundation.TypedEventHandler // Use this if you have a Windows.Foundation.TypedEventHandler
#define DEFINE_EVENT_WITH_TYPED_EVENT_HANDLER(className, name, eventHandler, sender, args) \ #define DEFINE_EVENT_WITH_TYPED_EVENT_HANDLER(className, name, eventHandler, sender, args) \
winrt::event_token className::name(Windows::Foundation::TypedEventHandler<sender, args> const& handler) { return eventHandler.add(handler); } \ winrt::event_token className::name(Windows::Foundation::TypedEventHandler<sender, args> const& handler) { return eventHandler.add(handler); } \
void className::name(winrt::event_token const& token) noexcept { eventHandler.remove(token); } void className::name(winrt::event_token const& token) noexcept { eventHandler.remove(token); }

View file

@ -40,111 +40,96 @@ public:
void GetConsoleOutputModeImpl(SCREEN_INFORMATION& context, void GetConsoleOutputModeImpl(SCREEN_INFORMATION& context,
ULONG& mode) noexcept override; ULONG& mode) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT SetConsoleInputModeImpl(InputBuffer& context,
HRESULT SetConsoleInputModeImpl(InputBuffer& context, const ULONG mode) noexcept override;
const ULONG mode) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT SetConsoleOutputModeImpl(SCREEN_INFORMATION& context,
HRESULT SetConsoleOutputModeImpl(SCREEN_INFORMATION& context, const ULONG Mode) noexcept override;
const ULONG Mode) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT GetNumberOfConsoleInputEventsImpl(const InputBuffer& context,
HRESULT GetNumberOfConsoleInputEventsImpl(const InputBuffer& context, ULONG& events) noexcept override;
ULONG& events) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT PeekConsoleInputAImpl(IConsoleInputObject& context,
HRESULT PeekConsoleInputAImpl(IConsoleInputObject& context, std::deque<std::unique_ptr<IInputEvent>>& outEvents,
std::deque<std::unique_ptr<IInputEvent>>& outEvents, const size_t eventsToRead,
const size_t eventsToRead, INPUT_READ_HANDLE_DATA& readHandleState,
INPUT_READ_HANDLE_DATA& readHandleState, std::unique_ptr<IWaitRoutine>& waiter) noexcept override;
std::unique_ptr<IWaitRoutine>& waiter) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT PeekConsoleInputWImpl(IConsoleInputObject& context,
HRESULT PeekConsoleInputWImpl(IConsoleInputObject& context, std::deque<std::unique_ptr<IInputEvent>>& outEvents,
std::deque<std::unique_ptr<IInputEvent>>& outEvents, const size_t eventsToRead,
const size_t eventsToRead, INPUT_READ_HANDLE_DATA& readHandleState,
INPUT_READ_HANDLE_DATA& readHandleState, std::unique_ptr<IWaitRoutine>& waiter) noexcept override;
std::unique_ptr<IWaitRoutine>& waiter) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT ReadConsoleInputAImpl(IConsoleInputObject& context,
HRESULT ReadConsoleInputAImpl(IConsoleInputObject& context, std::deque<std::unique_ptr<IInputEvent>>& outEvents,
std::deque<std::unique_ptr<IInputEvent>>& outEvents, const size_t eventsToRead,
const size_t eventsToRead, INPUT_READ_HANDLE_DATA& readHandleState,
INPUT_READ_HANDLE_DATA& readHandleState, std::unique_ptr<IWaitRoutine>& waiter) noexcept override;
std::unique_ptr<IWaitRoutine>& waiter) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT ReadConsoleInputWImpl(IConsoleInputObject& context,
HRESULT ReadConsoleInputWImpl(IConsoleInputObject& context, std::deque<std::unique_ptr<IInputEvent>>& outEvents,
std::deque<std::unique_ptr<IInputEvent>>& outEvents, const size_t eventsToRead,
const size_t eventsToRead, INPUT_READ_HANDLE_DATA& readHandleState,
INPUT_READ_HANDLE_DATA& readHandleState, std::unique_ptr<IWaitRoutine>& waiter) noexcept override;
std::unique_ptr<IWaitRoutine>& waiter) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT ReadConsoleAImpl(IConsoleInputObject& context,
HRESULT ReadConsoleAImpl(IConsoleInputObject& context, gsl::span<char> buffer,
gsl::span<char> buffer, size_t& written,
size_t& written, std::unique_ptr<IWaitRoutine>& waiter,
std::unique_ptr<IWaitRoutine>& waiter, const std::string_view initialData,
const std::string_view initialData, const std::wstring_view exeName,
const std::wstring_view exeName, INPUT_READ_HANDLE_DATA& readHandleState,
INPUT_READ_HANDLE_DATA& readHandleState, const HANDLE clientHandle,
const HANDLE clientHandle, const DWORD controlWakeupMask,
const DWORD controlWakeupMask, DWORD& controlKeyState) noexcept override;
DWORD& controlKeyState) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT ReadConsoleWImpl(IConsoleInputObject& context,
HRESULT ReadConsoleWImpl(IConsoleInputObject& context, gsl::span<char> buffer,
gsl::span<char> buffer, size_t& written,
size_t& written, std::unique_ptr<IWaitRoutine>& waiter,
std::unique_ptr<IWaitRoutine>& waiter, const std::string_view initialData,
const std::string_view initialData, const std::wstring_view exeName,
const std::wstring_view exeName, INPUT_READ_HANDLE_DATA& readHandleState,
INPUT_READ_HANDLE_DATA& readHandleState, const HANDLE clientHandle,
const HANDLE clientHandle, const DWORD controlWakeupMask,
const DWORD controlWakeupMask, DWORD& controlKeyState) noexcept override;
DWORD& controlKeyState) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT WriteConsoleAImpl(IConsoleOutputObject& context,
HRESULT WriteConsoleAImpl(IConsoleOutputObject& context, const std::string_view buffer,
const std::string_view buffer, size_t& read,
size_t& read, std::unique_ptr<IWaitRoutine>& waiter) noexcept override;
std::unique_ptr<IWaitRoutine>& waiter) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT WriteConsoleWImpl(IConsoleOutputObject& context,
HRESULT WriteConsoleWImpl(IConsoleOutputObject& context, const std::wstring_view buffer,
const std::wstring_view buffer, size_t& read,
size_t& read, std::unique_ptr<IWaitRoutine>& waiter) noexcept override;
std::unique_ptr<IWaitRoutine>& waiter) noexcept override;
#pragma region ThreadCreationInfo #pragma region ThreadCreationInfo
[[nodiscard]] [[nodiscard]] HRESULT GetConsoleLangIdImpl(LANGID& langId) noexcept override;
HRESULT GetConsoleLangIdImpl(LANGID& langId) noexcept override;
#pragma endregion #pragma endregion
#pragma endregion #pragma endregion
#pragma region L2 #pragma region L2
[[nodiscard]] [[nodiscard]] HRESULT FillConsoleOutputAttributeImpl(IConsoleOutputObject& OutContext,
HRESULT FillConsoleOutputAttributeImpl(IConsoleOutputObject& OutContext, const WORD attribute,
const WORD attribute, const size_t lengthToWrite,
const size_t lengthToWrite, const COORD startingCoordinate,
const COORD startingCoordinate, size_t& cellsModified) noexcept override;
size_t& cellsModified) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT FillConsoleOutputCharacterAImpl(IConsoleOutputObject& OutContext,
HRESULT FillConsoleOutputCharacterAImpl(IConsoleOutputObject& OutContext, const char character,
const char character, const size_t lengthToWrite,
const size_t lengthToWrite, const COORD startingCoordinate,
const COORD startingCoordinate, size_t& cellsModified) noexcept override;
size_t& cellsModified) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT FillConsoleOutputCharacterWImpl(IConsoleOutputObject& OutContext,
HRESULT FillConsoleOutputCharacterWImpl(IConsoleOutputObject& OutContext, const wchar_t character,
const wchar_t character, const size_t lengthToWrite,
const size_t lengthToWrite, const COORD startingCoordinate,
const COORD startingCoordinate, size_t& cellsModified) noexcept override;
size_t& cellsModified) noexcept override;
//// Process based. Restrict in protocol side? //// Process based. Restrict in protocol side?
//HRESULT GenerateConsoleCtrlEventImpl(const ULONG ProcessGroupFilter, //HRESULT GenerateConsoleCtrlEventImpl(const ULONG ProcessGroupFilter,
@ -154,273 +139,222 @@ public:
void FlushConsoleInputBuffer(InputBuffer& context) noexcept override; void FlushConsoleInputBuffer(InputBuffer& context) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT SetConsoleInputCodePageImpl(const ULONG codepage) noexcept override;
HRESULT SetConsoleInputCodePageImpl(const ULONG codepage) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT SetConsoleOutputCodePageImpl(const ULONG codepage) noexcept override;
HRESULT SetConsoleOutputCodePageImpl(const ULONG codepage) noexcept override;
void GetConsoleCursorInfoImpl(const SCREEN_INFORMATION& context, void GetConsoleCursorInfoImpl(const SCREEN_INFORMATION& context,
ULONG& size, ULONG& size,
bool& isVisible) noexcept override; bool& isVisible) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT SetConsoleCursorInfoImpl(SCREEN_INFORMATION& context,
HRESULT SetConsoleCursorInfoImpl(SCREEN_INFORMATION& context, const ULONG size,
const ULONG size, const bool isVisible) noexcept override;
const bool isVisible) noexcept override;
//// driver will pare down for non-Ex method //// driver will pare down for non-Ex method
void GetConsoleScreenBufferInfoExImpl(const SCREEN_INFORMATION& context, void GetConsoleScreenBufferInfoExImpl(const SCREEN_INFORMATION& context,
CONSOLE_SCREEN_BUFFER_INFOEX& data) noexcept override; CONSOLE_SCREEN_BUFFER_INFOEX& data) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT SetConsoleScreenBufferInfoExImpl(SCREEN_INFORMATION& context,
HRESULT SetConsoleScreenBufferInfoExImpl(SCREEN_INFORMATION& context, const CONSOLE_SCREEN_BUFFER_INFOEX& data) noexcept override;
const CONSOLE_SCREEN_BUFFER_INFOEX& data) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT SetConsoleScreenBufferSizeImpl(SCREEN_INFORMATION& context,
HRESULT SetConsoleScreenBufferSizeImpl(SCREEN_INFORMATION& context, const COORD size) noexcept override;
const COORD size) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT SetConsoleCursorPositionImpl(SCREEN_INFORMATION& context,
HRESULT SetConsoleCursorPositionImpl(SCREEN_INFORMATION& context, const COORD position) noexcept override;
const COORD position) noexcept override;
void GetLargestConsoleWindowSizeImpl(const SCREEN_INFORMATION& context, void GetLargestConsoleWindowSizeImpl(const SCREEN_INFORMATION& context,
COORD& size) noexcept override; COORD& size) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT ScrollConsoleScreenBufferAImpl(SCREEN_INFORMATION& context,
HRESULT ScrollConsoleScreenBufferAImpl(SCREEN_INFORMATION& context, const SMALL_RECT& source,
const SMALL_RECT& source, const COORD target,
const COORD target, std::optional<SMALL_RECT> clip,
std::optional<SMALL_RECT> clip, const char fillCharacter,
const char fillCharacter, const WORD fillAttribute) noexcept override;
const WORD fillAttribute) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT ScrollConsoleScreenBufferWImpl(SCREEN_INFORMATION& context,
HRESULT ScrollConsoleScreenBufferWImpl(SCREEN_INFORMATION& context, const SMALL_RECT& source,
const SMALL_RECT& source, const COORD target,
const COORD target, std::optional<SMALL_RECT> clip,
std::optional<SMALL_RECT> clip, const wchar_t fillCharacter,
const wchar_t fillCharacter, const WORD fillAttribute) noexcept override;
const WORD fillAttribute) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT SetConsoleTextAttributeImpl(SCREEN_INFORMATION& context,
HRESULT SetConsoleTextAttributeImpl(SCREEN_INFORMATION& context, const WORD attribute) noexcept override;
const WORD attribute) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT SetConsoleWindowInfoImpl(SCREEN_INFORMATION& context,
HRESULT SetConsoleWindowInfoImpl(SCREEN_INFORMATION& context, const bool isAbsolute,
const bool isAbsolute, const SMALL_RECT& windowRect) noexcept override;
const SMALL_RECT& windowRect) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT ReadConsoleOutputAttributeImpl(const SCREEN_INFORMATION& context,
HRESULT ReadConsoleOutputAttributeImpl(const SCREEN_INFORMATION& context, const COORD origin,
const COORD origin, gsl::span<WORD> buffer,
gsl::span<WORD> buffer, size_t& written) noexcept override;
size_t& written) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT ReadConsoleOutputCharacterAImpl(const SCREEN_INFORMATION& context,
HRESULT ReadConsoleOutputCharacterAImpl(const SCREEN_INFORMATION& context, const COORD origin,
const COORD origin, gsl::span<char> buffer,
gsl::span<char> buffer, size_t& written) noexcept override;
size_t& written) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT ReadConsoleOutputCharacterWImpl(const SCREEN_INFORMATION& context,
HRESULT ReadConsoleOutputCharacterWImpl(const SCREEN_INFORMATION& context, const COORD origin,
const COORD origin, gsl::span<wchar_t> buffer,
gsl::span<wchar_t> buffer, size_t& written) noexcept override;
size_t& written) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT WriteConsoleInputAImpl(InputBuffer& context,
HRESULT WriteConsoleInputAImpl(InputBuffer& context, const std::basic_string_view<INPUT_RECORD> buffer,
const std::basic_string_view<INPUT_RECORD> buffer, size_t& written,
size_t& written, const bool append) noexcept override;
const bool append) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT WriteConsoleInputWImpl(InputBuffer& context,
HRESULT WriteConsoleInputWImpl(InputBuffer& context, const std::basic_string_view<INPUT_RECORD> buffer,
const std::basic_string_view<INPUT_RECORD> buffer, size_t& written,
size_t& written, const bool append) noexcept override;
const bool append) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT WriteConsoleOutputAImpl(SCREEN_INFORMATION& context,
HRESULT WriteConsoleOutputAImpl(SCREEN_INFORMATION& context, gsl::span<CHAR_INFO> buffer,
gsl::span<CHAR_INFO> buffer, const Microsoft::Console::Types::Viewport& requestRectangle,
const Microsoft::Console::Types::Viewport& requestRectangle, Microsoft::Console::Types::Viewport& writtenRectangle) noexcept override;
Microsoft::Console::Types::Viewport& writtenRectangle) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT WriteConsoleOutputWImpl(SCREEN_INFORMATION& context,
HRESULT WriteConsoleOutputWImpl(SCREEN_INFORMATION& context, gsl::span<CHAR_INFO> buffer,
gsl::span<CHAR_INFO> buffer, const Microsoft::Console::Types::Viewport& requestRectangle,
const Microsoft::Console::Types::Viewport& requestRectangle, Microsoft::Console::Types::Viewport& writtenRectangle) noexcept override;
Microsoft::Console::Types::Viewport& writtenRectangle) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT WriteConsoleOutputAttributeImpl(IConsoleOutputObject& OutContext,
HRESULT WriteConsoleOutputAttributeImpl(IConsoleOutputObject& OutContext, const std::basic_string_view<WORD> attrs,
const std::basic_string_view<WORD> attrs, const COORD target,
const COORD target, size_t& used) noexcept override;
size_t& used) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT WriteConsoleOutputCharacterAImpl(IConsoleOutputObject& OutContext,
HRESULT WriteConsoleOutputCharacterAImpl(IConsoleOutputObject& OutContext, const std::string_view text,
const std::string_view text, const COORD target,
const COORD target, size_t& used) noexcept override;
size_t& used) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT WriteConsoleOutputCharacterWImpl(IConsoleOutputObject& OutContext,
HRESULT WriteConsoleOutputCharacterWImpl(IConsoleOutputObject& OutContext, const std::wstring_view text,
const std::wstring_view text, const COORD target,
const COORD target, size_t& used) noexcept override;
size_t& used) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT ReadConsoleOutputAImpl(const SCREEN_INFORMATION& context,
HRESULT ReadConsoleOutputAImpl(const SCREEN_INFORMATION& context, gsl::span<CHAR_INFO> buffer,
gsl::span<CHAR_INFO> buffer, const Microsoft::Console::Types::Viewport& sourceRectangle,
const Microsoft::Console::Types::Viewport& sourceRectangle, Microsoft::Console::Types::Viewport& readRectangle) noexcept override;
Microsoft::Console::Types::Viewport& readRectangle) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT ReadConsoleOutputWImpl(const SCREEN_INFORMATION& context,
HRESULT ReadConsoleOutputWImpl(const SCREEN_INFORMATION& context, gsl::span<CHAR_INFO> buffer,
gsl::span<CHAR_INFO> buffer, const Microsoft::Console::Types::Viewport& sourceRectangle,
const Microsoft::Console::Types::Viewport& sourceRectangle, Microsoft::Console::Types::Viewport& readRectangle) noexcept override;
Microsoft::Console::Types::Viewport& readRectangle) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT GetConsoleTitleAImpl(gsl::span<char> title,
HRESULT GetConsoleTitleAImpl(gsl::span<char> title, size_t& written,
size_t& written, size_t& needed) noexcept override;
size_t& needed) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT GetConsoleTitleWImpl(gsl::span<wchar_t> title,
HRESULT GetConsoleTitleWImpl(gsl::span<wchar_t> title, size_t& written,
size_t& written, size_t& needed) noexcept override;
size_t& needed) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT GetConsoleOriginalTitleAImpl(gsl::span<char> title,
HRESULT GetConsoleOriginalTitleAImpl(gsl::span<char> title, size_t& written,
size_t& written, size_t& needed) noexcept override;
size_t& needed) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT GetConsoleOriginalTitleWImpl(gsl::span<wchar_t> title,
HRESULT GetConsoleOriginalTitleWImpl(gsl::span<wchar_t> title, size_t& written,
size_t& written, size_t& needed) noexcept override;
size_t& needed) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT SetConsoleTitleAImpl(const std::string_view title) noexcept override;
HRESULT SetConsoleTitleAImpl(const std::string_view title) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT SetConsoleTitleWImpl(const std::wstring_view title) noexcept override;
HRESULT SetConsoleTitleWImpl(const std::wstring_view title) noexcept override;
#pragma endregion #pragma endregion
#pragma region L3 #pragma region L3
void GetNumberOfConsoleMouseButtonsImpl(ULONG& buttons) noexcept override; void GetNumberOfConsoleMouseButtonsImpl(ULONG& buttons) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT GetConsoleFontSizeImpl(const SCREEN_INFORMATION& context,
HRESULT GetConsoleFontSizeImpl(const SCREEN_INFORMATION& context, const DWORD index,
const DWORD index, COORD& size) noexcept override;
COORD& size) noexcept override;
//// driver will pare down for non-Ex method //// driver will pare down for non-Ex method
[[nodiscard]] [[nodiscard]] HRESULT GetCurrentConsoleFontExImpl(const SCREEN_INFORMATION& context,
HRESULT GetCurrentConsoleFontExImpl(const SCREEN_INFORMATION& context, const bool isForMaximumWindowSize,
const bool isForMaximumWindowSize, CONSOLE_FONT_INFOEX& consoleFontInfoEx) noexcept override;
CONSOLE_FONT_INFOEX& consoleFontInfoEx) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT SetConsoleDisplayModeImpl(SCREEN_INFORMATION& context,
HRESULT SetConsoleDisplayModeImpl(SCREEN_INFORMATION& context, const ULONG flags,
const ULONG flags, COORD& newSize) noexcept override;
COORD& newSize) noexcept override;
void GetConsoleDisplayModeImpl(ULONG& flags) noexcept override; void GetConsoleDisplayModeImpl(ULONG& flags) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT AddConsoleAliasAImpl(const std::string_view source,
HRESULT AddConsoleAliasAImpl(const std::string_view source, const std::string_view target,
const std::string_view target, const std::string_view exeName) noexcept override;
const std::string_view exeName) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT AddConsoleAliasWImpl(const std::wstring_view source,
HRESULT AddConsoleAliasWImpl(const std::wstring_view source, const std::wstring_view target,
const std::wstring_view target, const std::wstring_view exeName) noexcept override;
const std::wstring_view exeName) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT GetConsoleAliasAImpl(const std::string_view source,
HRESULT GetConsoleAliasAImpl(const std::string_view source, gsl::span<char> target,
gsl::span<char> target, size_t& written,
size_t& written, const std::string_view exeName) noexcept override;
const std::string_view exeName) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT GetConsoleAliasWImpl(const std::wstring_view source,
HRESULT GetConsoleAliasWImpl(const std::wstring_view source, gsl::span<wchar_t> target,
gsl::span<wchar_t> target, size_t& written,
size_t& written, const std::wstring_view exeName) noexcept override;
const std::wstring_view exeName) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT GetConsoleAliasesLengthAImpl(const std::string_view exeName,
HRESULT GetConsoleAliasesLengthAImpl(const std::string_view exeName, size_t& bufferRequired) noexcept override;
size_t& bufferRequired) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT GetConsoleAliasesLengthWImpl(const std::wstring_view exeName,
HRESULT GetConsoleAliasesLengthWImpl(const std::wstring_view exeName, size_t& bufferRequired) noexcept override;
size_t& bufferRequired) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT GetConsoleAliasExesLengthAImpl(size_t& bufferRequired) noexcept override;
HRESULT GetConsoleAliasExesLengthAImpl(size_t& bufferRequired) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT GetConsoleAliasExesLengthWImpl(size_t& bufferRequired) noexcept override;
HRESULT GetConsoleAliasExesLengthWImpl(size_t& bufferRequired) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT GetConsoleAliasesAImpl(const std::string_view exeName,
HRESULT GetConsoleAliasesAImpl(const std::string_view exeName, gsl::span<char> alias,
gsl::span<char> alias, size_t& written) noexcept override;
size_t& written) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT GetConsoleAliasesWImpl(const std::wstring_view exeName,
HRESULT GetConsoleAliasesWImpl(const std::wstring_view exeName, gsl::span<wchar_t> alias,
gsl::span<wchar_t> alias, size_t& written) noexcept override;
size_t& written) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT GetConsoleAliasExesAImpl(gsl::span<char> aliasExes,
HRESULT GetConsoleAliasExesAImpl(gsl::span<char> aliasExes, size_t& written) noexcept override;
size_t& written) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT GetConsoleAliasExesWImpl(gsl::span<wchar_t> aliasExes,
HRESULT GetConsoleAliasExesWImpl(gsl::span<wchar_t> aliasExes, size_t& written) noexcept override;
size_t& written) noexcept override;
#pragma region CMDext Private API #pragma region CMDext Private API
[[nodiscard]] [[nodiscard]] HRESULT ExpungeConsoleCommandHistoryAImpl(const std::string_view exeName) noexcept override;
HRESULT ExpungeConsoleCommandHistoryAImpl(const std::string_view exeName) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT ExpungeConsoleCommandHistoryWImpl(const std::wstring_view exeName) noexcept override;
HRESULT ExpungeConsoleCommandHistoryWImpl(const std::wstring_view exeName) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT SetConsoleNumberOfCommandsAImpl(const std::string_view exeName,
HRESULT SetConsoleNumberOfCommandsAImpl(const std::string_view exeName, const size_t numberOfCommands) noexcept override;
const size_t numberOfCommands) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT SetConsoleNumberOfCommandsWImpl(const std::wstring_view exeName,
HRESULT SetConsoleNumberOfCommandsWImpl(const std::wstring_view exeName, const size_t numberOfCommands) noexcept override;
const size_t numberOfCommands) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT GetConsoleCommandHistoryLengthAImpl(const std::string_view exeName,
HRESULT GetConsoleCommandHistoryLengthAImpl(const std::string_view exeName, size_t& length) noexcept override;
size_t& length) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT GetConsoleCommandHistoryLengthWImpl(const std::wstring_view exeName,
HRESULT GetConsoleCommandHistoryLengthWImpl(const std::wstring_view exeName, size_t& length) noexcept override;
size_t& length) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT GetConsoleCommandHistoryAImpl(const std::string_view exeName,
HRESULT GetConsoleCommandHistoryAImpl(const std::string_view exeName, gsl::span<char> commandHistory,
gsl::span<char> commandHistory, size_t& written) noexcept override;
size_t& written) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT GetConsoleCommandHistoryWImpl(const std::wstring_view exeName,
HRESULT GetConsoleCommandHistoryWImpl(const std::wstring_view exeName, gsl::span<wchar_t> commandHistory,
gsl::span<wchar_t> commandHistory, size_t& written) noexcept override;
size_t& written) noexcept override;
#pragma endregion #pragma endregion
@ -430,13 +364,11 @@ public:
void GetConsoleHistoryInfoImpl(CONSOLE_HISTORY_INFO& consoleHistoryInfo) noexcept override; void GetConsoleHistoryInfoImpl(CONSOLE_HISTORY_INFO& consoleHistoryInfo) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT SetConsoleHistoryInfoImpl(const CONSOLE_HISTORY_INFO& consoleHistoryInfo) noexcept override;
HRESULT SetConsoleHistoryInfoImpl(const CONSOLE_HISTORY_INFO& consoleHistoryInfo) noexcept override;
[[nodiscard]] [[nodiscard]] HRESULT SetCurrentConsoleFontExImpl(IConsoleOutputObject& context,
HRESULT SetCurrentConsoleFontExImpl(IConsoleOutputObject& context, const bool isForMaximumWindowSize,
const bool isForMaximumWindowSize, const CONSOLE_FONT_INFOEX& consoleFontInfoEx) noexcept override;
const CONSOLE_FONT_INFOEX& consoleFontInfoEx) noexcept override;
#pragma endregion #pragma endregion
}; };

View file

@ -14,7 +14,7 @@
#include "..\interactivity\inc\ServiceLocator.hpp" #include "..\interactivity\inc\ServiceLocator.hpp"
static constexpr size_t COMMAND_NUMBER_SIZE = 8; // size of command number buffer static constexpr size_t COMMAND_NUMBER_SIZE = 8; // size of command number buffer
// Routine Description: // Routine Description:
// - Calculates what the proposed size of the popup should be, based on the commands in the history // - Calculates what the proposed size of the popup should be, based on the commands in the history
@ -59,8 +59,9 @@ CommandListPopup::CommandListPopup(SCREEN_INFORMATION& screenInfo, const Command
_setBottomIndex(); _setBottomIndex();
} }
[[nodiscard]] [[nodiscard]] NTSTATUS CommandListPopup::_handlePopupKeys(COOKED_READ_DATA& cookedReadData,
NTSTATUS CommandListPopup::_handlePopupKeys(COOKED_READ_DATA& cookedReadData, const wchar_t wch, const DWORD modifiers) noexcept const wchar_t wch,
const DWORD modifiers) noexcept
{ {
try try
{ {
@ -146,8 +147,7 @@ void CommandListPopup::_setBottomIndex()
} }
} }
[[nodiscard]] [[nodiscard]] NTSTATUS CommandListPopup::_deleteSelection(COOKED_READ_DATA& cookedReadData) noexcept
NTSTATUS CommandListPopup::_deleteSelection(COOKED_READ_DATA& cookedReadData) noexcept
{ {
try try
{ {
@ -176,8 +176,7 @@ NTSTATUS CommandListPopup::_deleteSelection(COOKED_READ_DATA& cookedReadData) no
// - moves the selected history item up in the history list // - moves the selected history item up in the history list
// Arguments: // Arguments:
// - cookedReadData - the read wait object to operate upon // - cookedReadData - the read wait object to operate upon
[[nodiscard]] [[nodiscard]] NTSTATUS CommandListPopup::_swapUp(COOKED_READ_DATA& cookedReadData) noexcept
NTSTATUS CommandListPopup::_swapUp(COOKED_READ_DATA& cookedReadData) noexcept
{ {
try try
{ {
@ -199,8 +198,7 @@ NTSTATUS CommandListPopup::_swapUp(COOKED_READ_DATA& cookedReadData) noexcept
// - moves the selected history item down in the history list // - moves the selected history item down in the history list
// Arguments: // Arguments:
// - cookedReadData - the read wait object to operate upon // - cookedReadData - the read wait object to operate upon
[[nodiscard]] [[nodiscard]] NTSTATUS CommandListPopup::_swapDown(COOKED_READ_DATA& cookedReadData) noexcept
NTSTATUS CommandListPopup::_swapDown(COOKED_READ_DATA& cookedReadData) noexcept
{ {
try try
{ {
@ -285,8 +283,7 @@ void CommandListPopup::_cycleSelectionToMatchingCommands(COOKED_READ_DATA& cooke
// Return Value: // Return Value:
// - CONSOLE_STATUS_WAIT - we ran out of input, so a wait block was created // - CONSOLE_STATUS_WAIT - we ran out of input, so a wait block was created
// - CONSOLE_STATUS_READ_COMPLETE - user hit return // - CONSOLE_STATUS_READ_COMPLETE - user hit return
[[nodiscard]] [[nodiscard]] NTSTATUS CommandListPopup::Process(COOKED_READ_DATA& cookedReadData) noexcept
NTSTATUS CommandListPopup::Process(COOKED_READ_DATA& cookedReadData) noexcept
{ {
NTSTATUS Status = STATUS_SUCCESS; NTSTATUS Status = STATUS_SUCCESS;

View file

@ -17,14 +17,12 @@ Author:
#include "popup.h" #include "popup.h"
class CommandListPopup : public Popup class CommandListPopup : public Popup
{ {
public: public:
CommandListPopup(SCREEN_INFORMATION& screenInfo, const CommandHistory& history); CommandListPopup(SCREEN_INFORMATION& screenInfo, const CommandHistory& history);
[[nodiscard]] [[nodiscard]] NTSTATUS Process(COOKED_READ_DATA& cookedReadData) noexcept override;
NTSTATUS Process(COOKED_READ_DATA& cookedReadData) noexcept override;
protected: protected:
void _DrawContent() override; void _DrawContent() override;
@ -37,17 +35,13 @@ private:
void _handleReturn(COOKED_READ_DATA& cookedReadData); void _handleReturn(COOKED_READ_DATA& cookedReadData);
void _cycleSelectionToMatchingCommands(COOKED_READ_DATA& cookedReadData, const wchar_t wch); void _cycleSelectionToMatchingCommands(COOKED_READ_DATA& cookedReadData, const wchar_t wch);
void _setBottomIndex(); void _setBottomIndex();
[[nodiscard]] [[nodiscard]] NTSTATUS _handlePopupKeys(COOKED_READ_DATA& cookedReadData, const wchar_t wch, const DWORD modifiers) noexcept;
NTSTATUS _handlePopupKeys(COOKED_READ_DATA& cookedReadData, const wchar_t wch, const DWORD modifiers) noexcept; [[nodiscard]] NTSTATUS _deleteSelection(COOKED_READ_DATA& cookedReadData) noexcept;
[[nodiscard]] [[nodiscard]] NTSTATUS _swapUp(COOKED_READ_DATA& cookedReadData) noexcept;
NTSTATUS _deleteSelection(COOKED_READ_DATA& cookedReadData) noexcept; [[nodiscard]] NTSTATUS _swapDown(COOKED_READ_DATA& cookedReadData) noexcept;
[[nodiscard]]
NTSTATUS _swapUp(COOKED_READ_DATA& cookedReadData) noexcept;
[[nodiscard]]
NTSTATUS _swapDown(COOKED_READ_DATA& cookedReadData) noexcept;
SHORT _currentCommand; SHORT _currentCommand;
SHORT _bottomIndex; // number of command displayed on last line of popup SHORT _bottomIndex; // number of command displayed on last line of popup
const CommandHistory& _history; const CommandHistory& _history;
#ifdef UNIT_TESTING #ifdef UNIT_TESTING

View file

@ -102,7 +102,7 @@ void CommandNumberPopup::_handleEscape(COOKED_READ_DATA& cookedReadData) noexcep
void CommandNumberPopup::_handleReturn(COOKED_READ_DATA& cookedReadData) noexcept void CommandNumberPopup::_handleReturn(COOKED_READ_DATA& cookedReadData) noexcept
{ {
const short commandNumber = gsl::narrow<short>(std::min(static_cast<size_t>(_parse()), const short commandNumber = gsl::narrow<short>(std::min(static_cast<size_t>(_parse()),
cookedReadData.History().GetNumberOfCommands() - 1)); cookedReadData.History().GetNumberOfCommands() - 1));
CommandLine::Instance().EndAllPopups(); CommandLine::Instance().EndAllPopups();
SetCurrentCommandLine(cookedReadData, commandNumber); SetCurrentCommandLine(cookedReadData, commandNumber);
@ -113,15 +113,14 @@ void CommandNumberPopup::_handleReturn(COOKED_READ_DATA& cookedReadData) noexcep
// Return Value: // Return Value:
// - CONSOLE_STATUS_WAIT - we ran out of input, so a wait block was created // - CONSOLE_STATUS_WAIT - we ran out of input, so a wait block was created
// - CONSOLE_STATUS_READ_COMPLETE - user hit return // - CONSOLE_STATUS_READ_COMPLETE - user hit return
[[nodiscard]] [[nodiscard]] NTSTATUS CommandNumberPopup::Process(COOKED_READ_DATA& cookedReadData) noexcept
NTSTATUS CommandNumberPopup::Process(COOKED_READ_DATA& cookedReadData) noexcept
{ {
NTSTATUS Status = STATUS_SUCCESS; NTSTATUS Status = STATUS_SUCCESS;
WCHAR wch = UNICODE_NULL; WCHAR wch = UNICODE_NULL;
bool popupKeys = false; bool popupKeys = false;
DWORD modifiers = 0; DWORD modifiers = 0;
for(;;) for (;;)
{ {
Status = _getUserInput(cookedReadData, popupKeys, modifiers, wch); Status = _getUserInput(cookedReadData, popupKeys, modifiers, wch);
if (!NT_SUCCESS(Status)) if (!NT_SUCCESS(Status))

View file

@ -17,14 +17,12 @@ Author:
#include "popup.h" #include "popup.h"
class CommandNumberPopup final : public Popup class CommandNumberPopup final : public Popup
{ {
public: public:
CommandNumberPopup(SCREEN_INFORMATION& screenInfo); CommandNumberPopup(SCREEN_INFORMATION& screenInfo);
[[nodiscard]] [[nodiscard]] NTSTATUS Process(COOKED_READ_DATA& cookedReadData) noexcept override;
NTSTATUS Process(COOKED_READ_DATA& cookedReadData) noexcept override;
protected: protected:
void _DrawContent() override; void _DrawContent() override;

View file

@ -23,13 +23,13 @@ const std::wstring_view ConsoleArguments::FEATURE_PTY_ARG = L"pty";
ConsoleArguments::ConsoleArguments(const std::wstring& commandline, ConsoleArguments::ConsoleArguments(const std::wstring& commandline,
const HANDLE hStdIn, const HANDLE hStdIn,
const HANDLE hStdOut) const HANDLE hStdOut) :
: _commandline(commandline), _commandline(commandline),
_vtInHandle(hStdIn), _vtInHandle(hStdIn),
_vtOutHandle(hStdOut), _vtOutHandle(hStdOut),
_recievedEarlySizeChange{ false }, _recievedEarlySizeChange{ false },
_originalWidth{ -1 }, _originalWidth{ -1 },
_originalHeight{ -1 } _originalHeight{ -1 }
{ {
_clientCommandline = L""; _clientCommandline = L"";
_vtMode = L""; _vtMode = L"";
@ -46,10 +46,9 @@ ConsoleArguments::ConsoleArguments(const std::wstring& commandline,
ConsoleArguments::ConsoleArguments() : ConsoleArguments::ConsoleArguments() :
ConsoleArguments(L"", nullptr, nullptr) ConsoleArguments(L"", nullptr, nullptr)
{ {
} }
ConsoleArguments& ConsoleArguments::operator=(const ConsoleArguments & other) ConsoleArguments& ConsoleArguments::operator=(const ConsoleArguments& other)
{ {
if (this != &other) if (this != &other)
{ {
@ -106,8 +105,9 @@ void ConsoleArguments::s_ConsumeArg(_Inout_ std::vector<std::wstring>& args, _In
// Return Value: // Return Value:
// S_OK if we parsed the string successfully, otherwise E_INVALIDARG indicating // S_OK if we parsed the string successfully, otherwise E_INVALIDARG indicating
// failure. // failure.
[[nodiscard]] [[nodiscard]] HRESULT ConsoleArguments::s_GetArgumentValue(_Inout_ std::vector<std::wstring>& args,
HRESULT ConsoleArguments::s_GetArgumentValue(_Inout_ std::vector<std::wstring>& args, _Inout_ size_t& index, _Out_opt_ std::wstring* const pSetting) _Inout_ size_t& index,
_Out_opt_ std::wstring* const pSetting)
{ {
bool hasNext = (index + 1) < args.size(); bool hasNext = (index + 1) < args.size();
if (hasNext) if (hasNext)
@ -136,8 +136,7 @@ HRESULT ConsoleArguments::s_GetArgumentValue(_Inout_ std::vector<std::wstring>&
// Return Value: // Return Value:
// S_OK if we parsed the string successfully, otherwise E_INVALIDARG indicating // S_OK if we parsed the string successfully, otherwise E_INVALIDARG indicating
// failure. // failure.
[[nodiscard]] [[nodiscard]] HRESULT ConsoleArguments::s_HandleFeatureValue(_Inout_ std::vector<std::wstring>& args, _Inout_ size_t& index)
HRESULT ConsoleArguments::s_HandleFeatureValue(_Inout_ std::vector<std::wstring>& args, _Inout_ size_t& index)
{ {
HRESULT hr = E_INVALIDARG; HRESULT hr = E_INVALIDARG;
bool hasNext = (index + 1) < args.size(); bool hasNext = (index + 1) < args.size();
@ -167,10 +166,9 @@ HRESULT ConsoleArguments::s_HandleFeatureValue(_Inout_ std::vector<std::wstring>
// Return Value: // Return Value:
// S_OK if we parsed the short successfully, otherwise E_INVALIDARG indicating // S_OK if we parsed the short successfully, otherwise E_INVALIDARG indicating
// failure. This could be the case for non-numeric arguments, or for >SHORT_MAX args. // failure. This could be the case for non-numeric arguments, or for >SHORT_MAX args.
[[nodiscard]] [[nodiscard]] HRESULT ConsoleArguments::s_GetArgumentValue(_Inout_ std::vector<std::wstring>& args,
HRESULT ConsoleArguments::s_GetArgumentValue(_Inout_ std::vector<std::wstring>& args, _Inout_ size_t& index,
_Inout_ size_t& index, _Out_opt_ short* const pSetting)
_Out_opt_ short* const pSetting)
{ {
bool succeeded = (index + 1) < args.size(); bool succeeded = (index + 1) < args.size();
if (succeeded) if (succeeded)
@ -199,7 +197,6 @@ HRESULT ConsoleArguments::s_GetArgumentValue(_Inout_ std::vector<std::wstring>&
{ {
succeeded = false; succeeded = false;
} }
} }
s_ConsumeArg(args, index); s_ConsumeArg(args, index);
} }
@ -215,8 +212,7 @@ HRESULT ConsoleArguments::s_GetArgumentValue(_Inout_ std::vector<std::wstring>&
// - S_OK if we could successfully parse the given text and store it in the handle value location. // - S_OK if we could successfully parse the given text and store it in the handle value location.
// - E_INVALIDARG if we couldn't parse the text as a valid hex-encoded handle number OR // - E_INVALIDARG if we couldn't parse the text as a valid hex-encoded handle number OR
// if the handle value was already filled. // if the handle value was already filled.
[[nodiscard]] [[nodiscard]] HRESULT ConsoleArguments::s_ParseHandleArg(const std::wstring& handleAsText, _Inout_ DWORD& handleAsVal)
HRESULT ConsoleArguments::s_ParseHandleArg(const std::wstring& handleAsText, _Inout_ DWORD& handleAsVal)
{ {
HRESULT hr = S_OK; HRESULT hr = S_OK;
@ -259,10 +255,9 @@ HRESULT ConsoleArguments::s_ParseHandleArg(const std::wstring& handleAsText, _In
// Return Value: // Return Value:
// S_OK if we parsed the string successfully, otherwise E_INVALIDARG indicating // S_OK if we parsed the string successfully, otherwise E_INVALIDARG indicating
// failure. // failure.
[[nodiscard]] [[nodiscard]] HRESULT ConsoleArguments::_GetClientCommandline(_Inout_ std::vector<std::wstring>& args, const size_t index, const bool skipFirst)
HRESULT ConsoleArguments::_GetClientCommandline(_Inout_ std::vector<std::wstring>& args, const size_t index, const bool skipFirst)
{ {
auto start = args.begin()+index; auto start = args.begin() + index;
// Erase the first token. // Erase the first token.
// Used to get rid of the explicit commandline token "--" // Used to get rid of the explicit commandline token "--"
@ -278,12 +273,12 @@ HRESULT ConsoleArguments::_GetClientCommandline(_Inout_ std::vector<std::wstring
for (j = index; j < args.size(); j++) for (j = index; j < args.size(); j++)
{ {
_clientCommandline += args[j]; _clientCommandline += args[j];
if (j+1 < args.size()) if (j + 1 < args.size())
{ {
_clientCommandline += L" "; _clientCommandline += L" ";
} }
} }
args.erase(args.begin()+index, args.begin()+j); args.erase(args.begin() + index, args.begin() + j);
return S_OK; return S_OK;
} }
@ -297,8 +292,7 @@ HRESULT ConsoleArguments::_GetClientCommandline(_Inout_ std::vector<std::wstring
// Return Value: // Return Value:
// S_OK if we parsed our _commandline successfully, otherwise E_INVALIDARG // S_OK if we parsed our _commandline successfully, otherwise E_INVALIDARG
// indicating failure. // indicating failure.
[[nodiscard]] [[nodiscard]] HRESULT ConsoleArguments::ParseCommandline()
HRESULT ConsoleArguments::ParseCommandline()
{ {
// If the commandline was empty, quick return. // If the commandline was empty, quick return.
if (_commandline.length() == 0) if (_commandline.length() == 0)
@ -333,7 +327,7 @@ HRESULT ConsoleArguments::ParseCommandline()
std::wstring arg = args[i]; std::wstring arg = args[i];
if (arg.substr(0, HANDLE_PREFIX.length()) == HANDLE_PREFIX || if (arg.substr(0, HANDLE_PREFIX.length()) == HANDLE_PREFIX ||
arg == SERVER_HANDLE_ARG) arg == SERVER_HANDLE_ARG)
{ {
// server handle token accepted two ways: // server handle token accepted two ways:
// --server 0x4 (new method) // --server 0x4 (new method)

View file

@ -29,8 +29,7 @@ public:
ConsoleArguments& operator=(const ConsoleArguments& other); ConsoleArguments& operator=(const ConsoleArguments& other);
[[nodiscard]] [[nodiscard]] HRESULT ParseCommandline();
HRESULT ParseCommandline();
bool HasVtHandles() const; bool HasVtHandles() const;
bool InConptyMode() const noexcept; bool InConptyMode() const noexcept;
@ -101,7 +100,6 @@ private:
_originalWidth{ -1 }, _originalWidth{ -1 },
_originalHeight{ -1 } _originalHeight{ -1 }
{ {
} }
#endif #endif
@ -130,29 +128,23 @@ private:
short _originalWidth; short _originalWidth;
short _originalHeight; short _originalHeight;
[[nodiscard]] [[nodiscard]] HRESULT _GetClientCommandline(_Inout_ std::vector<std::wstring>& args,
HRESULT _GetClientCommandline(_Inout_ std::vector<std::wstring>& args, const size_t index,
const size_t index, const bool skipFirst);
const bool skipFirst);
static void s_ConsumeArg(_Inout_ std::vector<std::wstring>& args, static void s_ConsumeArg(_Inout_ std::vector<std::wstring>& args,
_In_ size_t& index); _In_ size_t& index);
[[nodiscard]] [[nodiscard]] static HRESULT s_GetArgumentValue(_Inout_ std::vector<std::wstring>& args,
static HRESULT s_GetArgumentValue(_Inout_ std::vector<std::wstring>& args, _Inout_ size_t& index,
_Inout_ size_t& index, _Out_opt_ std::wstring* const pSetting);
_Out_opt_ std::wstring* const pSetting); [[nodiscard]] static HRESULT s_GetArgumentValue(_Inout_ std::vector<std::wstring>& args,
[[nodiscard]] _Inout_ size_t& index,
static HRESULT s_GetArgumentValue(_Inout_ std::vector<std::wstring>& args, _Out_opt_ short* const pSetting);
_Inout_ size_t& index, [[nodiscard]] static HRESULT s_HandleFeatureValue(_Inout_ std::vector<std::wstring>& args,
_Out_opt_ short* const pSetting); _Inout_ size_t& index);
[[nodiscard]]
static HRESULT s_HandleFeatureValue(_Inout_ std::vector<std::wstring>& args,
_Inout_ size_t& index);
[[nodiscard]]
static HRESULT s_ParseHandleArg(const std::wstring& handleAsText,
_Inout_ DWORD& handleAsVal);
[[nodiscard]] static HRESULT s_ParseHandleArg(const std::wstring& handleAsText,
_Inout_ DWORD& handleAsVal);
#ifdef UNIT_TESTING #ifdef UNIT_TESTING
friend class ConsoleArgumentsTests; friend class ConsoleArgumentsTests;
@ -160,10 +152,12 @@ private:
}; };
#ifdef UNIT_TESTING #ifdef UNIT_TESTING
namespace WEX { namespace WEX
namespace TestExecution { {
namespace TestExecution
{
template<> template<>
class VerifyOutputTraits < ConsoleArguments > class VerifyOutputTraits<ConsoleArguments>
{ {
public: public:
static WEX::Common::NoThrowString ToString(const ConsoleArguments& ci) static WEX::Common::NoThrowString ToString(const ConsoleArguments& ci)
@ -205,26 +199,25 @@ namespace WEX {
}; };
template<> template<>
class VerifyCompareTraits < ConsoleArguments, ConsoleArguments> class VerifyCompareTraits<ConsoleArguments, ConsoleArguments>
{ {
public: public:
static bool AreEqual(const ConsoleArguments& expected, const ConsoleArguments& actual) static bool AreEqual(const ConsoleArguments& expected, const ConsoleArguments& actual)
{ {
return return expected.GetClientCommandline() == actual.GetClientCommandline() &&
expected.GetClientCommandline() == actual.GetClientCommandline() && expected.HasVtHandles() == actual.HasVtHandles() &&
expected.HasVtHandles() == actual.HasVtHandles() && expected.GetVtInHandle() == actual.GetVtInHandle() &&
expected.GetVtInHandle() == actual.GetVtInHandle() && expected.GetVtOutHandle() == actual.GetVtOutHandle() &&
expected.GetVtOutHandle() == actual.GetVtOutHandle() && expected.GetVtMode() == actual.GetVtMode() &&
expected.GetVtMode() == actual.GetVtMode() && expected.GetWidth() == actual.GetWidth() &&
expected.GetWidth() == actual.GetWidth() && expected.GetHeight() == actual.GetHeight() &&
expected.GetHeight() == actual.GetHeight() && expected.GetForceV1() == actual.GetForceV1() &&
expected.GetForceV1() == actual.GetForceV1() && expected.IsHeadless() == actual.IsHeadless() &&
expected.IsHeadless() == actual.IsHeadless() && expected.ShouldCreateServerHandle() == actual.ShouldCreateServerHandle() &&
expected.ShouldCreateServerHandle() == actual.ShouldCreateServerHandle() && expected.GetServerHandle() == actual.GetServerHandle() &&
expected.GetServerHandle() == actual.GetServerHandle() && expected.HasSignalHandle() == actual.HasSignalHandle() &&
expected.HasSignalHandle() == actual.HasSignalHandle() && expected.GetSignalHandle() == actual.GetSignalHandle() &&
expected.GetSignalHandle() == actual.GetSignalHandle() && expected.GetInheritCursor() == actual.GetInheritCursor();
expected.GetInheritCursor() == actual.GetInheritCursor();
} }
static bool AreSame(const ConsoleArguments& expected, const ConsoleArguments& actual) static bool AreSame(const ConsoleArguments& expected, const ConsoleArguments& actual)
@ -238,19 +231,18 @@ namespace WEX {
static bool IsNull(const ConsoleArguments& object) static bool IsNull(const ConsoleArguments& object)
{ {
return return object.GetClientCommandline().empty() &&
object.GetClientCommandline().empty() && (object.GetVtInHandle() == 0 || object.GetVtInHandle() == INVALID_HANDLE_VALUE) &&
(object.GetVtInHandle() == 0 || object.GetVtInHandle() == INVALID_HANDLE_VALUE) && (object.GetVtOutHandle() == 0 || object.GetVtOutHandle() == INVALID_HANDLE_VALUE) &&
(object.GetVtOutHandle() == 0 || object.GetVtOutHandle() == INVALID_HANDLE_VALUE) && object.GetVtMode().empty() &&
object.GetVtMode().empty() && !object.GetForceV1() &&
!object.GetForceV1() && (object.GetWidth() == 0) &&
(object.GetWidth() == 0) && (object.GetHeight() == 0) &&
(object.GetHeight() == 0) && !object.IsHeadless() &&
!object.IsHeadless() && !object.ShouldCreateServerHandle() &&
!object.ShouldCreateServerHandle() && object.GetServerHandle() == 0 &&
object.GetServerHandle() == 0 && (object.GetSignalHandle() == 0 || object.GetSignalHandle() == INVALID_HANDLE_VALUE) &&
(object.GetSignalHandle() == 0 || object.GetSignalHandle() == INVALID_HANDLE_VALUE) && !object.GetInheritCursor();
!object.GetInheritCursor();
} }
}; };
} }

View file

@ -19,8 +19,7 @@ CopyFromCharPopup::CopyFromCharPopup(SCREEN_INFORMATION& screenInfo) :
// Return Value: // Return Value:
// - CONSOLE_STATUS_WAIT - we ran out of input, so a wait block was created // - CONSOLE_STATUS_WAIT - we ran out of input, so a wait block was created
// - CONSOLE_STATUS_READ_COMPLETE - user hit return // - CONSOLE_STATUS_READ_COMPLETE - user hit return
[[nodiscard]] [[nodiscard]] NTSTATUS CopyFromCharPopup::Process(COOKED_READ_DATA& cookedReadData) noexcept
NTSTATUS CopyFromCharPopup::Process(COOKED_READ_DATA& cookedReadData) noexcept
{ {
// get user input // get user input
WCHAR Char = UNICODE_NULL; WCHAR Char = UNICODE_NULL;

View file

@ -22,8 +22,7 @@ class CopyFromCharPopup final : public Popup
public: public:
CopyFromCharPopup(SCREEN_INFORMATION& screenInfo); CopyFromCharPopup(SCREEN_INFORMATION& screenInfo);
[[nodiscard]] [[nodiscard]] NTSTATUS Process(COOKED_READ_DATA& cookedReadData) noexcept override;
NTSTATUS Process(COOKED_READ_DATA& cookedReadData) noexcept override;
protected: protected:
void _DrawContent() override; void _DrawContent() override;

View file

@ -50,8 +50,7 @@ void CopyToCharPopup::_copyToChar(COOKED_READ_DATA& cookedReadData, const std::w
// Return Value: // Return Value:
// - CONSOLE_STATUS_WAIT - we ran out of input, so a wait block was created // - CONSOLE_STATUS_WAIT - we ran out of input, so a wait block was created
// - CONSOLE_STATUS_READ_COMPLETE - user hit return // - CONSOLE_STATUS_READ_COMPLETE - user hit return
[[nodiscard]] [[nodiscard]] NTSTATUS CopyToCharPopup::Process(COOKED_READ_DATA& cookedReadData) noexcept
NTSTATUS CopyToCharPopup::Process(COOKED_READ_DATA& cookedReadData) noexcept
{ {
wchar_t wch = UNICODE_NULL; wchar_t wch = UNICODE_NULL;
bool popupKey = false; bool popupKey = false;

Some files were not shown because too many files have changed in this diff Show more