diff --git a/.clang-format b/.clang-format new file mode 100644 index 000000000..9e5a7d131 --- /dev/null +++ b/.clang-format @@ -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 diff --git a/doc/building.md b/doc/building.md index 509736947..efeb878db 100644 --- a/doc/building.md +++ b/doc/building.md @@ -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. +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 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 - `runft.cmd` - run the feature tests - `runuia.cmd` - run the UIA tests +- `runformat` - uses clang-format to format all c++ files to match our coding style. ## 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. - `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. +- `Invoke-CodeFormat` - uses clang-format to format all c++ files to match our coding style. ## Configuration Types diff --git a/src/buffer/out/AttrRow.cpp b/src/buffer/out/AttrRow.cpp index e25816cf8..e9efd8f60 100644 --- a/src/buffer/out/AttrRow.cpp +++ b/src/buffer/out/AttrRow.cpp @@ -4,14 +4,14 @@ #include "precomp.h" #include "AttrRow.hpp" - // Routine Description: - // - constructor - // Arguments: - // - cchRowWidth - the length of the default text attribute - // - attr - the default text attribute - // Return Value: - // - constructed object - // Note: will throw exception if unable to allocate memory for text attribute storage +// Routine Description: +// - constructor +// Arguments: +// - cchRowWidth - the length of the default text attribute +// - attr - the default text attribute +// Return Value: +// - constructed object +// Note: will throw exception if unable to allocate memory for text attribute storage ATTR_ROW::ATTR_ROW(const UINT cchRowWidth, const TextAttribute attr) { _list.push_back(TextAttributeRun(cchRowWidth, attr)); @@ -210,7 +210,6 @@ void ATTR_ROW::ReplaceLegacyAttrs(_In_ WORD wToBeReplacedAttr, _In_ WORD wReplac ReplaceAttrs(ToBeReplaced, ReplaceWith); } - // Method Description: // - Replaces all runs in the row with the given toBeReplacedAttr with the new // attribute replaceWith. @@ -230,7 +229,6 @@ void ATTR_ROW::ReplaceAttrs(const TextAttribute& toBeReplacedAttr, const TextAtt } } - // Routine Description: // - 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 @@ -245,11 +243,10 @@ void ATTR_ROW::ReplaceAttrs(const TextAttribute& toBeReplacedAttr, const TextAtt // Return Value: // - STATUS_NO_MEMORY if there wasn't enough memory to insert the runs // otherwise STATUS_SUCCESS if we were successful. -[[nodiscard]] -HRESULT ATTR_ROW::InsertAttrRuns(const std::basic_string_view newAttrs, - const size_t iStart, - const size_t iEnd, - const size_t cBufferWidth) +[[nodiscard]] HRESULT ATTR_ROW::InsertAttrRuns(const std::basic_string_view newAttrs, + const size_t iStart, + const size_t iEnd, + const size_t cBufferWidth) { // Definitions: // Existing Run = The run length encoded color array we're already storing in memory before this was called. diff --git a/src/buffer/out/AttrRow.hpp b/src/buffer/out/AttrRow.hpp index a45d814a6..2aba2a772 100644 --- a/src/buffer/out/AttrRow.hpp +++ b/src/buffer/out/AttrRow.hpp @@ -47,11 +47,10 @@ public: void Resize(const size_t newWidth); - [[nodiscard]] - HRESULT InsertAttrRuns(const std::basic_string_view newAttrs, - const size_t iStart, - const size_t iEnd, - const size_t cBufferWidth); + [[nodiscard]] HRESULT InsertAttrRuns(const std::basic_string_view newAttrs, + const size_t iStart, + const size_t iEnd, + const size_t cBufferWidth); static std::vector PackAttrs(const std::vector& attrs); @@ -65,12 +64,10 @@ public: friend class AttrRowIterator; private: - std::vector _list; size_t _cchRowWidth; #ifdef UNIT_TESTING friend class AttrRowTests; #endif - }; diff --git a/src/buffer/out/AttrRowIterator.hpp b/src/buffer/out/AttrRowIterator.hpp index 92aadef59..5ca7f72c1 100644 --- a/src/buffer/out/AttrRowIterator.hpp +++ b/src/buffer/out/AttrRowIterator.hpp @@ -13,7 +13,6 @@ Author(s): - Austin Diviness (AustDi) 04-Jun-2018 --*/ - #pragma once #include "TextAttribute.hpp" @@ -55,7 +54,7 @@ private: std::vector::const_iterator _run; const ATTR_ROW* _pAttrRow; size_t _currentAttributeIndex; // index of TextAttribute within the current TextAttributeRun - + void _increment(size_t count); void _decrement(size_t count); void _setToEnd(); diff --git a/src/buffer/out/CharRow.cpp b/src/buffer/out/CharRow.cpp index 2e5cf9993..60a7d0d14 100644 --- a/src/buffer/out/CharRow.cpp +++ b/src/buffer/out/CharRow.cpp @@ -101,8 +101,7 @@ void CharRow::Reset() // - newSize - the new width of the character and attributes rows // Return Value: // - S_OK on success, otherwise relevant error code -[[nodiscard]] -HRESULT CharRow::Resize(const size_t newSize) noexcept +[[nodiscard]] HRESULT CharRow::Resize(const size_t newSize) noexcept { try { @@ -263,7 +262,7 @@ std::wstring CharRow::GetTextRaw() const { std::wstring wstr; 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); for (auto it = glyph.begin(); it != glyph.end(); ++it) @@ -279,7 +278,7 @@ std::wstring CharRow::GetText() const std::wstring wstr; 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); if (!DbcsAttrAt(i).IsTrailing()) diff --git a/src/buffer/out/CharRow.hpp b/src/buffer/out/CharRow.hpp index 555dfd6be..c9ff3a0ae 100644 --- a/src/buffer/out/CharRow.hpp +++ b/src/buffer/out/CharRow.hpp @@ -54,8 +54,7 @@ public: bool WasDoubleBytePadded() const noexcept; size_t size() const noexcept; void Reset(); - [[nodiscard]] - HRESULT Resize(const size_t newSize) noexcept; + [[nodiscard]] HRESULT Resize(const size_t newSize) noexcept; size_t MeasureLeft() const; size_t MeasureRight() const noexcept; void ClearCell(const size_t column); @@ -116,8 +115,7 @@ void OverwriteColumns(InputIt1 startChars, InputIt1 endChars, InputIt2 startAttr endChars, startAttrs, outIt, - [](const wchar_t wch, const DbcsAttribute attr) - { - return CharRow::value_type{ wch, attr }; - }); + [](const wchar_t wch, const DbcsAttribute attr) { + return CharRow::value_type{ wch, attr }; + }); } diff --git a/src/buffer/out/CharRowCell.cpp b/src/buffer/out/CharRowCell.cpp index 180c3520c..a6c2d2fb6 100644 --- a/src/buffer/out/CharRowCell.cpp +++ b/src/buffer/out/CharRowCell.cpp @@ -5,7 +5,6 @@ #include "CharRowCell.hpp" #include "unicode.hpp" - // default glyph value, used for reseting the character data portion of a cell static constexpr wchar_t DefaultValue = UNICODE_SPACE; diff --git a/src/buffer/out/CharRowCell.hpp b/src/buffer/out/CharRowCell.hpp index cca4ad453..fd8785baf 100644 --- a/src/buffer/out/CharRowCell.hpp +++ b/src/buffer/out/CharRowCell.hpp @@ -18,14 +18,12 @@ Author(s): #include "DbcsAttribute.hpp" - #if (defined(_M_IX86) || defined(_M_AMD64)) // 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. #pragma pack(push, 1) #endif - class CharRowCell final { public: @@ -44,6 +42,7 @@ public: const wchar_t& Char() const noexcept; friend constexpr bool operator==(const CharRowCell& a, const CharRowCell& b) noexcept; + private: wchar_t _wch; DbcsAttribute _attr; diff --git a/src/buffer/out/CharRowCellReference.cpp b/src/buffer/out/CharRowCellReference.cpp index b380ae8ee..1f320756b 100644 --- a/src/buffer/out/CharRowCellReference.cpp +++ b/src/buffer/out/CharRowCellReference.cpp @@ -5,7 +5,6 @@ #include "UnicodeStorage.hpp" #include "CharRow.hpp" - // Routine Description: // - assignment operator. will store extended glyph data in a separate storage location // Arguments: @@ -96,7 +95,6 @@ CharRowCellReference::const_iterator CharRowCellReference::end() const { if (_cellData().DbcsAttr().IsGlyphStored()) { - const auto& chars = _parent.GetUnicodeStorage().GetText(_parent.GetStorageKey(_index)); return chars.data() + chars.size(); } diff --git a/src/buffer/out/CharRowCellReference.hpp b/src/buffer/out/CharRowCellReference.hpp index d1fb7e80c..64a42a177 100644 --- a/src/buffer/out/CharRowCellReference.hpp +++ b/src/buffer/out/CharRowCellReference.hpp @@ -23,7 +23,6 @@ class CharRow; class CharRowCellReference final { public: - using const_iterator = const wchar_t*; CharRowCellReference(CharRow& parent, const size_t index) : @@ -45,7 +44,6 @@ public: const_iterator begin() const; const_iterator end() const; - friend bool operator==(const CharRowCellReference& ref, const std::vector& glyph); friend bool operator==(const std::vector& glyph, const CharRowCellReference& ref); diff --git a/src/buffer/out/DbcsAttribute.hpp b/src/buffer/out/DbcsAttribute.hpp index 34045efc1..f92a707b1 100644 --- a/src/buffer/out/DbcsAttribute.hpp +++ b/src/buffer/out/DbcsAttribute.hpp @@ -139,5 +139,6 @@ constexpr bool operator==(const DbcsAttribute& a, const DbcsAttribute& b) noexce return a._attribute == b._attribute; } -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"); +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"); diff --git a/src/buffer/out/OutputCell.cpp b/src/buffer/out/OutputCell.cpp index 7cc1d36d7..59dc1c1f8 100644 --- a/src/buffer/out/OutputCell.cpp +++ b/src/buffer/out/OutputCell.cpp @@ -17,7 +17,6 @@ OutputCell::OutputCell() : _textAttribute{ InvalidTextAttribute }, _behavior{ TextAttributeBehavior::Stored } { - } OutputCell::OutputCell(const std::wstring_view charData, diff --git a/src/buffer/out/OutputCell.hpp b/src/buffer/out/OutputCell.hpp index 93614fca0..8599ddf7c 100644 --- a/src/buffer/out/OutputCell.hpp +++ b/src/buffer/out/OutputCell.hpp @@ -78,9 +78,9 @@ public: } 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. - std::wstring _text; + std::wstring _text; DbcsAttribute _dbcsAttribute; TextAttribute _textAttribute; TextAttributeBehavior _behavior; diff --git a/src/buffer/out/OutputCellIterator.cpp b/src/buffer/out/OutputCellIterator.cpp index 4c6912709..2068e73af 100644 --- a/src/buffer/out/OutputCellIterator.cpp +++ b/src/buffer/out/OutputCellIterator.cpp @@ -26,7 +26,6 @@ OutputCellIterator::OutputCellIterator(const wchar_t& wch, const size_t fillLimi _distance(0), _fillLimit(fillLimit) { - } // Routine Description: @@ -43,7 +42,6 @@ OutputCellIterator::OutputCellIterator(const TextAttribute& attr, const size_t f _distance(0), _fillLimit(fillLimit) { - } // Routine Description: @@ -61,7 +59,6 @@ OutputCellIterator::OutputCellIterator(const wchar_t& wch, const TextAttribute& _distance(0), _fillLimit(fillLimit) { - } // Routine Description: @@ -78,7 +75,6 @@ OutputCellIterator::OutputCellIterator(const CHAR_INFO& charInfo, const size_t f _distance(0), _fillLimit(fillLimit) { - } // Routine Description: @@ -94,7 +90,6 @@ OutputCellIterator::OutputCellIterator(const std::wstring_view utf16Text) : _distance(0), _fillLimit(0) { - } // Routine Description: @@ -111,7 +106,6 @@ OutputCellIterator::OutputCellIterator(const std::wstring_view utf16Text, const _pos(0), _fillLimit(0) { - } // Routine Description: @@ -131,7 +125,6 @@ OutputCellIterator::OutputCellIterator(const std::basic_string_view legacy _pos(0), _fillLimit(0) { - } // Routine Description: @@ -142,12 +135,11 @@ OutputCellIterator::OutputCellIterator(const std::basic_string_view c _mode(Mode::CharInfo), _currentView(s_GenerateView(charInfos.at(0))), _run(charInfos), - _attr(InvalidTextAttribute), + _attr(InvalidTextAttribute), _distance(0), _pos(0), _fillLimit(0) { - } // Routine Description: @@ -163,7 +155,6 @@ OutputCellIterator::OutputCellIterator(const std::basic_string_view _pos(0), _fillLimit(0) { - } // Routine Description: diff --git a/src/buffer/out/OutputCellIterator.hpp b/src/buffer/out/OutputCellIterator.hpp index dc7bdc958..b5b290507 100644 --- a/src/buffer/out/OutputCellIterator.hpp +++ b/src/buffer/out/OutputCellIterator.hpp @@ -47,7 +47,7 @@ public: OutputCellIterator& operator=(const OutputCellIterator& it) = default; operator bool() const noexcept; - + ptrdiff_t GetCellDistance(OutputCellIterator other) const noexcept; ptrdiff_t GetInputDistance(OutputCellIterator other) const noexcept; friend ptrdiff_t operator-(OutputCellIterator one, OutputCellIterator two) = delete; @@ -59,12 +59,11 @@ public: const OutputCellView* operator->() const; private: - - enum class Mode - { + enum class Mode + { // 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. - Loose, + Loose, // 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 @@ -90,10 +89,11 @@ private: std::basic_string_view _legacyAttrs; std::variant< - std::wstring_view, - std::basic_string_view, - std::basic_string_view, - std::monostate> _run; + std::wstring_view, + std::basic_string_view, + std::basic_string_view, + std::monostate> + _run; TextAttribute _attr; diff --git a/src/buffer/out/OutputCellRect.cpp b/src/buffer/out/OutputCellRect.cpp index 444e39479..37711c534 100644 --- a/src/buffer/out/OutputCellRect.cpp +++ b/src/buffer/out/OutputCellRect.cpp @@ -11,7 +11,6 @@ OutputCellRect::OutputCellRect() : _rows(0), _cols(0) { - } // Routine Description: @@ -57,7 +56,7 @@ OutputCellIterator OutputCellRect::GetRowIter(const size_t row) const } // 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. // Arguments: // - row - The Y position or row index in the buffer. @@ -69,7 +68,7 @@ OutputCell* OutputCellRect::_FindRowOffset(const size_t row) } // 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. // Arguments: // - row - The Y position or row index in the buffer. diff --git a/src/buffer/out/OutputCellRect.hpp b/src/buffer/out/OutputCellRect.hpp index 9d6b05b6c..ae7323250 100644 --- a/src/buffer/out/OutputCellRect.hpp +++ b/src/buffer/out/OutputCellRect.hpp @@ -40,7 +40,7 @@ public: private: std::vector _storage; - + OutputCell* _FindRowOffset(const size_t row); const OutputCell* _FindRowOffset(const size_t row) const; diff --git a/src/buffer/out/OutputCellView.cpp b/src/buffer/out/OutputCellView.cpp index b5de8a823..434333c03 100644 --- a/src/buffer/out/OutputCellView.cpp +++ b/src/buffer/out/OutputCellView.cpp @@ -21,7 +21,6 @@ OutputCellView::OutputCellView(const std::wstring_view view, _textAttr(textAttr), _behavior(behavior) { - } // Routine Description: @@ -91,9 +90,9 @@ TextAttributeBehavior OutputCellView::TextAttrBehavior() const noexcept bool OutputCellView::operator==(const OutputCellView& it) const noexcept { return _view == it._view && - _dbcsAttr == it._dbcsAttr && - _textAttr == it._textAttr && - _behavior == it._behavior; + _dbcsAttr == it._dbcsAttr && + _textAttr == it._textAttr && + _behavior == it._behavior; } // Routine Description: diff --git a/src/buffer/out/OutputCellView.hpp b/src/buffer/out/OutputCellView.hpp index 470222a0c..2c425d808 100644 --- a/src/buffer/out/OutputCellView.hpp +++ b/src/buffer/out/OutputCellView.hpp @@ -25,7 +25,6 @@ Revision History: class OutputCellView { public: - OutputCellView(const std::wstring_view view, const DbcsAttribute dbcsAttr, const TextAttribute textAttr, diff --git a/src/buffer/out/Row.cpp b/src/buffer/out/Row.cpp index e3a32f359..44ffd941f 100644 --- a/src/buffer/out/Row.cpp +++ b/src/buffer/out/Row.cpp @@ -87,8 +87,7 @@ bool ROW::Reset(const TextAttribute Attr) // - width - the new width, in cells // Return Value: // - S_OK if successful, otherwise relevant error -[[nodiscard]] -HRESULT ROW::Resize(const size_t width) +[[nodiscard]] HRESULT ROW::Resize(const size_t width) { RETURN_IF_FAILED(_charRow.Resize(width)); 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. // - 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: -// - 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 limitRight) { 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; // 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. diff --git a/src/buffer/out/Row.hpp b/src/buffer/out/Row.hpp index 697fad812..5bf05c858 100644 --- a/src/buffer/out/Row.hpp +++ b/src/buffer/out/Row.hpp @@ -46,8 +46,7 @@ public: void SetId(const SHORT id) noexcept; bool Reset(const TextAttribute Attr); - [[nodiscard]] - HRESULT Resize(const size_t width); + [[nodiscard]] HRESULT Resize(const size_t width); void ClearColumn(const size_t column); std::wstring GetText() const; diff --git a/src/buffer/out/RowCellIterator.cpp b/src/buffer/out/RowCellIterator.cpp index 2a681e1cf..0381e4d93 100644 --- a/src/buffer/out/RowCellIterator.cpp +++ b/src/buffer/out/RowCellIterator.cpp @@ -16,7 +16,6 @@ RowCellIterator::RowCellIterator(const ROW& row, const size_t start, const size_ _pos(start), _view(s_GenerateView(row, start)) { - } RowCellIterator::operator bool() const noexcept @@ -29,9 +28,9 @@ RowCellIterator::operator bool() const noexcept bool RowCellIterator::operator==(const RowCellIterator& it) const noexcept { return _row == it._row && - _start == it._start && - _length == it._length && - _pos == it._pos; + _start == it._start && + _length == it._length && + _pos == it._pos; } bool RowCellIterator::operator!=(const RowCellIterator& it) const noexcept { diff --git a/src/buffer/out/TextAttribute.hpp b/src/buffer/out/TextAttribute.hpp index 5d5485b6d..1a53bbb61 100644 --- a/src/buffer/out/TextAttribute.hpp +++ b/src/buffer/out/TextAttribute.hpp @@ -164,7 +164,8 @@ private: #ifdef UNIT_TESTING friend class TextBufferTests; friend class TextAttributeTests; - template friend class WEX::TestExecution::VerifyOutputTraits; + template + friend class WEX::TestExecution::VerifyOutputTraits; #endif }; @@ -210,13 +211,15 @@ constexpr bool operator!=(const WORD& legacyAttr, const TextAttribute& attr) noe #ifdef UNIT_TESTING -#define LOG_ATTR(attr) (Log::Comment(NoThrowString().Format(\ +#define LOG_ATTR(attr) (Log::Comment(NoThrowString().Format( \ L#attr L"=%s", VerifyOutputTraits::ToString(attr).GetBuffer()))) -namespace WEX { - namespace TestExecution { +namespace WEX +{ + namespace TestExecution + { template<> - class VerifyOutputTraits < TextAttribute > + class VerifyOutputTraits { public: static WEX::Common::NoThrowString ToString(const TextAttribute& attr) @@ -226,8 +229,7 @@ namespace WEX { VerifyOutputTraits::ToString(attr._foreground).GetBuffer(), VerifyOutputTraits::ToString(attr._background).GetBuffer(), attr.IsBold(), - attr._wAttrLegacy - ); + attr._wAttrLegacy); } }; } diff --git a/src/buffer/out/TextColor.cpp b/src/buffer/out/TextColor.cpp index 90c6323dd..76778a823 100644 --- a/src/buffer/out/TextColor.cpp +++ b/src/buffer/out/TextColor.cpp @@ -86,7 +86,6 @@ COLORREF TextColor::GetColor(std::basic_string_view colorTable, return colorTable[i + 8]; } } - } return defaultColor; diff --git a/src/buffer/out/TextColor.h b/src/buffer/out/TextColor.h index 52885b02d..6ba928414 100644 --- a/src/buffer/out/TextColor.h +++ b/src/buffer/out/TextColor.h @@ -49,7 +49,6 @@ enum class ColorType : BYTE struct TextColor { public: - constexpr TextColor() noexcept : _meta{ ColorType::IsDefault }, _red{ 0 }, @@ -105,7 +104,6 @@ public: return _index; } - private: ColorType _meta : 2; union @@ -119,7 +117,8 @@ private: #ifdef UNIT_TESTING friend class TextBufferTests; - template friend class WEX::TestExecution::VerifyOutputTraits; + template + friend class WEX::TestExecution::VerifyOutputTraits; #endif }; @@ -140,10 +139,12 @@ bool constexpr operator!=(const TextColor& a, const TextColor& b) noexcept #ifdef UNIT_TESTING -namespace WEX { - namespace TestExecution { +namespace WEX +{ + namespace TestExecution + { template<> - class VerifyOutputTraits < TextColor > + class VerifyOutputTraits { public: static WEX::Common::NoThrowString ToString(const TextColor& color) @@ -166,4 +167,4 @@ namespace WEX { } #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"); diff --git a/src/buffer/out/UnicodeStorage.hpp b/src/buffer/out/UnicodeStorage.hpp index 0df3e7eb3..1b386da47 100644 --- a/src/buffer/out/UnicodeStorage.hpp +++ b/src/buffer/out/UnicodeStorage.hpp @@ -21,10 +21,9 @@ Author(s): // std::unordered_map needs help to know how to hash a COORD namespace std { - template <> + template<> struct hash { - // Routine Description: // - hashes a coord. coord will be hashed by storing the x and y values consecutively in the lower // bits of a size_t. diff --git a/src/buffer/out/cursor.cpp b/src/buffer/out/cursor.cpp index e95e7eef2..6cb695978 100644 --- a/src/buffer/out/cursor.cpp +++ b/src/buffer/out/cursor.cpp @@ -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. //_cPosition = pOtherCursor->_cPosition; - _fHasMoved = OtherCursor._fHasMoved; - _fIsVisible = OtherCursor._fIsVisible; - _fIsOn = OtherCursor._fIsOn; - _fIsDouble = OtherCursor._fIsDouble; - _fBlinkingAllowed = OtherCursor._fBlinkingAllowed; - _fDelay = OtherCursor._fDelay; - _fIsConversionArea = OtherCursor._fIsConversionArea; + _fHasMoved = OtherCursor._fHasMoved; + _fIsVisible = OtherCursor._fIsVisible; + _fIsOn = OtherCursor._fIsOn; + _fIsDouble = OtherCursor._fIsDouble; + _fBlinkingAllowed = OtherCursor._fBlinkingAllowed; + _fDelay = OtherCursor._fDelay; + _fIsConversionArea = OtherCursor._fIsConversionArea; // A resize operation should invalidate the delayed end of line status, so do not copy. //_fDelayedEolWrap = OtherCursor._fDelayedEolWrap; //_coordDelayedAt = OtherCursor._coordDelayedAt; - _fDeferCursorRedraw = OtherCursor._fDeferCursorRedraw; - _fHaveDeferredCursorRedraw = OtherCursor._fHaveDeferredCursorRedraw; + _fDeferCursorRedraw = OtherCursor._fDeferCursorRedraw; + _fHaveDeferredCursorRedraw = OtherCursor._fHaveDeferredCursorRedraw; // Size will be handled seperately in the resize operation. //_ulSize = OtherCursor._ulSize; - _cursorType = OtherCursor._cursorType; - _color = OtherCursor._color; + _cursorType = OtherCursor._cursorType; + _color = OtherCursor._color; } void Cursor::DelayEOLWrap(const COORD coordDelayedAt) @@ -296,7 +296,7 @@ void Cursor::DelayEOLWrap(const COORD coordDelayedAt) void Cursor::ResetDelayEOLWrap() { - _coordDelayedAt = {0}; + _coordDelayedAt = { 0 }; _fDelayedEolWrap = false; } diff --git a/src/buffer/out/cursor.h b/src/buffer/out/cursor.h index 027d9f08d..496e96f1f 100644 --- a/src/buffer/out/cursor.h +++ b/src/buffer/out/cursor.h @@ -20,13 +20,12 @@ Revision History: #include "../inc/conattrs.hpp" // 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 Cursor final { public: - static const unsigned int s_InvertCursorColor = INVALID_COLOR; Cursor(const ULONG ulSize, TextBuffer& parentBuffer); @@ -94,19 +93,19 @@ private: // 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 _fIsVisible; // whether cursor is visible (set only through the API) - bool _fIsOn; // whether blinking cursor is on or not - bool _fIsDouble; // whether the cursor size should be doubled + bool _fIsVisible; // whether cursor is visible (set only through the API) + bool _fIsOn; // whether blinking cursor is on or not + 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 _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 _fIsPopupShown; // if a popup is being shown, turn off, stop blinking. - bool _fDelayedEolWrap; // don't wrap at EOL till the next char comes in. - COORD _coordDelayedAt; // coordinate the EOL wrap was delayed at. + bool _fDelayedEolWrap; // don't wrap at EOL till the next char comes in. + COORD _coordDelayedAt; // coordinate the EOL wrap was delayed at. 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? diff --git a/src/buffer/out/precomp.h b/src/buffer/out/precomp.h index adb1cfb93..b81322c90 100644 --- a/src/buffer/out/precomp.h +++ b/src/buffer/out/precomp.h @@ -17,6 +17,8 @@ Abstract: #pragma once +// clang-format off + // This includes support libraries from the CRT, STL, WIL, and GSL #include "LibraryIncludes.h" @@ -33,3 +35,5 @@ Abstract: #include "..\inc\operators.hpp" #include "..\inc\unicode.hpp" #pragma warning(pop) + +// clang-format on diff --git a/src/buffer/out/textBuffer.cpp b/src/buffer/out/textBuffer.cpp index ecdf8fb70..094ede520 100644 --- a/src/buffer/out/textBuffer.cpp +++ b/src/buffer/out/textBuffer.cpp @@ -748,8 +748,7 @@ const Cursor& TextBuffer::GetCursor() const return _cursor; } -[[nodiscard]] -TextAttribute TextBuffer::GetCurrentAttributes() const noexcept +[[nodiscard]] TextAttribute TextBuffer::GetCurrentAttributes() const noexcept { return _currentAttributes; } @@ -779,8 +778,7 @@ void TextBuffer::Reset() // - newSize - new size of screen. // Return Value: // - Success if successful. Invalid parameter if screen buffer size is unexpected. No memory if allocation failed. -[[nodiscard]] -NTSTATUS TextBuffer::ResizeTraditional(const COORD newSize) noexcept +[[nodiscard]] NTSTATUS TextBuffer::ResizeTraditional(const COORD newSize) noexcept { 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 // and cleanup the UnicodeStorage characters that might fall outside the resized buffer. _RefreshRowIDs(newSize.X); - } CATCH_RETURN(); @@ -1012,7 +1009,7 @@ const TextBuffer::TextAndColor TextBuffer::GetTextForClipboard(const bool lineSe // always apply \r\n for box selection 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_LINEFEED); diff --git a/src/buffer/out/textBuffer.hpp b/src/buffer/out/textBuffer.hpp index 7d46022e4..8e5aa2051 100644 --- a/src/buffer/out/textBuffer.hpp +++ b/src/buffer/out/textBuffer.hpp @@ -117,15 +117,13 @@ public: UINT TotalRowCount() const; - [[nodiscard]] - TextAttribute GetCurrentAttributes() const noexcept; + [[nodiscard]] TextAttribute GetCurrentAttributes() const noexcept; void SetCurrentAttributes(const TextAttribute currentAttributes) noexcept; void Reset(); - [[nodiscard]] - HRESULT ResizeTraditional(const COORD newSize) noexcept; + [[nodiscard]] HRESULT ResizeTraditional(const COORD newSize) noexcept; const UnicodeStorage& GetUnicodeStorage() const; UnicodeStorage& GetUnicodeStorage(); @@ -147,7 +145,6 @@ public: std::function GetBackgroundColor) const; private: - std::deque _storage; Cursor _cursor; diff --git a/src/buffer/out/textBufferCellIterator.cpp b/src/buffer/out/textBufferCellIterator.cpp index 765214a31..50948ab6b 100644 --- a/src/buffer/out/textBufferCellIterator.cpp +++ b/src/buffer/out/textBufferCellIterator.cpp @@ -68,11 +68,11 @@ TextBufferCellIterator::operator bool() const noexcept bool TextBufferCellIterator::operator==(const TextBufferCellIterator& it) const noexcept { return _pos == it._pos && - &_buffer == &it._buffer && - _exceeded == it._exceeded && - _bounds == it._bounds && - _pRow == it._pRow && - _attrIter == it._attrIter; + &_buffer == &it._buffer && + _exceeded == it._exceeded && + _bounds == it._bounds && + _pRow == it._pRow && + _attrIter == it._attrIter; } // Routine Description: diff --git a/src/buffer/out/textBufferCellIterator.hpp b/src/buffer/out/textBufferCellIterator.hpp index 75cc8d08c..730154f28 100644 --- a/src/buffer/out/textBufferCellIterator.hpp +++ b/src/buffer/out/textBufferCellIterator.hpp @@ -50,7 +50,6 @@ public: const OutputCellView* operator->() const noexcept; protected: - void _SetPos(const COORD newPos); void _GenerateView(); static const ROW* s_GetRow(const TextBuffer& buffer, const COORD pos); @@ -70,4 +69,3 @@ protected: friend class ApiRoutinesTests; #endif }; - diff --git a/src/buffer/out/textBufferTextIterator.cpp b/src/buffer/out/textBufferTextIterator.cpp index e1fe1a65b..05c6a4c99 100644 --- a/src/buffer/out/textBufferTextIterator.cpp +++ b/src/buffer/out/textBufferTextIterator.cpp @@ -38,4 +38,3 @@ const std::wstring_view* TextBufferTextIterator::operator->() const { return &_view.Chars(); } - diff --git a/src/buffer/out/textBufferTextIterator.hpp b/src/buffer/out/textBufferTextIterator.hpp index 8d8b5cbf9..845e86e19 100644 --- a/src/buffer/out/textBufferTextIterator.hpp +++ b/src/buffer/out/textBufferTextIterator.hpp @@ -28,7 +28,6 @@ public: const std::wstring_view* operator->() const; protected: - #if UNIT_TESTING friend class TextBufferIteratorTests; #endif diff --git a/src/buffer/out/ut_textbuffer/TextAttributeTests.cpp b/src/buffer/out/ut_textbuffer/TextAttributeTests.cpp index 090680304..da6d89ab6 100644 --- a/src/buffer/out/ut_textbuffer/TextAttributeTests.cpp +++ b/src/buffer/out/ut_textbuffer/TextAttributeTests.cpp @@ -72,8 +72,7 @@ void TextAttributeTests::TestRoundtripLegacy() void TextAttributeTests::TestRoundtripMetaBits() { - WORD metaFlags[] = - { + WORD metaFlags[] = { COMMON_LVB_GRID_HORIZONTAL, COMMON_LVB_GRID_LVERTICAL, COMMON_LVB_GRID_RVERTICAL, @@ -102,7 +101,7 @@ void TextAttributeTests::TestRoundtripExhaustive() // each takes a lot longer than checking. // 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 " - "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."); for (WORD wLegacy = 0; wLegacy < allAttrs; wLegacy++) { @@ -123,8 +122,7 @@ void TextAttributeTests::TestRoundtripExhaustive() if (!(isLegacy && areEqual)) { Log::Comment(NoThrowString().Format( - L"Failed on wLegacy=0x%x", wLegacy - )); + L"Failed on wLegacy=0x%x", wLegacy)); VERIFY_IS_TRUE(attr.IsLegacy()); VERIFY_ARE_EQUAL(wLegacy, attr.GetLegacyAttributes()); } diff --git a/src/buffer/out/ut_textbuffer/TextColorTests.cpp b/src/buffer/out/ut_textbuffer/TextColorTests.cpp index dc5c23adb..3497bdcae 100644 --- a/src/buffer/out/ut_textbuffer/TextColorTests.cpp +++ b/src/buffer/out/ut_textbuffer/TextColorTests.cpp @@ -199,7 +199,6 @@ void TextColorTests::TestChangeColor() color = rgbColor.GetColor(view, _defaultBg, true); VERIFY_ARE_EQUAL(_colorTable[15], color); - rgbColor.SetIndex(15); color = rgbColor.GetColor(view, _defaultFg, false); VERIFY_ARE_EQUAL(_colorTable[15], color); diff --git a/src/buffer/out/ut_textbuffer/UnicodeStorageTests.cpp b/src/buffer/out/ut_textbuffer/UnicodeStorageTests.cpp index 9ba5aceac..4781d4c05 100644 --- a/src/buffer/out/ut_textbuffer/UnicodeStorageTests.cpp +++ b/src/buffer/out/ut_textbuffer/UnicodeStorageTests.cpp @@ -15,7 +15,6 @@ class UnicodeStorageTests { TEST_CLASS(UnicodeStorageTests); - TEST_METHOD(CanOverwriteEmoji) { UnicodeStorage storage; diff --git a/src/buffer/out/ut_textbuffer/precomp.h b/src/buffer/out/ut_textbuffer/precomp.h index 42155ece0..e5fb1dd09 100644 --- a/src/buffer/out/ut_textbuffer/precomp.h +++ b/src/buffer/out/ut_textbuffer/precomp.h @@ -17,6 +17,8 @@ Abstract: #pragma once +// clang-format off + // This includes support libraries from the CRT, STL, WIL, and GSL #include "LibraryIncludes.h" @@ -35,3 +37,5 @@ Abstract: #include "..\inc\operators.hpp" #include "..\inc\unicode.hpp" #pragma warning(pop) + +// clang-format on diff --git a/src/cascadia/Microsoft.UI.Xaml.Markup/XamlApplication.cpp b/src/cascadia/Microsoft.UI.Xaml.Markup/XamlApplication.cpp index 62dbb4b88..e37a1bd0e 100644 --- a/src/cascadia/Microsoft.UI.Xaml.Markup/XamlApplication.cpp +++ b/src/cascadia/Microsoft.UI.Xaml.Markup/XamlApplication.cpp @@ -10,10 +10,10 @@ namespace xaml = ::winrt::Windows::UI::Xaml; extern "C" { - WINBASEAPI HMODULE WINAPI LoadLibraryExW(_In_ LPCWSTR lpLibFileName, _Reserved_ HANDLE hFile, _In_ DWORD dwFlags); - 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 LRESULT WINAPI DispatchMessageW(_In_ CONST MSG* lpMsg); +WINBASEAPI HMODULE WINAPI LoadLibraryExW(_In_ LPCWSTR lpLibFileName, _Reserved_ HANDLE hFile, _In_ DWORD dwFlags); +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 LRESULT WINAPI DispatchMessageW(_In_ CONST MSG* lpMsg); } namespace winrt::Microsoft::UI::Xaml::Markup::implementation diff --git a/src/cascadia/Microsoft.UI.Xaml.Markup/XamlApplication.h b/src/cascadia/Microsoft.UI.Xaml.Markup/XamlApplication.h index af9823f6f..59f81f33e 100644 --- a/src/cascadia/Microsoft.UI.Xaml.Markup/XamlApplication.h +++ b/src/cascadia/Microsoft.UI.Xaml.Markup/XamlApplication.h @@ -39,6 +39,7 @@ namespace winrt::Microsoft::UI::Xaml::Markup::factory_implementation public: XamlApplication(); ~XamlApplication(); + private: std::vector m_preloadInstances; }; diff --git a/src/cascadia/Microsoft.UI.Xaml.Markup/pch.h b/src/cascadia/Microsoft.UI.Xaml.Markup/pch.h index eb8e9db80..723474601 100644 --- a/src/cascadia/Microsoft.UI.Xaml.Markup/pch.h +++ b/src/cascadia/Microsoft.UI.Xaml.Markup/pch.h @@ -19,4 +19,3 @@ #include #include - diff --git a/src/cascadia/TerminalApp/App.cpp b/src/cascadia/TerminalApp/App.cpp index c19574698..e08763c65 100644 --- a/src/cascadia/TerminalApp/App.cpp +++ b/src/cascadia/TerminalApp/App.cpp @@ -36,7 +36,6 @@ namespace winrt namespace winrt::TerminalApp::implementation { - App::App() : App(winrt::TerminalApp::XamlMetaDataProvider()) { @@ -44,8 +43,8 @@ namespace winrt::TerminalApp::implementation App::App(Windows::UI::Xaml::Markup::IXamlMetadataProvider const& parentProvider) : base_type(parentProvider), - _settings{ }, - _tabs{ }, + _settings{}, + _tabs{}, _loadedInitialSettings{ false }, _settingsLoadedResult{ S_OK }, _dialogLock{} @@ -138,7 +137,7 @@ namespace winrt::TerminalApp::implementation _newTabButton.HorizontalAlignment(HorizontalAlignment::Left); // 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); }); @@ -263,7 +262,6 @@ namespace winrt::TerminalApp::implementation return TermControl::GetProposedDimensions(settings, dpi); } - bool App::GetShowTabsInTitlebar() { if (!_loadedInitialSettings) @@ -322,7 +320,7 @@ namespace winrt::TerminalApp::implementation profileMenuItem.FontWeight(FontWeights::Bold()); } - profileMenuItem.Click([this, profileIndex](auto&&, auto&&){ + profileMenuItem.Click([this, profileIndex](auto&&, auto&&) { this->_OpenNewTab({ profileIndex }); }); newTabFlyout.Items().Append(profileMenuItem); @@ -391,7 +389,7 @@ namespace winrt::TerminalApp::implementation // Return Value: // - void App::_SettingsButtonOnClick(const IInspectable&, - const RoutedEventArgs&) + const RoutedEventArgs&) { LaunchSettings(); } @@ -440,8 +438,7 @@ namespace winrt::TerminalApp::implementation // `CascadiaSettings::LoadAll` for details. // Return Value: // - S_OK if we successfully parsed the settings, otherwise an appropriate HRESULT. - [[nodiscard]] - HRESULT App::_TryLoadSettings(const bool saveOnLoad) noexcept + [[nodiscard]] HRESULT App::_TryLoadSettings(const bool saveOnLoad) noexcept { HRESULT hr = E_FAIL; @@ -514,32 +511,33 @@ namespace winrt::TerminalApp::implementation std::filesystem::path fileParser = localPathCopy.c_str(); const auto folder = fileParser.parent_path(); - _reader.create(folder.c_str(), false, wil::FolderChangeEvents::All, - [this](wil::FolderChangeEvent event, PCWSTR fileModified) - { - // We want file modifications, AND when files are renamed to be - // profiles.json. This second case will oftentimes happen with text - // editors, who will write a temp file, then rename it to be the - // actual file you wrote. So listen for that too. - if (!(event == wil::FolderChangeEvent::Modified || - event == wil::FolderChangeEvent::RenameNewName)) - { - return; - } + _reader.create(folder.c_str(), + false, + wil::FolderChangeEvents::All, + [this](wil::FolderChangeEvent event, PCWSTR fileModified) { + // We want file modifications, AND when files are renamed to be + // profiles.json. This second case will oftentimes happen with text + // editors, who will write a temp file, then rename it to be the + // actual file you wrote. So listen for that too. + if (!(event == wil::FolderChangeEvent::Modified || + event == wil::FolderChangeEvent::RenameNewName)) + { + return; + } - const auto localPathCopy = CascadiaSettings::GetSettingsPath(); - std::filesystem::path settingsParser = localPathCopy.c_str(); - std::filesystem::path modifiedParser = fileModified; + const auto localPathCopy = CascadiaSettings::GetSettingsPath(); + std::filesystem::path settingsParser = localPathCopy.c_str(); + std::filesystem::path modifiedParser = fileModified; - // Getting basename (filename.ext) - const auto settingsBasename = settingsParser.filename(); - const auto modifiedBasename = modifiedParser.filename(); + // Getting basename (filename.ext) + const auto settingsBasename = settingsParser.filename(); + const auto modifiedBasename = modifiedParser.filename(); - if (settingsBasename == modifiedBasename) - { - this->_ReloadSettings(); - } - }); + if (settingsBasename == modifiedBasename) + { + this->_ReloadSettings(); + } + }); } // Method Description: @@ -574,12 +572,12 @@ namespace winrt::TerminalApp::implementation // Refresh UI elements auto profiles = _settings->GetProfiles(); - for (auto &profile : profiles) + for (auto& profile : profiles) { const GUID profileGuid = profile.GetGuid(); TerminalSettings settings = _settings->MakeSettings(profileGuid); - for (auto &tab : _tabs) + for (auto& tab : _tabs) { // Attempt to reload the settings of any panes with this profile tab->UpdateSettings(settings, profileGuid); @@ -600,7 +598,6 @@ namespace winrt::TerminalApp::implementation // profile, which might have changed _CreateNewTabFlyout(); }); - } // Method Description: @@ -673,7 +670,7 @@ namespace winrt::TerminalApp::implementation // GH#1117: This is a workaround because _tabView.SelectedIndex(tabIndex) // sometimes set focus to an incorrect tab after removing some tabs auto tab = _tabs.at(tabIndex); - _tabView.Dispatcher().RunAsync(CoreDispatcherPriority::Normal, [tab, this](){ + _tabView.Dispatcher().RunAsync(CoreDispatcherPriority::Normal, [tab, this]() { auto tabViewItem = tab->GetTabViewItem(); _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 // is called, we don't really care anymore about handling the event. std::weak_ptr weakTabPtr = hostingTab; - term.TitleChanged([this, weakTabPtr](auto newTitle){ + term.TitleChanged([this, weakTabPtr](auto newTitle) { auto tab = weakTabPtr.lock(); if (!tab) { @@ -801,8 +798,7 @@ namespace winrt::TerminalApp::implementation _UpdateTitle(tab); }); - term.GetControl().GotFocus([this, weakTabPtr](auto&&, auto&&) - { + term.GetControl().GotFocus([this, weakTabPtr](auto&&, auto&&) { auto tab = weakTabPtr.lock(); if (!tab) { @@ -850,7 +846,7 @@ namespace winrt::TerminalApp::implementation tabViewItem.PointerPressed({ this, &App::_OnTabClick }); // 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]() { _RemoveTabViewItem(tabViewItem); }); @@ -945,8 +941,7 @@ namespace winrt::TerminalApp::implementation // we clamp the values to the range [0, tabCount) while still supporting moving // leftward from 0 to tabCount - 1. _SetFocusedTabIndex( - static_cast((tabCount + focusedTabIndex + (bMoveRight ? 1 : -1)) % tabCount) - ); + static_cast((tabCount + focusedTabIndex + (bMoveRight ? 1 : -1)) % tabCount)); } // Method Description: diff --git a/src/cascadia/TerminalApp/App.h b/src/cascadia/TerminalApp/App.h index f8a5c66bd..40f7bc150 100644 --- a/src/cascadia/TerminalApp/App.h +++ b/src/cascadia/TerminalApp/App.h @@ -18,9 +18,8 @@ namespace winrt::TerminalApp::implementation { - // We dont use AppT as it does not provide access to protected constructors - template + template using AppT_Override = App_base; struct App : AppT_Override @@ -75,8 +74,7 @@ namespace winrt::TerminalApp::implementation fire_and_forget _ShowOkDialog(const winrt::hstring& titleKey, const winrt::hstring& contentKey); - [[nodiscard]] - HRESULT _TryLoadSettings(const bool saveOnLoad) noexcept; + [[nodiscard]] HRESULT _TryLoadSettings(const bool saveOnLoad) noexcept; void _LoadSettings(); void _OpenSettings(); @@ -92,7 +90,6 @@ namespace winrt::TerminalApp::implementation void _UpdateTabIcon(std::shared_ptr tab); void _UpdateTitle(std::shared_ptr tab); - void _RegisterTerminalEvents(Microsoft::Terminal::TerminalControl::TermControl term, std::shared_ptr hostingTab); void _CreateNewTabFromSettings(GUID profileGuid, winrt::Microsoft::Terminal::Settings::TerminalSettings settings); diff --git a/src/cascadia/TerminalApp/AppKeyBindings.cpp b/src/cascadia/TerminalApp/AppKeyBindings.cpp index 91c459d91..9430d9f95 100644 --- a/src/cascadia/TerminalApp/AppKeyBindings.cpp +++ b/src/cascadia/TerminalApp/AppKeyBindings.cpp @@ -23,7 +23,10 @@ namespace winrt::TerminalApp::implementation { for (auto& kv : _keyShortcuts) { - if (kv.second == action) return kv.first; + if (kv.second == action) + { + return kv.first; + } } return { nullptr }; } @@ -43,114 +46,114 @@ namespace winrt::TerminalApp::implementation { switch (action) { - case ShortcutAction::CopyText: - _CopyTextHandlers(); - return true; - case ShortcutAction::PasteText: - _PasteTextHandlers(); - return true; - case ShortcutAction::NewTab: - _NewTabHandlers(); - return true; - case ShortcutAction::OpenSettings: - _OpenSettingsHandlers(); - return true; + case ShortcutAction::CopyText: + _CopyTextHandlers(); + return true; + case ShortcutAction::PasteText: + _PasteTextHandlers(); + return true; + case ShortcutAction::NewTab: + _NewTabHandlers(); + return true; + case ShortcutAction::OpenSettings: + _OpenSettingsHandlers(); + return true; - case ShortcutAction::NewTabProfile0: - _NewTabWithProfileHandlers(0); - return true; - case ShortcutAction::NewTabProfile1: - _NewTabWithProfileHandlers(1); - return true; - case ShortcutAction::NewTabProfile2: - _NewTabWithProfileHandlers(2); - return true; - case ShortcutAction::NewTabProfile3: - _NewTabWithProfileHandlers(3); - return true; - case ShortcutAction::NewTabProfile4: - _NewTabWithProfileHandlers(4); - return true; - case ShortcutAction::NewTabProfile5: - _NewTabWithProfileHandlers(5); - return true; - case ShortcutAction::NewTabProfile6: - _NewTabWithProfileHandlers(6); - return true; - case ShortcutAction::NewTabProfile7: - _NewTabWithProfileHandlers(7); - return true; - case ShortcutAction::NewTabProfile8: - _NewTabWithProfileHandlers(8); - return true; + case ShortcutAction::NewTabProfile0: + _NewTabWithProfileHandlers(0); + return true; + case ShortcutAction::NewTabProfile1: + _NewTabWithProfileHandlers(1); + return true; + case ShortcutAction::NewTabProfile2: + _NewTabWithProfileHandlers(2); + return true; + case ShortcutAction::NewTabProfile3: + _NewTabWithProfileHandlers(3); + return true; + case ShortcutAction::NewTabProfile4: + _NewTabWithProfileHandlers(4); + return true; + case ShortcutAction::NewTabProfile5: + _NewTabWithProfileHandlers(5); + return true; + case ShortcutAction::NewTabProfile6: + _NewTabWithProfileHandlers(6); + return true; + case ShortcutAction::NewTabProfile7: + _NewTabWithProfileHandlers(7); + return true; + case ShortcutAction::NewTabProfile8: + _NewTabWithProfileHandlers(8); + return true; - case ShortcutAction::NewWindow: - _NewWindowHandlers(); - return true; - case ShortcutAction::CloseWindow: - _CloseWindowHandlers(); - return true; - case ShortcutAction::CloseTab: - _CloseTabHandlers(); - return true; + case ShortcutAction::NewWindow: + _NewWindowHandlers(); + return true; + case ShortcutAction::CloseWindow: + _CloseWindowHandlers(); + return true; + case ShortcutAction::CloseTab: + _CloseTabHandlers(); + return true; - case ShortcutAction::ScrollUp: - _ScrollUpHandlers(); - return true; - case ShortcutAction::ScrollDown: - _ScrollDownHandlers(); - return true; - case ShortcutAction::ScrollUpPage: - _ScrollUpPageHandlers(); - return true; - case ShortcutAction::ScrollDownPage: - _ScrollDownPageHandlers(); - return true; + case ShortcutAction::ScrollUp: + _ScrollUpHandlers(); + return true; + case ShortcutAction::ScrollDown: + _ScrollDownHandlers(); + return true; + case ShortcutAction::ScrollUpPage: + _ScrollUpPageHandlers(); + return true; + case ShortcutAction::ScrollDownPage: + _ScrollDownPageHandlers(); + return true; - case ShortcutAction::NextTab: - _NextTabHandlers(); - return true; - case ShortcutAction::PrevTab: - _PrevTabHandlers(); - return true; + case ShortcutAction::NextTab: + _NextTabHandlers(); + return true; + case ShortcutAction::PrevTab: + _PrevTabHandlers(); + return true; - case ShortcutAction::SplitVertical: - _SplitVerticalHandlers(); - return true; - case ShortcutAction::SplitHorizontal: - _SplitHorizontalHandlers(); - return true; + case ShortcutAction::SplitVertical: + _SplitVerticalHandlers(); + return true; + case ShortcutAction::SplitHorizontal: + _SplitHorizontalHandlers(); + return true; - case ShortcutAction::SwitchToTab0: - _SwitchToTabHandlers(0); - return true; - case ShortcutAction::SwitchToTab1: - _SwitchToTabHandlers(1); - return true; - case ShortcutAction::SwitchToTab2: - _SwitchToTabHandlers(2); - return true; - case ShortcutAction::SwitchToTab3: - _SwitchToTabHandlers(3); - return true; - case ShortcutAction::SwitchToTab4: - _SwitchToTabHandlers(4); - return true; - case ShortcutAction::SwitchToTab5: - _SwitchToTabHandlers(5); - return true; - case ShortcutAction::SwitchToTab6: - _SwitchToTabHandlers(6); - return true; - case ShortcutAction::SwitchToTab7: - _SwitchToTabHandlers(7); - return true; - case ShortcutAction::SwitchToTab8: - _SwitchToTabHandlers(8); - return true; + case ShortcutAction::SwitchToTab0: + _SwitchToTabHandlers(0); + return true; + case ShortcutAction::SwitchToTab1: + _SwitchToTabHandlers(1); + return true; + case ShortcutAction::SwitchToTab2: + _SwitchToTabHandlers(2); + return true; + case ShortcutAction::SwitchToTab3: + _SwitchToTabHandlers(3); + return true; + case ShortcutAction::SwitchToTab4: + _SwitchToTabHandlers(4); + return true; + case ShortcutAction::SwitchToTab5: + _SwitchToTabHandlers(5); + return true; + case ShortcutAction::SwitchToTab6: + _SwitchToTabHandlers(6); + return true; + case ShortcutAction::SwitchToTab7: + _SwitchToTabHandlers(7); + return true; + case ShortcutAction::SwitchToTab8: + _SwitchToTabHandlers(8); + return true; - default: - return false; + default: + return false; } return false; } @@ -208,6 +211,7 @@ namespace winrt::TerminalApp::implementation } // -------------------------------- Events --------------------------------- + // clang-format off DEFINE_EVENT(AppKeyBindings, CopyText, _CopyTextHandlers, TerminalApp::CopyTextEventArgs); DEFINE_EVENT(AppKeyBindings, PasteText, _PasteTextHandlers, TerminalApp::PasteTextEventArgs); 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, ScrollDownPage, _ScrollDownPageHandlers, TerminalApp::ScrollDownPageEventArgs); DEFINE_EVENT(AppKeyBindings, OpenSettings, _OpenSettingsHandlers, TerminalApp::OpenSettingsEventArgs); + // clang-format on } diff --git a/src/cascadia/TerminalApp/AppKeyBindings.h b/src/cascadia/TerminalApp/AppKeyBindings.h index 6bbd657f7..4e762d095 100644 --- a/src/cascadia/TerminalApp/AppKeyBindings.h +++ b/src/cascadia/TerminalApp/AppKeyBindings.h @@ -39,6 +39,7 @@ namespace winrt::TerminalApp::implementation static Windows::System::VirtualKeyModifiers ConvertVKModifiers(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(PasteText, _PasteTextHandlers, TerminalApp::PasteTextEventArgs); DECLARE_EVENT(NewTab, _NewTabHandlers, TerminalApp::NewTabEventArgs); @@ -58,11 +59,11 @@ namespace winrt::TerminalApp::implementation DECLARE_EVENT(ScrollUpPage, _ScrollUpPageHandlers, TerminalApp::ScrollUpPageEventArgs); DECLARE_EVENT(ScrollDownPage, _ScrollDownPageHandlers, TerminalApp::ScrollDownPageEventArgs); DECLARE_EVENT(OpenSettings, _OpenSettingsHandlers, TerminalApp::OpenSettingsEventArgs); + // clang-format on private: std::unordered_map _keyShortcuts; bool _DoAction(ShortcutAction action); - }; } diff --git a/src/cascadia/TerminalApp/AppKeyBindingsSerialization.cpp b/src/cascadia/TerminalApp/AppKeyBindingsSerialization.cpp index 9ef61436f..2eed0e907 100644 --- a/src/cascadia/TerminalApp/AppKeyBindingsSerialization.cpp +++ b/src/cascadia/TerminalApp/AppKeyBindingsSerialization.cpp @@ -58,7 +58,7 @@ static constexpr std::string_view SplitVerticalKey{ "splitVertical" }; // 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 // about here. -static const std::map> commandNames { +static const std::map> commandNames{ { CopyTextKey, ShortcutAction::CopyText }, { PasteTextKey, ShortcutAction::PasteText }, { NewTabKey, ShortcutAction::NewTab }, @@ -211,5 +211,4 @@ winrt::TerminalApp::AppKeyBindings AppKeyBindingsSerialization::FromJson(const J } } return newBindings; - } diff --git a/src/cascadia/TerminalApp/CascadiaSettings.cpp b/src/cascadia/TerminalApp/CascadiaSettings.cpp index 4846e4b89..e778d226d 100644 --- a/src/cascadia/TerminalApp/CascadiaSettings.cpp +++ b/src/cascadia/TerminalApp/CascadiaSettings.cpp @@ -18,8 +18,7 @@ using namespace Microsoft::Console; // {2bde4a90-d05f-401c-9492-e40884ead1d8} // uuidv5 properties: name format is UTF-16LE bytes -static constexpr GUID TERMINAL_PROFILE_NAMESPACE_GUID = -{ 0x2bde4a90, 0xd05f, 0x401c, { 0x94, 0x92, 0xe4, 0x8, 0x84, 0xea, 0xd1, 0xd8 } }; +static constexpr GUID TERMINAL_PROFILE_NAMESPACE_GUID = { 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_EXTENSION{ L".png" }; @@ -29,19 +28,17 @@ CascadiaSettings::CascadiaSettings() : _globals{}, _profiles{} { - } CascadiaSettings::~CascadiaSettings() { - } ColorScheme _CreateCampbellScheme() { - ColorScheme campbellScheme { L"Campbell", - RGB(242, 242, 242), - RGB(12, 12, 12) }; + ColorScheme campbellScheme{ L"Campbell", + RGB(242, 242, 242), + RGB(12, 12, 12) }; auto& campbellTable = campbellScheme.GetTable(); auto campbellSpan = gsl::span(&campbellTable[0], gsl::narrow(COLOR_TABLE_SIZE)); Utils::InitializeCampbellColorTable(campbellSpan); @@ -50,6 +47,8 @@ ColorScheme _CreateCampbellScheme() return campbellScheme; } +// clang-format off + ColorScheme _CreateOneHalfDarkScheme() { // First 8 dark colors per: https://github.com/sonph/onehalf/blob/master/putty/onehalf-dark.reg @@ -167,6 +166,8 @@ ColorScheme _CreateSolarizedLightScheme() return solarizedLightScheme; } +// clang-format on + // Method Description: // - Create the set of schemes to use as the default schemes. Currently creates // 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 // keychord,action pairings from that file keyBindings.SetKeyBinding(ShortcutAction::NewTab, - KeyChord{ KeyModifiers::Ctrl, - static_cast('T') }); + KeyChord{ KeyModifiers::Ctrl, + static_cast('T') }); keyBindings.SetKeyBinding(ShortcutAction::CloseTab, - KeyChord{ KeyModifiers::Ctrl, - static_cast('W') }); + KeyChord{ KeyModifiers::Ctrl, + static_cast('W') }); keyBindings.SetKeyBinding(ShortcutAction::OpenSettings, - KeyChord{ KeyModifiers::Ctrl, - VK_OEM_COMMA }); + KeyChord{ KeyModifiers::Ctrl, + VK_OEM_COMMA }); keyBindings.SetKeyBinding(ShortcutAction::NextTab, - KeyChord{ KeyModifiers::Ctrl, - VK_TAB }); + KeyChord{ KeyModifiers::Ctrl, + VK_TAB }); keyBindings.SetKeyBinding(ShortcutAction::PrevTab, - KeyChord{ KeyModifiers::Ctrl | KeyModifiers::Shift, - VK_TAB }); + KeyChord{ KeyModifiers::Ctrl | KeyModifiers::Shift, + VK_TAB }); // Yes these are offset by one. // 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& pro std::wstring command(systemPath.get()); command += L"\\wsl.exe --list"; - THROW_IF_WIN32_BOOL_FALSE(CreateProcessW(nullptr, const_cast(command.c_str()), nullptr, nullptr, - TRUE, CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi)); + THROW_IF_WIN32_BOOL_FALSE(CreateProcessW(nullptr, + const_cast(command.c_str()), + nullptr, + nullptr, + TRUE, + CREATE_NO_WINDOW, + nullptr, + nullptr, + &si, + &pi)); switch (WaitForSingleObject(pi.hProcess, INFINITE)) { case WAIT_OBJECT_0: @@ -524,9 +533,10 @@ void CascadiaSettings::_AppendWslProfiles(std::vector& pro DWORD bytesAvailable; 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") }; - //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::getline(pipe, wline); //remove the header from the output. + std::getline(pipe, wline); // remove the header from the output. while (pipe.tellp() < bytesAvailable) { std::getline(pipe, wline); @@ -571,7 +581,7 @@ std::wstring CascadiaSettings::ExpandEnvironmentVariableString(std::wstring_view } while (requiredSize != result.size()); // Trim the terminating null character - result.resize(requiredSize-1); + result.resize(requiredSize - 1); return result; } diff --git a/src/cascadia/TerminalApp/CascadiaSettings.h b/src/cascadia/TerminalApp/CascadiaSettings.h index 74d069f1f..f8a511328 100644 --- a/src/cascadia/TerminalApp/CascadiaSettings.h +++ b/src/cascadia/TerminalApp/CascadiaSettings.h @@ -20,7 +20,6 @@ Author(s): #include "GlobalAppSettings.h" #include "Profile.h" - namespace TerminalApp { class CascadiaSettings; @@ -28,7 +27,6 @@ namespace TerminalApp class TerminalApp::CascadiaSettings final { - public: CascadiaSettings(); ~CascadiaSettings(); @@ -52,11 +50,11 @@ public: const Profile* FindProfile(GUID profileGuid) const noexcept; void CreateDefaults(); + private: GlobalAppSettings _globals; std::vector _profiles; - void _CreateDefaultKeybindings(); void _CreateDefaultSchemes(); void _CreateDefaultProfiles(); diff --git a/src/cascadia/TerminalApp/CascadiaSettingsSerialization.cpp b/src/cascadia/TerminalApp/CascadiaSettingsSerialization.cpp index 1d5142576..547991437 100644 --- a/src/cascadia/TerminalApp/CascadiaSettingsSerialization.cpp +++ b/src/cascadia/TerminalApp/CascadiaSettingsSerialization.cpp @@ -17,7 +17,7 @@ using namespace winrt::Windows::Storage; using namespace winrt::Windows::Storage::Streams; 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::string_view ProfilesKey{ "profiles" }; @@ -40,7 +40,8 @@ std::unique_ptr CascadiaSettings::LoadAll(const bool saveOnLoa { std::unique_ptr resultPtr; std::optional fileData = _IsPackaged() ? - _LoadAsPackagedApp() : _LoadAsUnpackagedApp(); + _LoadAsPackagedApp() : + _LoadAsUnpackagedApp(); const bool foundFile = fileData.has_value(); if (foundFile) @@ -340,7 +341,6 @@ std::optional CascadiaSettings::_LoadAsPackagedApp() return { resultString }; } - // Method Description: // - Reads the content in UTF-8 enconding of our settings file using the Win32 APIs // Arguments: diff --git a/src/cascadia/TerminalApp/ColorScheme.cpp b/src/cascadia/TerminalApp/ColorScheme.cpp index 07ce50bb9..30832d036 100644 --- a/src/cascadia/TerminalApp/ColorScheme.cpp +++ b/src/cascadia/TerminalApp/ColorScheme.cpp @@ -17,8 +17,7 @@ static constexpr std::string_view NameKey{ "name" }; static constexpr std::string_view TableKey{ "colors" }; static constexpr std::string_view ForegroundKey{ "foreground" }; static constexpr std::string_view BackgroundKey{ "background" }; -static constexpr std::array TableColors = -{ +static constexpr std::array TableColors = { "black", "red", "green", @@ -39,25 +38,22 @@ static constexpr std::array TableColors = ColorScheme::ColorScheme() : _schemeName{ L"" }, - _table{ }, + _table{}, _defaultForeground{ RGB(242, 242, 242) }, _defaultBackground{ RGB(12, 12, 12) } { - } ColorScheme::ColorScheme(std::wstring name, COLORREF defaultFg, COLORREF defaultBg) : _schemeName{ name }, - _table{ }, + _table{}, _defaultForeground{ defaultFg }, _defaultBackground{ defaultBg } { - } ColorScheme::~ColorScheme() { - } // Method Description: @@ -157,7 +153,6 @@ ColorScheme ColorScheme::FromJson(const Json::Value& json) return result; } - std::wstring_view ColorScheme::GetName() const noexcept { return { _schemeName }; diff --git a/src/cascadia/TerminalApp/ColorScheme.h b/src/cascadia/TerminalApp/ColorScheme.h index 9ff65ad5e..49d6616e0 100644 --- a/src/cascadia/TerminalApp/ColorScheme.h +++ b/src/cascadia/TerminalApp/ColorScheme.h @@ -27,7 +27,6 @@ namespace TerminalApp class TerminalApp::ColorScheme { - public: ColorScheme(); ColorScheme(std::wstring name, COLORREF defaultFg, COLORREF defaultBg); diff --git a/src/cascadia/TerminalApp/GlobalAppSettings.cpp b/src/cascadia/TerminalApp/GlobalAppSettings.cpp index eb19218a4..4357a4ac3 100644 --- a/src/cascadia/TerminalApp/GlobalAppSettings.cpp +++ b/src/cascadia/TerminalApp/GlobalAppSettings.cpp @@ -39,12 +39,10 @@ GlobalAppSettings::GlobalAppSettings() : _showTabsInTitlebar{ true }, _requestedTheme{ ElementTheme::Default } { - } GlobalAppSettings::~GlobalAppSettings() { - } const std::vector& GlobalAppSettings::GetColorSchemes() const noexcept @@ -52,7 +50,6 @@ const std::vector& GlobalAppSettings::GetColorSchemes() const noexc return _colorSchemes; } - std::vector& GlobalAppSettings::GetColorSchemes() noexcept { return _colorSchemes; @@ -207,7 +204,6 @@ GlobalAppSettings GlobalAppSettings::FromJson(const Json::Value& json) return result; } - // Method Description: // - Helper function for converting a user-specified cursor style corresponding // CursorStyle enum value @@ -240,11 +236,11 @@ std::wstring_view GlobalAppSettings::_SerializeTheme(const ElementTheme theme) n { switch (theme) { - case ElementTheme::Light: - return LightThemeValue; - case ElementTheme::Dark: - return DarkThemeValue; - default: - return SystemThemeValue; + case ElementTheme::Light: + return LightThemeValue; + case ElementTheme::Dark: + return DarkThemeValue; + default: + return SystemThemeValue; } } diff --git a/src/cascadia/TerminalApp/GlobalAppSettings.h b/src/cascadia/TerminalApp/GlobalAppSettings.h index cd83fcdf4..cd18e3c12 100644 --- a/src/cascadia/TerminalApp/GlobalAppSettings.h +++ b/src/cascadia/TerminalApp/GlobalAppSettings.h @@ -24,7 +24,6 @@ namespace TerminalApp class TerminalApp::GlobalAppSettings final { - public: GlobalAppSettings(); ~GlobalAppSettings(); @@ -73,5 +72,4 @@ private: 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; - }; diff --git a/src/cascadia/TerminalApp/KeyChordSerialization.cpp b/src/cascadia/TerminalApp/KeyChordSerialization.cpp index 20816066a..9a94c4168 100644 --- a/src/cascadia/TerminalApp/KeyChordSerialization.cpp +++ b/src/cascadia/TerminalApp/KeyChordSerialization.cpp @@ -12,6 +12,7 @@ static constexpr std::wstring_view ALT_KEY{ L"alt" }; static constexpr int MAX_CHORD_PARTS = 4; +// clang-format off static const std::unordered_map vkeyNamePairs { { VK_BACK , L"backspace"}, { VK_TAB , L"tab"}, @@ -83,6 +84,7 @@ static const std::unordered_map vkeyNamePairs { // #define VK_OEM_6 0xDD // ']}' for US // #define VK_OEM_7 0xDE // ''"' for US }; +// clang-format on // Function Description: // - Deserializes the given string into a new KeyChord instance. If this @@ -104,7 +106,7 @@ winrt::Microsoft::Terminal::Settings::KeyChord KeyChordSerialization::FromString std::vector parts; std::wstringstream wss(wstr); - while(std::getline(wss, temp, L'+')) + while (std::getline(wss, temp, L'+')) { parts.push_back(temp); diff --git a/src/cascadia/TerminalApp/Pane.cpp b/src/cascadia/TerminalApp/Pane.cpp index 1c24f6f2a..33f63f332 100644 --- a/src/cascadia/TerminalApp/Pane.cpp +++ b/src/cascadia/TerminalApp/Pane.cpp @@ -376,7 +376,6 @@ void Pane::_CloseChild(const bool closeFirst) _root.Children().Append(_separatorRoot); _root.Children().Append(_secondChild->GetRootElement()); - // If the closed child was focused, transfer the focus to it's first sibling. if (closedChild->_lastFocused) { @@ -398,14 +397,14 @@ void Pane::_CloseChild(const bool closeFirst) // - void Pane::_SetupChildCloseHandlers() { - _firstClosedToken = _firstChild->Closed([this](){ - _root.Dispatcher().RunAsync(CoreDispatcherPriority::Normal, [=](){ + _firstClosedToken = _firstChild->Closed([this]() { + _root.Dispatcher().RunAsync(CoreDispatcherPriority::Normal, [=]() { _CloseChild(true); }); }); - _secondClosedToken = _secondChild->Closed([this](){ - _root.Dispatcher().RunAsync(CoreDispatcherPriority::Normal, [=](){ + _secondClosedToken = _secondChild->Closed([this]() { + _root.Dispatcher().RunAsync(CoreDispatcherPriority::Normal, [=]() { _CloseChild(false); }); }); @@ -468,7 +467,6 @@ void Pane::_ApplySplitDefinitions() Controls::Grid::SetColumn(_firstChild->GetRootElement(), 0); Controls::Grid::SetColumn(_separatorRoot, 1); Controls::Grid::SetColumn(_secondChild->GetRootElement(), 2); - } else if (_splitState == SplitState::Horizontal) { @@ -478,7 +476,6 @@ void Pane::_ApplySplitDefinitions() } } - // Method Description: // - 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 diff --git a/src/cascadia/TerminalApp/Pane.h b/src/cascadia/TerminalApp/Pane.h index 737b9f0b8..b82105f3c 100644 --- a/src/cascadia/TerminalApp/Pane.h +++ b/src/cascadia/TerminalApp/Pane.h @@ -18,16 +18,13 @@ // Author: // - Mike Griese (zadjii-msft) 16-May-2019 - #pragma once #include #include "../../cascadia/inc/cppwinrt_utils.h" class Pane : public std::enable_shared_from_this { - public: - enum class SplitState : int { None = 0, diff --git a/src/cascadia/TerminalApp/Profile.cpp b/src/cascadia/TerminalApp/Profile.cpp index 47c50aab0..bffa0ed91 100644 --- a/src/cascadia/TerminalApp/Profile.cpp +++ b/src/cascadia/TerminalApp/Profile.cpp @@ -63,13 +63,13 @@ Profile::Profile() : { } -Profile::Profile(const winrt::guid& guid): +Profile::Profile(const winrt::guid& guid) : _guid(guid), _name{ L"Default" }, _schemeName{}, - _defaultForeground{ }, - _defaultBackground{ }, + _defaultForeground{}, + _defaultBackground{}, _colorTable{}, _historySize{ DEFAULT_HISTORY_SIZE }, _snapOnInput{ true }, @@ -78,24 +78,23 @@ Profile::Profile(const winrt::guid& guid): _cursorHeight{ DEFAULT_CURSOR_HEIGHT }, _commandline{ L"cmd.exe" }, - _startingDirectory{ }, + _startingDirectory{}, _fontFace{ DEFAULT_FONT_FACE }, _fontSize{ DEFAULT_FONT_SIZE }, _acrylicTransparency{ 0.5 }, _useAcrylic{ false }, - _scrollbarState{ }, + _scrollbarState{}, _closeOnExit{ true }, _padding{ DEFAULT_PADDING }, - _icon{ }, - _backgroundImage{ }, - _backgroundImageOpacity{ }, - _backgroundImageStretchMode{ } + _icon{}, + _backgroundImage{}, + _backgroundImageOpacity{}, + _backgroundImageStretchMode{} { } Profile::~Profile() { - } GUID Profile::GetGuid() const noexcept @@ -494,8 +493,8 @@ void Profile::SetIconPath(std::wstring_view path) noexcept std::wstring_view Profile::GetIconPath() const noexcept { return HasIcon() ? - std::wstring_view{ _icon.value().c_str(), _icon.value().size() } : - std::wstring_view{ L"", 0 }; + std::wstring_view{ _icon.value().c_str(), _icon.value().size() } : + std::wstring_view{ L"", 0 }; } // Method Description: @@ -661,16 +660,16 @@ std::wstring_view Profile::_SerializeCursorStyle(const CursorStyle cursorShape) { switch (cursorShape) { - case CursorStyle::Underscore: - return CursorShapeUnderscore; - case CursorStyle::FilledBox: - return CursorShapeFilledbox; - case CursorStyle::EmptyBox: - return CursorShapeEmptybox; - case CursorStyle::Vintage: - return CursorShapeVintage; - default: - case CursorStyle::Bar: - return CursorShapeBar; + case CursorStyle::Underscore: + return CursorShapeUnderscore; + case CursorStyle::FilledBox: + return CursorShapeFilledbox; + case CursorStyle::EmptyBox: + return CursorShapeEmptybox; + case CursorStyle::Vintage: + return CursorShapeVintage; + default: + case CursorStyle::Bar: + return CursorShapeBar; } } diff --git a/src/cascadia/TerminalApp/Profile.h b/src/cascadia/TerminalApp/Profile.h index b2fc7d964..938bbf7fa 100644 --- a/src/cascadia/TerminalApp/Profile.h +++ b/src/cascadia/TerminalApp/Profile.h @@ -23,7 +23,6 @@ namespace TerminalApp class TerminalApp::Profile final { - public: Profile(const winrt::guid& guid); Profile(); @@ -55,7 +54,6 @@ public: bool GetCloseOnExit() const noexcept; private: - static std::wstring EvaluateStartingDirectory(const std::wstring& directory); static winrt::Microsoft::Terminal::Settings::ScrollbarState ParseScrollbarState(const std::wstring& scrollbarState); diff --git a/src/cascadia/TerminalApp/Tab.cpp b/src/cascadia/TerminalApp/Tab.cpp index cd239337f..0d7d8382c 100644 --- a/src/cascadia/TerminalApp/Tab.cpp +++ b/src/cascadia/TerminalApp/Tab.cpp @@ -165,7 +165,7 @@ void Tab::SetTabText(const winrt::hstring& text) { // Copy the hstring, so we don't capture a dead reference 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); }); } @@ -181,7 +181,7 @@ void Tab::SetTabText(const winrt::hstring& text) void Tab::Scroll(const int delta) { auto control = GetFocusedTerminalControl(); - control.GetControl().Dispatcher().RunAsync(CoreDispatcherPriority::Normal, [control, delta](){ + control.GetControl().Dispatcher().RunAsync(CoreDispatcherPriority::Normal, [control, delta]() { const auto currentOffset = control.GetScrollOffset(); control.KeyboardScrollViewport(currentOffset + delta); }); diff --git a/src/cascadia/TerminalApp/Tab.h b/src/cascadia/TerminalApp/Tab.h index 5cb383394..84c1910a5 100644 --- a/src/cascadia/TerminalApp/Tab.h +++ b/src/cascadia/TerminalApp/Tab.h @@ -7,7 +7,6 @@ class Tab { - public: 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); private: - std::shared_ptr _rootPane{ nullptr }; bool _focused{ false }; diff --git a/src/cascadia/TerminalConnection/ConhostConnection.cpp b/src/cascadia/TerminalConnection/ConhostConnection.cpp index b4d8173b7..a6cb79bc4 100644 --- a/src/cascadia/TerminalConnection/ConhostConnection.cpp +++ b/src/cascadia/TerminalConnection/ConhostConnection.cpp @@ -8,7 +8,7 @@ // STARTF_USESTDHANDLES is only defined in WINAPI_PARTITION_DESKTOP // We're just gonna manually define it for this prototyping code #ifndef STARTF_USESTDHANDLES -#define STARTF_USESTDHANDLES 0x00000100 +#define STARTF_USESTDHANDLES 0x00000100 #endif #include "ConhostConnection.g.cpp" @@ -135,8 +135,14 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation void ConhostConnection::Close() { - if (!_connected) return; - if (_closing) return; + if (!_connected) + { + return; + } + if (_closing) + { + return; + } _closing = true; // TODO: // terminate the output thread @@ -181,12 +187,14 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation _disconnectHandlers(); return (DWORD)-1; } - } - if (dwRead == 0) continue; + if (dwRead == 0) + { + continue; + } // Convert buffer to hstring char* pchStr = (char*)(buffer); - std::string str{pchStr, dwRead}; + std::string str{ pchStr, dwRead }; auto hstr = winrt::to_hstring(str); // Pass the output to our registered event handlers diff --git a/src/cascadia/TerminalConnection/ConhostConnection.h b/src/cascadia/TerminalConnection/ConhostConnection.h index 93c29235e..e7fef93dc 100644 --- a/src/cascadia/TerminalConnection/ConhostConnection.h +++ b/src/cascadia/TerminalConnection/ConhostConnection.h @@ -32,7 +32,7 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation hstring _startingDirectory{}; 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 _signalPipe{ INVALID_HANDLE_VALUE }; DWORD _outputThreadId{}; diff --git a/src/cascadia/TerminalConnection/ConptyConnection.cpp b/src/cascadia/TerminalConnection/ConptyConnection.cpp index d9ce3cf9c..f8234a287 100644 --- a/src/cascadia/TerminalConnection/ConptyConnection.cpp +++ b/src/cascadia/TerminalConnection/ConptyConnection.cpp @@ -22,7 +22,6 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation _commandline = commandline; _initialRows = initialRows; _initialCols = initialCols; - } winrt::event_token ConptyConnection::TerminalOutput(TerminalConnection::TerminalOutputEventArgs const& handler) @@ -97,7 +96,6 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation throw hresult_not_implemented(); } - // Function Description: // - Sample function which combines the creation of some basic anonymous pipes // and passes them to CreatePseudoConsole. @@ -112,7 +110,7 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation _Out_ HANDLE* phOutput, _Out_ HPCON* phPC) { - if(phPC == NULL || phInput == NULL || phOutput == NULL) + if (phPC == NULL || phInput == NULL || phOutput == NULL) { return E_INVALIDARG; } @@ -180,7 +178,7 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation { bool fSuccess; - COORD dimensions{_initialCols, _initialRows}; + COORD dimensions{ _initialCols, _initialRows }; THROW_IF_FAILED(_CreatePseudoConsoleAndHandles(dimensions, 0, &_inPipe, &_outPipe, &_hPC)); STARTUPINFOEX siEx; @@ -195,33 +193,33 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation THROW_IF_FAILED(_AttachPseudoConsole(_hPC, siEx.lpAttributeList)); - std::wstring realCommand = _commandline.c_str();//winrt::to_string(_commandline); - if (realCommand == L""){ + std::wstring realCommand = _commandline.c_str(); //winrt::to_string(_commandline); + if (realCommand == L"") + { realCommand = L"cmd.exe"; } std::unique_ptr mutableCommandline = std::make_unique(realCommand.length() + 1); 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); fSuccess = !!CreateProcessW( nullptr, mutableCommandline.get(), - nullptr, // lpProcessAttributes - nullptr, // lpThreadAttributes - true, // bInheritHandles - EXTENDED_STARTUPINFO_PRESENT, // dwCreationFlags - nullptr, // lpEnvironment - nullptr, // lpCurrentDirectory - &siEx.StartupInfo, // lpStartupInfo - &_piClient // lpProcessInformation + nullptr, // lpProcessAttributes + nullptr, // lpThreadAttributes + true, // bInheritHandles + EXTENDED_STARTUPINFO_PRESENT, // dwCreationFlags + nullptr, // lpEnvironment + nullptr, // lpCurrentDirectory + &siEx.StartupInfo, // lpStartupInfo + &_piClient // lpProcessInformation ); THROW_LAST_ERROR_IF(!fSuccess); DeleteProcThreadAttributeList(siEx.lpAttributeList); } - DWORD WINAPI ConptyConnection::StaticOutputThreadProc(LPVOID lpParameter) { ConptyConnection* const pInstance = (ConptyConnection*)lpParameter; @@ -243,7 +241,7 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation // Convert buffer to hstring char* pchStr = (char*)(buffer); - std::string str{pchStr, dwRead}; + std::string str{ pchStr, dwRead }; auto hstr = winrt::to_hstring(str); // Pass the output to our registered event handlers diff --git a/src/cascadia/TerminalConnection/ConptyConnection.h b/src/cascadia/TerminalConnection/ConptyConnection.h index fd5099761..4e9b46e75 100644 --- a/src/cascadia/TerminalConnection/ConptyConnection.h +++ b/src/cascadia/TerminalConnection/ConptyConnection.h @@ -32,7 +32,7 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation hstring _commandline; 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 HPCON _hPC; DWORD _outputThreadId; diff --git a/src/cascadia/TerminalConnection/EchoConnection.cpp b/src/cascadia/TerminalConnection/EchoConnection.cpp index b75729e19..1df63ad81 100644 --- a/src/cascadia/TerminalConnection/EchoConnection.cpp +++ b/src/cascadia/TerminalConnection/EchoConnection.cpp @@ -32,7 +32,7 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation void EchoConnection::TerminalDisconnected(winrt::event_token const& token) noexcept { token; - } + } void EchoConnection::Start() { @@ -45,7 +45,7 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation { if (wch < 0x20) { - prettyPrint << L"^" << (wchar_t)(wch+0x40); + prettyPrint << L"^" << (wchar_t)(wch + 0x40); } else if (wch == 0x7f) { diff --git a/src/cascadia/TerminalControl/TermControl.cpp b/src/cascadia/TerminalControl/TermControl.cpp index 1575434f0..f4afc3a3e 100644 --- a/src/cascadia/TerminalControl/TermControl.cpp +++ b/src/cascadia/TerminalControl/TermControl.cpp @@ -21,7 +21,6 @@ using namespace winrt::Microsoft::Terminal::Settings; namespace winrt::Microsoft::Terminal::TerminalControl::implementation { - TermControl::TermControl() : TermControl(Settings::TerminalSettings{}) { @@ -85,7 +84,7 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation // 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 - _loadedRevoker = swapChainPanel.Loaded(winrt::auto_revoke, [this] (auto /*s*/, auto /*e*/){ + _loadedRevoker = swapChainPanel.Loaded(winrt::auto_revoke, [this](auto /*s*/, auto /*e*/) { _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. // Subscribe to the connection's disconnected event and call our connection closed handlers. - _connection.TerminalDisconnected([=]() { + _connection.TerminalDisconnected([=]() { _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 // terminal. - _root.Dispatcher().RunAsync(CoreDispatcherPriority::Normal,[this](){ + _root.Dispatcher().RunAsync(CoreDispatcherPriority::Normal, [this]() { // Update our control settings _ApplyUISettings(); // 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 auto imageSource = brush.ImageSource().try_as(); - if (imageSource == nullptr || imageSource.UriSource() == nullptr - || imageSource.UriSource().RawUri() != imageUri.RawUri()) + if (imageSource == nullptr || + imageSource.UriSource() == nullptr || + imageSource.UriSource().RawUri() != imageUri.RawUri()) { // Note that BitmapImage handles the image load asynchronously, // which is especially important since the image @@ -376,8 +376,7 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation } auto chain = _renderEngine->GetSwapChain(); - _swapChainPanel.Dispatcher().RunAsync(CoreDispatcherPriority::High, [=]() - { + _swapChainPanel.Dispatcher().RunAsync(CoreDispatcherPriority::High, [=]() { auto lock = _terminal->LockForWriting(); auto nativePanel = _swapChainPanel.as(); nativePanel->SetSwapChain(chain.Get()); @@ -391,7 +390,7 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation 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(); _terminal = std::make_unique<::Microsoft::Terminal::Core::Terminal>(); @@ -457,8 +456,7 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation _terminal->SetWriteInputCallback(inputFn); auto chain = _renderEngine->GetSwapChain(); - _swapChainPanel.Dispatcher().RunAsync(CoreDispatcherPriority::High, [this, chain]() - { + _swapChainPanel.Dispatcher().RunAsync(CoreDispatcherPriority::High, [this, chain]() { _terminal->LockConsole(); auto nativePanel = _swapChainPanel.as(); 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 // PreviewKeyDown for our purposes // These two handlers _must_ be on _controlRoot, not _root. - _controlRoot.PreviewKeyDown({this, &TermControl::_KeyDownHandler }); - _controlRoot.CharacterReceived({this, &TermControl::_CharacterHandler }); + _controlRoot.PreviewKeyDown({ this, &TermControl::_KeyDownHandler }); + _controlRoot.CharacterReceived({ this, &TermControl::_CharacterHandler }); auto pfnTitleChanged = std::bind(&TermControl::_TerminalTitleChanged, this, std::placeholders::_1); _terminal->SetTitleChangedCallback(pfnTitleChanged); @@ -560,7 +558,7 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation } void TermControl::_CharacterHandler(winrt::Windows::Foundation::IInspectable const& /*sender*/, - Input::CharacterReceivedRoutedEventArgs const& e) + Input::CharacterReceivedRoutedEventArgs const& e) { if (_closing) { @@ -1008,7 +1006,6 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation // TODO: MSFT:20895307 If the font doesn't exist, this doesn't // actually fail. We need a way to gracefully fallback. _renderer->TriggerFontChange(newDpi, _desiredFont, _actualFont); - } // Method Description: @@ -1147,7 +1144,8 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation hstring TermControl::Title() { - if (!_initializedTerminal) return L""; + if (!_initializedTerminal) + return L""; hstring hstr(_terminal->GetConsoleTitle()); return hstr; @@ -1177,21 +1175,21 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation _connection.TerminalOutput(_connectionOutputEventToken); // 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(); // cursorTimer timer, now stopped, is destroyed. } - if (auto localConnection{std::exchange(_connection, nullptr)}) + if (auto localConnection{ std::exchange(_connection, nullptr) }) { localConnection.Close(); // 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(); // renderer is destroyed @@ -1199,7 +1197,7 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation // renderEngine is destroyed } - if (auto localTerminal{std::exchange(_terminal, nullptr)}) + if (auto localTerminal{ std::exchange(_terminal, nullptr) }) { _initializedTerminal = false; // terminal is destroyed. @@ -1357,11 +1355,15 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation switch (paddingPropIndex) { - case 1: return ThicknessHelper::FromUniformLength(thicknessArr[0]); - case 2: return ThicknessHelper::FromLengths(thicknessArr[0], thicknessArr[1], thicknessArr[0], thicknessArr[1]); - // 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(); + case 1: + return ThicknessHelper::FromUniformLength(thicknessArr[0]); + case 2: + return ThicknessHelper::FromLengths(thicknessArr[0], thicknessArr[1], thicknessArr[0], thicknessArr[1]); + // 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) { // Exclude padding from cursor position calculation - COORD terminalPosition = - { + COORD terminalPosition = { static_cast(cursorPosition.X - _root.Padding().Left), static_cast(cursorPosition.Y - _root.Padding().Top) }; @@ -1434,13 +1435,15 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation return terminalPosition; } + // clang-format off // -------------------------------- WinRT Events --------------------------------- // Winrt events need a method for adding a callback to the event and removing the callback. // These macros will define them both for you. - DEFINE_EVENT(TermControl, TitleChanged, _titleChangedHandlers, TerminalControl::TitleChangedEventArgs); - DEFINE_EVENT(TermControl, ConnectionClosed, _connectionClosedHandlers, TerminalControl::ConnectionClosedEventArgs); - DEFINE_EVENT(TermControl, CopyToClipboard, _clipboardCopyHandlers, TerminalControl::CopyToClipboardEventArgs); - DEFINE_EVENT(TermControl, ScrollPositionChanged, _scrollPositionChangedHandlers, TerminalControl::ScrollPositionChangedEventArgs); + DEFINE_EVENT(TermControl, TitleChanged, _titleChangedHandlers, TerminalControl::TitleChangedEventArgs); + DEFINE_EVENT(TermControl, ConnectionClosed, _connectionClosedHandlers, TerminalControl::ConnectionClosedEventArgs); + DEFINE_EVENT(TermControl, CopyToClipboard, _clipboardCopyHandlers, TerminalControl::CopyToClipboardEventArgs); + DEFINE_EVENT(TermControl, ScrollPositionChanged, _scrollPositionChangedHandlers, TerminalControl::ScrollPositionChangedEventArgs); + // clang-format on DEFINE_EVENT_WITH_TYPED_EVENT_HANDLER(TermControl, PasteFromClipboard, _clipboardPasteHandlers, TerminalControl::TermControl, TerminalControl::PasteFromClipboardEventArgs); } diff --git a/src/cascadia/TerminalControl/TermControl.h b/src/cascadia/TerminalControl/TermControl.h index 6b62b38fc..b02991240 100644 --- a/src/cascadia/TerminalControl/TermControl.h +++ b/src/cascadia/TerminalControl/TermControl.h @@ -18,7 +18,8 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation public PasteFromClipboardEventArgsT { public: - PasteFromClipboardEventArgs(std::function clipboardDataHandler) : m_clipboardDataHandler(clipboardDataHandler) { } + PasteFromClipboardEventArgs(std::function clipboardDataHandler) : + m_clipboardDataHandler(clipboardDataHandler) {} 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); + // clang-format off // -------------------------------- WinRT Events --------------------------------- DECLARE_EVENT(TitleChanged, _titleChangedHandlers, TerminalControl::TitleChangedEventArgs); DECLARE_EVENT(ConnectionClosed, _connectionClosedHandlers, TerminalControl::ConnectionClosedEventArgs); @@ -60,6 +62,7 @@ namespace winrt::Microsoft::Terminal::TerminalControl::implementation DECLARE_EVENT(CopyToClipboard, _clipboardCopyHandlers, TerminalControl::CopyToClipboardEventArgs); DECLARE_EVENT_WITH_TYPED_EVENT_HANDLER(PasteFromClipboard, _clipboardPasteHandlers, TerminalControl::TermControl, TerminalControl::PasteFromClipboardEventArgs); + // clang-format on private: TerminalConnection::ITerminalConnection _connection; diff --git a/src/cascadia/TerminalControl/pch.h b/src/cascadia/TerminalControl/pch.h index 516572299..c807bc1f2 100644 --- a/src/cascadia/TerminalControl/pch.h +++ b/src/cascadia/TerminalControl/pch.h @@ -30,4 +30,3 @@ #include #include - diff --git a/src/cascadia/TerminalCore/ITerminalInput.hpp b/src/cascadia/TerminalCore/ITerminalInput.hpp index 9d4a41cb9..67bfb944c 100644 --- a/src/cascadia/TerminalCore/ITerminalInput.hpp +++ b/src/cascadia/TerminalCore/ITerminalInput.hpp @@ -12,10 +12,8 @@ namespace Microsoft::Terminal::Core virtual bool SendKeyEvent(const WORD vkey, const bool ctrlPressed, const bool altPressed, const bool shiftPressed) = 0; // void SendMouseEvent(uint row, uint col, KeyModifiers modifiers); - [[nodiscard]] - virtual HRESULT UserResize(const COORD size) noexcept = 0; + [[nodiscard]] virtual HRESULT UserResize(const COORD size) noexcept = 0; virtual void UserScrollViewport(const int viewTop) = 0; virtual int GetScrollOffset() = 0; - }; } diff --git a/src/cascadia/TerminalCore/Terminal.cpp b/src/cascadia/TerminalCore/Terminal.cpp index 10cb6f84d..006ee1e50 100644 --- a/src/cascadia/TerminalCore/Terminal.cpp +++ b/src/cascadia/TerminalCore/Terminal.cpp @@ -22,7 +22,7 @@ using namespace Microsoft::Console::VirtualTerminal; static std::wstring _KeyEventsToText(std::deque>& inEventsToWrite) { std::wstring wstr = L""; - for(auto& ev : inEventsToWrite) + for (auto& ev : inEventsToWrite) { if (ev->EventType() == InputEventType::KeyEvent) { @@ -35,7 +35,7 @@ static std::wstring _KeyEventsToText(std::deque>& i } Terminal::Terminal() : - _mutableViewport{Viewport::Empty()}, + _mutableViewport{ Viewport::Empty() }, _title{ L"" }, _colorTable{}, _defaultFg{ RGB(255, 255, 255) }, @@ -46,13 +46,15 @@ Terminal::Terminal() : _boxSelection{ false }, _selectionActive{ false }, _selectionAnchor{ 0, 0 }, - _endSelectionPosition { 0, 0 } + _endSelectionPosition{ 0, 0 } { _stateMachine = std::make_unique(new OutputStateMachineEngine(new TerminalDispatch(*this))); - auto passAlongInput = [&](std::deque>& inEventsToWrite) - { - if(!_pfnWriteInput) return; + auto passAlongInput = [&](std::deque>& inEventsToWrite) { + if (!_pfnWriteInput) + { + return; + } std::wstring wstr = _KeyEventsToText(inEventsToWrite); _pfnWriteInput(wstr); }; @@ -64,10 +66,10 @@ Terminal::Terminal() : void Terminal::Create(COORD viewportSize, SHORT scrollbackLines, IRenderTarget& renderTarget) { - _mutableViewport = Viewport::FromDimensions({ 0,0 }, viewportSize); + _mutableViewport = Viewport::FromDimensions({ 0, 0 }, viewportSize); _scrollbackLines = scrollbackLines; - const COORD bufferSize { viewportSize.X, - Utils::ClampToShortMax(viewportSize.Y + scrollbackLines, 1) }; + const COORD bufferSize{ viewportSize.X, + Utils::ClampToShortMax(viewportSize.Y + scrollbackLines, 1) }; const TextAttribute attr{}; const UINT cursorSize = 12; _buffer = std::make_unique(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 // - renderTarget: A render target the terminal can use for paint invalidation. 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), Utils::ClampToShortMax(settings.InitialRows(), 1) }; @@ -102,22 +104,22 @@ void Terminal::UpdateSettings(winrt::Microsoft::Terminal::Settings::ICoreSetting CursorType cursorShape = CursorType::VerticalBar; switch (settings.CursorShape()) { - case CursorStyle::Underscore: - cursorShape = CursorType::Underscore; - break; - case CursorStyle::FilledBox: - cursorShape = CursorType::FullBox; - break; - case CursorStyle::EmptyBox: - cursorShape = CursorType::EmptyBox; - break; - case CursorStyle::Vintage: - cursorShape = CursorType::Legacy; - break; - default: - case CursorStyle::Bar: - cursorShape = CursorType::VerticalBar; - break; + case CursorStyle::Underscore: + cursorShape = CursorType::Underscore; + break; + case CursorStyle::FilledBox: + cursorShape = CursorType::FullBox; + break; + case CursorStyle::EmptyBox: + cursorShape = CursorType::EmptyBox; + break; + case CursorStyle::Vintage: + cursorShape = CursorType::Legacy; + break; + default: + case CursorStyle::Bar: + cursorShape = CursorType::VerticalBar; + break; } _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 // nothing to do (the viewportSize is the same as our current size), or an // appropriate HRESULT for failing to resize. -[[nodiscard]] -HRESULT Terminal::UserResize(const COORD viewportSize) noexcept +[[nodiscard]] HRESULT Terminal::UserResize(const COORD viewportSize) noexcept { const auto oldDimensions = _mutableViewport.Dimensions(); if (viewportSize == oldDimensions) @@ -212,11 +213,10 @@ bool Terminal::SendKeyEvent(const WORD vkey, _NotifyScrollEvent(); } - DWORD modifiers = 0 - | (ctrlPressed? LEFT_CTRL_PRESSED : 0) - | (altPressed? LEFT_ALT_PRESSED : 0) - | (shiftPressed? SHIFT_PRESSED : 0) - ; + DWORD modifiers = 0 | + (ctrlPressed ? LEFT_CTRL_PRESSED : 0) | + (altPressed ? LEFT_ALT_PRESSED : 0) | + (shiftPressed ? SHIFT_PRESSED : 0); // 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 @@ -241,7 +241,7 @@ bool Terminal::SendKeyEvent(const WORD vkey, 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); return translated && manuallyHandled; @@ -252,8 +252,7 @@ bool Terminal::SendKeyEvent(const WORD vkey, // Return Value: // - a shared_lock which can be used to unlock the terminal. The shared_lock // will release this lock when it's destructed. -[[nodiscard]] -std::shared_lock Terminal::LockForReading() +[[nodiscard]] std::shared_lock Terminal::LockForReading() { return std::shared_lock(_readWriteLock); } @@ -263,13 +262,11 @@ std::shared_lock Terminal::LockForReading() // Return Value: // - a unique_lock which can be used to unlock the terminal. The unique_lock // will release this lock when it's destructed. -[[nodiscard]] -std::unique_lock Terminal::LockForWriting() +[[nodiscard]] std::unique_lock Terminal::LockForWriting() { return std::unique_lock(_readWriteLock); } - Viewport Terminal::_GetMutableViewport() const noexcept { 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. 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 cellDistance = end.GetCellDistance(it); i += cellDistance - 1; @@ -353,7 +350,7 @@ void Terminal::_WriteBuffer(const std::wstring_view& stringView) } 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 cellDistance = end.GetCellDistance(it); proposedCursorPosition.X += gsl::narrow(cellDistance); @@ -364,7 +361,7 @@ void Terminal::_WriteBuffer(const std::wstring_view& stringView) const auto newRows = proposedCursorPosition.Y - bufferSize.Height() + 1; if (newRows > 0) { - for(auto dy = 0; dy < newRows; dy++) + for (auto dy = 0; dy < newRows; dy++) { _buffer->IncrementCircularBuffer(); 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)); if (newViewTop != _mutableViewport.Top()) { - _mutableViewport = Viewport::FromDimensions({0, gsl::narrow(newViewTop)}, _mutableViewport.Dimensions()); + _mutableViewport = Viewport::FromDimensions({ 0, gsl::narrow(newViewTop) }, _mutableViewport.Dimensions()); notifyScroll = true; } } @@ -527,8 +524,12 @@ std::vector Terminal::_GetSelectionRects() const const COORD endSelectionPositionWithOffset = { _endSelectionPosition.X, temp2 }; // NOTE: (0,0) is top-left so vertical comparison is inverted - const COORD &higherCoord = (selectionAnchorWithOffset.Y <= endSelectionPositionWithOffset.Y) ? selectionAnchorWithOffset : endSelectionPositionWithOffset; - const COORD &lowerCoord = (selectionAnchorWithOffset.Y > endSelectionPositionWithOffset.Y) ? selectionAnchorWithOffset : endSelectionPositionWithOffset; + const COORD& higherCoord = (selectionAnchorWithOffset.Y <= endSelectionPositionWithOffset.Y) ? + selectionAnchorWithOffset : + endSelectionPositionWithOffset; + const COORD& lowerCoord = (selectionAnchorWithOffset.Y > endSelectionPositionWithOffset.Y) ? + selectionAnchorWithOffset : + endSelectionPositionWithOffset; selectionArea.reserve(lowerCoord.Y - higherCoord.Y + 1); for (auto row = higherCoord.Y; row <= lowerCoord.Y; row++) @@ -568,8 +569,8 @@ void Terminal::SetBoxSelection(const bool isEnabled) noexcept void Terminal::ClearSelection() noexcept { _selectionActive = false; - _selectionAnchor = {0, 0}; - _endSelectionPosition = {0, 0}; + _selectionAnchor = { 0, 0 }; + _endSelectionPosition = { 0, 0 }; _selectionAnchor_YOffset = 0; _endSelectionPosition_YOffset = 0; diff --git a/src/cascadia/TerminalCore/Terminal.hpp b/src/cascadia/TerminalCore/Terminal.hpp index 593321694..5ca844a66 100644 --- a/src/cascadia/TerminalCore/Terminal.hpp +++ b/src/cascadia/TerminalCore/Terminal.hpp @@ -34,28 +34,26 @@ class Microsoft::Terminal::Core::Terminal final : { public: Terminal(); - virtual ~Terminal() {}; + virtual ~Terminal(){}; void Create(COORD viewportSize, SHORT scrollbackLines, Microsoft::Console::Render::IRenderTarget& renderTarget); 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); // Write goes through the parser void Write(std::wstring_view stringView); - [[nodiscard]] - std::shared_lock LockForReading(); - [[nodiscard]] - std::unique_lock LockForWriting(); + [[nodiscard]] std::shared_lock LockForReading(); + [[nodiscard]] std::unique_lock LockForWriting(); short GetBufferHeight() const noexcept; - #pragma region ITerminalApi +#pragma region ITerminalApi // These methods are defined in TerminalApi.cpp bool PrintString(std::wstring_view stringView) override; bool ExecuteChar(wchar_t wch) override; @@ -74,21 +72,20 @@ public: bool SetCursorStyle(const ::Microsoft::Console::VirtualTerminal::DispatchTypes::CursorStyle cursorStyle) override; bool SetDefaultForeground(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 bool SendKeyEvent(const WORD vkey, const bool ctrlPressed, const bool altPressed, const bool shiftPressed) override; - [[nodiscard]] - HRESULT UserResize(const COORD viewportSize) noexcept override; + [[nodiscard]] HRESULT UserResize(const COORD viewportSize) noexcept override; void UserScrollViewport(const int viewTop) override; int GetScrollOffset() override; - #pragma endregion +#pragma endregion - #pragma region IRenderData +#pragma region IRenderData // These methods are defined in TerminalRenderData.cpp Microsoft::Console::Types::Viewport GetViewport() noexcept override; const TextBuffer& GetTextBuffer() noexcept override; @@ -110,7 +107,7 @@ public: const std::wstring GetConsoleTitle() const noexcept override; void LockConsole() noexcept override; void UnlockConsole() noexcept override; - #pragma endregion +#pragma endregion void SetWriteInputCallback(std::function pfn) noexcept; void SetTitleChangedCallback(std::function pfn) noexcept; @@ -120,7 +117,7 @@ public: void SetCursorVisible(const bool isVisible) noexcept; bool IsCursorBlinkingAllowed() const noexcept; - #pragma region TextSelection +#pragma region TextSelection const bool IsSelectionActive() const noexcept; void SetSelectionAnchor(const COORD position); void SetEndSelectionPosition(const COORD position); @@ -128,9 +125,9 @@ public: void ClearSelection() noexcept; const std::wstring RetrieveSelectedTextFromBuffer(bool trimTrailingWhitespace) const; - #pragma endregion +#pragma endregion - private: +private: std::function _pfnWriteInput; std::function _pfnTitleChanged; std::function _pfnScrollPositionChanged; @@ -193,4 +190,3 @@ public: std::vector _GetSelectionRects() const; }; - diff --git a/src/cascadia/TerminalCore/TerminalApi.cpp b/src/cascadia/TerminalCore/TerminalApi.cpp index 745696ff9..27ca646b3 100644 --- a/src/cascadia/TerminalCore/TerminalApi.cpp +++ b/src/cascadia/TerminalCore/TerminalApi.cpp @@ -17,7 +17,7 @@ bool Terminal::PrintString(std::wstring_view stringView) bool Terminal::ExecuteChar(wchar_t wch) { - std::wstring_view view{&wch, 1}; + std::wstring_view view{ &wch, 1 }; _WriteBuffer(view); return true; } @@ -106,7 +106,7 @@ bool Terminal::SetCursorPosition(short x, short y) const auto viewOrigin = viewport.Origin(); const short absoluteX = viewOrigin.X + x; const short absoluteY = viewOrigin.Y + y; - COORD newPos{absoluteX, absoluteY}; + COORD newPos{ absoluteX, absoluteY }; viewport.Clamp(newPos); _buffer->GetCursor().SetPosition(newPos); diff --git a/src/cascadia/TerminalCore/TerminalDispatch.cpp b/src/cascadia/TerminalCore/TerminalDispatch.cpp index 154ee53e0..832cd55e8 100644 --- a/src/cascadia/TerminalCore/TerminalDispatch.cpp +++ b/src/cascadia/TerminalCore/TerminalDispatch.cpp @@ -13,7 +13,6 @@ using namespace ::Microsoft::Console::VirtualTerminal; TerminalDispatch::TerminalDispatch(ITerminalApi& terminalApi) : _terminalApi{ terminalApi } { - } void TerminalDispatch::Execute(const wchar_t wchControl) @@ -26,7 +25,7 @@ void TerminalDispatch::Print(const wchar_t wchPrintable) _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 }); } @@ -44,7 +43,7 @@ bool TerminalDispatch::CursorPosition(const unsigned int uiLine, bool TerminalDispatch::CursorForward(const unsigned int uiDistance) { const auto cursorPos = _terminalApi.GetCursorPosition(); - const COORD newCursorPos { cursorPos.X + gsl::narrow(uiDistance), cursorPos.Y }; + const COORD newCursorPos{ cursorPos.X + gsl::narrow(uiDistance), cursorPos.Y }; return _terminalApi.SetCursorPosition(newCursorPos.X, newCursorPos.Y); } diff --git a/src/cascadia/TerminalCore/TerminalDispatch.hpp b/src/cascadia/TerminalCore/TerminalDispatch.hpp index 68bfcfb52..60ecb6283 100644 --- a/src/cascadia/TerminalCore/TerminalDispatch.hpp +++ b/src/cascadia/TerminalCore/TerminalDispatch.hpp @@ -11,7 +11,7 @@ public: virtual ~TerminalDispatch(){}; virtual void Execute(const wchar_t wchControl) 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, const size_t cOptions) override; @@ -43,5 +43,4 @@ private: bool _SetBoldColorHelper(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); - }; diff --git a/src/cascadia/TerminalCore/TerminalDispatchGraphics.cpp b/src/cascadia/TerminalCore/TerminalDispatchGraphics.cpp index 55c004e33..03dab6c84 100644 --- a/src/cascadia/TerminalCore/TerminalDispatchGraphics.cpp +++ b/src/cascadia/TerminalCore/TerminalDispatchGraphics.cpp @@ -6,6 +6,7 @@ using namespace ::Microsoft::Terminal::Core; using namespace ::Microsoft::Console::VirtualTerminal; +// clang-format off const BYTE RED_ATTR = 0x01; const BYTE GREEN_ATTR = 0x02; 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_CYAN = BRIGHT_ATTR | GREEN_ATTR | BLUE_ATTR; const BYTE BRIGHT_WHITE = BRIGHT_ATTR | RED_ATTR | GREEN_ATTR | BLUE_ATTR; +// clang-format on // Routine Description: // 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 // 5 - true, parsed an RGB color. bool TerminalDispatch::_SetRgbColorsHelper(_In_reads_(cOptions) const DispatchTypes::GraphicsOptions* const rgOptions, - const size_t cOptions, - _Out_ size_t* const pcOptionsConsumed) + const size_t cOptions, + _Out_ size_t* const pcOptionsConsumed) { COLORREF color = 0; bool isForeground = false; @@ -105,9 +107,9 @@ bool TerminalDispatch::_SetRgbColorsHelper(_In_reads_(cOptions) const DispatchTy { *pcOptionsConsumed = 5; // ensure that each value fits in a byte - unsigned int red = rgOptions[2] > 255? 255 : rgOptions[2]; - unsigned int green = rgOptions[3] > 255? 255 : rgOptions[3]; - unsigned int blue = rgOptions[4] > 255? 255 : rgOptions[4]; + unsigned int red = rgOptions[2] > 255 ? 255 : rgOptions[2]; + unsigned int green = rgOptions[3] > 255 ? 255 : rgOptions[3]; + unsigned int blue = rgOptions[4] > 255 ? 255 : rgOptions[4]; color = RGB(red, green, blue); @@ -120,8 +122,8 @@ bool TerminalDispatch::_SetRgbColorsHelper(_In_reads_(cOptions) const DispatchTy { unsigned int tableIndex = rgOptions[2]; fSuccess = isForeground ? - _terminalApi.SetTextForegroundIndex((BYTE)tableIndex) : - _terminalApi.SetTextBackgroundIndex((BYTE)tableIndex); + _terminalApi.SetTextForegroundIndex((BYTE)tableIndex) : + _terminalApi.SetTextBackgroundIndex((BYTE)tableIndex); } } } @@ -307,7 +309,7 @@ bool TerminalDispatch::SetGraphicsRendition(const DispatchTypes::GraphicsOptions size_t cOptionsConsumed = 0; // _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. } diff --git a/src/cascadia/TerminalCore/terminalrenderdata.cpp b/src/cascadia/TerminalCore/terminalrenderdata.cpp index 8b9b9c8ac..b55c03ac9 100644 --- a/src/cascadia/TerminalCore/terminalrenderdata.cpp +++ b/src/cascadia/TerminalCore/terminalrenderdata.cpp @@ -128,14 +128,14 @@ const std::wstring Terminal::GetConsoleTitle() const noexcept // operation. // Callers should make sure to also call Terminal::UnlockConsole once // they're done with any querying they need to do. -void Terminal::LockConsole() noexcept +void Terminal::LockConsole() noexcept { _readWriteLock.lock_shared(); } // Method Description: // - Unlocks the terminal after a call to Terminal::LockConsole. -void Terminal::UnlockConsole() noexcept +void Terminal::UnlockConsole() noexcept { _readWriteLock.unlock_shared(); } diff --git a/src/cascadia/TerminalSettings/TerminalSettings.cpp b/src/cascadia/TerminalSettings/TerminalSettings.cpp index 26ca1d3d3..938a489f8 100644 --- a/src/cascadia/TerminalSettings/TerminalSettings.cpp +++ b/src/cascadia/TerminalSettings/TerminalSettings.cpp @@ -32,7 +32,6 @@ namespace winrt::Microsoft::Terminal::Settings::implementation _keyBindings{ nullptr }, _scrollbarState{ ScrollbarState::Visible } { - } uint32_t TerminalSettings::DefaultForeground() diff --git a/src/cascadia/TerminalSettings/pch.h b/src/cascadia/TerminalSettings/pch.h index 8f45542e8..c8166477b 100644 --- a/src/cascadia/TerminalSettings/pch.h +++ b/src/cascadia/TerminalSettings/pch.h @@ -20,4 +20,3 @@ #include #include - diff --git a/src/cascadia/UnitTests_TerminalCore/ScreenSizeLimitsTest.cpp b/src/cascadia/UnitTests_TerminalCore/ScreenSizeLimitsTest.cpp index 514105fad..ead5fe953 100644 --- a/src/cascadia/UnitTests_TerminalCore/ScreenSizeLimitsTest.cpp +++ b/src/cascadia/UnitTests_TerminalCore/ScreenSizeLimitsTest.cpp @@ -16,121 +16,117 @@ using namespace Microsoft::Terminal::Core; namespace TerminalCoreUnitTests { -class MockTermSettings : public winrt::implements -{ -public: - MockTermSettings(int32_t historySize, int32_t initialRows, int32_t initialCols) : - _historySize(historySize), - _initialRows(initialRows), - _initialCols(initialCols) - { } + class MockTermSettings : public winrt::implements + { + public: + MockTermSettings(int32_t historySize, int32_t initialRows, int32_t initialCols) : + _historySize(historySize), + _initialRows(initialRows), + _initialCols(initialCols) + { + } - // property getters - all implemented - int32_t HistorySize() { return _historySize; } - int32_t InitialRows() { return _initialRows; } - int32_t InitialCols() { return _initialCols; } - uint32_t DefaultForeground() { return COLOR_WHITE; } - uint32_t DefaultBackground() { return COLOR_BLACK; } - bool SnapOnInput() { return false; } - uint32_t CursorColor() { return COLOR_WHITE; } - CursorStyle CursorShape() const noexcept { return CursorStyle::Vintage; } - uint32_t CursorHeight() { return 42UL; } + // property getters - all implemented + int32_t HistorySize() { return _historySize; } + int32_t InitialRows() { return _initialRows; } + int32_t InitialCols() { return _initialCols; } + uint32_t DefaultForeground() { return COLOR_WHITE; } + uint32_t DefaultBackground() { return COLOR_BLACK; } + bool SnapOnInput() { return false; } + uint32_t CursorColor() { return COLOR_WHITE; } + CursorStyle CursorShape() const noexcept { return CursorStyle::Vintage; } + uint32_t CursorHeight() { return 42UL; } - // other implemented methods - uint32_t GetColorTableEntry(int32_t) const { return 123; } + // other implemented methods + uint32_t GetColorTableEntry(int32_t) const { return 123; } - // property setters - all unimplemented - void HistorySize(int32_t) { } - void InitialRows(int32_t) { } - void InitialCols(int32_t) { } - void DefaultForeground(uint32_t) { } - void DefaultBackground(uint32_t) { } - void SnapOnInput(bool) { } - void CursorColor(uint32_t) { } - void CursorShape(CursorStyle const&) noexcept { } - void CursorHeight(uint32_t) { } + // property setters - all unimplemented + void HistorySize(int32_t) {} + void InitialRows(int32_t) {} + void InitialCols(int32_t) {} + void DefaultForeground(uint32_t) {} + void DefaultBackground(uint32_t) {} + void SnapOnInput(bool) {} + void CursorColor(uint32_t) {} + void CursorShape(CursorStyle const&) noexcept {} + void CursorHeight(uint32_t) {} - // other unimplemented methods - void SetColorTableEntry(int32_t /* index */, uint32_t /* value */) { } + // other unimplemented methods + void SetColorTableEntry(int32_t /* index */, uint32_t /* value */) {} -private: - int32_t _historySize; - int32_t _initialRows; - int32_t _initialCols; -}; + private: + int32_t _historySize; + int32_t _initialRows; + int32_t _initialCols; + }; #define WCS(x) WCSHELPER(x) #define WCSHELPER(x) L#x -class ScreenSizeLimitsTest -{ - TEST_CLASS(ScreenSizeLimitsTest); - - TEST_METHOD(ScreenWidthAndHeightAreClampedToBounds) + class ScreenSizeLimitsTest { - DummyRenderTarget emptyRenderTarget; + TEST_CLASS(ScreenSizeLimitsTest); - // Negative values for initial visible row count or column count - // are clamped to 1. Too-large positive values are clamped to SHRT_MAX. - auto negativeColumnsSettings = winrt::make(10000, 9999999, -1234); - 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"); + TEST_METHOD(ScreenWidthAndHeightAreClampedToBounds) + { + DummyRenderTarget emptyRenderTarget; - // Zero values are clamped to 1 as well. - auto zeroRowsSettings = winrt::make(10000, 0, 9999999); - Terminal zeroRowsTerminal; - zeroRowsTerminal.CreateFromSettings(zeroRowsSettings, emptyRenderTarget); - 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)); - } + // Negative values for initial visible row count or column count + // are clamped to 1. Too-large positive values are clamped to SHRT_MAX. + auto negativeColumnsSettings = winrt::make(10000, 9999999, -1234); + 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"); - TEST_METHOD(ScrollbackHistorySizeIsClampedToBounds) - { - // 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 values are clamped to 1 as well. + auto zeroRowsSettings = winrt::make(10000, 0, 9999999); + Terminal zeroRowsTerminal; + zeroRowsTerminal.CreateFromSettings(zeroRowsSettings, emptyRenderTarget); + 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; - DummyRenderTarget emptyRenderTarget; + TEST_METHOD(ScrollbackHistorySizeIsClampedToBounds) + { + // 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. - auto noHistorySettings = winrt::make(0, visibleRowCount, 100); - Terminal noHistoryTerminal; - noHistoryTerminal.CreateFromSettings(noHistorySettings, emptyRenderTarget); - VERIFY_ARE_EQUAL(noHistoryTerminal.GetTextBuffer().TotalRowCount(), visibleRowCount, - L"History size of 0 is accepted"); + const unsigned int visibleRowCount = 100; + DummyRenderTarget emptyRenderTarget; - // Negative history sizes are clamped to zero. - auto negativeHistorySizeSettings = winrt::make(-100, visibleRowCount, 100); - Terminal negativeHistorySizeTerminal; - negativeHistorySizeTerminal.CreateFromSettings(negativeHistorySizeSettings, emptyRenderTarget); - VERIFY_ARE_EQUAL(negativeHistorySizeTerminal.GetTextBuffer().TotalRowCount(), visibleRowCount, - L"Negative history size is clamped to 0"); + // Zero history size is acceptable. + auto noHistorySettings = winrt::make(0, visibleRowCount, 100); + Terminal noHistoryTerminal; + noHistoryTerminal.CreateFromSettings(noHistorySettings, emptyRenderTarget); + VERIFY_ARE_EQUAL(noHistoryTerminal.GetTextBuffer().TotalRowCount(), visibleRowCount, L"History size of 0 is accepted"); - // History size + initial visible rows == SHRT_MAX is acceptable. - auto maxHistorySizeSettings = winrt::make(SHRT_MAX - visibleRowCount, visibleRowCount, 100); - Terminal maxHistorySizeTerminal; - maxHistorySizeTerminal.CreateFromSettings(maxHistorySizeSettings, emptyRenderTarget); - VERIFY_ARE_EQUAL(maxHistorySizeTerminal.GetTextBuffer().TotalRowCount(), static_cast(SHRT_MAX), - L"History size == SHRT_MAX - initial row count is accepted"); + // Negative history sizes are clamped to zero. + auto negativeHistorySizeSettings = winrt::make(-100, visibleRowCount, 100); + Terminal negativeHistorySizeTerminal; + negativeHistorySizeTerminal.CreateFromSettings(negativeHistorySizeSettings, emptyRenderTarget); + VERIFY_ARE_EQUAL(negativeHistorySizeTerminal.GetTextBuffer().TotalRowCount(), visibleRowCount, L"Negative history size is clamped to 0"); - // History size + initial visible rows == SHRT_MAX + 1 will be clamped slightly. - auto justTooBigHistorySizeSettings = winrt::make(SHRT_MAX - visibleRowCount + 1, visibleRowCount, 100); - Terminal justTooBigHistorySizeTerminal; - justTooBigHistorySizeTerminal.CreateFromSettings(justTooBigHistorySizeSettings, emptyRenderTarget); - VERIFY_ARE_EQUAL(justTooBigHistorySizeTerminal.GetTextBuffer().TotalRowCount(), static_cast(SHRT_MAX), - L"History size == 1 + SHRT_MAX - initial row count is clamped to SHRT_MAX - initial row count"); + // History size + initial visible rows == SHRT_MAX is acceptable. + auto maxHistorySizeSettings = winrt::make(SHRT_MAX - visibleRowCount, visibleRowCount, 100); + Terminal maxHistorySizeTerminal; + maxHistorySizeTerminal.CreateFromSettings(maxHistorySizeSettings, emptyRenderTarget); + VERIFY_ARE_EQUAL(maxHistorySizeTerminal.GetTextBuffer().TotalRowCount(), static_cast(SHRT_MAX), L"History size == SHRT_MAX - initial row count is accepted"); - // Ridiculously large history sizes are also clamped. - auto farTooBigHistorySizeSettings = winrt::make(99999999, visibleRowCount, 100); - Terminal farTooBigHistorySizeTerminal; - farTooBigHistorySizeTerminal.CreateFromSettings(farTooBigHistorySizeSettings, emptyRenderTarget); - VERIFY_ARE_EQUAL(farTooBigHistorySizeTerminal.GetTextBuffer().TotalRowCount(), static_cast(SHRT_MAX), - L"History size that is far too large is clamped to SHRT_MAX - initial row count"); - } -}; + // History size + initial visible rows == SHRT_MAX + 1 will be clamped slightly. + auto justTooBigHistorySizeSettings = winrt::make(SHRT_MAX - visibleRowCount + 1, visibleRowCount, 100); + Terminal justTooBigHistorySizeTerminal; + justTooBigHistorySizeTerminal.CreateFromSettings(justTooBigHistorySizeSettings, emptyRenderTarget); + VERIFY_ARE_EQUAL(justTooBigHistorySizeTerminal.GetTextBuffer().TotalRowCount(), static_cast(SHRT_MAX), L"History size == 1 + SHRT_MAX - initial row count is clamped to SHRT_MAX - initial row count"); + + // Ridiculously large history sizes are also clamped. + auto farTooBigHistorySizeSettings = winrt::make(99999999, visibleRowCount, 100); + Terminal farTooBigHistorySizeTerminal; + farTooBigHistorySizeTerminal.CreateFromSettings(farTooBigHistorySizeSettings, emptyRenderTarget); + VERIFY_ARE_EQUAL(farTooBigHistorySizeTerminal.GetTextBuffer().TotalRowCount(), static_cast(SHRT_MAX), L"History size that is far too large is clamped to SHRT_MAX - initial row count"); + } + }; } diff --git a/src/cascadia/UnitTests_TerminalCore/SelectionTest.cpp b/src/cascadia/UnitTests_TerminalCore/SelectionTest.cpp index f84471211..ffdcc1ad9 100644 --- a/src/cascadia/UnitTests_TerminalCore/SelectionTest.cpp +++ b/src/cascadia/UnitTests_TerminalCore/SelectionTest.cpp @@ -39,9 +39,9 @@ namespace TerminalCoreUnitTests // Validate selection area VERIFY_ARE_EQUAL(selectionRects.size(), static_cast(1)); - + auto selection = term.GetViewport().ConvertToOrigin(selectionRects.at(0)).ToInclusive(); - VerifyCompareTraits::AreEqual({5, 10, 10, 5}, selection); + VerifyCompareTraits::AreEqual({ 5, 10, 10, 5 }, selection); } TEST_METHOD(SelectArea) @@ -73,20 +73,20 @@ namespace TerminalCoreUnitTests { auto selection = viewport.ConvertToOrigin(selectionRect).ToInclusive(); - if (rowValue == 10) + if (rowValue == 10) { // Verify top line - VerifyCompareTraits::AreEqual({5, 10, rightBoundary, 10}, selection); + VerifyCompareTraits::AreEqual({ 5, 10, rightBoundary, 10 }, selection); } else if (rowValue == 20) { // Verify bottom line - VerifyCompareTraits::AreEqual({0, 20, 15, 20}, selection); + VerifyCompareTraits::AreEqual({ 0, 20, 15, 20 }, selection); } else { // Verify other lines (full) - VerifyCompareTraits::AreEqual({0, rowValue, rightBoundary, rowValue}, selection); + VerifyCompareTraits::AreEqual({ 0, rowValue, rightBoundary, rowValue }, selection); } rowValue++; @@ -123,7 +123,7 @@ namespace TerminalCoreUnitTests auto selection = viewport.ConvertToOrigin(selectionRect).ToInclusive(); // Verify all lines - VerifyCompareTraits::AreEqual({5, rowValue, 15, rowValue}, selection); + VerifyCompareTraits::AreEqual({ 5, rowValue, 15, rowValue }, selection); rowValue++; } @@ -135,7 +135,7 @@ namespace TerminalCoreUnitTests DummyRenderTarget emptyRT; SHORT scrollbackLines = 5; term.Create({ 100, 100 }, scrollbackLines, emptyRT); - + // Used for two things: // - click y-pos // - keep track of row we're verifying @@ -162,17 +162,17 @@ namespace TerminalCoreUnitTests if (rowValue == 10) { // Verify top line - VerifyCompareTraits::AreEqual({5, 10, rightBoundary, 10}, selection); + VerifyCompareTraits::AreEqual({ 5, 10, rightBoundary, 10 }, selection); } else if (rowValue == 20) { // Verify bottom line - VerifyCompareTraits::AreEqual({0, 20, 15, 20}, selection); + VerifyCompareTraits::AreEqual({ 0, 20, 15, 20 }, selection); } else { // Verify other lines (full) - VerifyCompareTraits::AreEqual({0, rowValue, rightBoundary, rowValue}, selection); + VerifyCompareTraits::AreEqual({ 0, rowValue, rightBoundary, rowValue }, selection); } rowValue++; diff --git a/src/cascadia/WindowsTerminal/AppHost.cpp b/src/cascadia/WindowsTerminal/AppHost.cpp index 12f0132e4..1407f7073 100644 --- a/src/cascadia/WindowsTerminal/AppHost.cpp +++ b/src/cascadia/WindowsTerminal/AppHost.cpp @@ -102,7 +102,8 @@ void AppHost::AppTitleChanged(winrt::hstring newTitle) // - // Return Value: // - -void AppHost::LastTabClosed() { +void AppHost::LastTabClosed() +{ _window->Close(); } @@ -140,7 +141,8 @@ void AppHost::_HandleCreateWindow(const HWND hwnd, const RECT proposedRect) // Create a RECT from our requested client size 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 // 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. LOG_LAST_ERROR(); nonClient = Viewport::FromDimensions({ _currentWidth, - _currentHeight }).ToRect(); + _currentHeight }) + .ToRect(); } } - const auto adjustedHeight = nonClient.bottom - nonClient.top; 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); - bool succeeded = SetWindowPos(hwnd, nullptr, + bool succeeded = SetWindowPos(hwnd, + nullptr, newPos.Left(), newPos.Top(), 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 // the originally proposed window size. LOG_LAST_ERROR_IF(!succeeded); - - } diff --git a/src/cascadia/WindowsTerminal/BaseWindow.h b/src/cascadia/WindowsTerminal/BaseWindow.h index 76ea29bbc..996084261 100644 --- a/src/cascadia/WindowsTerminal/BaseWindow.h +++ b/src/cascadia/WindowsTerminal/BaseWindow.h @@ -4,26 +4,25 @@ #pragma once // Custom window messages -#define CM_UPDATE_TITLE (WM_USER) +#define CM_UPDATE_TITLE (WM_USER) -template +template class BaseWindow { public: virtual ~BaseWindow() = 0; static T* GetThisFromHandle(HWND const window) noexcept { - return reinterpret_cast(GetWindowLongPtr(window, GWLP_USERDATA)); + return reinterpret_cast(GetWindowLongPtr(window, GWLP_USERDATA)); } - [[nodiscard]] - static LRESULT __stdcall WndProc(HWND const window, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept + [[nodiscard]] static LRESULT __stdcall WndProc(HWND const window, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept { WINRT_ASSERT(window); if (WM_NCCREATE == message) { - auto cs = reinterpret_cast(lparam); + auto cs = reinterpret_cast(lparam); T* that = static_cast(cs->lpCreateParams); WINRT_ASSERT(that); WINRT_ASSERT(!that->_window); @@ -41,10 +40,10 @@ public: return DefWindowProc(window, message, wparam, lparam); } - [[nodiscard]] - virtual LRESULT MessageHandler(UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept + [[nodiscard]] virtual LRESULT MessageHandler(UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept { - switch (message) { + switch (message) + { case WM_DPICHANGED: { return HandleDpiChange(_window, wparam, lparam); @@ -100,8 +99,7 @@ public: } // DPI Change handler. on WM_DPICHANGE resize the window - [[nodiscard]] - LRESULT HandleDpiChange(const HWND hWnd, const WPARAM wParam, const LPARAM lParam) + [[nodiscard]] LRESULT HandleDpiChange(const HWND hWnd, const WPARAM wParam, const LPARAM lParam) { _inDpiChange = true; const HWND hWndStatic = GetWindow(hWnd, GW_CHILD); @@ -112,9 +110,7 @@ public: // Resize the window auto lprcNewScale = reinterpret_cast(lParam); - SetWindowPos(hWnd, nullptr, lprcNewScale->left, lprcNewScale->top, - lprcNewScale->right - lprcNewScale->left, lprcNewScale->bottom - lprcNewScale->top, - SWP_NOZORDER | SWP_NOACTIVATE); + SetWindowPos(hWnd, nullptr, lprcNewScale->left, lprcNewScale->top, lprcNewScale->right - lprcNewScale->left, lprcNewScale->bottom - lprcNewScale->top, SWP_NOZORDER | SWP_NOACTIVATE); _currentDpi = uDpi; } @@ -202,5 +198,7 @@ protected: bool _minimized = false; }; -template -inline BaseWindow::~BaseWindow() { } +template +inline BaseWindow::~BaseWindow() +{ +} diff --git a/src/cascadia/WindowsTerminal/IslandWindow.cpp b/src/cascadia/WindowsTerminal/IslandWindow.cpp index a9a728a65..4e1964360 100644 --- a/src/cascadia/WindowsTerminal/IslandWindow.cpp +++ b/src/cascadia/WindowsTerminal/IslandWindow.cpp @@ -49,13 +49,18 @@ void IslandWindow::MakeWindow() noexcept // window, the system will give us a chance to set its size in WM_CREATE. // WM_CREATE will be handled synchronously, before CreateWindow returns. WINRT_VERIFY(CreateWindow(wc.lpszClassName, - L"Windows Terminal", - WS_OVERLAPPEDWINDOW, - CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, - nullptr, nullptr, wc.hInstance, this)); + L"Windows Terminal", + WS_OVERLAPPEDWINDOW, + CW_USEDEFAULT, + CW_USEDEFAULT, + CW_USEDEFAULT, + CW_USEDEFAULT, + nullptr, + nullptr, + wc.hInstance, + this)); WINRT_ASSERT(_window); - } // Method Description: @@ -144,11 +149,10 @@ void IslandWindow::OnSize() } } -[[nodiscard]] -LRESULT IslandWindow::MessageHandler(UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept +[[nodiscard]] LRESULT IslandWindow::MessageHandler(UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept { - switch (message) { - + switch (message) + { case WM_CREATE: { _HandleCreateWindow(wparam, lparam); @@ -205,4 +209,3 @@ void IslandWindow::SetRootContent(winrt::Windows::UI::Xaml::UIElement content) _rootGrid.Children().Clear(); _rootGrid.Children().Append(content); } - diff --git a/src/cascadia/WindowsTerminal/IslandWindow.h b/src/cascadia/WindowsTerminal/IslandWindow.h index e8958c6eb..706f76c7a 100644 --- a/src/cascadia/WindowsTerminal/IslandWindow.h +++ b/src/cascadia/WindowsTerminal/IslandWindow.h @@ -16,8 +16,7 @@ public: void Close(); virtual void OnSize(); - [[nodiscard]] - virtual LRESULT MessageHandler(UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept override; + [[nodiscard]] virtual LRESULT MessageHandler(UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept override; void OnResize(const UINT width, const UINT height) override; void OnMinimize() override; void OnRestore() override; diff --git a/src/cascadia/WindowsTerminal/NonClientIslandWindow.cpp b/src/cascadia/WindowsTerminal/NonClientIslandWindow.cpp index 3669a19f7..08e057a17 100644 --- a/src/cascadia/WindowsTerminal/NonClientIslandWindow.cpp +++ b/src/cascadia/WindowsTerminal/NonClientIslandWindow.cpp @@ -25,7 +25,7 @@ constexpr int RECT_HEIGHT(const RECT* const pRect) } NonClientIslandWindow::NonClientIslandWindow() noexcept : - IslandWindow{ }, + IslandWindow{}, _nonClientInteropWindowHandle{ nullptr }, _nonClientRootGrid{ nullptr }, _nonClientSource{ nullptr }, @@ -71,7 +71,6 @@ void NonClientIslandWindow::SetNonClientContent(winrt::Windows::UI::Xaml::UIElem _nonClientRootGrid.Children().Append(content); } - // Method Description: // - Set the height we expect to reserve for the non-client content. // Arguments: @@ -104,7 +103,6 @@ Viewport NonClientIslandWindow::GetTitlebarContentArea() const noexcept const auto titlebarHeight = titlebarContentHeight - (_titlebarMarginTop + _titlebarMarginBottom); - COORD titlebarOrigin = { static_cast(_windowMarginSides), static_cast(_titlebarMarginTop) }; @@ -172,7 +170,8 @@ void NonClientIslandWindow::OnSize() auto titlebarArea = GetTitlebarContentArea(); // update the interop window size - SetWindowPos(_interopWindowHandle, 0, + SetWindowPos(_interopWindowHandle, + 0, clientArea.Left(), clientArea.Top(), clientArea.Width(), @@ -188,7 +187,8 @@ void NonClientIslandWindow::OnSize() } // update the interop window size - SetWindowPos(_nonClientInteropWindowHandle, 0, + SetWindowPos(_nonClientInteropWindowHandle, + 0, titlebarArea.Left(), titlebarArea.Top(), titlebarArea.Width(), @@ -209,8 +209,7 @@ void NonClientIslandWindow::OnSize() // NOTE: // Largely taken from code on: // https://docs.microsoft.com/en-us/windows/desktop/dwm/customframe -[[nodiscard]] -LRESULT NonClientIslandWindow::HitTestNCA(POINT ptMouse) const noexcept +[[nodiscard]] LRESULT NonClientIslandWindow::HitTestNCA(POINT ptMouse) const noexcept { // Get the window rectangle. RECT rcWindow = BaseWindow::GetWindowRect(); @@ -249,13 +248,14 @@ LRESULT NonClientIslandWindow::HitTestNCA(POINT ptMouse) const noexcept uCol = 2; // right side } + // clang-format off // Hit test (HTTOPLEFT, ... HTBOTTOMRIGHT) - LRESULT hitTests[3][3] = - { - { HTTOPLEFT, fOnResizeBorder ? HTTOP : HTCAPTION, HTTOPRIGHT }, - { HTLEFT, HTNOWHERE, HTRIGHT }, - { HTBOTTOMLEFT, HTBOTTOM, HTBOTTOMRIGHT }, + LRESULT hitTests[3][3] = { + { HTTOPLEFT, fOnResizeBorder ? HTTOP : HTCAPTION, HTTOPRIGHT }, + { HTLEFT, HTNOWHERE, HTRIGHT }, + { HTBOTTOMLEFT, HTBOTTOM, HTBOTTOMRIGHT }, }; + // clang-format on return hitTests[uRow][uCol]; } @@ -270,7 +270,7 @@ MARGINS NonClientIslandWindow::GetFrameMargins() const noexcept { const auto titlebarView = GetTitlebarContentArea(); - MARGINS margins{0}; + MARGINS margins{ 0 }; margins.cxLeftWidth = _windowMarginSides; margins.cxRightWidth = _windowMarginSides; margins.cyBottomHeight = _windowMarginBottom; @@ -285,8 +285,7 @@ MARGINS NonClientIslandWindow::GetFrameMargins() const noexcept // - // Return Value: // - the HRESULT returned by DwmExtendFrameIntoClientArea. -[[nodiscard]] -HRESULT NonClientIslandWindow::_UpdateFrameMargins() const noexcept +[[nodiscard]] HRESULT NonClientIslandWindow::_UpdateFrameMargins() const noexcept { // 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 @@ -314,8 +313,8 @@ HRESULT NonClientIslandWindow::_UpdateFrameMargins() const noexcept // origin in pixels. Measures the outer edges of the potential window. // NOTE: // Heavily taken from WindowMetrics::GetMaxWindowRectInPixels in conhost. -RECT NonClientIslandWindow::GetMaxWindowRectInPixels(const RECT * const prcSuggested, - _Out_opt_ UINT * pDpiSuggested) +RECT NonClientIslandWindow::GetMaxWindowRectInPixels(const RECT* const prcSuggested, + _Out_opt_ UINT* pDpiSuggested) { // prepare rectangle RECT rc = *prcSuggested; @@ -389,10 +388,9 @@ RECT NonClientIslandWindow::GetMaxWindowRectInPixels(const RECT * const prcSugge // Return Value: // - The return value is the result of the message processing and depends on the // message sent. -[[nodiscard]] -LRESULT NonClientIslandWindow::MessageHandler(UINT const message, - WPARAM const wParam, - LPARAM const lParam) noexcept +[[nodiscard]] LRESULT NonClientIslandWindow::MessageHandler(UINT const message, + WPARAM const wParam, + LPARAM const lParam) noexcept { LRESULT lRet = 0; @@ -417,11 +415,11 @@ LRESULT NonClientIslandWindow::MessageHandler(UINT const message, if (wParam == TRUE && lParam) { // Calculate new NCCALCSIZE_PARAMS based on custom NCA inset. - NCCALCSIZE_PARAMS *pncsp = reinterpret_cast(lParam); + NCCALCSIZE_PARAMS* pncsp = reinterpret_cast(lParam); - pncsp->rgrc[0].left = pncsp->rgrc[0].left + 0; - pncsp->rgrc[0].top = pncsp->rgrc[0].top + 0; - pncsp->rgrc[0].right = pncsp->rgrc[0].right - 0; + pncsp->rgrc[0].left = pncsp->rgrc[0].left + 0; + pncsp->rgrc[0].top = pncsp->rgrc[0].top + 0; + pncsp->rgrc[0].right = pncsp->rgrc[0].right - 0; pncsp->rgrc[0].bottom = pncsp->rgrc[0].bottom - 0; return 0; @@ -438,7 +436,7 @@ LRESULT NonClientIslandWindow::MessageHandler(UINT const message, // Handle hit testing in the NCA if not handled by DwmDefWindowProc. 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) { @@ -466,7 +464,6 @@ LRESULT NonClientIslandWindow::MessageHandler(UINT const message, break; } } - } 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, // keep it from moving entirely. We'll get a WM_DPICHANGED, resize the // window, and then process the restriction in a few window messages. - if ( ((int)dpiOfMaximum == _currentDpi) && - ( (suggestedWidth > maxWidth) || - (suggestedHeight > maxHeight) ) ) + if (((int)dpiOfMaximum == _currentDpi) && + ((suggestedWidth > maxWidth) || + (suggestedHeight > maxHeight))) { auto offset = 0; // Determine which side of the window to use for the offset @@ -642,7 +639,7 @@ bool NonClientIslandWindow::_HandleWindowPosChanging(WINDOWPOS* const windowPos) else { // Clear our maximization state - _maximizedMargins = {0}; + _maximizedMargins = { 0 }; // Immediately after resoring down, don't update our frame margins. If // you do this here, then a small gap will appear between the titlebar diff --git a/src/cascadia/WindowsTerminal/NonClientIslandWindow.h b/src/cascadia/WindowsTerminal/NonClientIslandWindow.h index c40bd942d..cc7451565 100644 --- a/src/cascadia/WindowsTerminal/NonClientIslandWindow.h +++ b/src/cascadia/WindowsTerminal/NonClientIslandWindow.h @@ -31,8 +31,7 @@ public: virtual void OnSize() override; - [[nodiscard]] - virtual LRESULT MessageHandler(UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept override; + [[nodiscard]] virtual LRESULT MessageHandler(UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept override; void SetNonClientContent(winrt::Windows::UI::Xaml::UIElement content); @@ -43,7 +42,6 @@ public: void SetNonClientHeight(const int contentHeight) noexcept; private: - winrt::Windows::UI::Xaml::Hosting::DesktopWindowXamlSource _nonClientSource; HWND _nonClientInteropWindowHandle; @@ -63,14 +61,12 @@ private: MARGINS _maximizedMargins; bool _isMaximized; - [[nodiscard]] - LRESULT HitTestNCA(POINT ptMouse) const noexcept; + [[nodiscard]] LRESULT HitTestNCA(POINT ptMouse) const noexcept; - [[nodiscard]] - HRESULT _UpdateFrameMargins() const noexcept; + [[nodiscard]] HRESULT _UpdateFrameMargins() const noexcept; void _HandleActivateWindow(); 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); }; diff --git a/src/cascadia/WindowsTerminal/resource.h b/src/cascadia/WindowsTerminal/resource.h index 34124b61e..60c7c3d28 100644 --- a/src/cascadia/WindowsTerminal/resource.h +++ b/src/cascadia/WindowsTerminal/resource.h @@ -6,9 +6,9 @@ // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 103 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1001 -#define _APS_NEXT_SYMED_VALUE 101 +#define _APS_NEXT_RESOURCE_VALUE 103 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 #endif #endif diff --git a/src/cascadia/inc/cppwinrt_utils.h b/src/cascadia/inc/cppwinrt_utils.h index a0197a364..8a36d12c3 100644 --- a/src/cascadia/inc/cppwinrt_utils.h +++ b/src/cascadia/inc/cppwinrt_utils.h @@ -20,30 +20,32 @@ Revision History: // This is a helper macro to make declaring events easier. // This will declare the event handler and the methods for adding and removing a // handler callback from the event -#define DECLARE_EVENT(name, eventHandler, args) \ - public: \ - winrt::event_token name(args const& handler); \ +#define DECLARE_EVENT(name, eventHandler, args) \ +public: \ + winrt::event_token name(args const& handler); \ void name(winrt::event_token const& token) noexcept; \ - private: \ + \ +private: \ winrt::event eventHandler; // 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 // the callback. This macro will define them both for you, because they // don't really vary from event to event. -#define DEFINE_EVENT(className, name, eventHandler, args) \ - winrt::event_token className::name(args const& handler) { return eventHandler.add(handler); } \ - void className::name(winrt::event_token const& token) noexcept { eventHandler.remove(token); } +#define DEFINE_EVENT(className, name, eventHandler, args) \ + winrt::event_token className::name(args const& handler) { return eventHandler.add(handler); } \ + void className::name(winrt::event_token const& token) noexcept { eventHandler.remove(token); } // This is a helper macro to make declaring events easier. // This will declare the event handler and the methods for adding and removing a // handler callback from the event. // Use this if you have a Windows.Foundation.TypedEventHandler -#define DECLARE_EVENT_WITH_TYPED_EVENT_HANDLER(name, eventHandler, sender, args) \ - public: \ +#define DECLARE_EVENT_WITH_TYPED_EVENT_HANDLER(name, eventHandler, sender, args) \ +public: \ winrt::event_token name(Windows::Foundation::TypedEventHandler const& handler); \ - void name(winrt::event_token const& token) noexcept; \ - private: \ + void name(winrt::event_token const& token) noexcept; \ + \ +private: \ winrt::event> eventHandler; // 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 // don't really vary from event to event. // Use this if you have a Windows.Foundation.TypedEventHandler -#define DEFINE_EVENT_WITH_TYPED_EVENT_HANDLER(className, name, eventHandler, sender, args) \ - winrt::event_token className::name(Windows::Foundation::TypedEventHandler const& handler) { return eventHandler.add(handler); } \ - void className::name(winrt::event_token const& token) noexcept { eventHandler.remove(token); } \ No newline at end of file +#define DEFINE_EVENT_WITH_TYPED_EVENT_HANDLER(className, name, eventHandler, sender, args) \ + winrt::event_token className::name(Windows::Foundation::TypedEventHandler const& handler) { return eventHandler.add(handler); } \ + void className::name(winrt::event_token const& token) noexcept { eventHandler.remove(token); } \ No newline at end of file diff --git a/src/host/ApiRoutines.h b/src/host/ApiRoutines.h index 2aff07e01..b02909335 100644 --- a/src/host/ApiRoutines.h +++ b/src/host/ApiRoutines.h @@ -40,111 +40,96 @@ public: void GetConsoleOutputModeImpl(SCREEN_INFORMATION& context, ULONG& mode) noexcept override; - [[nodiscard]] - HRESULT SetConsoleInputModeImpl(InputBuffer& context, - const ULONG mode) noexcept override; + [[nodiscard]] HRESULT SetConsoleInputModeImpl(InputBuffer& context, + const ULONG mode) noexcept override; - [[nodiscard]] - HRESULT SetConsoleOutputModeImpl(SCREEN_INFORMATION& context, - const ULONG Mode) noexcept override; + [[nodiscard]] HRESULT SetConsoleOutputModeImpl(SCREEN_INFORMATION& context, + const ULONG Mode) noexcept override; - [[nodiscard]] - HRESULT GetNumberOfConsoleInputEventsImpl(const InputBuffer& context, - ULONG& events) noexcept override; + [[nodiscard]] HRESULT GetNumberOfConsoleInputEventsImpl(const InputBuffer& context, + ULONG& events) noexcept override; - [[nodiscard]] - HRESULT PeekConsoleInputAImpl(IConsoleInputObject& context, - std::deque>& outEvents, - const size_t eventsToRead, - INPUT_READ_HANDLE_DATA& readHandleState, - std::unique_ptr& waiter) noexcept override; + [[nodiscard]] HRESULT PeekConsoleInputAImpl(IConsoleInputObject& context, + std::deque>& outEvents, + const size_t eventsToRead, + INPUT_READ_HANDLE_DATA& readHandleState, + std::unique_ptr& waiter) noexcept override; - [[nodiscard]] - HRESULT PeekConsoleInputWImpl(IConsoleInputObject& context, - std::deque>& outEvents, - const size_t eventsToRead, - INPUT_READ_HANDLE_DATA& readHandleState, - std::unique_ptr& waiter) noexcept override; + [[nodiscard]] HRESULT PeekConsoleInputWImpl(IConsoleInputObject& context, + std::deque>& outEvents, + const size_t eventsToRead, + INPUT_READ_HANDLE_DATA& readHandleState, + std::unique_ptr& waiter) noexcept override; - [[nodiscard]] - HRESULT ReadConsoleInputAImpl(IConsoleInputObject& context, - std::deque>& outEvents, - const size_t eventsToRead, - INPUT_READ_HANDLE_DATA& readHandleState, - std::unique_ptr& waiter) noexcept override; + [[nodiscard]] HRESULT ReadConsoleInputAImpl(IConsoleInputObject& context, + std::deque>& outEvents, + const size_t eventsToRead, + INPUT_READ_HANDLE_DATA& readHandleState, + std::unique_ptr& waiter) noexcept override; - [[nodiscard]] - HRESULT ReadConsoleInputWImpl(IConsoleInputObject& context, - std::deque>& outEvents, - const size_t eventsToRead, - INPUT_READ_HANDLE_DATA& readHandleState, - std::unique_ptr& waiter) noexcept override; + [[nodiscard]] HRESULT ReadConsoleInputWImpl(IConsoleInputObject& context, + std::deque>& outEvents, + const size_t eventsToRead, + INPUT_READ_HANDLE_DATA& readHandleState, + std::unique_ptr& waiter) noexcept override; - [[nodiscard]] - HRESULT ReadConsoleAImpl(IConsoleInputObject& context, - gsl::span buffer, - size_t& written, - std::unique_ptr& waiter, - const std::string_view initialData, - const std::wstring_view exeName, - INPUT_READ_HANDLE_DATA& readHandleState, - const HANDLE clientHandle, - const DWORD controlWakeupMask, - DWORD& controlKeyState) noexcept override; + [[nodiscard]] HRESULT ReadConsoleAImpl(IConsoleInputObject& context, + gsl::span buffer, + size_t& written, + std::unique_ptr& waiter, + const std::string_view initialData, + const std::wstring_view exeName, + INPUT_READ_HANDLE_DATA& readHandleState, + const HANDLE clientHandle, + const DWORD controlWakeupMask, + DWORD& controlKeyState) noexcept override; - [[nodiscard]] - HRESULT ReadConsoleWImpl(IConsoleInputObject& context, - gsl::span buffer, - size_t& written, - std::unique_ptr& waiter, - const std::string_view initialData, - const std::wstring_view exeName, - INPUT_READ_HANDLE_DATA& readHandleState, - const HANDLE clientHandle, - const DWORD controlWakeupMask, - DWORD& controlKeyState) noexcept override; + [[nodiscard]] HRESULT ReadConsoleWImpl(IConsoleInputObject& context, + gsl::span buffer, + size_t& written, + std::unique_ptr& waiter, + const std::string_view initialData, + const std::wstring_view exeName, + INPUT_READ_HANDLE_DATA& readHandleState, + const HANDLE clientHandle, + const DWORD controlWakeupMask, + DWORD& controlKeyState) noexcept override; - [[nodiscard]] - HRESULT WriteConsoleAImpl(IConsoleOutputObject& context, - const std::string_view buffer, - size_t& read, - std::unique_ptr& waiter) noexcept override; + [[nodiscard]] HRESULT WriteConsoleAImpl(IConsoleOutputObject& context, + const std::string_view buffer, + size_t& read, + std::unique_ptr& waiter) noexcept override; - [[nodiscard]] - HRESULT WriteConsoleWImpl(IConsoleOutputObject& context, - const std::wstring_view buffer, - size_t& read, - std::unique_ptr& waiter) noexcept override; + [[nodiscard]] HRESULT WriteConsoleWImpl(IConsoleOutputObject& context, + const std::wstring_view buffer, + size_t& read, + std::unique_ptr& waiter) noexcept override; #pragma region ThreadCreationInfo - [[nodiscard]] - HRESULT GetConsoleLangIdImpl(LANGID& langId) noexcept override; + [[nodiscard]] HRESULT GetConsoleLangIdImpl(LANGID& langId) noexcept override; #pragma endregion #pragma endregion #pragma region L2 - [[nodiscard]] - HRESULT FillConsoleOutputAttributeImpl(IConsoleOutputObject& OutContext, - const WORD attribute, - const size_t lengthToWrite, - const COORD startingCoordinate, - size_t& cellsModified) noexcept override; + [[nodiscard]] HRESULT FillConsoleOutputAttributeImpl(IConsoleOutputObject& OutContext, + const WORD attribute, + const size_t lengthToWrite, + const COORD startingCoordinate, + size_t& cellsModified) noexcept override; - [[nodiscard]] - HRESULT FillConsoleOutputCharacterAImpl(IConsoleOutputObject& OutContext, - const char character, - const size_t lengthToWrite, - const COORD startingCoordinate, - size_t& cellsModified) noexcept override; + [[nodiscard]] HRESULT FillConsoleOutputCharacterAImpl(IConsoleOutputObject& OutContext, + const char character, + const size_t lengthToWrite, + const COORD startingCoordinate, + size_t& cellsModified) noexcept override; - [[nodiscard]] - HRESULT FillConsoleOutputCharacterWImpl(IConsoleOutputObject& OutContext, - const wchar_t character, - const size_t lengthToWrite, - const COORD startingCoordinate, - size_t& cellsModified) noexcept override; + [[nodiscard]] HRESULT FillConsoleOutputCharacterWImpl(IConsoleOutputObject& OutContext, + const wchar_t character, + const size_t lengthToWrite, + const COORD startingCoordinate, + size_t& cellsModified) noexcept override; //// Process based. Restrict in protocol side? //HRESULT GenerateConsoleCtrlEventImpl(const ULONG ProcessGroupFilter, @@ -154,273 +139,222 @@ public: void FlushConsoleInputBuffer(InputBuffer& context) noexcept override; - [[nodiscard]] - HRESULT SetConsoleInputCodePageImpl(const ULONG codepage) noexcept override; + [[nodiscard]] HRESULT SetConsoleInputCodePageImpl(const ULONG codepage) noexcept override; - [[nodiscard]] - HRESULT SetConsoleOutputCodePageImpl(const ULONG codepage) noexcept override; + [[nodiscard]] HRESULT SetConsoleOutputCodePageImpl(const ULONG codepage) noexcept override; void GetConsoleCursorInfoImpl(const SCREEN_INFORMATION& context, ULONG& size, bool& isVisible) noexcept override; - [[nodiscard]] - HRESULT SetConsoleCursorInfoImpl(SCREEN_INFORMATION& context, - const ULONG size, - const bool isVisible) noexcept override; + [[nodiscard]] HRESULT SetConsoleCursorInfoImpl(SCREEN_INFORMATION& context, + const ULONG size, + const bool isVisible) noexcept override; //// driver will pare down for non-Ex method void GetConsoleScreenBufferInfoExImpl(const SCREEN_INFORMATION& context, CONSOLE_SCREEN_BUFFER_INFOEX& data) noexcept override; - [[nodiscard]] - HRESULT SetConsoleScreenBufferInfoExImpl(SCREEN_INFORMATION& context, - const CONSOLE_SCREEN_BUFFER_INFOEX& data) noexcept override; + [[nodiscard]] HRESULT SetConsoleScreenBufferInfoExImpl(SCREEN_INFORMATION& context, + const CONSOLE_SCREEN_BUFFER_INFOEX& data) noexcept override; - [[nodiscard]] - HRESULT SetConsoleScreenBufferSizeImpl(SCREEN_INFORMATION& context, - const COORD size) noexcept override; + [[nodiscard]] HRESULT SetConsoleScreenBufferSizeImpl(SCREEN_INFORMATION& context, + const COORD size) noexcept override; - [[nodiscard]] - HRESULT SetConsoleCursorPositionImpl(SCREEN_INFORMATION& context, - const COORD position) noexcept override; + [[nodiscard]] HRESULT SetConsoleCursorPositionImpl(SCREEN_INFORMATION& context, + const COORD position) noexcept override; void GetLargestConsoleWindowSizeImpl(const SCREEN_INFORMATION& context, COORD& size) noexcept override; - [[nodiscard]] - HRESULT ScrollConsoleScreenBufferAImpl(SCREEN_INFORMATION& context, - const SMALL_RECT& source, - const COORD target, - std::optional clip, - const char fillCharacter, - const WORD fillAttribute) noexcept override; + [[nodiscard]] HRESULT ScrollConsoleScreenBufferAImpl(SCREEN_INFORMATION& context, + const SMALL_RECT& source, + const COORD target, + std::optional clip, + const char fillCharacter, + const WORD fillAttribute) noexcept override; - [[nodiscard]] - HRESULT ScrollConsoleScreenBufferWImpl(SCREEN_INFORMATION& context, - const SMALL_RECT& source, - const COORD target, - std::optional clip, - const wchar_t fillCharacter, - const WORD fillAttribute) noexcept override; + [[nodiscard]] HRESULT ScrollConsoleScreenBufferWImpl(SCREEN_INFORMATION& context, + const SMALL_RECT& source, + const COORD target, + std::optional clip, + const wchar_t fillCharacter, + const WORD fillAttribute) noexcept override; - [[nodiscard]] - HRESULT SetConsoleTextAttributeImpl(SCREEN_INFORMATION& context, - const WORD attribute) noexcept override; + [[nodiscard]] HRESULT SetConsoleTextAttributeImpl(SCREEN_INFORMATION& context, + const WORD attribute) noexcept override; - [[nodiscard]] - HRESULT SetConsoleWindowInfoImpl(SCREEN_INFORMATION& context, - const bool isAbsolute, - const SMALL_RECT& windowRect) noexcept override; + [[nodiscard]] HRESULT SetConsoleWindowInfoImpl(SCREEN_INFORMATION& context, + const bool isAbsolute, + const SMALL_RECT& windowRect) noexcept override; - [[nodiscard]] - HRESULT ReadConsoleOutputAttributeImpl(const SCREEN_INFORMATION& context, - const COORD origin, - gsl::span buffer, - size_t& written) noexcept override; + [[nodiscard]] HRESULT ReadConsoleOutputAttributeImpl(const SCREEN_INFORMATION& context, + const COORD origin, + gsl::span buffer, + size_t& written) noexcept override; - [[nodiscard]] - HRESULT ReadConsoleOutputCharacterAImpl(const SCREEN_INFORMATION& context, - const COORD origin, - gsl::span buffer, - size_t& written) noexcept override; + [[nodiscard]] HRESULT ReadConsoleOutputCharacterAImpl(const SCREEN_INFORMATION& context, + const COORD origin, + gsl::span buffer, + size_t& written) noexcept override; - [[nodiscard]] - HRESULT ReadConsoleOutputCharacterWImpl(const SCREEN_INFORMATION& context, - const COORD origin, - gsl::span buffer, - size_t& written) noexcept override; + [[nodiscard]] HRESULT ReadConsoleOutputCharacterWImpl(const SCREEN_INFORMATION& context, + const COORD origin, + gsl::span buffer, + size_t& written) noexcept override; - [[nodiscard]] - HRESULT WriteConsoleInputAImpl(InputBuffer& context, - const std::basic_string_view buffer, - size_t& written, - const bool append) noexcept override; + [[nodiscard]] HRESULT WriteConsoleInputAImpl(InputBuffer& context, + const std::basic_string_view buffer, + size_t& written, + const bool append) noexcept override; - [[nodiscard]] - HRESULT WriteConsoleInputWImpl(InputBuffer& context, - const std::basic_string_view buffer, - size_t& written, - const bool append) noexcept override; + [[nodiscard]] HRESULT WriteConsoleInputWImpl(InputBuffer& context, + const std::basic_string_view buffer, + size_t& written, + const bool append) noexcept override; - [[nodiscard]] - HRESULT WriteConsoleOutputAImpl(SCREEN_INFORMATION& context, - gsl::span buffer, - const Microsoft::Console::Types::Viewport& requestRectangle, - Microsoft::Console::Types::Viewport& writtenRectangle) noexcept override; + [[nodiscard]] HRESULT WriteConsoleOutputAImpl(SCREEN_INFORMATION& context, + gsl::span buffer, + const Microsoft::Console::Types::Viewport& requestRectangle, + Microsoft::Console::Types::Viewport& writtenRectangle) noexcept override; - [[nodiscard]] - HRESULT WriteConsoleOutputWImpl(SCREEN_INFORMATION& context, - gsl::span buffer, - const Microsoft::Console::Types::Viewport& requestRectangle, - Microsoft::Console::Types::Viewport& writtenRectangle) noexcept override; + [[nodiscard]] HRESULT WriteConsoleOutputWImpl(SCREEN_INFORMATION& context, + gsl::span buffer, + const Microsoft::Console::Types::Viewport& requestRectangle, + Microsoft::Console::Types::Viewport& writtenRectangle) noexcept override; - [[nodiscard]] - HRESULT WriteConsoleOutputAttributeImpl(IConsoleOutputObject& OutContext, - const std::basic_string_view attrs, - const COORD target, - size_t& used) noexcept override; + [[nodiscard]] HRESULT WriteConsoleOutputAttributeImpl(IConsoleOutputObject& OutContext, + const std::basic_string_view attrs, + const COORD target, + size_t& used) noexcept override; - [[nodiscard]] - HRESULT WriteConsoleOutputCharacterAImpl(IConsoleOutputObject& OutContext, - const std::string_view text, - const COORD target, - size_t& used) noexcept override; + [[nodiscard]] HRESULT WriteConsoleOutputCharacterAImpl(IConsoleOutputObject& OutContext, + const std::string_view text, + const COORD target, + size_t& used) noexcept override; - [[nodiscard]] - HRESULT WriteConsoleOutputCharacterWImpl(IConsoleOutputObject& OutContext, - const std::wstring_view text, - const COORD target, - size_t& used) noexcept override; + [[nodiscard]] HRESULT WriteConsoleOutputCharacterWImpl(IConsoleOutputObject& OutContext, + const std::wstring_view text, + const COORD target, + size_t& used) noexcept override; - [[nodiscard]] - HRESULT ReadConsoleOutputAImpl(const SCREEN_INFORMATION& context, - gsl::span buffer, - const Microsoft::Console::Types::Viewport& sourceRectangle, - Microsoft::Console::Types::Viewport& readRectangle) noexcept override; + [[nodiscard]] HRESULT ReadConsoleOutputAImpl(const SCREEN_INFORMATION& context, + gsl::span buffer, + const Microsoft::Console::Types::Viewport& sourceRectangle, + Microsoft::Console::Types::Viewport& readRectangle) noexcept override; - [[nodiscard]] - HRESULT ReadConsoleOutputWImpl(const SCREEN_INFORMATION& context, - gsl::span buffer, - const Microsoft::Console::Types::Viewport& sourceRectangle, - Microsoft::Console::Types::Viewport& readRectangle) noexcept override; + [[nodiscard]] HRESULT ReadConsoleOutputWImpl(const SCREEN_INFORMATION& context, + gsl::span buffer, + const Microsoft::Console::Types::Viewport& sourceRectangle, + Microsoft::Console::Types::Viewport& readRectangle) noexcept override; - [[nodiscard]] - HRESULT GetConsoleTitleAImpl(gsl::span title, - size_t& written, - size_t& needed) noexcept override; + [[nodiscard]] HRESULT GetConsoleTitleAImpl(gsl::span title, + size_t& written, + size_t& needed) noexcept override; - [[nodiscard]] - HRESULT GetConsoleTitleWImpl(gsl::span title, - size_t& written, - size_t& needed) noexcept override; + [[nodiscard]] HRESULT GetConsoleTitleWImpl(gsl::span title, + size_t& written, + size_t& needed) noexcept override; - [[nodiscard]] - HRESULT GetConsoleOriginalTitleAImpl(gsl::span title, - size_t& written, - size_t& needed) noexcept override; + [[nodiscard]] HRESULT GetConsoleOriginalTitleAImpl(gsl::span title, + size_t& written, + size_t& needed) noexcept override; - [[nodiscard]] - HRESULT GetConsoleOriginalTitleWImpl(gsl::span title, - size_t& written, - size_t& needed) noexcept override; + [[nodiscard]] HRESULT GetConsoleOriginalTitleWImpl(gsl::span title, + size_t& written, + size_t& needed) noexcept override; - [[nodiscard]] - HRESULT SetConsoleTitleAImpl(const std::string_view title) noexcept override; + [[nodiscard]] HRESULT SetConsoleTitleAImpl(const std::string_view title) noexcept override; - [[nodiscard]] - HRESULT SetConsoleTitleWImpl(const std::wstring_view title) noexcept override; + [[nodiscard]] HRESULT SetConsoleTitleWImpl(const std::wstring_view title) noexcept override; #pragma endregion #pragma region L3 void GetNumberOfConsoleMouseButtonsImpl(ULONG& buttons) noexcept override; - [[nodiscard]] - HRESULT GetConsoleFontSizeImpl(const SCREEN_INFORMATION& context, - const DWORD index, - COORD& size) noexcept override; + [[nodiscard]] HRESULT GetConsoleFontSizeImpl(const SCREEN_INFORMATION& context, + const DWORD index, + COORD& size) noexcept override; //// driver will pare down for non-Ex method - [[nodiscard]] - HRESULT GetCurrentConsoleFontExImpl(const SCREEN_INFORMATION& context, - const bool isForMaximumWindowSize, - CONSOLE_FONT_INFOEX& consoleFontInfoEx) noexcept override; + [[nodiscard]] HRESULT GetCurrentConsoleFontExImpl(const SCREEN_INFORMATION& context, + const bool isForMaximumWindowSize, + CONSOLE_FONT_INFOEX& consoleFontInfoEx) noexcept override; - [[nodiscard]] - HRESULT SetConsoleDisplayModeImpl(SCREEN_INFORMATION& context, - const ULONG flags, - COORD& newSize) noexcept override; + [[nodiscard]] HRESULT SetConsoleDisplayModeImpl(SCREEN_INFORMATION& context, + const ULONG flags, + COORD& newSize) noexcept override; void GetConsoleDisplayModeImpl(ULONG& flags) noexcept override; - [[nodiscard]] - HRESULT AddConsoleAliasAImpl(const std::string_view source, - const std::string_view target, - const std::string_view exeName) noexcept override; + [[nodiscard]] HRESULT AddConsoleAliasAImpl(const std::string_view source, + const std::string_view target, + const std::string_view exeName) noexcept override; - [[nodiscard]] - HRESULT AddConsoleAliasWImpl(const std::wstring_view source, - const std::wstring_view target, - const std::wstring_view exeName) noexcept override; + [[nodiscard]] HRESULT AddConsoleAliasWImpl(const std::wstring_view source, + const std::wstring_view target, + const std::wstring_view exeName) noexcept override; - [[nodiscard]] - HRESULT GetConsoleAliasAImpl(const std::string_view source, - gsl::span target, - size_t& written, - const std::string_view exeName) noexcept override; + [[nodiscard]] HRESULT GetConsoleAliasAImpl(const std::string_view source, + gsl::span target, + size_t& written, + const std::string_view exeName) noexcept override; - [[nodiscard]] - HRESULT GetConsoleAliasWImpl(const std::wstring_view source, - gsl::span target, - size_t& written, - const std::wstring_view exeName) noexcept override; + [[nodiscard]] HRESULT GetConsoleAliasWImpl(const std::wstring_view source, + gsl::span target, + size_t& written, + const std::wstring_view exeName) noexcept override; - [[nodiscard]] - HRESULT GetConsoleAliasesLengthAImpl(const std::string_view exeName, - size_t& bufferRequired) noexcept override; + [[nodiscard]] HRESULT GetConsoleAliasesLengthAImpl(const std::string_view exeName, + size_t& bufferRequired) noexcept override; - [[nodiscard]] - HRESULT GetConsoleAliasesLengthWImpl(const std::wstring_view exeName, - size_t& bufferRequired) noexcept override; + [[nodiscard]] HRESULT GetConsoleAliasesLengthWImpl(const std::wstring_view exeName, + size_t& bufferRequired) noexcept override; - [[nodiscard]] - HRESULT GetConsoleAliasExesLengthAImpl(size_t& bufferRequired) noexcept override; + [[nodiscard]] HRESULT GetConsoleAliasExesLengthAImpl(size_t& bufferRequired) noexcept override; - [[nodiscard]] - HRESULT GetConsoleAliasExesLengthWImpl(size_t& bufferRequired) noexcept override; + [[nodiscard]] HRESULT GetConsoleAliasExesLengthWImpl(size_t& bufferRequired) noexcept override; - [[nodiscard]] - HRESULT GetConsoleAliasesAImpl(const std::string_view exeName, - gsl::span alias, - size_t& written) noexcept override; + [[nodiscard]] HRESULT GetConsoleAliasesAImpl(const std::string_view exeName, + gsl::span alias, + size_t& written) noexcept override; - [[nodiscard]] - HRESULT GetConsoleAliasesWImpl(const std::wstring_view exeName, - gsl::span alias, - size_t& written) noexcept override; + [[nodiscard]] HRESULT GetConsoleAliasesWImpl(const std::wstring_view exeName, + gsl::span alias, + size_t& written) noexcept override; - [[nodiscard]] - HRESULT GetConsoleAliasExesAImpl(gsl::span aliasExes, - size_t& written) noexcept override; + [[nodiscard]] HRESULT GetConsoleAliasExesAImpl(gsl::span aliasExes, + size_t& written) noexcept override; - [[nodiscard]] - HRESULT GetConsoleAliasExesWImpl(gsl::span aliasExes, - size_t& written) noexcept override; + [[nodiscard]] HRESULT GetConsoleAliasExesWImpl(gsl::span aliasExes, + size_t& written) noexcept override; #pragma region CMDext Private API - [[nodiscard]] - HRESULT ExpungeConsoleCommandHistoryAImpl(const std::string_view exeName) noexcept override; + [[nodiscard]] HRESULT ExpungeConsoleCommandHistoryAImpl(const std::string_view exeName) noexcept override; - [[nodiscard]] - HRESULT ExpungeConsoleCommandHistoryWImpl(const std::wstring_view exeName) noexcept override; + [[nodiscard]] HRESULT ExpungeConsoleCommandHistoryWImpl(const std::wstring_view exeName) noexcept override; - [[nodiscard]] - HRESULT SetConsoleNumberOfCommandsAImpl(const std::string_view exeName, - const size_t numberOfCommands) noexcept override; + [[nodiscard]] HRESULT SetConsoleNumberOfCommandsAImpl(const std::string_view exeName, + const size_t numberOfCommands) noexcept override; - [[nodiscard]] - HRESULT SetConsoleNumberOfCommandsWImpl(const std::wstring_view exeName, - const size_t numberOfCommands) noexcept override; + [[nodiscard]] HRESULT SetConsoleNumberOfCommandsWImpl(const std::wstring_view exeName, + const size_t numberOfCommands) noexcept override; - [[nodiscard]] - HRESULT GetConsoleCommandHistoryLengthAImpl(const std::string_view exeName, - size_t& length) noexcept override; + [[nodiscard]] HRESULT GetConsoleCommandHistoryLengthAImpl(const std::string_view exeName, + size_t& length) noexcept override; - [[nodiscard]] - HRESULT GetConsoleCommandHistoryLengthWImpl(const std::wstring_view exeName, - size_t& length) noexcept override; + [[nodiscard]] HRESULT GetConsoleCommandHistoryLengthWImpl(const std::wstring_view exeName, + size_t& length) noexcept override; - [[nodiscard]] - HRESULT GetConsoleCommandHistoryAImpl(const std::string_view exeName, - gsl::span commandHistory, - size_t& written) noexcept override; + [[nodiscard]] HRESULT GetConsoleCommandHistoryAImpl(const std::string_view exeName, + gsl::span commandHistory, + size_t& written) noexcept override; - [[nodiscard]] - HRESULT GetConsoleCommandHistoryWImpl(const std::wstring_view exeName, - gsl::span commandHistory, - size_t& written) noexcept override; + [[nodiscard]] HRESULT GetConsoleCommandHistoryWImpl(const std::wstring_view exeName, + gsl::span commandHistory, + size_t& written) noexcept override; #pragma endregion @@ -430,13 +364,11 @@ public: void GetConsoleHistoryInfoImpl(CONSOLE_HISTORY_INFO& consoleHistoryInfo) noexcept override; - [[nodiscard]] - HRESULT SetConsoleHistoryInfoImpl(const CONSOLE_HISTORY_INFO& consoleHistoryInfo) noexcept override; + [[nodiscard]] HRESULT SetConsoleHistoryInfoImpl(const CONSOLE_HISTORY_INFO& consoleHistoryInfo) noexcept override; - [[nodiscard]] - HRESULT SetCurrentConsoleFontExImpl(IConsoleOutputObject& context, - const bool isForMaximumWindowSize, - const CONSOLE_FONT_INFOEX& consoleFontInfoEx) noexcept override; + [[nodiscard]] HRESULT SetCurrentConsoleFontExImpl(IConsoleOutputObject& context, + const bool isForMaximumWindowSize, + const CONSOLE_FONT_INFOEX& consoleFontInfoEx) noexcept override; #pragma endregion }; diff --git a/src/host/CommandListPopup.cpp b/src/host/CommandListPopup.cpp index 3cc3ebc13..4143b1954 100644 --- a/src/host/CommandListPopup.cpp +++ b/src/host/CommandListPopup.cpp @@ -14,7 +14,7 @@ #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: // - 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(); } -[[nodiscard]] -NTSTATUS CommandListPopup::_handlePopupKeys(COOKED_READ_DATA& cookedReadData, const wchar_t wch, const DWORD modifiers) noexcept +[[nodiscard]] NTSTATUS CommandListPopup::_handlePopupKeys(COOKED_READ_DATA& cookedReadData, + const wchar_t wch, + const DWORD modifiers) noexcept { try { @@ -146,8 +147,7 @@ void CommandListPopup::_setBottomIndex() } } -[[nodiscard]] -NTSTATUS CommandListPopup::_deleteSelection(COOKED_READ_DATA& cookedReadData) noexcept +[[nodiscard]] NTSTATUS CommandListPopup::_deleteSelection(COOKED_READ_DATA& cookedReadData) noexcept { try { @@ -176,8 +176,7 @@ NTSTATUS CommandListPopup::_deleteSelection(COOKED_READ_DATA& cookedReadData) no // - moves the selected history item up in the history list // Arguments: // - cookedReadData - the read wait object to operate upon -[[nodiscard]] -NTSTATUS CommandListPopup::_swapUp(COOKED_READ_DATA& cookedReadData) noexcept +[[nodiscard]] NTSTATUS CommandListPopup::_swapUp(COOKED_READ_DATA& cookedReadData) noexcept { try { @@ -199,8 +198,7 @@ NTSTATUS CommandListPopup::_swapUp(COOKED_READ_DATA& cookedReadData) noexcept // - moves the selected history item down in the history list // Arguments: // - cookedReadData - the read wait object to operate upon -[[nodiscard]] -NTSTATUS CommandListPopup::_swapDown(COOKED_READ_DATA& cookedReadData) noexcept +[[nodiscard]] NTSTATUS CommandListPopup::_swapDown(COOKED_READ_DATA& cookedReadData) noexcept { try { @@ -285,8 +283,7 @@ void CommandListPopup::_cycleSelectionToMatchingCommands(COOKED_READ_DATA& cooke // Return Value: // - CONSOLE_STATUS_WAIT - we ran out of input, so a wait block was created // - CONSOLE_STATUS_READ_COMPLETE - user hit return -[[nodiscard]] -NTSTATUS CommandListPopup::Process(COOKED_READ_DATA& cookedReadData) noexcept +[[nodiscard]] NTSTATUS CommandListPopup::Process(COOKED_READ_DATA& cookedReadData) noexcept { NTSTATUS Status = STATUS_SUCCESS; diff --git a/src/host/CommandListPopup.hpp b/src/host/CommandListPopup.hpp index 07bd60e16..a893b9055 100644 --- a/src/host/CommandListPopup.hpp +++ b/src/host/CommandListPopup.hpp @@ -17,14 +17,12 @@ Author: #include "popup.h" - class CommandListPopup : public Popup { public: CommandListPopup(SCREEN_INFORMATION& screenInfo, const CommandHistory& history); - [[nodiscard]] - NTSTATUS Process(COOKED_READ_DATA& cookedReadData) noexcept override; + [[nodiscard]] NTSTATUS Process(COOKED_READ_DATA& cookedReadData) noexcept override; protected: void _DrawContent() override; @@ -37,17 +35,13 @@ private: void _handleReturn(COOKED_READ_DATA& cookedReadData); void _cycleSelectionToMatchingCommands(COOKED_READ_DATA& cookedReadData, const wchar_t wch); void _setBottomIndex(); - [[nodiscard]] - NTSTATUS _handlePopupKeys(COOKED_READ_DATA& cookedReadData, const wchar_t wch, const DWORD modifiers) noexcept; - [[nodiscard]] - NTSTATUS _deleteSelection(COOKED_READ_DATA& cookedReadData) noexcept; - [[nodiscard]] - NTSTATUS _swapUp(COOKED_READ_DATA& cookedReadData) noexcept; - [[nodiscard]] - NTSTATUS _swapDown(COOKED_READ_DATA& cookedReadData) noexcept; + [[nodiscard]] NTSTATUS _handlePopupKeys(COOKED_READ_DATA& cookedReadData, const wchar_t wch, const DWORD modifiers) noexcept; + [[nodiscard]] NTSTATUS _deleteSelection(COOKED_READ_DATA& cookedReadData) noexcept; + [[nodiscard]] NTSTATUS _swapUp(COOKED_READ_DATA& cookedReadData) noexcept; + [[nodiscard]] NTSTATUS _swapDown(COOKED_READ_DATA& cookedReadData) noexcept; 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; #ifdef UNIT_TESTING diff --git a/src/host/CommandNumberPopup.cpp b/src/host/CommandNumberPopup.cpp index 94c431943..fbbfff05c 100644 --- a/src/host/CommandNumberPopup.cpp +++ b/src/host/CommandNumberPopup.cpp @@ -102,7 +102,7 @@ void CommandNumberPopup::_handleEscape(COOKED_READ_DATA& cookedReadData) noexcep void CommandNumberPopup::_handleReturn(COOKED_READ_DATA& cookedReadData) noexcept { const short commandNumber = gsl::narrow(std::min(static_cast(_parse()), - cookedReadData.History().GetNumberOfCommands() - 1)); + cookedReadData.History().GetNumberOfCommands() - 1)); CommandLine::Instance().EndAllPopups(); SetCurrentCommandLine(cookedReadData, commandNumber); @@ -113,15 +113,14 @@ void CommandNumberPopup::_handleReturn(COOKED_READ_DATA& cookedReadData) noexcep // Return Value: // - CONSOLE_STATUS_WAIT - we ran out of input, so a wait block was created // - CONSOLE_STATUS_READ_COMPLETE - user hit return -[[nodiscard]] -NTSTATUS CommandNumberPopup::Process(COOKED_READ_DATA& cookedReadData) noexcept +[[nodiscard]] NTSTATUS CommandNumberPopup::Process(COOKED_READ_DATA& cookedReadData) noexcept { NTSTATUS Status = STATUS_SUCCESS; WCHAR wch = UNICODE_NULL; bool popupKeys = false; DWORD modifiers = 0; - for(;;) + for (;;) { Status = _getUserInput(cookedReadData, popupKeys, modifiers, wch); if (!NT_SUCCESS(Status)) diff --git a/src/host/CommandNumberPopup.hpp b/src/host/CommandNumberPopup.hpp index d92013e7e..92f80c883 100644 --- a/src/host/CommandNumberPopup.hpp +++ b/src/host/CommandNumberPopup.hpp @@ -17,14 +17,12 @@ Author: #include "popup.h" - class CommandNumberPopup final : public Popup { public: CommandNumberPopup(SCREEN_INFORMATION& screenInfo); - [[nodiscard]] - NTSTATUS Process(COOKED_READ_DATA& cookedReadData) noexcept override; + [[nodiscard]] NTSTATUS Process(COOKED_READ_DATA& cookedReadData) noexcept override; protected: void _DrawContent() override; diff --git a/src/host/ConsoleArguments.cpp b/src/host/ConsoleArguments.cpp index 1d06001da..2e3d0c21f 100644 --- a/src/host/ConsoleArguments.cpp +++ b/src/host/ConsoleArguments.cpp @@ -23,13 +23,13 @@ const std::wstring_view ConsoleArguments::FEATURE_PTY_ARG = L"pty"; ConsoleArguments::ConsoleArguments(const std::wstring& commandline, const HANDLE hStdIn, - const HANDLE hStdOut) - : _commandline(commandline), - _vtInHandle(hStdIn), - _vtOutHandle(hStdOut), - _recievedEarlySizeChange{ false }, - _originalWidth{ -1 }, - _originalHeight{ -1 } + const HANDLE hStdOut) : + _commandline(commandline), + _vtInHandle(hStdIn), + _vtOutHandle(hStdOut), + _recievedEarlySizeChange{ false }, + _originalWidth{ -1 }, + _originalHeight{ -1 } { _clientCommandline = L""; _vtMode = L""; @@ -46,10 +46,9 @@ ConsoleArguments::ConsoleArguments(const std::wstring& commandline, ConsoleArguments::ConsoleArguments() : ConsoleArguments(L"", nullptr, nullptr) { - } -ConsoleArguments& ConsoleArguments::operator=(const ConsoleArguments & other) +ConsoleArguments& ConsoleArguments::operator=(const ConsoleArguments& other) { if (this != &other) { @@ -106,8 +105,9 @@ void ConsoleArguments::s_ConsumeArg(_Inout_ std::vector& args, _In // Return Value: // S_OK if we parsed the string successfully, otherwise E_INVALIDARG indicating // failure. -[[nodiscard]] -HRESULT ConsoleArguments::s_GetArgumentValue(_Inout_ std::vector& args, _Inout_ size_t& index, _Out_opt_ std::wstring* const pSetting) +[[nodiscard]] HRESULT ConsoleArguments::s_GetArgumentValue(_Inout_ std::vector& args, + _Inout_ size_t& index, + _Out_opt_ std::wstring* const pSetting) { bool hasNext = (index + 1) < args.size(); if (hasNext) @@ -136,8 +136,7 @@ HRESULT ConsoleArguments::s_GetArgumentValue(_Inout_ std::vector& // Return Value: // S_OK if we parsed the string successfully, otherwise E_INVALIDARG indicating // failure. -[[nodiscard]] -HRESULT ConsoleArguments::s_HandleFeatureValue(_Inout_ std::vector& args, _Inout_ size_t& index) +[[nodiscard]] HRESULT ConsoleArguments::s_HandleFeatureValue(_Inout_ std::vector& args, _Inout_ size_t& index) { HRESULT hr = E_INVALIDARG; bool hasNext = (index + 1) < args.size(); @@ -167,10 +166,9 @@ HRESULT ConsoleArguments::s_HandleFeatureValue(_Inout_ std::vector // Return Value: // 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. -[[nodiscard]] -HRESULT ConsoleArguments::s_GetArgumentValue(_Inout_ std::vector& args, - _Inout_ size_t& index, - _Out_opt_ short* const pSetting) +[[nodiscard]] HRESULT ConsoleArguments::s_GetArgumentValue(_Inout_ std::vector& args, + _Inout_ size_t& index, + _Out_opt_ short* const pSetting) { bool succeeded = (index + 1) < args.size(); if (succeeded) @@ -199,7 +197,6 @@ HRESULT ConsoleArguments::s_GetArgumentValue(_Inout_ std::vector& { succeeded = false; } - } s_ConsumeArg(args, index); } @@ -215,8 +212,7 @@ HRESULT ConsoleArguments::s_GetArgumentValue(_Inout_ std::vector& // - 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 // if the handle value was already filled. -[[nodiscard]] -HRESULT ConsoleArguments::s_ParseHandleArg(const std::wstring& handleAsText, _Inout_ DWORD& handleAsVal) +[[nodiscard]] HRESULT ConsoleArguments::s_ParseHandleArg(const std::wstring& handleAsText, _Inout_ DWORD& handleAsVal) { HRESULT hr = S_OK; @@ -259,10 +255,9 @@ HRESULT ConsoleArguments::s_ParseHandleArg(const std::wstring& handleAsText, _In // Return Value: // S_OK if we parsed the string successfully, otherwise E_INVALIDARG indicating // failure. -[[nodiscard]] -HRESULT ConsoleArguments::_GetClientCommandline(_Inout_ std::vector& args, const size_t index, const bool skipFirst) +[[nodiscard]] HRESULT ConsoleArguments::_GetClientCommandline(_Inout_ std::vector& args, const size_t index, const bool skipFirst) { - auto start = args.begin()+index; + auto start = args.begin() + index; // Erase the first token. // Used to get rid of the explicit commandline token "--" @@ -278,12 +273,12 @@ HRESULT ConsoleArguments::_GetClientCommandline(_Inout_ std::vector& args, - const size_t index, - const bool skipFirst); + [[nodiscard]] HRESULT _GetClientCommandline(_Inout_ std::vector& args, + const size_t index, + const bool skipFirst); static void s_ConsumeArg(_Inout_ std::vector& args, _In_ size_t& index); - [[nodiscard]] - static HRESULT s_GetArgumentValue(_Inout_ std::vector& args, - _Inout_ size_t& index, - _Out_opt_ std::wstring* const pSetting); - [[nodiscard]] - static HRESULT s_GetArgumentValue(_Inout_ std::vector& args, - _Inout_ size_t& index, - _Out_opt_ short* const pSetting); - [[nodiscard]] - static HRESULT s_HandleFeatureValue(_Inout_ std::vector& args, - _Inout_ size_t& index); - - [[nodiscard]] - static HRESULT s_ParseHandleArg(const std::wstring& handleAsText, - _Inout_ DWORD& handleAsVal); + [[nodiscard]] static HRESULT s_GetArgumentValue(_Inout_ std::vector& args, + _Inout_ size_t& index, + _Out_opt_ std::wstring* const pSetting); + [[nodiscard]] static HRESULT s_GetArgumentValue(_Inout_ std::vector& args, + _Inout_ size_t& index, + _Out_opt_ short* const pSetting); + [[nodiscard]] static HRESULT s_HandleFeatureValue(_Inout_ std::vector& args, + _Inout_ size_t& index); + [[nodiscard]] static HRESULT s_ParseHandleArg(const std::wstring& handleAsText, + _Inout_ DWORD& handleAsVal); #ifdef UNIT_TESTING friend class ConsoleArgumentsTests; @@ -160,10 +152,12 @@ private: }; #ifdef UNIT_TESTING -namespace WEX { - namespace TestExecution { +namespace WEX +{ + namespace TestExecution + { template<> - class VerifyOutputTraits < ConsoleArguments > + class VerifyOutputTraits { public: static WEX::Common::NoThrowString ToString(const ConsoleArguments& ci) @@ -205,26 +199,25 @@ namespace WEX { }; template<> - class VerifyCompareTraits < ConsoleArguments, ConsoleArguments> + class VerifyCompareTraits { public: static bool AreEqual(const ConsoleArguments& expected, const ConsoleArguments& actual) { - return - expected.GetClientCommandline() == actual.GetClientCommandline() && - expected.HasVtHandles() == actual.HasVtHandles() && - expected.GetVtInHandle() == actual.GetVtInHandle() && - expected.GetVtOutHandle() == actual.GetVtOutHandle() && - expected.GetVtMode() == actual.GetVtMode() && - expected.GetWidth() == actual.GetWidth() && - expected.GetHeight() == actual.GetHeight() && - expected.GetForceV1() == actual.GetForceV1() && - expected.IsHeadless() == actual.IsHeadless() && - expected.ShouldCreateServerHandle() == actual.ShouldCreateServerHandle() && - expected.GetServerHandle() == actual.GetServerHandle() && - expected.HasSignalHandle() == actual.HasSignalHandle() && - expected.GetSignalHandle() == actual.GetSignalHandle() && - expected.GetInheritCursor() == actual.GetInheritCursor(); + return expected.GetClientCommandline() == actual.GetClientCommandline() && + expected.HasVtHandles() == actual.HasVtHandles() && + expected.GetVtInHandle() == actual.GetVtInHandle() && + expected.GetVtOutHandle() == actual.GetVtOutHandle() && + expected.GetVtMode() == actual.GetVtMode() && + expected.GetWidth() == actual.GetWidth() && + expected.GetHeight() == actual.GetHeight() && + expected.GetForceV1() == actual.GetForceV1() && + expected.IsHeadless() == actual.IsHeadless() && + expected.ShouldCreateServerHandle() == actual.ShouldCreateServerHandle() && + expected.GetServerHandle() == actual.GetServerHandle() && + expected.HasSignalHandle() == actual.HasSignalHandle() && + expected.GetSignalHandle() == actual.GetSignalHandle() && + expected.GetInheritCursor() == actual.GetInheritCursor(); } static bool AreSame(const ConsoleArguments& expected, const ConsoleArguments& actual) @@ -238,19 +231,18 @@ namespace WEX { static bool IsNull(const ConsoleArguments& object) { - return - object.GetClientCommandline().empty() && - (object.GetVtInHandle() == 0 || object.GetVtInHandle() == INVALID_HANDLE_VALUE) && - (object.GetVtOutHandle() == 0 || object.GetVtOutHandle() == INVALID_HANDLE_VALUE) && - object.GetVtMode().empty() && - !object.GetForceV1() && - (object.GetWidth() == 0) && - (object.GetHeight() == 0) && - !object.IsHeadless() && - !object.ShouldCreateServerHandle() && - object.GetServerHandle() == 0 && - (object.GetSignalHandle() == 0 || object.GetSignalHandle() == INVALID_HANDLE_VALUE) && - !object.GetInheritCursor(); + return object.GetClientCommandline().empty() && + (object.GetVtInHandle() == 0 || object.GetVtInHandle() == INVALID_HANDLE_VALUE) && + (object.GetVtOutHandle() == 0 || object.GetVtOutHandle() == INVALID_HANDLE_VALUE) && + object.GetVtMode().empty() && + !object.GetForceV1() && + (object.GetWidth() == 0) && + (object.GetHeight() == 0) && + !object.IsHeadless() && + !object.ShouldCreateServerHandle() && + object.GetServerHandle() == 0 && + (object.GetSignalHandle() == 0 || object.GetSignalHandle() == INVALID_HANDLE_VALUE) && + !object.GetInheritCursor(); } }; } diff --git a/src/host/CopyFromCharPopup.cpp b/src/host/CopyFromCharPopup.cpp index d267238a3..0e30dbc6a 100644 --- a/src/host/CopyFromCharPopup.cpp +++ b/src/host/CopyFromCharPopup.cpp @@ -19,8 +19,7 @@ CopyFromCharPopup::CopyFromCharPopup(SCREEN_INFORMATION& screenInfo) : // Return Value: // - CONSOLE_STATUS_WAIT - we ran out of input, so a wait block was created // - CONSOLE_STATUS_READ_COMPLETE - user hit return -[[nodiscard]] -NTSTATUS CopyFromCharPopup::Process(COOKED_READ_DATA& cookedReadData) noexcept +[[nodiscard]] NTSTATUS CopyFromCharPopup::Process(COOKED_READ_DATA& cookedReadData) noexcept { // get user input WCHAR Char = UNICODE_NULL; diff --git a/src/host/CopyFromCharPopup.hpp b/src/host/CopyFromCharPopup.hpp index 9de8f9838..5d6804b6c 100644 --- a/src/host/CopyFromCharPopup.hpp +++ b/src/host/CopyFromCharPopup.hpp @@ -22,8 +22,7 @@ class CopyFromCharPopup final : public Popup public: CopyFromCharPopup(SCREEN_INFORMATION& screenInfo); - [[nodiscard]] - NTSTATUS Process(COOKED_READ_DATA& cookedReadData) noexcept override; + [[nodiscard]] NTSTATUS Process(COOKED_READ_DATA& cookedReadData) noexcept override; protected: void _DrawContent() override; diff --git a/src/host/CopyToCharPopup.cpp b/src/host/CopyToCharPopup.cpp index 6b6baeb5f..b18f0ad67 100644 --- a/src/host/CopyToCharPopup.cpp +++ b/src/host/CopyToCharPopup.cpp @@ -50,8 +50,7 @@ void CopyToCharPopup::_copyToChar(COOKED_READ_DATA& cookedReadData, const std::w // Return Value: // - CONSOLE_STATUS_WAIT - we ran out of input, so a wait block was created // - CONSOLE_STATUS_READ_COMPLETE - user hit return -[[nodiscard]] -NTSTATUS CopyToCharPopup::Process(COOKED_READ_DATA& cookedReadData) noexcept +[[nodiscard]] NTSTATUS CopyToCharPopup::Process(COOKED_READ_DATA& cookedReadData) noexcept { wchar_t wch = UNICODE_NULL; bool popupKey = false; diff --git a/src/host/CopyToCharPopup.hpp b/src/host/CopyToCharPopup.hpp index a961bc119..a1c490d3b 100644 --- a/src/host/CopyToCharPopup.hpp +++ b/src/host/CopyToCharPopup.hpp @@ -22,8 +22,8 @@ class CopyToCharPopup final : public Popup public: CopyToCharPopup(SCREEN_INFORMATION& screenInfo); - [[nodiscard]] - NTSTATUS Process(COOKED_READ_DATA& cookedReadData) noexcept override; + [[nodiscard]] NTSTATUS Process(COOKED_READ_DATA& cookedReadData) noexcept override; + protected: void _DrawContent() override; diff --git a/src/host/CursorBlinker.cpp b/src/host/CursorBlinker.cpp index 810413dda..d32622ab8 100644 --- a/src/host/CursorBlinker.cpp +++ b/src/host/CursorBlinker.cpp @@ -115,8 +115,8 @@ void CursorBlinker::TimerRoutine(SCREEN_INFORMATION& ScreenInfo) // Don't blink the cursor for remote sessions. if ((!ServiceLocator::LocateSystemConfigurationProvider()->IsCaretBlinkingEnabled() || _uCaretBlinkTime == -1 || - (!cursor.IsBlinkingAllowed())) && - cursor.IsOn()) + (!cursor.IsBlinkingAllowed())) && + cursor.IsOn()) { goto DoScroll; } diff --git a/src/host/PtySignalInputThread.cpp b/src/host/PtySignalInputThread.cpp index 311b5ed03..c2218d0a7 100644 --- a/src/host/PtySignalInputThread.cpp +++ b/src/host/PtySignalInputThread.cpp @@ -77,8 +77,7 @@ void PtySignalInputThread::ConnectConsole() noexcept // Return Value: // - S_OK if the thread runs to completion. // - Otherwise it may cause an application termination another route and never return. -[[nodiscard]] -HRESULT PtySignalInputThread::_InputThread() +[[nodiscard]] HRESULT PtySignalInputThread::_InputThread() { unsigned short signalId; while (_GetData(&signalId, sizeof(signalId))) @@ -102,7 +101,7 @@ HRESULT PtySignalInputThread::_InputThread() SUCCEEDED(UShortToShort(resizeMsg.sy, &sRows)) && (sColumns > 0 && sRows > 0)) { - ServiceLocator::LocateGlobals().launchArgs.SetExpectedSize({sColumns, sRows}); + ServiceLocator::LocateGlobals().launchArgs.SetExpectedSize({ sColumns, sRows }); } break; } @@ -165,8 +164,7 @@ bool PtySignalInputThread::_GetData(_Out_writes_bytes_(cbBuffer) void* const pBu // Method Description: // - Starts the PTY Signal input thread. -[[nodiscard]] -HRESULT PtySignalInputThread::Start() noexcept +[[nodiscard]] HRESULT PtySignalInputThread::Start() noexcept { RETURN_LAST_ERROR_IF(!_hFile); diff --git a/src/host/PtySignalInputThread.hpp b/src/host/PtySignalInputThread.hpp index cc2c2ceed..ea9419a32 100644 --- a/src/host/PtySignalInputThread.hpp +++ b/src/host/PtySignalInputThread.hpp @@ -23,8 +23,7 @@ namespace Microsoft::Console PtySignalInputThread(_In_ wil::unique_hfile hPipe); ~PtySignalInputThread(); - [[nodiscard]] - HRESULT Start() noexcept; + [[nodiscard]] HRESULT Start() noexcept; static DWORD WINAPI StaticThreadProc(_In_ LPVOID lpParameter); // Prevent copying and assignment. @@ -34,8 +33,7 @@ namespace Microsoft::Console void ConnectConsole() noexcept; private: - [[nodiscard]] - HRESULT _InputThread(); + [[nodiscard]] HRESULT _InputThread(); bool _GetData(_Out_writes_bytes_(cbBuffer) void* const pBuffer, const DWORD cbBuffer); void _Shutdown(); diff --git a/src/host/ScreenBufferRenderTarget.cpp b/src/host/ScreenBufferRenderTarget.cpp index 7f07837d1..72631a8ee 100644 --- a/src/host/ScreenBufferRenderTarget.cpp +++ b/src/host/ScreenBufferRenderTarget.cpp @@ -13,7 +13,6 @@ ScreenBufferRenderTarget::ScreenBufferRenderTarget(SCREEN_INFORMATION& owner) : void ScreenBufferRenderTarget::TriggerRedraw(const Microsoft::Console::Types::Viewport& region) { - auto* pRenderer = ServiceLocator::LocateGlobals().pRender; const auto* pActive = &ServiceLocator::LocateGlobals().getConsoleInformation().GetActiveOutputBuffer().GetActiveBuffer(); if (pRenderer != nullptr && pActive == &_owner) diff --git a/src/host/ScreenBufferRenderTarget.hpp b/src/host/ScreenBufferRenderTarget.hpp index 434df4c37..d90f80c0f 100644 --- a/src/host/ScreenBufferRenderTarget.hpp +++ b/src/host/ScreenBufferRenderTarget.hpp @@ -42,5 +42,4 @@ public: private: SCREEN_INFORMATION& _owner; - }; diff --git a/src/host/VtInputThread.cpp b/src/host/VtInputThread.cpp index be383216e..e7e968204 100644 --- a/src/host/VtInputThread.cpp +++ b/src/host/VtInputThread.cpp @@ -56,8 +56,7 @@ VtInputThread::VtInputThread(_In_ wil::unique_hfile hPipe, // - cch - number of UTF-8 characters in charBuffer // Return Value: // - S_OK on success, otherwise an appropriate failure. -[[nodiscard]] -HRESULT VtInputThread::_HandleRunInput(_In_reads_(cch) const byte* const charBuffer, const int cch) +[[nodiscard]] HRESULT VtInputThread::_HandleRunInput(_In_reads_(cch) const byte* const charBuffer, const int cch) { // Make sure to call the GLOBAL Lock/Unlock, not the gci's lock/unlock. // Only the global unlock attempts to dispatch ctrl events. If you use the @@ -157,11 +156,10 @@ DWORD VtInputThread::_InputThread() // Method Description: // - Starts the VT input thread. -[[nodiscard]] -HRESULT VtInputThread::Start() +[[nodiscard]] HRESULT VtInputThread::Start() { RETURN_HR_IF(E_HANDLE, !_hFile); - + HANDLE hThread = nullptr; // 0 is the right value, https://blogs.msdn.microsoft.com/oldnewthing/20040223-00/?p=40503 DWORD dwThreadId = 0; diff --git a/src/host/VtInputThread.hpp b/src/host/VtInputThread.hpp index 8da1322e0..9f596d709 100644 --- a/src/host/VtInputThread.hpp +++ b/src/host/VtInputThread.hpp @@ -24,14 +24,12 @@ namespace Microsoft::Console public: VtInputThread(_In_ wil::unique_hfile hPipe, const bool inheritCursor); - [[nodiscard]] - HRESULT Start(); + [[nodiscard]] HRESULT Start(); static DWORD WINAPI StaticVtInputThreadProc(_In_ LPVOID lpParameter); void DoReadInput(const bool throwOnFail); private: - [[nodiscard]] - HRESULT _HandleRunInput(_In_reads_(cch) const byte* const charBuffer, const int cch); + [[nodiscard]] HRESULT _HandleRunInput(_In_reads_(cch) const byte* const charBuffer, const int cch); DWORD _InputThread(); wil::unique_hfile _hFile; diff --git a/src/host/VtIo.cpp b/src/host/VtIo.cpp index d3df222d6..3ea8d7fb3 100644 --- a/src/host/VtIo.cpp +++ b/src/host/VtIo.cpp @@ -39,8 +39,7 @@ VtIo::VtIo() : // IO mode string // Return Value: // S_OK if we parsed the string successfully, otherwise E_INVALIDARG indicating failure. -[[nodiscard]] -HRESULT VtIo::ParseIoMode(const std::wstring& VtMode, _Out_ VtIoMode& ioMode) +[[nodiscard]] HRESULT VtIo::ParseIoMode(const std::wstring& VtMode, _Out_ VtIoMode& ioMode) { ioMode = VtIoMode::INVALID; @@ -71,8 +70,7 @@ HRESULT VtIo::ParseIoMode(const std::wstring& VtMode, _Out_ VtIoMode& ioMode) return S_OK; } -[[nodiscard]] -HRESULT VtIo::Initialize(const ConsoleArguments * const pArgs) +[[nodiscard]] HRESULT VtIo::Initialize(const ConsoleArguments* const pArgs) { _lookingForCursorPosition = pArgs->GetInheritCursor(); @@ -106,8 +104,10 @@ HRESULT VtIo::Initialize(const ConsoleArguments * const pArgs) // Return Value: // S_OK if we initialized successfully, otherwise an appropriate HRESULT // indicating failure. -[[nodiscard]] -HRESULT VtIo::_Initialize(const HANDLE InHandle, const HANDLE OutHandle, const std::wstring& VtMode, _In_opt_ const HANDLE SignalHandle) +[[nodiscard]] HRESULT VtIo::_Initialize(const HANDLE InHandle, + const HANDLE OutHandle, + const std::wstring& VtMode, + _In_opt_ const HANDLE SignalHandle) { FAIL_FAST_IF_MSG(_initialized, "Someone attempted to double-_Initialize VtIo"); @@ -133,8 +133,7 @@ HRESULT VtIo::_Initialize(const HANDLE InHandle, const HANDLE OutHandle, const s // S_OK if we initialized successfully, // S_FALSE if VtIo hasn't been initialized (or we're not in conpty mode) // otherwise an appropriate HRESULT indicating failure. -[[nodiscard]] -HRESULT VtIo::CreateIoHandlers() noexcept +[[nodiscard]] HRESULT VtIo::CreateIoHandlers() noexcept { if (!_initialized) { @@ -152,7 +151,7 @@ HRESULT VtIo::CreateIoHandlers() noexcept if (IsValidHandle(_hOutput.get())) { - Viewport initialViewport = Viewport::FromDimensions({0, 0}, + Viewport initialViewport = Viewport::FromDimensions({ 0, 0 }, gci.GetWindowSize().X, gci.GetWindowSize().Y); switch (_IoMode) @@ -217,8 +216,7 @@ bool VtIo::IsUsingVt() const // Return Value: // S_OK if we started successfully or had nothing to start, otherwise an // appropriate HRESULT indicating failure. -[[nodiscard]] -HRESULT VtIo::StartIfNeeded() +[[nodiscard]] HRESULT VtIo::StartIfNeeded() { // If we haven't been set up, do nothing (because there's nothing to start) if (!_objectsCreated) @@ -250,7 +248,7 @@ HRESULT VtIo::StartIfNeeded() if (_lookingForCursorPosition && _pVtRenderEngine && _pVtInputThread) { LOG_IF_FAILED(_pVtRenderEngine->RequestCursor()); - while(_lookingForCursorPosition) + while (_lookingForCursorPosition) { _pVtInputThread->DoReadInput(false); } @@ -283,8 +281,7 @@ HRESULT VtIo::StartIfNeeded() // - S_FALSE if we're not in VtIo mode, // S_OK if we succeeded, // otherwise an appropriate HRESULT indicating failure. -[[nodiscard]] -HRESULT VtIo::CreateAndStartSignalThread() noexcept +[[nodiscard]] HRESULT VtIo::CreateAndStartSignalThread() noexcept { if (!_initialized) { @@ -315,8 +312,7 @@ HRESULT VtIo::CreateAndStartSignalThread() noexcept // Return Value: // - S_OK if the renderer successfully suppressed the next repaint, otherwise an // appropriate HRESULT indicating failure. -[[nodiscard]] -HRESULT VtIo::SuppressResizeRepaint() +[[nodiscard]] HRESULT VtIo::SuppressResizeRepaint() { HRESULT hr = S_OK; if (_pVtRenderEngine) @@ -334,8 +330,7 @@ HRESULT VtIo::SuppressResizeRepaint() // Return Value: // - S_OK if we successfully inherited the cursor or did nothing, else an // appropriate HRESULT -[[nodiscard]] -HRESULT VtIo::SetCursorPosition(const COORD coordCursor) +[[nodiscard]] HRESULT VtIo::SetCursorPosition(const COORD coordCursor) { HRESULT hr = S_OK; if (_lookingForCursorPosition) @@ -377,7 +372,6 @@ void VtIo::CloseOutput() _ShutdownIfNeeded(); } - void VtIo::_ShutdownIfNeeded() { // The callers should have both accquired the _shutdownLock at this point - diff --git a/src/host/VtIo.hpp b/src/host/VtIo.hpp index bfd1a88e4..dc037b937 100644 --- a/src/host/VtIo.hpp +++ b/src/host/VtIo.hpp @@ -19,27 +19,19 @@ namespace Microsoft::Console::VirtualTerminal VtIo(); virtual ~VtIo() override = default; - [[nodiscard]] - HRESULT Initialize(const ConsoleArguments* const pArgs); + [[nodiscard]] HRESULT Initialize(const ConsoleArguments* const pArgs); - - [[nodiscard]] - HRESULT CreateAndStartSignalThread() noexcept; - [[nodiscard]] - HRESULT CreateIoHandlers() noexcept; + [[nodiscard]] HRESULT CreateAndStartSignalThread() noexcept; + [[nodiscard]] HRESULT CreateIoHandlers() noexcept; bool IsUsingVt() const; - [[nodiscard]] - HRESULT StartIfNeeded(); + [[nodiscard]] HRESULT StartIfNeeded(); - [[nodiscard]] - static HRESULT ParseIoMode(const std::wstring& VtMode, _Out_ VtIoMode& ioMode); + [[nodiscard]] static HRESULT ParseIoMode(const std::wstring& VtMode, _Out_ VtIoMode& ioMode); - [[nodiscard]] - HRESULT SuppressResizeRepaint(); - [[nodiscard]] - HRESULT SetCursorPosition(const COORD coordCursor); + [[nodiscard]] HRESULT SuppressResizeRepaint(); + [[nodiscard]] HRESULT SetCursorPosition(const COORD coordCursor); void CloseInput() override; void CloseOutput() override; @@ -62,13 +54,12 @@ namespace Microsoft::Console::VirtualTerminal std::unique_ptr _pVtInputThread; std::unique_ptr _pPtySignalInputThread; - [[nodiscard]] - HRESULT _Initialize(const HANDLE InHandle, const HANDLE OutHandle, const std::wstring& VtMode, _In_opt_ const HANDLE SignalHandle); + [[nodiscard]] HRESULT _Initialize(const HANDLE InHandle, const HANDLE OutHandle, const std::wstring& VtMode, _In_opt_ const HANDLE SignalHandle); void _ShutdownIfNeeded(); - #ifdef UNIT_TESTING +#ifdef UNIT_TESTING friend class VtIoTests; - #endif +#endif }; } diff --git a/src/host/_output.cpp b/src/host/_output.cpp index 8dfb79b9c..6a0a9ff70 100644 --- a/src/host/_output.cpp +++ b/src/host/_output.cpp @@ -68,11 +68,10 @@ void WriteToScreen(SCREEN_INFORMATION& screenInfo, const Viewport& region) // - used - number of elements written // Return Value: // - S_OK, E_INVALIDARG or similar HRESULT error. -[[nodiscard]] -HRESULT ApiRoutines::WriteConsoleOutputAttributeImpl(IConsoleOutputObject& OutContext, - const std::basic_string_view attrs, - const COORD target, - size_t& used) noexcept +[[nodiscard]] HRESULT ApiRoutines::WriteConsoleOutputAttributeImpl(IConsoleOutputObject& OutContext, + const std::basic_string_view attrs, + const COORD target, + size_t& used) noexcept { // Set used to 0 from the beginning in case we exit early. used = 0; @@ -109,11 +108,10 @@ HRESULT ApiRoutines::WriteConsoleOutputAttributeImpl(IConsoleOutputObject& OutCo // - used - number of elements written // Return Value: // - S_OK, E_INVALIDARG or similar HRESULT error. -[[nodiscard]] -HRESULT ApiRoutines::WriteConsoleOutputCharacterWImpl(IConsoleOutputObject& OutContext, - const std::wstring_view chars, - const COORD target, - size_t& used) noexcept +[[nodiscard]] HRESULT ApiRoutines::WriteConsoleOutputCharacterWImpl(IConsoleOutputObject& OutContext, + const std::wstring_view chars, + const COORD target, + size_t& used) noexcept { // Set used to 0 from the beginning in case we exit early. used = 0; @@ -153,11 +151,10 @@ HRESULT ApiRoutines::WriteConsoleOutputCharacterWImpl(IConsoleOutputObject& OutC // - used - number of elements written // Return Value: // - S_OK, E_INVALIDARG or similar HRESULT error. -[[nodiscard]] -HRESULT ApiRoutines::WriteConsoleOutputCharacterAImpl(IConsoleOutputObject& OutContext, - const std::string_view chars, - const COORD target, - size_t& used) noexcept +[[nodiscard]] HRESULT ApiRoutines::WriteConsoleOutputCharacterAImpl(IConsoleOutputObject& OutContext, + const std::string_view chars, + const COORD target, + size_t& used) noexcept { // Set used to 0 from the beginning in case we exit early. used = 0; @@ -195,12 +192,11 @@ HRESULT ApiRoutines::WriteConsoleOutputCharacterAImpl(IConsoleOutputObject& OutC // - cellsModified - the number of elements written // Return Value: // - S_OK or suitable HRESULT code from failure to write (memory issues, invalid arg, etc.) -[[nodiscard]] -HRESULT ApiRoutines::FillConsoleOutputAttributeImpl(IConsoleOutputObject& OutContext, - const WORD attribute, - const size_t lengthToWrite, - const COORD startingCoordinate, - size_t& cellsModified) noexcept +[[nodiscard]] HRESULT ApiRoutines::FillConsoleOutputAttributeImpl(IConsoleOutputObject& OutContext, + const WORD attribute, + const size_t lengthToWrite, + const COORD startingCoordinate, + size_t& cellsModified) noexcept { // Set modified cells to 0 from the beginning. cellsModified = 0; @@ -239,7 +235,6 @@ HRESULT ApiRoutines::FillConsoleOutputAttributeImpl(IConsoleOutputObject& OutCon { useThisAttr = TextAttribute(screenBuffer.GetAttributes()); } - } const OutputCellIterator it(useThisAttr, lengthToWrite); @@ -267,12 +262,11 @@ HRESULT ApiRoutines::FillConsoleOutputAttributeImpl(IConsoleOutputObject& OutCon // - cellsModified - the number of elements written // Return Value: // - S_OK or suitable HRESULT code from failure to write (memory issues, invalid arg, etc.) -[[nodiscard]] -HRESULT ApiRoutines::FillConsoleOutputCharacterWImpl(IConsoleOutputObject& OutContext, - const wchar_t character, - const size_t lengthToWrite, - const COORD startingCoordinate, - size_t& cellsModified) noexcept +[[nodiscard]] HRESULT ApiRoutines::FillConsoleOutputCharacterWImpl(IConsoleOutputObject& OutContext, + const wchar_t character, + const size_t lengthToWrite, + const COORD startingCoordinate, + size_t& cellsModified) noexcept { // Set modified cells to 0 from the beginning. cellsModified = 0; @@ -319,12 +313,11 @@ HRESULT ApiRoutines::FillConsoleOutputCharacterWImpl(IConsoleOutputObject& OutCo // - cellsModified - the number of elements written // Return Value: // - S_OK or suitable HRESULT code from failure to write (memory issues, invalid arg, etc.) -[[nodiscard]] -HRESULT ApiRoutines::FillConsoleOutputCharacterAImpl(IConsoleOutputObject& OutContext, - const char character, - const size_t lengthToWrite, - const COORD startingCoordinate, - size_t& cellsModified) noexcept +[[nodiscard]] HRESULT ApiRoutines::FillConsoleOutputCharacterAImpl(IConsoleOutputObject& OutContext, + const char character, + const size_t lengthToWrite, + const COORD startingCoordinate, + size_t& cellsModified) noexcept { const auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); diff --git a/src/host/_stream.cpp b/src/host/_stream.cpp index edb335411..42608e1e0 100644 --- a/src/host/_stream.cpp +++ b/src/host/_stream.cpp @@ -27,7 +27,7 @@ using namespace Microsoft::Console::Types; using Microsoft::Console::Interactivity::ServiceLocator; using Microsoft::Console::VirtualTerminal::StateMachine; // Used by WriteCharsLegacy. -#define IS_GLYPH_CHAR(wch) (((wch) < L' ') || ((wch) == 0x007F)) +#define IS_GLYPH_CHAR(wch) (((wch) < L' ') || ((wch) == 0x007F)) // Routine Description: // - This routine updates the cursor position. Its input is the non-special @@ -40,11 +40,10 @@ using Microsoft::Console::VirtualTerminal::StateMachine; // - coordCursor - New location of cursor. // - fKeepCursorVisible - TRUE if changing window origin desirable when hit right edge // Return Value: -[[nodiscard]] -NTSTATUS AdjustCursorPosition(SCREEN_INFORMATION& screenInfo, - _In_ COORD coordCursor, - const BOOL fKeepCursorVisible, - _Inout_opt_ PSHORT psScrollY) +[[nodiscard]] NTSTATUS AdjustCursorPosition(SCREEN_INFORMATION& screenInfo, + _In_ COORD coordCursor, + const BOOL fKeepCursorVisible, + _Inout_opt_ PSHORT psScrollY) { const COORD bufferSize = screenInfo.GetBufferSize().Dimensions(); if (coordCursor.X < 0) @@ -110,7 +109,7 @@ NTSTATUS AdjustCursorPosition(SCREEN_INFORMATION& screenInfo, // margin down, then move the viewport down. const SHORT delta = coordCursor.Y - srMargins.Bottom; - SMALL_RECT scrollRect{0}; + SMALL_RECT scrollRect{ 0 }; scrollRect.Left = 0; scrollRect.Top = srMargins.Bottom + 1; // One below margins scrollRect.Bottom = bufferSize.Y - 1; // -1, otherwise this would be an exclusive rect. @@ -130,7 +129,7 @@ NTSTATUS AdjustCursorPosition(SCREEN_INFORMATION& screenInfo, // new rows at the bottom. // If we do this, then the viewport is now one line higher than it used // to be, so it needs to move down by one less line. - for(auto i = 0; i < newRows; i++) + for (auto i = 0; i < newRows; i++) { screenInfo.GetTextBuffer().IncrementCircularBuffer(); moveToYPosition--; @@ -143,7 +142,7 @@ NTSTATUS AdjustCursorPosition(SCREEN_INFORMATION& screenInfo, // Unset the margins to scroll the content below the margins, // then restore them after. - screenInfo.SetScrollMargins(Viewport::FromInclusive({0})); + screenInfo.SetScrollMargins(Viewport::FromInclusive({ 0 })); try { ScrollRegion(screenInfo, scrollRect, std::nullopt, newPostMarginsOrigin, UNICODE_SPACE, bufferAttributes); @@ -163,7 +162,7 @@ NTSTATUS AdjustCursorPosition(SCREEN_INFORMATION& screenInfo, // displays the correct text. if (newViewOrigin == viewport.Origin()) { - Viewport invalid = Viewport::FromDimensions(viewport.Origin(), {viewport.Width(), delta}); + Viewport invalid = Viewport::FromDimensions(viewport.Origin(), { viewport.Width(), delta }); screenInfo.GetRenderTarget().TriggerRedraw(invalid); } @@ -187,7 +186,7 @@ NTSTATUS AdjustCursorPosition(SCREEN_INFORMATION& screenInfo, SMALL_RECT scrollRect = { 0 }; scrollRect.Top = srMargins.Top; scrollRect.Bottom = srMargins.Bottom; - scrollRect.Left = screenInfo.GetViewport().Left(); // NOTE: Left/Right Scroll margins don't do anything currently. + scrollRect.Left = screenInfo.GetViewport().Left(); // NOTE: Left/Right Scroll margins don't do anything currently. scrollRect.Right = screenInfo.GetViewport().RightInclusive(); COORD dest; @@ -300,16 +299,15 @@ NTSTATUS AdjustCursorPosition(SCREEN_INFORMATION& screenInfo, // Return Value: // Note: // - This routine does not process tabs and backspace properly. That code will be implemented as part of the line editing services. -[[nodiscard]] -NTSTATUS WriteCharsLegacy(SCREEN_INFORMATION& screenInfo, - _In_range_(<= , pwchBuffer) const wchar_t* const pwchBufferBackupLimit, - _In_ const wchar_t* pwchBuffer, - _In_reads_bytes_(*pcb) const wchar_t* pwchRealUnicode, - _Inout_ size_t* const pcb, - _Out_opt_ size_t* const pcSpaces, - const SHORT sOriginalXPosition, - const DWORD dwFlags, - _Inout_opt_ PSHORT const psScrollY) +[[nodiscard]] NTSTATUS WriteCharsLegacy(SCREEN_INFORMATION& screenInfo, + _In_range_(<=, pwchBuffer) const wchar_t* const pwchBufferBackupLimit, + _In_ const wchar_t* pwchBuffer, + _In_reads_bytes_(*pcb) const wchar_t* pwchRealUnicode, + _Inout_ size_t* const pcb, + _Out_opt_ size_t* const pcSpaces, + const SHORT sOriginalXPosition, + const DWORD dwFlags, + _Inout_opt_ PSHORT const psScrollY) { const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); TextBuffer& textBuffer = screenInfo.GetTextBuffer(); @@ -404,7 +402,7 @@ NTSTATUS WriteCharsLegacy(SCREEN_INFORMATION& screenInfo, wchar_t* LocalBufPtr = LocalBuffer; while (*pcb < BufferSize && i < LOCAL_BUFFER_SIZE && XPosition < coordScreenBufferSize.X) { -#pragma prefast(suppress:26019, "Buffer is taken in multiples of 2. Validation is ok.") +#pragma prefast(suppress : 26019, "Buffer is taken in multiples of 2. Validation is ok.") const wchar_t Char = *lpString; const wchar_t RealUnicodeChar = *pwchRealUnicode; if (!IS_GLYPH_CHAR(RealUnicodeChar) || fUnprocessed) @@ -491,7 +489,6 @@ NTSTATUS WriteCharsLegacy(SCREEN_INFORMATION& screenInfo, // if char is ctrl char, write ^char. if ((dwFlags & WC_ECHO) && (IS_CONTROL_CHAR(RealUnicodeChar))) { - CtrlChar: if (i < (LOCAL_BUFFER_SIZE - 1)) { @@ -563,8 +560,7 @@ NTSTATUS WriteCharsLegacy(SCREEN_INFORMATION& screenInfo, const auto itEnd = screenInfo.Write(it); // Notify accessibility - screenInfo.NotifyAccessibilityEventing(CursorPosition.X, CursorPosition.Y, - CursorPosition.X + gsl::narrow(i - 1), CursorPosition.Y); + screenInfo.NotifyAccessibilityEventing(CursorPosition.X, CursorPosition.Y, CursorPosition.X + gsl::narrow(i - 1), CursorPosition.Y); // The number of "spaces" or "cells" we have consumed needs to be reported and stored for later // when/if we need to erase the command line. @@ -641,14 +637,15 @@ NTSTATUS WriteCharsLegacy(SCREEN_INFORMATION& screenInfo, } for (i = 0, Tmp2 = buffer.get(), Tmp = pwchBufferBackupLimit; - i < bufferSize; i++, Tmp++) + i < bufferSize; + i++, Tmp++) { // see 18120085, these two need to be seperate if statements if (*Tmp == UNICODE_BACKSPACE) { //it is important we do nothing in the else case for // this one instead of falling through to the below else. - if(Tmp2 > buffer.get()) + if (Tmp2 > buffer.get()) { Tmp2--; } @@ -665,11 +662,10 @@ NTSTATUS WriteCharsLegacy(SCREEN_INFORMATION& screenInfo, } else { -#pragma prefast(suppress:26001, "This is fine. Tmp2 has to have advanced or it would equal pBuffer.") +#pragma prefast(suppress : 26001, "This is fine. Tmp2 has to have advanced or it would equal pBuffer.") LastChar = *(Tmp2 - 1); } - if (LastChar == UNICODE_TAB) { CursorPosition.X -= (SHORT)(RetrieveNumberOfSpaces(sOriginalXPosition, @@ -810,7 +806,6 @@ NTSTATUS WriteCharsLegacy(SCREEN_INFORMATION& screenInfo, } CATCH_LOG(); } - } Status = AdjustCursorPosition(screenInfo, CursorPosition, (dwFlags & WC_KEEP_CURSOR_VISIBLE) != 0, psScrollY); break; @@ -936,16 +931,15 @@ NTSTATUS WriteCharsLegacy(SCREEN_INFORMATION& screenInfo, // Return Value: // Note: // - This routine does not process tabs and backspace properly. That code will be implemented as part of the line editing services. -[[nodiscard]] -NTSTATUS WriteChars(SCREEN_INFORMATION& screenInfo, - _In_range_(<= , pwchBuffer) const wchar_t* const pwchBufferBackupLimit, - _In_ const wchar_t* pwchBuffer, - _In_reads_bytes_(*pcb) const wchar_t* pwchRealUnicode, - _Inout_ size_t* const pcb, - _Out_opt_ size_t* const pcSpaces, - const SHORT sOriginalXPosition, - const DWORD dwFlags, - _Inout_opt_ PSHORT const psScrollY) +[[nodiscard]] NTSTATUS WriteChars(SCREEN_INFORMATION& screenInfo, + _In_range_(<=, pwchBuffer) const wchar_t* const pwchBufferBackupLimit, + _In_ const wchar_t* pwchBuffer, + _In_reads_bytes_(*pcb) const wchar_t* pwchRealUnicode, + _Inout_ size_t* const pcb, + _Out_opt_ size_t* const pcSpaces, + const SHORT sOriginalXPosition, + const DWORD dwFlags, + _Inout_opt_ PSHORT const psScrollY) { if (!WI_IsFlagSet(screenInfo.OutputMode, ENABLE_VIRTUAL_TERMINAL_PROCESSING) || !WI_IsFlagSet(screenInfo.OutputMode, ENABLE_PROCESSED_OUTPUT)) @@ -1011,11 +1005,10 @@ NTSTATUS WriteChars(SCREEN_INFORMATION& screenInfo, // - STATUS_SUCCESS if OK. // - CONSOLE_STATUS_WAIT if we couldn't finish now and need to be called back later (see ppWaiter). // - Or a suitable NTSTATUS format error code for memory/string/math failures. -[[nodiscard]] -NTSTATUS DoWriteConsole(_In_reads_bytes_(*pcbBuffer) PWCHAR pwchBuffer, - _Inout_ size_t* const pcbBuffer, - SCREEN_INFORMATION& screenInfo, - std::unique_ptr& waiter) +[[nodiscard]] NTSTATUS DoWriteConsole(_In_reads_bytes_(*pcbBuffer) PWCHAR pwchBuffer, + _Inout_ size_t* const pcbBuffer, + SCREEN_INFORMATION& screenInfo, + std::unique_ptr& waiter) { const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); if (WI_IsAnyFlagSet(gci.Flags, (CONSOLE_SUSPENDED | CONSOLE_SELECTING | CONSOLE_SCROLLBAR_TRACKING))) @@ -1061,11 +1054,10 @@ NTSTATUS DoWriteConsole(_In_reads_bytes_(*pcbBuffer) PWCHAR pwchBuffer, // - S_OK if successful. // - S_OK if we need to wait (check if ppWaiter is not nullptr). // - Or a suitable HRESULT code for math/string/memory failures. -[[nodiscard]] -HRESULT WriteConsoleWImplHelper(IConsoleOutputObject& context, - const std::wstring_view buffer, - size_t& read, - std::unique_ptr& waiter) noexcept +[[nodiscard]] HRESULT WriteConsoleWImplHelper(IConsoleOutputObject& context, + const std::wstring_view buffer, + size_t& read, + std::unique_ptr& waiter) noexcept { try { @@ -1107,11 +1099,10 @@ HRESULT WriteConsoleWImplHelper(IConsoleOutputObject& context, // - S_OK if successful. // - S_OK if we need to wait (check if ppWaiter is not nullptr). // - Or a suitable HRESULT code for math/string/memory failures. -[[nodiscard]] -HRESULT ApiRoutines::WriteConsoleAImpl(IConsoleOutputObject& context, - const std::string_view buffer, - size_t& read, - std::unique_ptr& waiter) noexcept +[[nodiscard]] HRESULT ApiRoutines::WriteConsoleAImpl(IConsoleOutputObject& context, + const std::string_view buffer, + size_t& read, + std::unique_ptr& waiter) noexcept { try { @@ -1183,7 +1174,7 @@ HRESULT ApiRoutines::WriteConsoleAImpl(IConsoleOutputObject& context, unsigned int uiTextBufferLength; RETURN_IF_FAILED(SizeTToUInt(buffer.size(), &uiTextBufferLength)); - if (!ScreenInfo.WriteConsoleDbcsLeadByte[0] || *(PUCHAR)BufPtr < (UCHAR) ' ') + if (!ScreenInfo.WriteConsoleDbcsLeadByte[0] || *(PUCHAR)BufPtr < (UCHAR)' ') { dbcsNumBytes = 0; BufPtrNumBytes = uiTextBufferLength; @@ -1354,11 +1345,10 @@ HRESULT ApiRoutines::WriteConsoleAImpl(IConsoleOutputObject& context, // - S_OK if successful. // - S_OK if we need to wait (check if ppWaiter is not nullptr). // - Or a suitable HRESULT code for math/string/memory failures. -[[nodiscard]] -HRESULT ApiRoutines::WriteConsoleWImpl(IConsoleOutputObject& context, - const std::wstring_view buffer, - size_t& read, - std::unique_ptr& waiter) noexcept +[[nodiscard]] HRESULT ApiRoutines::WriteConsoleWImpl(IConsoleOutputObject& context, + const std::wstring_view buffer, + size_t& read, + std::unique_ptr& waiter) noexcept { try { diff --git a/src/host/_stream.h b/src/host/_stream.h index 8b60d1a54..c2e2963bc 100644 --- a/src/host/_stream.h +++ b/src/host/_stream.h @@ -35,15 +35,13 @@ Arguments: Return Value: --*/ -[[nodiscard]] -NTSTATUS AdjustCursorPosition(SCREEN_INFORMATION& screenInfo, - _In_ COORD coordCursor, - const BOOL fKeepCursorVisible, - _Inout_opt_ PSHORT psScrollY); +[[nodiscard]] NTSTATUS AdjustCursorPosition(SCREEN_INFORMATION& screenInfo, + _In_ COORD coordCursor, + const BOOL fKeepCursorVisible, + _Inout_opt_ PSHORT psScrollY); #define LOCAL_BUFFER_SIZE 100 - /*++ Routine Description: This routine writes a string to the screen, processing any embedded @@ -71,33 +69,30 @@ Note: This routine does not process tabs and backspace properly. That code will be implemented as part of the line editing services. --*/ -[[nodiscard]] -NTSTATUS WriteCharsLegacy(SCREEN_INFORMATION& screenInfo, - _In_range_(<= , pwchBuffer) const wchar_t* const pwchBufferBackupLimit, - _In_ const wchar_t* pwchBuffer, - _In_reads_bytes_(*pcb) const wchar_t* pwchRealUnicode, - _Inout_ size_t* const pcb, - _Out_opt_ size_t* const pcSpaces, - const SHORT sOriginalXPosition, - const DWORD dwFlags, - _Inout_opt_ PSHORT const psScrollY); +[[nodiscard]] NTSTATUS WriteCharsLegacy(SCREEN_INFORMATION& screenInfo, + _In_range_(<=, pwchBuffer) const wchar_t* const pwchBufferBackupLimit, + _In_ const wchar_t* pwchBuffer, + _In_reads_bytes_(*pcb) const wchar_t* pwchRealUnicode, + _Inout_ size_t* const pcb, + _Out_opt_ size_t* const pcSpaces, + const SHORT sOriginalXPosition, + const DWORD dwFlags, + _Inout_opt_ PSHORT const psScrollY); // The new entry point for WriteChars to act as an intercept in case we place a Virtual Terminal processor in the way. -[[nodiscard]] -NTSTATUS WriteChars(SCREEN_INFORMATION& screenInfo, - _In_range_(<= , pwchBuffer) const wchar_t* const pwchBufferBackupLimit, - _In_ const wchar_t* pwchBuffer, - _In_reads_bytes_(*pcb) const wchar_t* pwchRealUnicode, - _Inout_ size_t* const pcb, - _Out_opt_ size_t* const pcSpaces, - const SHORT sOriginalXPosition, - const DWORD dwFlags, - _Inout_opt_ PSHORT const psScrollY); +[[nodiscard]] NTSTATUS WriteChars(SCREEN_INFORMATION& screenInfo, + _In_range_(<=, pwchBuffer) const wchar_t* const pwchBufferBackupLimit, + _In_ const wchar_t* pwchBuffer, + _In_reads_bytes_(*pcb) const wchar_t* pwchRealUnicode, + _Inout_ size_t* const pcb, + _Out_opt_ size_t* const pcSpaces, + const SHORT sOriginalXPosition, + const DWORD dwFlags, + _Inout_opt_ PSHORT const psScrollY); // NOTE: console lock must be held when calling this routine // String has been translated to unicode at this point. -[[nodiscard]] -NTSTATUS DoWriteConsole(_In_reads_bytes_(*pcbBuffer) PWCHAR pwchBuffer, - _In_ size_t* const pcbBuffer, - SCREEN_INFORMATION& screenInfo, - std::unique_ptr& waiter); +[[nodiscard]] NTSTATUS DoWriteConsole(_In_reads_bytes_(*pcbBuffer) PWCHAR pwchBuffer, + _In_ size_t* const pcbBuffer, + SCREEN_INFORMATION& screenInfo, + std::unique_ptr& waiter); diff --git a/src/host/alias.cpp b/src/host/alias.cpp index 562782eb2..7a0e77fda 100644 --- a/src/host/alias.cpp +++ b/src/host/alias.cpp @@ -44,12 +44,13 @@ struct case_insensitive_equality }; std::unordered_map, - case_insensitive_hash, - case_insensitive_equality> g_aliasData; + std::unordered_map, + case_insensitive_hash, + case_insensitive_equality> + g_aliasData; // Routine Description: // - Adds a command line alias to the global set. @@ -60,10 +61,9 @@ std::unordered_map> target, - size_t& writtenOrNeeded, - const std::wstring_view exeName) +[[nodiscard]] HRESULT GetConsoleAliasWImplHelper(const std::wstring_view source, + std::optional> target, + size_t& writtenOrNeeded, + const std::wstring_view exeName) { // Ensure output variables are initialized writtenOrNeeded = 0; @@ -199,11 +197,10 @@ HRESULT GetConsoleAliasWImplHelper(const std::wstring_view source, // - exeName - The client EXE application attached to the host whose set we should check // Return Value: // - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors. -[[nodiscard]] -HRESULT ApiRoutines::GetConsoleAliasAImpl(const std::string_view source, - gsl::span target, - size_t& written, - const std::string_view exeName) noexcept +[[nodiscard]] HRESULT ApiRoutines::GetConsoleAliasAImpl(const std::string_view source, + gsl::span target, + size_t& written, + const std::string_view exeName) noexcept { const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); UINT const codepage = gci.CP; @@ -273,11 +270,10 @@ HRESULT ApiRoutines::GetConsoleAliasAImpl(const std::string_view source, // - exeName - The client EXE application attached to the host whose set we should check // Return Value: // - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors. -[[nodiscard]] -HRESULT ApiRoutines::GetConsoleAliasWImpl(const std::wstring_view source, - gsl::span target, - size_t& written, - const std::wstring_view exeName) noexcept +[[nodiscard]] HRESULT ApiRoutines::GetConsoleAliasWImpl(const std::wstring_view source, + gsl::span target, + size_t& written, + const std::wstring_view exeName) noexcept { LockConsole(); auto Unlock = wil::scope_exit([&] { UnlockConsole(); }); @@ -312,15 +308,14 @@ static std::wstring aliasesSeparator(L"="); // - bufferRequired - Receives the length of buffer that would be required to retrieve all aliases for the given exe. // Return Value: // - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors. -[[nodiscard]] -HRESULT GetConsoleAliasesLengthWImplHelper(const std::wstring_view exeName, - const bool countInUnicode, - const UINT codepage, - size_t& bufferRequired) +[[nodiscard]] HRESULT GetConsoleAliasesLengthWImplHelper(const std::wstring_view exeName, + const bool countInUnicode, + const UINT codepage, + size_t& bufferRequired) { // Ensure output variables are initialized bufferRequired = 0; - + try { const std::wstring exeNameString(exeName); @@ -378,9 +373,8 @@ HRESULT GetConsoleAliasesLengthWImplHelper(const std::wstring_view exeName, // - bufferRequired - Receives the length of buffer that would be required to retrieve all aliases for the given exe. // Return Value: // - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors. -[[nodiscard]] -HRESULT ApiRoutines::GetConsoleAliasesLengthAImpl(const std::string_view exeName, - size_t& bufferRequired) noexcept +[[nodiscard]] HRESULT ApiRoutines::GetConsoleAliasesLengthAImpl(const std::string_view exeName, + size_t& bufferRequired) noexcept { const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); UINT const codepage = gci.CP; @@ -409,9 +403,8 @@ HRESULT ApiRoutines::GetConsoleAliasesLengthAImpl(const std::string_view exeName // - bufferRequired - Receives the length of buffer that would be required to retrieve all aliases for the given exe. // Return Value: // - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors. -[[nodiscard]] -HRESULT ApiRoutines::GetConsoleAliasesLengthWImpl(const std::wstring_view exeName, - size_t& bufferRequired) noexcept +[[nodiscard]] HRESULT ApiRoutines::GetConsoleAliasesLengthWImpl(const std::wstring_view exeName, + size_t& bufferRequired) noexcept { LockConsole(); auto Unlock = wil::scope_exit([&] { UnlockConsole(); }); @@ -449,10 +442,9 @@ void Alias::s_ClearCmdExeAliases() // or how many characters would have been needed (if buffer is nullopt). // Return Value: // - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors. -[[nodiscard]] -HRESULT GetConsoleAliasesWImplHelper(const std::wstring_view exeName, - std::optional> aliasBuffer, - size_t& writtenOrNeeded) +[[nodiscard]] HRESULT GetConsoleAliasesWImplHelper(const std::wstring_view exeName, + std::optional> aliasBuffer, + size_t& writtenOrNeeded) { // Ensure output variables are initialized. writtenOrNeeded = 0; @@ -537,10 +529,9 @@ HRESULT GetConsoleAliasesWImplHelper(const std::wstring_view exeName, // - written - Will specify how many characters were written // Return Value: // - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors. -[[nodiscard]] -HRESULT ApiRoutines::GetConsoleAliasesAImpl(const std::string_view exeName, - gsl::span alias, - size_t& written) noexcept +[[nodiscard]] HRESULT ApiRoutines::GetConsoleAliasesAImpl(const std::string_view exeName, + gsl::span alias, + size_t& written) noexcept { const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); UINT const codepage = gci.CP; @@ -602,10 +593,9 @@ HRESULT ApiRoutines::GetConsoleAliasesAImpl(const std::string_view exeName, // - written - Will specify how many characters were written // Return Value: // - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors. -[[nodiscard]] -HRESULT ApiRoutines::GetConsoleAliasesWImpl(const std::wstring_view exeName, - gsl::span alias, - size_t& written) noexcept +[[nodiscard]] HRESULT ApiRoutines::GetConsoleAliasesWImpl(const std::wstring_view exeName, + gsl::span alias, + size_t& written) noexcept { LockConsole(); auto Unlock = wil::scope_exit([&] { UnlockConsole(); }); @@ -628,8 +618,7 @@ HRESULT ApiRoutines::GetConsoleAliasesWImpl(const std::wstring_view exeName, // - bufferRequired - Receives the length of buffer that would be required to retrieve all relevant EXE names. // Return Value: // - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors. -[[nodiscard]] -HRESULT GetConsoleAliasExesLengthImplHelper(const bool countInUnicode, const UINT codepage, size_t& bufferRequired) +[[nodiscard]] HRESULT GetConsoleAliasExesLengthImplHelper(const bool countInUnicode, const UINT codepage, size_t& bufferRequired) { // Ensure output variables are initialized bufferRequired = 0; @@ -665,8 +654,7 @@ HRESULT GetConsoleAliasExesLengthImplHelper(const bool countInUnicode, const UIN // - bufferRequired - Receives the length of buffer that would be required to retrieve all relevant EXE names. // Return Value: // - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors. -[[nodiscard]] -HRESULT ApiRoutines::GetConsoleAliasExesLengthAImpl(size_t& bufferRequired) noexcept +[[nodiscard]] HRESULT ApiRoutines::GetConsoleAliasExesLengthAImpl(size_t& bufferRequired) noexcept { LockConsole(); const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); @@ -681,8 +669,7 @@ HRESULT ApiRoutines::GetConsoleAliasExesLengthAImpl(size_t& bufferRequired) noex // - bufferRequired - Pointer to receive the length of buffer that would be required to retrieve all relevant EXE names. // Return Value: // - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors. -[[nodiscard]] -HRESULT ApiRoutines::GetConsoleAliasExesLengthWImpl(size_t& bufferRequired) noexcept +[[nodiscard]] HRESULT ApiRoutines::GetConsoleAliasExesLengthWImpl(size_t& bufferRequired) noexcept { LockConsole(); auto Unlock = wil::scope_exit([&] { UnlockConsole(); }); @@ -704,9 +691,8 @@ HRESULT ApiRoutines::GetConsoleAliasExesLengthWImpl(size_t& bufferRequired) noex // or how many characters would have been needed (if buffer is nullopt). // Return Value: // - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors. -[[nodiscard]] -HRESULT GetConsoleAliasExesWImplHelper(std::optional> aliasExesBuffer, - size_t& writtenOrNeeded) +[[nodiscard]] HRESULT GetConsoleAliasExesWImplHelper(std::optional> aliasExesBuffer, + size_t& writtenOrNeeded) { // Ensure output variables are initialized. writtenOrNeeded = 0; @@ -747,12 +733,10 @@ HRESULT GetConsoleAliasExesWImplHelper(std::optional> aliasEx // Accumulate the total written amount. RETURN_IF_FAILED(SizeTAdd(cchTotalLength, cchNeeded, &cchTotalLength)); - } writtenOrNeeded = cchTotalLength; - return S_OK; } @@ -764,9 +748,8 @@ HRESULT GetConsoleAliasExesWImplHelper(std::optional> aliasEx // - written - Specifies how many characters were written // Return Value: // - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors. -[[nodiscard]] -HRESULT ApiRoutines::GetConsoleAliasExesAImpl(gsl::span aliasExes, - size_t& written) noexcept +[[nodiscard]] HRESULT ApiRoutines::GetConsoleAliasExesAImpl(gsl::span aliasExes, + size_t& written) noexcept { const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); UINT const codepage = gci.CP; @@ -824,9 +807,8 @@ HRESULT ApiRoutines::GetConsoleAliasExesAImpl(gsl::span aliasExes, // - pcchAliasExesBufferWrittenOrNeeded - Pointer to space that will specify how many characters were written // Return Value: // - Check HRESULT with SUCCEEDED. Can return memory, safe math, safe string, or locale conversion errors. -[[nodiscard]] -HRESULT ApiRoutines::GetConsoleAliasExesWImpl(gsl::span aliasExes, - size_t& written) noexcept +[[nodiscard]] HRESULT ApiRoutines::GetConsoleAliasExesWImpl(gsl::span aliasExes, + size_t& written) noexcept { LockConsole(); auto Unlock = wil::scope_exit([&] { UnlockConsole(); }); diff --git a/src/host/alias.h b/src/host/alias.h index 2ee82c012..ab8624b9f 100644 --- a/src/host/alias.h +++ b/src/host/alias.h @@ -11,9 +11,6 @@ Abstract: --*/ #pragma once - - - class Alias { public: @@ -31,7 +28,6 @@ public: const std::wstring& exeName, size_t& lineCount); - private: static void s_TrimLeadingSpaces(std::wstring& str); static void s_TrimTrailingCrLf(std::wstring& str); @@ -60,7 +56,7 @@ private: size_t& lineCount); static void s_AppendCrLf(std::wstring& appendToStr, - size_t& lineCount); + size_t& lineCount); #ifdef UNIT_TESTING static void s_TestAddAlias(std::wstring& exe, diff --git a/src/host/cmdline.cpp b/src/host/cmdline.cpp index 290f9d364..d59c638c4 100644 --- a/src/host/cmdline.cpp +++ b/src/host/cmdline.cpp @@ -63,7 +63,7 @@ bool IsValidStringBuffer(_In_ bool Unicode, _In_reads_bytes_(Size) PVOID Buffer, while (Count > 0) { ULONG const StringSize = va_arg(Marker, ULONG); - PVOID* StringStart = va_arg(Marker, PVOID *); + PVOID* StringStart = va_arg(Marker, PVOID*); // Make sure the string fits in the supplied buffer and that it is properly aligned. if (StringSize > Size) @@ -115,12 +115,10 @@ bool IsWordDelim(const std::wstring_view charData) CommandLine::CommandLine() : _isVisible{ true } { - } CommandLine::~CommandLine() { - } CommandLine& CommandLine::Instance() @@ -231,7 +229,7 @@ void DeleteCommandLine(COOKED_READ_DATA& cookedReadData, const bool fUpdateField if (coordOriginalCursor.Y < 0) { CharsToWrite += coordBufferSize.X * coordOriginalCursor.Y; - CharsToWrite += cookedReadData.OriginalCursorPosition().X; // account for prompt + CharsToWrite += cookedReadData.OriginalCursorPosition().X; // account for prompt cookedReadData.OriginalCursorPosition().X = 0; cookedReadData.OriginalCursorPosition().Y = 0; coordOriginalCursor.X = 0; @@ -267,7 +265,7 @@ void RedrawCommandLine(COOKED_READ_DATA& cookedReadData) cookedReadData.OriginalCursorPosition() = cookedReadData.ScreenInfo().GetTextBuffer().GetCursor().GetPosition(); SHORT ScrollY = 0; -#pragma prefast(suppress:28931, "Status is not unused. It's used in debug assertions.") +#pragma prefast(suppress : 28931, "Status is not unused. It's used in debug assertions.") NTSTATUS Status = WriteCharsLegacy(cookedReadData.ScreenInfo(), cookedReadData.BufferStartPtr(), cookedReadData.BufferStartPtr(), @@ -331,8 +329,7 @@ void SetCurrentCommandLine(COOKED_READ_DATA& cookedReadData, _In_ SHORT Index) / // Return Value: // - CONSOLE_STATUS_WAIT - we ran out of input, so a wait block was created // - STATUS_SUCCESS - read was fully completed (user hit return) -[[nodiscard]] -NTSTATUS CommandLine::_startCommandListPopup(COOKED_READ_DATA& cookedReadData) +[[nodiscard]] NTSTATUS CommandLine::_startCommandListPopup(COOKED_READ_DATA& cookedReadData) { if (cookedReadData.HasHistory() && cookedReadData.History().GetNumberOfCommands()) @@ -357,8 +354,7 @@ NTSTATUS CommandLine::_startCommandListPopup(COOKED_READ_DATA& cookedReadData) // Return Value: // - CONSOLE_STATUS_WAIT - we ran out of input, so a wait block was created // - STATUS_SUCCESS - read was fully completed (user hit return) -[[nodiscard]] -NTSTATUS CommandLine::_startCopyFromCharPopup(COOKED_READ_DATA& cookedReadData) +[[nodiscard]] NTSTATUS CommandLine::_startCopyFromCharPopup(COOKED_READ_DATA& cookedReadData) { // Delete the current command from cursor position to the // letter specified by the user. The user is prompted via @@ -385,8 +381,7 @@ NTSTATUS CommandLine::_startCopyFromCharPopup(COOKED_READ_DATA& cookedReadData) // - CONSOLE_STATUS_WAIT - we ran out of input, so a wait block was created // - STATUS_SUCCESS - read was fully completed (user hit return) // - S_FALSE - if we couldn't make a popup because we had no commands -[[nodiscard]] -NTSTATUS CommandLine::_startCopyToCharPopup(COOKED_READ_DATA& cookedReadData) +[[nodiscard]] NTSTATUS CommandLine::_startCopyToCharPopup(COOKED_READ_DATA& cookedReadData) { // copy the previous command to the current command, up to but // not including the character specified by the user. the user @@ -413,8 +408,7 @@ NTSTATUS CommandLine::_startCopyToCharPopup(COOKED_READ_DATA& cookedReadData) // - CONSOLE_STATUS_WAIT - we ran out of input, so a wait block was created // - STATUS_SUCCESS - read was fully completed (user hit return) // - S_FALSE - if we couldn't make a popup because we had no commands or it wouldn't fit. -[[nodiscard]] -HRESULT CommandLine::StartCommandNumberPopup(COOKED_READ_DATA& cookedReadData) +[[nodiscard]] HRESULT CommandLine::StartCommandNumberPopup(COOKED_READ_DATA& cookedReadData) { if (cookedReadData.HasHistory() && cookedReadData.History().GetNumberOfCommands() && @@ -454,20 +448,17 @@ HRESULT CommandLine::StartCommandNumberPopup(COOKED_READ_DATA& cookedReadData) void CommandLine::_processHistoryCycling(COOKED_READ_DATA& cookedReadData, const CommandHistory::SearchDirection searchDirection) { - // for doskey compatibility, buffer isn't circular. don't do anything if attempting // to cycle history past the bounds of the history buffer if (!cookedReadData.HasHistory()) { return; } - else if (searchDirection == CommandHistory::SearchDirection::Previous - && cookedReadData.History().AtFirstCommand()) + else if (searchDirection == CommandHistory::SearchDirection::Previous && cookedReadData.History().AtFirstCommand()) { return; } - else if (searchDirection == CommandHistory::SearchDirection::Next - && cookedReadData.History().AtLastCommand()) + else if (searchDirection == CommandHistory::SearchDirection::Next && cookedReadData.History().AtLastCommand()) { return; } @@ -716,7 +707,6 @@ COORD CommandLine::_moveCursorLeftByWord(COOKED_READ_DATA& cookedReadData) noexc FAIL_FAST_IF(!(LastWord >= cookedReadData.BufferStartPtr())); if (LastWord != cookedReadData.BufferStartPtr()) { - // LastWord is currently pointing to the last character // of the previous word, unless it backed up to the beginning // of the buffer. @@ -729,13 +719,13 @@ COORD CommandLine::_moveCursorLeftByWord(COOKED_READ_DATA& cookedReadData) noexc cookedReadData.InsertionPoint() = (ULONG)(cookedReadData.BufferCurrentPtr() - cookedReadData.BufferStartPtr()); cursorPosition = cookedReadData.OriginalCursorPosition(); cursorPosition.X = (SHORT)(cursorPosition.X + - RetrieveTotalNumberOfSpaces(cookedReadData.OriginalCursorPosition().X, - cookedReadData.BufferStartPtr(), - cookedReadData.InsertionPoint())); + RetrieveTotalNumberOfSpaces(cookedReadData.OriginalCursorPosition().X, + cookedReadData.BufferStartPtr(), + cookedReadData.InsertionPoint())); const SHORT sScreenBufferSizeX = cookedReadData.ScreenInfo().GetBufferSize().Width(); if (CheckBisectStringW(cookedReadData.BufferStartPtr(), - cookedReadData.InsertionPoint() + 1, - sScreenBufferSizeX - cookedReadData.OriginalCursorPosition().X)) + cookedReadData.InsertionPoint() + 1, + sScreenBufferSizeX - cookedReadData.OriginalCursorPosition().X)) { cursorPosition.X++; } @@ -759,9 +749,9 @@ COORD CommandLine::_moveCursorLeft(COOKED_READ_DATA& cookedReadData) cursorPosition.X = cookedReadData.ScreenInfo().GetTextBuffer().GetCursor().GetPosition().X; cursorPosition.Y = cookedReadData.ScreenInfo().GetTextBuffer().GetCursor().GetPosition().Y; cursorPosition.X = (SHORT)(cursorPosition.X - - RetrieveNumberOfSpaces(cookedReadData.OriginalCursorPosition().X, - cookedReadData.BufferStartPtr(), - cookedReadData.InsertionPoint())); + RetrieveNumberOfSpaces(cookedReadData.OriginalCursorPosition().X, + cookedReadData.BufferStartPtr(), + cookedReadData.InsertionPoint())); const SHORT sScreenBufferSizeX = cookedReadData.ScreenInfo().GetBufferSize().Width(); if (CheckBisectProcessW(cookedReadData.ScreenInfo(), cookedReadData.BufferStartPtr(), @@ -843,8 +833,8 @@ COORD CommandLine::_moveCursorRightByWord(COOKED_READ_DATA& cookedReadData) noex cookedReadData.InsertionPoint())); const SHORT sScreenBufferSizeX = cookedReadData.ScreenInfo().GetBufferSize().Width(); if (CheckBisectStringW(cookedReadData.BufferStartPtr(), - cookedReadData.InsertionPoint() + 1, - sScreenBufferSizeX - cookedReadData.OriginalCursorPosition().X)) + cookedReadData.InsertionPoint() + 1, + sScreenBufferSizeX - cookedReadData.OriginalCursorPosition().X)) { cursorPosition.X++; } @@ -867,9 +857,9 @@ COORD CommandLine::_moveCursorRight(COOKED_READ_DATA& cookedReadData) noexcept { cursorPosition = cookedReadData.ScreenInfo().GetTextBuffer().GetCursor().GetPosition(); cursorPosition.X = (SHORT)(cursorPosition.X + - RetrieveNumberOfSpaces(cookedReadData.OriginalCursorPosition().X, - cookedReadData.BufferStartPtr(), - cookedReadData.InsertionPoint())); + RetrieveNumberOfSpaces(cookedReadData.OriginalCursorPosition().X, + cookedReadData.BufferStartPtr(), + cookedReadData.InsertionPoint())); if (CheckBisectProcessW(cookedReadData.ScreenInfo(), cookedReadData.BufferStartPtr(), cookedReadData.InsertionPoint() + 2, @@ -934,7 +924,7 @@ void CommandLine::_insertCtrlZ(COOKED_READ_DATA& cookedReadData) noexcept { size_t NumSpaces = 0; - *cookedReadData.BufferCurrentPtr() = (WCHAR)0x1a; // ctrl-z + *cookedReadData.BufferCurrentPtr() = (WCHAR)0x1a; // ctrl-z cookedReadData.BytesRead() += sizeof(WCHAR); cookedReadData.InsertionPoint()++; if (cookedReadData.IsEchoInput()) @@ -942,14 +932,14 @@ void CommandLine::_insertCtrlZ(COOKED_READ_DATA& cookedReadData) noexcept short ScrollY = 0; size_t CharsToWrite = sizeof(WCHAR); FAIL_FAST_IF_NTSTATUS_FAILED(WriteCharsLegacy(cookedReadData.ScreenInfo(), - cookedReadData.BufferStartPtr(), - cookedReadData.BufferCurrentPtr(), - cookedReadData.BufferCurrentPtr(), - &CharsToWrite, - &NumSpaces, - cookedReadData.OriginalCursorPosition().X, - WC_DESTRUCTIVE_BACKSPACE | WC_KEEP_CURSOR_VISIBLE | WC_ECHO, - &ScrollY)); + cookedReadData.BufferStartPtr(), + cookedReadData.BufferCurrentPtr(), + cookedReadData.BufferCurrentPtr(), + &CharsToWrite, + &NumSpaces, + cookedReadData.OriginalCursorPosition().X, + WC_DESTRUCTIVE_BACKSPACE | WC_KEEP_CURSOR_VISIBLE | WC_ECHO, + &ScrollY)); cookedReadData.OriginalCursorPosition().Y += ScrollY; cookedReadData.VisibleCharCount() += NumSpaces; } @@ -1021,9 +1011,9 @@ COORD CommandLine::_cycleMatchingCommandHistoryToPrompt(COOKED_READ_DATA& cooked { SHORT index; if (cookedReadData.History().FindMatchingCommand({ cookedReadData.BufferStartPtr(), cookedReadData.InsertionPoint() }, - cookedReadData.History().LastDisplayed, - index, - CommandHistory::MatchOptions::None)) + cookedReadData.History().LastDisplayed, + index, + CommandHistory::MatchOptions::None)) { SHORT CurrentPos; @@ -1074,7 +1064,9 @@ COORD CommandLine::DeleteFromRightOfCursor(COOKED_READ_DATA& cookedReadData) noe if (!cookedReadData.AtEol()) { // Delete commandline. -#pragma prefast(suppress:__WARNING_BUFFER_OVERFLOW, "Not sure why prefast is getting confused here") + // clang-format off +#pragma prefast(suppress: __WARNING_BUFFER_OVERFLOW, "Not sure why prefast is getting confused here") + // clang-format on DeleteCommandLine(cookedReadData, false); // Delete char. @@ -1124,10 +1116,9 @@ COORD CommandLine::DeleteFromRightOfCursor(COOKED_READ_DATA& cookedReadData) noe // - CONSOLE_STATUS_WAIT - CommandListPopup ran out of input // - CONSOLE_STATUS_READ_COMPLETE - user hit in CommandListPopup // - STATUS_SUCCESS - everything's cool -[[nodiscard]] -NTSTATUS CommandLine::ProcessCommandLine(COOKED_READ_DATA& cookedReadData, - _In_ WCHAR wch, - const DWORD dwKeyState) +[[nodiscard]] NTSTATUS CommandLine::ProcessCommandLine(COOKED_READ_DATA& cookedReadData, + _In_ WCHAR wch, + const DWORD dwKeyState) { const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); COORD cursorPosition = cookedReadData.ScreenInfo().GetTextBuffer().GetCursor().GetPosition(); diff --git a/src/host/cmdline.h b/src/host/cmdline.h index f186a65e0..8dd873aa9 100644 --- a/src/host/cmdline.h +++ b/src/host/cmdline.h @@ -63,7 +63,6 @@ Notes: #include "readDataCooked.hpp" #include "popup.h" - class CommandLine { public: @@ -76,13 +75,11 @@ public: void Show(); bool IsVisible() const noexcept; - [[nodiscard]] - NTSTATUS ProcessCommandLine(COOKED_READ_DATA& cookedReadData, - _In_ WCHAR wch, - const DWORD dwKeyState); + [[nodiscard]] NTSTATUS ProcessCommandLine(COOKED_READ_DATA& cookedReadData, + _In_ WCHAR wch, + const DWORD dwKeyState); - [[nodiscard]] - HRESULT StartCommandNumberPopup(COOKED_READ_DATA& cookedReadData); + [[nodiscard]] HRESULT StartCommandNumberPopup(COOKED_READ_DATA& cookedReadData); bool HasPopup() const noexcept; Popup& GetPopup(); @@ -97,6 +94,7 @@ public: void DeletePromptAfterCursor(COOKED_READ_DATA& cookedReadData) noexcept; COORD DeleteFromRightOfCursor(COOKED_READ_DATA& cookedReadData) noexcept; + protected: CommandLine(); @@ -104,12 +102,9 @@ protected: CommandLine(CommandLine const&) = delete; CommandLine& operator=(CommandLine const&) = delete; - [[nodiscard]] - NTSTATUS CommandLine::_startCommandListPopup(COOKED_READ_DATA& cookedReadData); - [[nodiscard]] - NTSTATUS CommandLine::_startCopyFromCharPopup(COOKED_READ_DATA& cookedReadData); - [[nodiscard]] - NTSTATUS CommandLine::_startCopyToCharPopup(COOKED_READ_DATA& cookedReadData); + [[nodiscard]] NTSTATUS CommandLine::_startCommandListPopup(COOKED_READ_DATA& cookedReadData); + [[nodiscard]] NTSTATUS CommandLine::_startCopyFromCharPopup(COOKED_READ_DATA& cookedReadData); + [[nodiscard]] NTSTATUS CommandLine::_startCopyToCharPopup(COOKED_READ_DATA& cookedReadData); void _processHistoryCycling(COOKED_READ_DATA& cookedReadData, const CommandHistory::SearchDirection searchDirection); void _setPromptToOldestCommand(COOKED_READ_DATA& cookedReadData); @@ -126,43 +121,39 @@ protected: void _fillPromptWithPreviousCommandFragment(COOKED_READ_DATA& cookedReadData) noexcept; COORD _cycleMatchingCommandHistoryToPrompt(COOKED_READ_DATA& cookedReadData); - #ifdef UNIT_TESTING friend class CommandLineTests; friend class CommandNumberPopupTests; #endif private: - std::deque> _popups; bool _isVisible; }; - void DeleteCommandLine(COOKED_READ_DATA& cookedReadData, const bool fUpdateFields); void RedrawCommandLine(COOKED_READ_DATA& cookedReadData); // Values for WriteChars(), WriteCharsLegacy() dwFlags #define WC_DESTRUCTIVE_BACKSPACE 0x01 -#define WC_KEEP_CURSOR_VISIBLE 0x02 -#define WC_ECHO 0x04 +#define WC_KEEP_CURSOR_VISIBLE 0x02 +#define WC_ECHO 0x04 // This is no longer necessary. The buffer will always be Unicode. We don't need to perform special work to check if we're in a raster font // and convert the entire buffer to match (and all insertions). //#define WC_FALSIFY_UNICODE 0x08 -#define WC_LIMIT_BACKSPACE 0x10 -#define WC_NONDESTRUCTIVE_TAB 0x20 +#define WC_LIMIT_BACKSPACE 0x10 +#define WC_NONDESTRUCTIVE_TAB 0x20 //#define WC_NEWLINE_SAVE_X 0x40 - This has been replaced with an output mode flag instead as it's line discipline behavior that may not necessarily be coupled with VT. -#define WC_DELAY_EOL_WRAP 0x80 +#define WC_DELAY_EOL_WRAP 0x80 // Word delimiters bool IsWordDelim(const wchar_t wch); bool IsWordDelim(const std::wstring_view charData); -[[nodiscard]] -HRESULT DoSrvSetConsoleTitleW(const std::wstring_view title) noexcept; +[[nodiscard]] HRESULT DoSrvSetConsoleTitleW(const std::wstring_view title) noexcept; bool IsValidStringBuffer(_In_ bool Unicode, _In_reads_bytes_(Size) PVOID Buffer, _In_ ULONG Size, _In_ ULONG Count, ...); diff --git a/src/host/conareainfo.cpp b/src/host/conareainfo.cpp index c2a0cc591..9ac5d8771 100644 --- a/src/host/conareainfo.cpp +++ b/src/host/conareainfo.cpp @@ -131,8 +131,7 @@ void ConversionAreaInfo::ClearArea() noexcept Paint(); } -[[nodiscard]] -HRESULT ConversionAreaInfo::Resize(const COORD newSize) noexcept +[[nodiscard]] HRESULT ConversionAreaInfo::Resize(const COORD newSize) noexcept { // attempt to resize underlying buffers RETURN_IF_NTSTATUS_FAILED(_screenBuffer->ResizeScreenBuffer(newSize, FALSE)); @@ -150,7 +149,6 @@ HRESULT ConversionAreaInfo::Resize(const COORD newSize) noexcept return S_OK; } - void ConversionAreaInfo::SetWindowInfo(const SMALL_RECT view) noexcept { if (view.Left != _caInfo.rcViewCaWindow.Left || @@ -184,7 +182,7 @@ void ConversionAreaInfo::SetViewPos(const COORD pos) noexcept { CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); - SMALL_RECT OldRegion = _caInfo.rcViewCaWindow;; + SMALL_RECT OldRegion = _caInfo.rcViewCaWindow; OldRegion.Left += _caInfo.coordConView.X; OldRegion.Right += _caInfo.coordConView.X; OldRegion.Top += _caInfo.coordConView.Y; diff --git a/src/host/conareainfo.h b/src/host/conareainfo.h index 8964faaa2..d7689b966 100644 --- a/src/host/conareainfo.h +++ b/src/host/conareainfo.h @@ -55,8 +55,7 @@ public: void SetHidden(const bool fIsHidden) noexcept; void ClearArea() noexcept; - [[nodiscard]] - HRESULT Resize(const COORD newSize) noexcept; + [[nodiscard]] HRESULT Resize(const COORD newSize) noexcept; void SetViewPos(const COORD pos) noexcept; void SetWindowInfo(const SMALL_RECT view) noexcept; diff --git a/src/host/conattrs.cpp b/src/host/conattrs.cpp index 42583d328..7dba87e07 100644 --- a/src/host/conattrs.cpp +++ b/src/host/conattrs.cpp @@ -24,11 +24,11 @@ struct _HSL // constructs an HSL color from a RGB Color. _HSL(const COLORREF rgb) { - const double r = (double) GetRValue(rgb); - const double g = (double) GetGValue(rgb); - const double b = (double) GetBValue(rgb); + const double r = (double)GetRValue(rgb); + const double g = (double)GetGValue(rgb); + const double b = (double)GetBValue(rgb); - const auto[min, max] = std::minmax({ r, g, b }); + const auto [min, max] = std::minmax({ r, g, b }); const auto diff = max - min; const auto sum = max + min; @@ -39,18 +39,18 @@ struct _HSL s = (max == 0) ? 0 : diff / max; //Hue - double q = (diff == 0)? 0 : 60.0/diff; + double q = (diff == 0) ? 0 : 60.0 / diff; if (max == r) { - h = (g < b)? ((360.0 + q * (g - b))/360.0) : ((q * (g - b))/360.0); + h = (g < b) ? ((360.0 + q * (g - b)) / 360.0) : ((q * (g - b)) / 360.0); } else if (max == g) { - h = (120.0 + q * (b - r))/360.0; + h = (120.0 + q * (b - r)) / 360.0; } else if (max == b) { - h = (240.0 + q * (r - g))/360.0; + h = (240.0 + q * (r - g)) / 360.0; } else { @@ -71,9 +71,9 @@ struct _HSL static double _FindDifference(const _HSL* const phslColorA, const COLORREF rgbColorB) { const _HSL hslColorB = _HSL(rgbColorB); - return sqrt( pow((hslColorB.h - phslColorA->h), 2) + - pow((hslColorB.s - phslColorA->s), 2) + - pow((hslColorB.l - phslColorA->l), 2) ); + return sqrt(pow((hslColorB.h - phslColorA->h), 2) + + pow((hslColorB.s - phslColorA->s), 2) + + pow((hslColorB.l - phslColorA->l), 2)); } //Routine Description: @@ -201,8 +201,8 @@ COLORREF ForegroundColor(const WORD wLegacyAttrs, const byte iColorTableIndex = LOBYTE(wLegacyAttrs) & FG_ATTRS; return (iColorTableIndex < cColorTable && iColorTableIndex >= 0) ? - ColorTable[iColorTableIndex] : - INVALID_COLOR; + ColorTable[iColorTableIndex] : + INVALID_COLOR; } // Method Description: @@ -220,6 +220,6 @@ COLORREF BackgroundColor(const WORD wLegacyAttrs, const byte iColorTableIndex = (LOBYTE(wLegacyAttrs) & BG_ATTRS) >> 4; return (iColorTableIndex < cColorTable && iColorTableIndex >= 0) ? - ColorTable[iColorTableIndex] : - INVALID_COLOR; + ColorTable[iColorTableIndex] : + INVALID_COLOR; } diff --git a/src/host/conddkrefs.h b/src/host/conddkrefs.h index e5978a46e..8da95c179 100644 --- a/src/host/conddkrefs.h +++ b/src/host/conddkrefs.h @@ -15,44 +15,46 @@ and it's easier to include a copy of the infrequently changing defs here. #ifndef _DDK_INCLUDED -#pragma region wdm.h (public DDK) +#pragma region wdm.h(public DDK) // // Define the base asynchronous I/O argument types // -extern "C" +extern "C" { + +// +// ClientId +// + +typedef struct _CLIENT_ID { + HANDLE UniqueProcess; + HANDLE UniqueThread; +} CLIENT_ID; +typedef CLIENT_ID* PCLIENT_ID; - // - // ClientId - // +// POBJECT_ATTRIBUTES - typedef struct _CLIENT_ID { - HANDLE UniqueProcess; - HANDLE UniqueThread; - } CLIENT_ID; - typedef CLIENT_ID *PCLIENT_ID; +// +// Unicode strings are counted 16-bit character strings. If they are +// NULL terminated, Length does not include trailing NULL. +// - // POBJECT_ATTRIBUTES - - // - // Unicode strings are counted 16-bit character strings. If they are - // NULL terminated, Length does not include trailing NULL. - // - - typedef struct _UNICODE_STRING { - USHORT Length; - USHORT MaximumLength; +typedef struct _UNICODE_STRING +{ + USHORT Length; + USHORT MaximumLength; #ifdef MIDL_PASS - [size_is(MaximumLength / 2), length_is((Length) / 2)] USHORT * Buffer; + [size_is(MaximumLength / 2), length_is((Length) / 2)] USHORT* Buffer; #else // MIDL_PASS - _Field_size_bytes_part_(MaximumLength, Length) PWCH Buffer; + _Field_size_bytes_part_(MaximumLength, Length) PWCH Buffer; #endif // MIDL_PASS - } UNICODE_STRING; - typedef UNICODE_STRING *PUNICODE_STRING; - typedef const UNICODE_STRING *PCUNICODE_STRING; +} UNICODE_STRING; +typedef UNICODE_STRING* PUNICODE_STRING; +typedef const UNICODE_STRING* PCUNICODE_STRING; - // OBJECT_ATTRIBUTES +// OBJECT_ATTRIBUTES +// clang-format off #define OBJ_INHERIT 0x00000002L #define OBJ_PERMANENT 0x00000010L #define OBJ_EXCLUSIVE 0x00000020L @@ -62,63 +64,67 @@ extern "C" #define OBJ_KERNEL_HANDLE 0x00000200L #define OBJ_FORCE_ACCESS_CHECK 0x00000400L #define OBJ_VALID_ATTRIBUTES 0x000007F2L +// clang-format on - typedef struct _OBJECT_ATTRIBUTES { - ULONG Length; - HANDLE RootDirectory; - PUNICODE_STRING ObjectName; - ULONG Attributes; - PVOID SecurityDescriptor; // Points to type SECURITY_DESCRIPTOR - PVOID SecurityQualityOfService; // Points to type SECURITY_QUALITY_OF_SERVICE - } OBJECT_ATTRIBUTES; - typedef OBJECT_ATTRIBUTES *POBJECT_ATTRIBUTES; - typedef CONST OBJECT_ATTRIBUTES *PCOBJECT_ATTRIBUTES; +typedef struct _OBJECT_ATTRIBUTES +{ + ULONG Length; + HANDLE RootDirectory; + PUNICODE_STRING ObjectName; + ULONG Attributes; + PVOID SecurityDescriptor; // Points to type SECURITY_DESCRIPTOR + PVOID SecurityQualityOfService; // Points to type SECURITY_QUALITY_OF_SERVICE +} OBJECT_ATTRIBUTES; +typedef OBJECT_ATTRIBUTES* POBJECT_ATTRIBUTES; +typedef CONST OBJECT_ATTRIBUTES* PCOBJECT_ATTRIBUTES; - //++ - // - // VOID - // InitializeObjectAttributes( - // _Out_ POBJECT_ATTRIBUTES p, - // _In_ PUNICODE_STRING n, - // _In_ ULONG a, - // _In_ HANDLE r, - // _In_ PSECURITY_DESCRIPTOR s - // ) - // - //-- +//++ +// +// VOID +// InitializeObjectAttributes( +// _Out_ POBJECT_ATTRIBUTES p, +// _In_ PUNICODE_STRING n, +// _In_ ULONG a, +// _In_ HANDLE r, +// _In_ PSECURITY_DESCRIPTOR s +// ) +// +//-- -#define InitializeObjectAttributes( p, n, a, r, s ) { \ - (p)->Length = sizeof( OBJECT_ATTRIBUTES ); \ - (p)->RootDirectory = r; \ - (p)->Attributes = a; \ - (p)->ObjectName = n; \ - (p)->SecurityDescriptor = s; \ - (p)->SecurityQualityOfService = NULL; \ +#define InitializeObjectAttributes(p, n, a, r, s) \ + { \ + (p)->Length = sizeof(OBJECT_ATTRIBUTES); \ + (p)->RootDirectory = r; \ + (p)->Attributes = a; \ + (p)->ObjectName = n; \ + (p)->SecurityDescriptor = s; \ + (p)->SecurityQualityOfService = NULL; \ } - // UNICODE_STRING +// UNICODE_STRING +// OBJ_CASE_INSENSITIVE +// OBJ_INHERIT +// InitializeObjectAttributes +typedef struct _IO_STATUS_BLOCK +{ + union + { + NTSTATUS Status; + PVOID Pointer; + } DUMMYUNIONNAME; - // OBJ_CASE_INSENSITIVE - // OBJ_INHERIT - // InitializeObjectAttributes + ULONG_PTR Information; +} IO_STATUS_BLOCK, *PIO_STATUS_BLOCK; - typedef struct _IO_STATUS_BLOCK { - union { - NTSTATUS Status; - PVOID Pointer; - } DUMMYUNIONNAME; - - ULONG_PTR Information; - } IO_STATUS_BLOCK, *PIO_STATUS_BLOCK; - - // - // Define the file system information class values - // - // WARNING: The order of the following values are assumed by the I/O system. - // Any changes made here should be reflected there as well. +// +// Define the file system information class values +// +// WARNING: The order of the following values are assumed by the I/O system. +// Any changes made here should be reflected there as well. +// clang-format off typedef enum _FSINFOCLASS { FileFsVolumeInformation = 1, FileFsLabelInformation, // 2 @@ -135,100 +141,79 @@ extern "C" FileFsMetadataSizeInformation, // 13 FileFsMaximumInformation } FS_INFORMATION_CLASS, *PFS_INFORMATION_CLASS; +// clang-format on #ifndef DEVICE_TYPE #define DEVICE_TYPE DWORD #endif - typedef struct _FILE_FS_DEVICE_INFORMATION { - DEVICE_TYPE DeviceType; - ULONG Characteristics; - } FILE_FS_DEVICE_INFORMATION, *PFILE_FS_DEVICE_INFORMATION; +typedef struct _FILE_FS_DEVICE_INFORMATION +{ + DEVICE_TYPE DeviceType; + ULONG Characteristics; +} FILE_FS_DEVICE_INFORMATION, *PFILE_FS_DEVICE_INFORMATION; #pragma region IOCTL codes - // - // Define the various device type values. Note that values used by Microsoft - // Corporation are in the range 0-32767, and 32768-65535 are reserved for use - // by customers. - // +// +// Define the various device type values. Note that values used by Microsoft +// Corporation are in the range 0-32767, and 32768-65535 are reserved for use +// by customers. +// #ifndef FILE_DEVICE_CONSOLE -#define FILE_DEVICE_CONSOLE 0x00000050 +#define FILE_DEVICE_CONSOLE 0x00000050 #endif - // - // Macro definition for defining IOCTL and FSCTL function control codes. Note - // that function codes 0-2047 are reserved for Microsoft Corporation, and - // 2048-4095 are reserved for customers. - // +// +// Macro definition for defining IOCTL and FSCTL function control codes. Note +// that function codes 0-2047 are reserved for Microsoft Corporation, and +// 2048-4095 are reserved for customers. +// #ifndef CTL_CODE -#define CTL_CODE( DeviceType, Function, Method, Access ) ( \ - ((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \ -) +#define CTL_CODE(DeviceType, Function, Method, Access) ( \ + ((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method)) #endif - // - // Define the method codes for how buffers are passed for I/O and FS controls - // +// +// Define the method codes for how buffers are passed for I/O and FS controls +// -#define METHOD_BUFFERED 0 -#define METHOD_IN_DIRECT 1 -#define METHOD_OUT_DIRECT 2 +#define METHOD_BUFFERED 0 +#define METHOD_IN_DIRECT 1 +#define METHOD_OUT_DIRECT 2 #ifndef METHOD_NEITHER -#define METHOD_NEITHER 3 +#define METHOD_NEITHER 3 #endif - // - // Define some easier to comprehend aliases: - // METHOD_DIRECT_TO_HARDWARE (writes, aka METHOD_IN_DIRECT) - // METHOD_DIRECT_FROM_HARDWARE (reads, aka METHOD_OUT_DIRECT) - // +// +// Define some easier to comprehend aliases: +// METHOD_DIRECT_TO_HARDWARE (writes, aka METHOD_IN_DIRECT) +// METHOD_DIRECT_FROM_HARDWARE (reads, aka METHOD_OUT_DIRECT) +// -#define METHOD_DIRECT_TO_HARDWARE METHOD_IN_DIRECT -#define METHOD_DIRECT_FROM_HARDWARE METHOD_OUT_DIRECT +#define METHOD_DIRECT_TO_HARDWARE METHOD_IN_DIRECT +#define METHOD_DIRECT_FROM_HARDWARE METHOD_OUT_DIRECT - // - // Define the access check value for any access - // - // - // The FILE_READ_ACCESS and FILE_WRITE_ACCESS constants are also defined in - // ntioapi.h as FILE_READ_DATA and FILE_WRITE_DATA. The values for these - // constants *MUST* always be in sync. - // - // - // FILE_SPECIAL_ACCESS is checked by the NT I/O system the same as FILE_ANY_ACCESS. - // The file systems, however, may add additional access checks for I/O and FS controls - // that use this value. - // - - -#define FILE_ANY_ACCESS 0 -#define FILE_SPECIAL_ACCESS (FILE_ANY_ACCESS) -#define FILE_READ_ACCESS ( 0x0001 ) // file & pipe -#define FILE_WRITE_ACCESS ( 0x0002 ) // file & pipe #pragma endregion - }; #pragma endregion -#pragma region ntifs.h (public DDK) +#pragma region ntifs.h(public DDK) -extern "C" -{ -#define RtlOffsetToPointer(B,O) ((PCHAR)( ((PCHAR)(B)) + ((ULONG_PTR)(O)) )) +extern "C" { +#define RtlOffsetToPointer(B, O) ((PCHAR)(((PCHAR)(B)) + ((ULONG_PTR)(O)))) - __kernel_entry NTSYSCALLAPI - NTSTATUS +__kernel_entry NTSYSCALLAPI + NTSTATUS NTAPI NtQueryVolumeInformationFile( _In_ HANDLE FileHandle, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _Out_writes_bytes_(Length) PVOID FsInformation, _In_ ULONG Length, - _In_ FS_INFORMATION_CLASS FsInformationClass - ); + _In_ FS_INFORMATION_CLASS FsInformationClass); }; #pragma endregion diff --git a/src/host/conimeinfo.cpp b/src/host/conimeinfo.cpp index 3d7dd98cb..56a813199 100644 --- a/src/host/conimeinfo.cpp +++ b/src/host/conimeinfo.cpp @@ -14,14 +14,13 @@ #include "../types/inc/Utf16Parser.hpp" // Attributes flags: -#define COMMON_LVB_GRID_SINGLEFLAG 0x2000 // DBCS: Grid attribute: use for ime cursor. +#define COMMON_LVB_GRID_SINGLEFLAG 0x2000 // DBCS: Grid attribute: use for ime cursor. using Microsoft::Console::Interactivity::ServiceLocator; ConsoleImeInfo::ConsoleImeInfo() : _isSavedCursorVisible(false) { - } // Routine Description: @@ -121,8 +120,7 @@ void ConsoleImeInfo::ClearAllAreas() // - newSize - New size for conversion areas // Return Value: // - S_OK or appropriate failure HRESULT. -[[nodiscard]] -HRESULT ConsoleImeInfo::ResizeAllAreas(const COORD newSize) +[[nodiscard]] HRESULT ConsoleImeInfo::ResizeAllAreas(const COORD newSize) { for (auto& area : ConvAreaCompStr) { @@ -144,8 +142,7 @@ HRESULT ConsoleImeInfo::ResizeAllAreas(const COORD newSize) // - // Return Value: // - Status successful or appropriate HRESULT response. -[[nodiscard]] -HRESULT ConsoleImeInfo::_AddConversionArea() +[[nodiscard]] HRESULT ConsoleImeInfo::_AddConversionArea() { const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); @@ -456,11 +453,11 @@ void ConsoleImeInfo::_InsertConvertedString(const std::wstring_view text) const DWORD dwControlKeyState = GetControlKeyState(0); std::deque> inEvents; KeyEvent keyEvent{ TRUE, // keydown - 1, // repeatCount - 0, // virtualKeyCode - 0, // virtualScanCode - 0, // charData - dwControlKeyState }; // activeModifierKeys + 1, // repeatCount + 0, // virtualKeyCode + 0, // virtualScanCode + 0, // charData + dwControlKeyState }; // activeModifierKeys for (const auto& ch : text) { diff --git a/src/host/conimeinfo.h b/src/host/conimeinfo.h index 1959bd96f..bdc82847f 100644 --- a/src/host/conimeinfo.h +++ b/src/host/conimeinfo.h @@ -45,8 +45,7 @@ public: void RefreshAreaAttributes(); void ClearAllAreas(); - [[nodiscard]] - HRESULT ResizeAllAreas(const COORD newSize); + [[nodiscard]] HRESULT ResizeAllAreas(const COORD newSize); void WriteCompMessage(const std::wstring_view text, const std::basic_string_view attributes, @@ -57,8 +56,7 @@ public: void RedrawCompMessage(); private: - [[nodiscard]] - HRESULT _AddConversionArea(); + [[nodiscard]] HRESULT _AddConversionArea(); void _ClearComposition(); @@ -77,10 +75,10 @@ private: const std::basic_string_view colorArray); std::vector::const_iterator _WriteConversionArea(const std::vector::const_iterator begin, - const std::vector::const_iterator end, - COORD& pos, - const Microsoft::Console::Types::Viewport view, - SCREEN_INFORMATION& screenInfo); + const std::vector::const_iterator end, + COORD& pos, + const Microsoft::Console::Types::Viewport view, + SCREEN_INFORMATION& screenInfo); void _SaveCursorVisibility(); void _RestoreCursorVisibility(); diff --git a/src/host/conserv.h b/src/host/conserv.h index e5ddce7bf..713e519d3 100644 --- a/src/host/conserv.h +++ b/src/host/conserv.h @@ -36,7 +36,7 @@ Revision History: * bytes. */ -#define PACKCOORD(pt) (MAKELONG(((pt).X), ((pt).Y))) +#define PACKCOORD(pt) (MAKELONG(((pt).X), ((pt).Y))) typedef struct _CONSOLE_API_CONNECTINFO { diff --git a/src/host/consoleInformation.cpp b/src/host/consoleInformation.cpp index 575462953..34d99a10c 100644 --- a/src/host/consoleInformation.cpp +++ b/src/host/consoleInformation.cpp @@ -57,19 +57,19 @@ bool CONSOLE_INFORMATION::IsConsoleLocked() const return _csConsoleLock.OwningThread == (HANDLE)GetCurrentThreadId(); } -#pragma prefast(suppress:26135, "Adding lock annotation spills into entire project. Future work.") +#pragma prefast(suppress : 26135, "Adding lock annotation spills into entire project. Future work.") void CONSOLE_INFORMATION::LockConsole() { EnterCriticalSection(&_csConsoleLock); } -#pragma prefast(suppress:26135, "Adding lock annotation spills into entire project. Future work.") +#pragma prefast(suppress : 26135, "Adding lock annotation spills into entire project. Future work.") bool CONSOLE_INFORMATION::TryLockConsole() { return !!TryEnterCriticalSection(&_csConsoleLock); } -#pragma prefast(suppress:26135, "Adding lock annotation spills into entire project. Future work.") +#pragma prefast(suppress : 26135, "Adding lock annotation spills into entire project. Future work.") void CONSOLE_INFORMATION::UnlockConsole() { LeaveCriticalSection(&_csConsoleLock); @@ -88,8 +88,7 @@ ULONG CONSOLE_INFORMATION::GetCSRecursionCount() // - title - Window Title to display // Return Value: // - STATUS_SUCCESS if successful. -[[nodiscard]] -NTSTATUS CONSOLE_INFORMATION::AllocateConsole(const std::wstring_view title) +[[nodiscard]] NTSTATUS CONSOLE_INFORMATION::AllocateConsole(const std::wstring_view title) { CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); // Synchronize flags @@ -108,7 +107,7 @@ NTSTATUS CONSOLE_INFORMATION::AllocateConsole(const std::wstring_view title) { gci.pInputBuffer = new InputBuffer(); } - catch(...) + catch (...) { return NTSTATUS_FROM_HRESULT(wil::ResultFromCaughtException()); } @@ -378,14 +377,15 @@ Microsoft::Console::CursorBlinker& CONSOLE_INFORMATION::GetCursorBlinker() noexc // - a CHAR_INFO containing legacy information about the cell CHAR_INFO CONSOLE_INFORMATION::AsCharInfo(const OutputCellView& cell) const noexcept { - CHAR_INFO ci { 0 }; + CHAR_INFO ci{ 0 }; ci.Char.UnicodeChar = Utf16ToUcs2(cell.Chars()); // If the current text attributes aren't legacy attributes, then // use gci to look up the correct legacy attributes to use // (for mapping RGB values to the nearest table value) const auto& attr = cell.TextAttr(); - ci.Attributes = GenerateLegacyAttributes(attr);; + ci.Attributes = GenerateLegacyAttributes(attr); + ; ci.Attributes |= cell.DbcsAttr().GeneratePublicApiAttributeFormat(); return ci; } diff --git a/src/host/conv.h b/src/host/conv.h index e72e3724d..b9f7c753a 100644 --- a/src/host/conv.h +++ b/src/host/conv.h @@ -25,7 +25,5 @@ Revision History: void WriteConvRegionToScreen(const SCREEN_INFORMATION& ScreenInfo, const Microsoft::Console::Types::Viewport& convRegion); -[[nodiscard]] -HRESULT ConsoleImeResizeCompStrView(); -[[nodiscard]] -HRESULT ConsoleImeResizeCompStrScreenBuffer(const COORD coordNewScreenSize); +[[nodiscard]] HRESULT ConsoleImeResizeCompStrView(); +[[nodiscard]] HRESULT ConsoleImeResizeCompStrScreenBuffer(const COORD coordNewScreenSize); diff --git a/src/host/convarea.cpp b/src/host/convarea.cpp index d37a96eee..b3f451699 100644 --- a/src/host/convarea.cpp +++ b/src/host/convarea.cpp @@ -77,8 +77,7 @@ void WriteConvRegionToScreen(const SCREEN_INFORMATION& ScreenInfo, } } -[[nodiscard]] -HRESULT ConsoleImeResizeCompStrView() +[[nodiscard]] HRESULT ConsoleImeResizeCompStrView() { try { @@ -91,8 +90,7 @@ HRESULT ConsoleImeResizeCompStrView() return S_OK; } -[[nodiscard]] -HRESULT ConsoleImeResizeCompStrScreenBuffer(const COORD coordNewScreenSize) +[[nodiscard]] HRESULT ConsoleImeResizeCompStrScreenBuffer(const COORD coordNewScreenSize) { CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); ConsoleImeInfo* const pIme = &gci.ConsoleIme; @@ -100,8 +98,7 @@ HRESULT ConsoleImeResizeCompStrScreenBuffer(const COORD coordNewScreenSize) return pIme->ResizeAllAreas(coordNewScreenSize); } -[[nodiscard]] -HRESULT ImeStartComposition() +[[nodiscard]] HRESULT ImeStartComposition() { auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); gci.LockConsole(); @@ -111,8 +108,7 @@ HRESULT ImeStartComposition() return S_OK; } -[[nodiscard]] -HRESULT ImeEndComposition() +[[nodiscard]] HRESULT ImeEndComposition() { auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); gci.LockConsole(); @@ -122,10 +118,9 @@ HRESULT ImeEndComposition() return S_OK; } -[[nodiscard]] -HRESULT ImeComposeData(std::wstring_view text, - std::basic_string_view attributes, - std::basic_string_view colorArray) +[[nodiscard]] HRESULT ImeComposeData(std::wstring_view text, + std::basic_string_view attributes, + std::basic_string_view colorArray) { try { @@ -140,8 +135,7 @@ HRESULT ImeComposeData(std::wstring_view text, return S_OK; } -[[nodiscard]] -HRESULT ImeClearComposeData() +[[nodiscard]] HRESULT ImeClearComposeData() { try { @@ -156,8 +150,7 @@ HRESULT ImeClearComposeData() return S_OK; } -[[nodiscard]] -HRESULT ImeComposeResult(std::wstring_view text) +[[nodiscard]] HRESULT ImeComposeResult(std::wstring_view text) { try { diff --git a/src/host/conwinuserrefs.h b/src/host/conwinuserrefs.h index 130ae2440..63ac131b3 100644 --- a/src/host/conwinuserrefs.h +++ b/src/host/conwinuserrefs.h @@ -11,74 +11,79 @@ Abstract: #pragma once -#pragma region WinUserK.h (private internal) +#pragma region WinUserK.h(private internal) -extern "C" +extern "C" { +/* WinUserK */ +/* + * Console window startup optimization. + */ + +typedef enum _CONSOLECONTROL { - /* WinUserK */ - /* + Reserved1, + ConsoleNotifyConsoleApplication, + Reserved2, + ConsoleSetCaretInfo, + Reserved3, + ConsoleSetForeground, + ConsoleSetWindowOwner, + ConsoleEndTask, +} CONSOLECONTROL; + +// +// CtrlFlags definitions +// +#define CONSOLE_CTRL_C_FLAG 0x00000001 +#define CONSOLE_CTRL_BREAK_FLAG 0x00000002 +#define CONSOLE_CTRL_CLOSE_FLAG 0x00000004 + +#define CONSOLE_CTRL_LOGOFF_FLAG 0x00000010 +#define CONSOLE_CTRL_SHUTDOWN_FLAG 0x00000020 + +typedef struct _CONSOLEENDTASK +{ + HANDLE ProcessId; + HWND hwnd; + ULONG ConsoleEventCode; + ULONG ConsoleFlags; +} CONSOLEENDTASK, *PCONSOLEENDTASK; + +typedef struct _CONSOLEWINDOWOWNER +{ + HWND hwnd; + ULONG ProcessId; + ULONG ThreadId; +} CONSOLEWINDOWOWNER, *PCONSOLEWINDOWOWNER; + +typedef struct _CONSOLESETFOREGROUND +{ + HANDLE hProcess; + BOOL bForeground; +} CONSOLESETFOREGROUND, *PCONSOLESETFOREGROUND; + +/* * Console window startup optimization. */ +#define CPI_NEWPROCESSWINDOW 0x0001 - typedef enum _CONSOLECONTROL { - Reserved1, - ConsoleNotifyConsoleApplication, - Reserved2, - ConsoleSetCaretInfo, - Reserved3, - ConsoleSetForeground, - ConsoleSetWindowOwner, - ConsoleEndTask, - } CONSOLECONTROL; +typedef struct _CONSOLE_PROCESS_INFO +{ + IN DWORD dwProcessID; + IN DWORD dwFlags; +} CONSOLE_PROCESS_INFO, *PCONSOLE_PROCESS_INFO; - // - // CtrlFlags definitions - // -#define CONSOLE_CTRL_C_FLAG 0x00000001 -#define CONSOLE_CTRL_BREAK_FLAG 0x00000002 -#define CONSOLE_CTRL_CLOSE_FLAG 0x00000004 +typedef struct _CONSOLE_CARET_INFO +{ + IN HWND hwnd; + IN RECT rc; +} CONSOLE_CARET_INFO, *PCONSOLE_CARET_INFO; -#define CONSOLE_CTRL_LOGOFF_FLAG 0x00000010 -#define CONSOLE_CTRL_SHUTDOWN_FLAG 0x00000020 +NTSTATUS ConsoleControl( + __in CONSOLECONTROL Command, + __in_bcount_opt(ConsoleInformationLength) PVOID ConsoleInformation, + __in DWORD ConsoleInformationLength); - typedef struct _CONSOLEENDTASK { - HANDLE ProcessId; - HWND hwnd; - ULONG ConsoleEventCode; - ULONG ConsoleFlags; - } CONSOLEENDTASK, *PCONSOLEENDTASK; - - typedef struct _CONSOLEWINDOWOWNER { - HWND hwnd; - ULONG ProcessId; - ULONG ThreadId; - } CONSOLEWINDOWOWNER, *PCONSOLEWINDOWOWNER; - - typedef struct _CONSOLESETFOREGROUND { - HANDLE hProcess; - BOOL bForeground; - } CONSOLESETFOREGROUND, *PCONSOLESETFOREGROUND; - - /* - * Console window startup optimization. - */ -#define CPI_NEWPROCESSWINDOW 0x0001 - - typedef struct _CONSOLE_PROCESS_INFO { - IN DWORD dwProcessID; - IN DWORD dwFlags; - } CONSOLE_PROCESS_INFO, *PCONSOLE_PROCESS_INFO; - - typedef struct _CONSOLE_CARET_INFO { - IN HWND hwnd; - IN RECT rc; - } CONSOLE_CARET_INFO, *PCONSOLE_CARET_INFO; - - NTSTATUS ConsoleControl( - __in CONSOLECONTROL Command, - __in_bcount_opt(ConsoleInformationLength) PVOID ConsoleInformation, - __in DWORD ConsoleInformationLength); - - /* END WinUserK */ +/* END WinUserK */ }; #pragma endregion diff --git a/src/host/dbcs.cpp b/src/host/dbcs.cpp index f85e32fce..e04c83361 100644 --- a/src/host/dbcs.cpp +++ b/src/host/dbcs.cpp @@ -21,7 +21,7 @@ using Microsoft::Console::Interactivity::ServiceLocator; // Return Value: // - TRUE - Bisected character. // - FALSE - Correctly. -bool CheckBisectStringA(_In_reads_bytes_(cbBuf) PCHAR pchBuf, _In_ DWORD cbBuf, const CPINFO * const pCPInfo) +bool CheckBisectStringA(_In_reads_bytes_(cbBuf) PCHAR pchBuf, _In_ DWORD cbBuf, const CPINFO* const pCPInfo) { while (cbBuf) { @@ -102,7 +102,7 @@ DWORD UnicodeRasterFontCellMungeOnRead(const gsl::span buffer) // - pCPInfo - the code page to check the char in. // Return Value: // true if ch is a lead byte, false otherwise. -bool IsDBCSLeadByteConsole(const CHAR ch, const CPINFO * const pCPInfo) +bool IsDBCSLeadByteConsole(const CHAR ch, const CPINFO* const pCPInfo) { FAIL_FAST_IF_NULL(pCPInfo); // NOTE: This must be unsigned for the comparison. If we compare signed, this will never hit @@ -128,12 +128,12 @@ BYTE CodePageToCharSet(const UINT uiCodePage) CHARSETINFO csi; const auto inputServices = ServiceLocator::LocateInputServices(); - if (nullptr == inputServices || !inputServices->TranslateCharsetInfo((DWORD *) IntToPtr(uiCodePage), &csi, TCI_SRCCODEPAGE)) + if (nullptr == inputServices || !inputServices->TranslateCharsetInfo((DWORD*)IntToPtr(uiCodePage), &csi, TCI_SRCCODEPAGE)) { csi.ciCharset = OEM_CHARSET; } - return (BYTE) csi.ciCharset; + return (BYTE)csi.ciCharset; } BOOL IsAvailableEastAsianCodePage(const UINT uiCodePage) @@ -153,20 +153,20 @@ BOOL IsAvailableEastAsianCodePage(const UINT uiCodePage) } _Ret_range_(0, cbAnsi) -ULONG TranslateUnicodeToOem(_In_reads_(cchUnicode) PCWCHAR pwchUnicode, - const ULONG cchUnicode, - _Out_writes_bytes_(cbAnsi) PCHAR pchAnsi, - const ULONG cbAnsi, - _Out_ std::unique_ptr& partialEvent) + ULONG TranslateUnicodeToOem(_In_reads_(cchUnicode) PCWCHAR pwchUnicode, + const ULONG cchUnicode, + _Out_writes_bytes_(cbAnsi) PCHAR pchAnsi, + const ULONG cbAnsi, + _Out_ std::unique_ptr& partialEvent) { const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); - PWCHAR const TmpUni = new(std::nothrow) WCHAR[cchUnicode]; + PWCHAR const TmpUni = new (std::nothrow) WCHAR[cchUnicode]; if (TmpUni == nullptr) { return 0; } - memcpy(TmpUni, pwchUnicode, cchUnicode* sizeof(WCHAR)); + memcpy(TmpUni, pwchUnicode, cchUnicode * sizeof(WCHAR)); BYTE AsciiDbcs[2]; AsciiDbcs[1] = 0; @@ -177,11 +177,11 @@ ULONG TranslateUnicodeToOem(_In_reads_(cchUnicode) PCWCHAR pwchUnicode, if (IsGlyphFullWidth(TmpUni[i])) { ULONG const NumBytes = sizeof(AsciiDbcs); - ConvertToOem(gci.CP, &TmpUni[i], 1, (LPSTR) & AsciiDbcs[0], NumBytes); + ConvertToOem(gci.CP, &TmpUni[i], 1, (LPSTR)&AsciiDbcs[0], NumBytes); if (IsDBCSLeadByteConsole(AsciiDbcs[0], &gci.CPInfo)) { if (j < cbAnsi - 1) - { // -1 is safe DBCS in buffer + { // -1 is safe DBCS in buffer pchAnsi[j] = AsciiDbcs[0]; j++; pchAnsi[j] = AsciiDbcs[1]; diff --git a/src/host/dbcs.h b/src/host/dbcs.h index 7076506f4..53762d118 100644 --- a/src/host/dbcs.h +++ b/src/host/dbcs.h @@ -20,19 +20,19 @@ Revision History: #include "screenInfo.hpp" -bool CheckBisectStringA(_In_reads_bytes_(cbBuf) PCHAR pchBuf, _In_ DWORD cbBuf, const CPINFO * const pCPInfo); +bool CheckBisectStringA(_In_reads_bytes_(cbBuf) PCHAR pchBuf, _In_ DWORD cbBuf, const CPINFO* const pCPInfo); DWORD UnicodeRasterFontCellMungeOnRead(const gsl::span buffer); -bool IsDBCSLeadByteConsole(const CHAR ch, const CPINFO * const pCPInfo); +bool IsDBCSLeadByteConsole(const CHAR ch, const CPINFO* const pCPInfo); BYTE CodePageToCharSet(const UINT uiCodePage); BOOL IsAvailableEastAsianCodePage(const UINT uiCodePage); _Ret_range_(0, cbAnsi) -ULONG TranslateUnicodeToOem(_In_reads_(cchUnicode) PCWCHAR pwchUnicode, - const ULONG cchUnicode, - _Out_writes_bytes_(cbAnsi) PCHAR pchAnsi, - const ULONG cbAnsi, - _Out_ std::unique_ptr& partialEvent); + ULONG TranslateUnicodeToOem(_In_reads_(cchUnicode) PCWCHAR pwchUnicode, + const ULONG cchUnicode, + _Out_writes_bytes_(cbAnsi) PCHAR pchAnsi, + const ULONG cbAnsi, + _Out_ std::unique_ptr& partialEvent); diff --git a/src/host/directio.cpp b/src/host/directio.cpp index 620c228f7..645b28e2f 100644 --- a/src/host/directio.cpp +++ b/src/host/directio.cpp @@ -74,8 +74,7 @@ void EventsToUnicode(_Inout_ std::deque>& inEvents, const KeyEvent* const keyEventEndByte = static_cast(inEvents.front().get()); inEvents.pop_front(); - char inBytes[] = - { + char inBytes[] = { static_cast(keyEvent->GetCharData()), static_cast(keyEventEndByte->GetCharData()) }; @@ -90,8 +89,7 @@ void EventsToUnicode(_Inout_ std::deque>& inEvents, } else { - char inBytes[] = - { + char inBytes[] = { static_cast(keyEvent->GetCharData()) }; try @@ -153,14 +151,13 @@ void EventsToUnicode(_Inout_ std::deque>& inEvents, // - CONSOLE_STATUS_WAIT - If we didn't have enough data or needed to // block, this will be returned along with context in *ppWaiter. // - Or an out of memory/math/string error message in NTSTATUS format. -[[nodiscard]] -static NTSTATUS _DoGetConsoleInput(InputBuffer& inputBuffer, - std::deque>& outEvents, - const size_t eventReadCount, - INPUT_READ_HANDLE_DATA& readHandleState, - const bool IsUnicode, - const bool IsPeek, - std::unique_ptr& waiter) noexcept +[[nodiscard]] static NTSTATUS _DoGetConsoleInput(InputBuffer& inputBuffer, + std::deque>& outEvents, + const size_t eventReadCount, + INPUT_READ_HANDLE_DATA& readHandleState, + const bool IsUnicode, + const bool IsPeek, + std::unique_ptr& waiter) noexcept { try { @@ -268,12 +265,11 @@ static NTSTATUS _DoGetConsoleInput(InputBuffer& inputBuffer, // - waiter - If we have to wait (not enough data to fill client // buffer), this contains context that will allow the server to // restore this call later. -[[nodiscard]] -HRESULT ApiRoutines::PeekConsoleInputAImpl(IConsoleInputObject& context, - std::deque>& outEvents, - const size_t eventsToRead, - INPUT_READ_HANDLE_DATA& readHandleState, - std::unique_ptr& waiter) noexcept +[[nodiscard]] HRESULT ApiRoutines::PeekConsoleInputAImpl(IConsoleInputObject& context, + std::deque>& outEvents, + const size_t eventsToRead, + INPUT_READ_HANDLE_DATA& readHandleState, + std::unique_ptr& waiter) noexcept { try { @@ -304,12 +300,11 @@ HRESULT ApiRoutines::PeekConsoleInputAImpl(IConsoleInputObject& context, // - waiter - If we have to wait (not enough data to fill client // buffer), this contains context that will allow the server to // restore this call later. -[[nodiscard]] -HRESULT ApiRoutines::PeekConsoleInputWImpl(IConsoleInputObject& context, - std::deque>& outEvents, - const size_t eventsToRead, - INPUT_READ_HANDLE_DATA& readHandleState, - std::unique_ptr& waiter) noexcept +[[nodiscard]] HRESULT ApiRoutines::PeekConsoleInputWImpl(IConsoleInputObject& context, + std::deque>& outEvents, + const size_t eventsToRead, + INPUT_READ_HANDLE_DATA& readHandleState, + std::unique_ptr& waiter) noexcept { try { @@ -340,12 +335,11 @@ HRESULT ApiRoutines::PeekConsoleInputWImpl(IConsoleInputObject& context, // - waiter - If we have to wait (not enough data to fill client // buffer), this contains context that will allow the server to // restore this call later. -[[nodiscard]] -HRESULT ApiRoutines::ReadConsoleInputAImpl(IConsoleInputObject& context, - std::deque>& outEvents, - const size_t eventsToRead, - INPUT_READ_HANDLE_DATA& readHandleState, - std::unique_ptr& waiter) noexcept +[[nodiscard]] HRESULT ApiRoutines::ReadConsoleInputAImpl(IConsoleInputObject& context, + std::deque>& outEvents, + const size_t eventsToRead, + INPUT_READ_HANDLE_DATA& readHandleState, + std::unique_ptr& waiter) noexcept { try { @@ -376,12 +370,11 @@ HRESULT ApiRoutines::ReadConsoleInputAImpl(IConsoleInputObject& context, // - waiter - If we have to wait (not enough data to fill client // buffer), this contains context that will allow the server to // restore this call later. -[[nodiscard]] -HRESULT ApiRoutines::ReadConsoleInputWImpl(IConsoleInputObject& context, - std::deque>& outEvents, - const size_t eventsToRead, - INPUT_READ_HANDLE_DATA& readHandleState, - std::unique_ptr& waiter) noexcept +[[nodiscard]] HRESULT ApiRoutines::ReadConsoleInputWImpl(IConsoleInputObject& context, + std::deque>& outEvents, + const size_t eventsToRead, + INPUT_READ_HANDLE_DATA& readHandleState, + std::unique_ptr& waiter) noexcept { try { @@ -406,11 +399,10 @@ HRESULT ApiRoutines::ReadConsoleInputWImpl(IConsoleInputObject& context, // buffer, false if they should be written to the front // Return Value: // - HRESULT indicating success or failure -[[nodiscard]] -static HRESULT _WriteConsoleInputWImplHelper(InputBuffer& context, - std::deque>& events, - size_t& written, - const bool append) noexcept +[[nodiscard]] static HRESULT _WriteConsoleInputWImplHelper(InputBuffer& context, + std::deque>& events, + size_t& written, + const bool append) noexcept { try { @@ -441,11 +433,10 @@ static HRESULT _WriteConsoleInputWImplHelper(InputBuffer& context, // buffer, false if they should be written to the front // Return Value: // - HRESULT indicating success or failure -[[nodiscard]] -HRESULT DoSrvPrivateWriteConsoleInputW(_Inout_ InputBuffer* const pInputBuffer, - _Inout_ std::deque>& events, - _Out_ size_t& eventsWritten, - const bool append) noexcept +[[nodiscard]] HRESULT DoSrvPrivateWriteConsoleInputW(_Inout_ InputBuffer* const pInputBuffer, + _Inout_ std::deque>& events, + _Out_ size_t& eventsWritten, + const bool append) noexcept { return _WriteConsoleInputWImplHelper(*pInputBuffer, events, eventsWritten, append); } @@ -460,11 +451,10 @@ HRESULT DoSrvPrivateWriteConsoleInputW(_Inout_ InputBuffer* const pInputBuffer, // buffer, false if they should be written to the front // Return Value: // - HRESULT indicating success or failure -[[nodiscard]] -HRESULT ApiRoutines::WriteConsoleInputAImpl(InputBuffer& context, - const std::basic_string_view buffer, - size_t& written, - const bool append) noexcept +[[nodiscard]] HRESULT ApiRoutines::WriteConsoleInputAImpl(InputBuffer& context, + const std::basic_string_view buffer, + size_t& written, + const bool append) noexcept { written = 0; @@ -505,11 +495,10 @@ HRESULT ApiRoutines::WriteConsoleInputAImpl(InputBuffer& context, // buffer, false if they should be written to the front // Return Value: // - HRESULT indicating success or failure -[[nodiscard]] -HRESULT ApiRoutines::WriteConsoleInputWImpl(InputBuffer& context, - const std::basic_string_view buffer, - size_t& written, - const bool append) noexcept +[[nodiscard]] HRESULT ApiRoutines::WriteConsoleInputWImpl(InputBuffer& context, + const std::basic_string_view buffer, + size_t& written, + const bool append) noexcept { written = 0; @@ -535,10 +524,9 @@ HRESULT ApiRoutines::WriteConsoleInputWImpl(InputBuffer& context, // - eventsWritten - on output, the number of events written // Return Value: // - HRESULT indicating success or failure -[[nodiscard]] -HRESULT DoSrvPrivatePrependConsoleInput(_Inout_ InputBuffer* const pInputBuffer, - _Inout_ std::deque>& events, - _Out_ size_t& eventsWritten) +[[nodiscard]] HRESULT DoSrvPrivatePrependConsoleInput(_Inout_ InputBuffer* const pInputBuffer, + _Inout_ std::deque>& events, + _Out_ size_t& eventsWritten) { LockConsole(); auto Unlock = wil::scope_exit([&] { UnlockConsole(); }); @@ -576,9 +564,8 @@ HRESULT DoSrvPrivatePrependConsoleInput(_Inout_ InputBuffer* const pInputBuffer, // - key - The keyevent to send to the console. // Return Value: // - HRESULT indicating success or failure -[[nodiscard]] -HRESULT DoSrvPrivateWriteConsoleControlInput(_Inout_ InputBuffer* const /*pInputBuffer*/, - _In_ KeyEvent key) +[[nodiscard]] HRESULT DoSrvPrivateWriteConsoleControlInput(_Inout_ InputBuffer* const /*pInputBuffer*/, + _In_ KeyEvent key) { LockConsole(); auto Unlock = wil::scope_exit([&] { UnlockConsole(); }); @@ -597,8 +584,9 @@ HRESULT DoSrvPrivateWriteConsoleControlInput(_Inout_ InputBuffer* const /*pInput // - rectangle - This is the rectangle describing the region that the buffer covers. // Return Value: // - Generally S_OK. Could be a memory or math error code. -[[nodiscard]] -static HRESULT _ConvertCellsToAInplace(const UINT codepage, const gsl::span buffer, const Viewport rectangle) noexcept +[[nodiscard]] static HRESULT _ConvertCellsToAInplace(const UINT codepage, + const gsl::span buffer, + const Viewport rectangle) noexcept { try { @@ -675,8 +663,9 @@ static HRESULT _ConvertCellsToAInplace(const UINT codepage, const gsl::span buffer, const Viewport& rectangle) noexcept +[[nodiscard]] static HRESULT _ConvertCellsToWInplace(const UINT codepage, + gsl::span buffer, + const Viewport& rectangle) noexcept { try { @@ -746,8 +735,7 @@ static HRESULT _ConvertCellsToWInplace(const UINT codepage, gsl::span CATCH_RETURN(); } -[[nodiscard]] -static std::vector _ConvertCellsToMungedW(gsl::span buffer, const Viewport& rectangle) +[[nodiscard]] static std::vector _ConvertCellsToMungedW(gsl::span buffer, const Viewport& rectangle) { std::vector result; result.reserve(buffer.size() * 2); // we estimate we'll need up to double the cells if they all expand. @@ -783,7 +771,6 @@ static std::vector _ConvertCellsToMungedW(gsl::span buffer candidate.Attributes = bufferIter->Attributes; WI_ClearAllFlags(candidate.Attributes, COMMON_LVB_SBCSDBCS); WI_SetFlag(candidate.Attributes, COMMON_LVB_TRAILING_BYTE); - } else { @@ -807,11 +794,10 @@ static std::vector _ConvertCellsToMungedW(gsl::span buffer return result; } -[[nodiscard]] -static HRESULT _ReadConsoleOutputWImplHelper(const SCREEN_INFORMATION& context, - gsl::span targetBuffer, - const Microsoft::Console::Types::Viewport& requestRectangle, - Microsoft::Console::Types::Viewport& readRectangle) noexcept +[[nodiscard]] static HRESULT _ReadConsoleOutputWImplHelper(const SCREEN_INFORMATION& context, + gsl::span targetBuffer, + const Microsoft::Console::Types::Viewport& requestRectangle, + Microsoft::Console::Types::Viewport& readRectangle) noexcept { try { @@ -900,11 +886,10 @@ static HRESULT _ReadConsoleOutputWImplHelper(const SCREEN_INFORMATION& context, CATCH_RETURN(); } -[[nodiscard]] -HRESULT ApiRoutines::ReadConsoleOutputAImpl(const SCREEN_INFORMATION& context, - gsl::span buffer, - const Microsoft::Console::Types::Viewport& sourceRectangle, - Microsoft::Console::Types::Viewport& readRectangle) noexcept +[[nodiscard]] HRESULT ApiRoutines::ReadConsoleOutputAImpl(const SCREEN_INFORMATION& context, + gsl::span buffer, + const Microsoft::Console::Types::Viewport& sourceRectangle, + Microsoft::Console::Types::Viewport& readRectangle) noexcept { LockConsole(); auto Unlock = wil::scope_exit([&] { UnlockConsole(); }); @@ -923,11 +908,10 @@ HRESULT ApiRoutines::ReadConsoleOutputAImpl(const SCREEN_INFORMATION& context, CATCH_RETURN(); } -[[nodiscard]] -HRESULT ApiRoutines::ReadConsoleOutputWImpl(const SCREEN_INFORMATION& context, - gsl::span buffer, - const Microsoft::Console::Types::Viewport& sourceRectangle, - Microsoft::Console::Types::Viewport& readRectangle) noexcept +[[nodiscard]] HRESULT ApiRoutines::ReadConsoleOutputWImpl(const SCREEN_INFORMATION& context, + gsl::span buffer, + const Microsoft::Console::Types::Viewport& sourceRectangle, + Microsoft::Console::Types::Viewport& readRectangle) noexcept { LockConsole(); auto Unlock = wil::scope_exit([&] { UnlockConsole(); }); @@ -948,11 +932,10 @@ HRESULT ApiRoutines::ReadConsoleOutputWImpl(const SCREEN_INFORMATION& context, CATCH_RETURN(); } -[[nodiscard]] -static HRESULT _WriteConsoleOutputWImplHelper(SCREEN_INFORMATION& context, - gsl::span buffer, - const Viewport& requestRectangle, - Viewport& writtenRectangle) noexcept +[[nodiscard]] static HRESULT _WriteConsoleOutputWImplHelper(SCREEN_INFORMATION& context, + gsl::span buffer, + const Viewport& requestRectangle, + Viewport& writtenRectangle) noexcept { try { @@ -1055,11 +1038,10 @@ static HRESULT _WriteConsoleOutputWImplHelper(SCREEN_INFORMATION& context, CATCH_RETURN(); } -[[nodiscard]] -HRESULT ApiRoutines::WriteConsoleOutputAImpl(SCREEN_INFORMATION& context, - gsl::span buffer, - const Viewport& requestRectangle, - Viewport& writtenRectangle) noexcept +[[nodiscard]] HRESULT ApiRoutines::WriteConsoleOutputAImpl(SCREEN_INFORMATION& context, + gsl::span buffer, + const Viewport& requestRectangle, + Viewport& writtenRectangle) noexcept { LockConsole(); auto Unlock = wil::scope_exit([&] { UnlockConsole(); }); @@ -1077,11 +1059,10 @@ HRESULT ApiRoutines::WriteConsoleOutputAImpl(SCREEN_INFORMATION& context, CATCH_RETURN(); } -[[nodiscard]] -HRESULT ApiRoutines::WriteConsoleOutputWImpl(SCREEN_INFORMATION& context, - gsl::span buffer, - const Viewport& requestRectangle, - Viewport& writtenRectangle) noexcept +[[nodiscard]] HRESULT ApiRoutines::WriteConsoleOutputWImpl(SCREEN_INFORMATION& context, + gsl::span buffer, + const Viewport& requestRectangle, + Viewport& writtenRectangle) noexcept { LockConsole(); auto Unlock = wil::scope_exit([&] { UnlockConsole(); }); @@ -1105,11 +1086,10 @@ HRESULT ApiRoutines::WriteConsoleOutputWImpl(SCREEN_INFORMATION& context, CATCH_RETURN(); } -[[nodiscard]] -HRESULT ApiRoutines::ReadConsoleOutputAttributeImpl(const SCREEN_INFORMATION& context, - const COORD origin, - gsl::span buffer, - size_t& written) noexcept +[[nodiscard]] HRESULT ApiRoutines::ReadConsoleOutputAttributeImpl(const SCREEN_INFORMATION& context, + const COORD origin, + gsl::span buffer, + size_t& written) noexcept { written = 0; @@ -1127,11 +1107,10 @@ HRESULT ApiRoutines::ReadConsoleOutputAttributeImpl(const SCREEN_INFORMATION& co CATCH_RETURN(); } -[[nodiscard]] -HRESULT ApiRoutines::ReadConsoleOutputCharacterAImpl(const SCREEN_INFORMATION& context, - const COORD origin, - gsl::span buffer, - size_t& written) noexcept +[[nodiscard]] HRESULT ApiRoutines::ReadConsoleOutputCharacterAImpl(const SCREEN_INFORMATION& context, + const COORD origin, + gsl::span buffer, + size_t& written) noexcept { written = 0; @@ -1145,7 +1124,7 @@ HRESULT ApiRoutines::ReadConsoleOutputCharacterAImpl(const SCREEN_INFORMATION& c buffer.size()); // for compatibility reasons, if we receive more chars than can fit in the buffer - // then we don't send anything back. + // then we don't send anything back. if (chars.size() <= gsl::narrow(buffer.size())) { std::copy(chars.cbegin(), chars.cend(), buffer.begin()); @@ -1157,11 +1136,10 @@ HRESULT ApiRoutines::ReadConsoleOutputCharacterAImpl(const SCREEN_INFORMATION& c CATCH_RETURN(); } -[[nodiscard]] -HRESULT ApiRoutines::ReadConsoleOutputCharacterWImpl(const SCREEN_INFORMATION& context, - const COORD origin, - gsl::span buffer, - size_t& written) noexcept +[[nodiscard]] HRESULT ApiRoutines::ReadConsoleOutputCharacterWImpl(const SCREEN_INFORMATION& context, + const COORD origin, + gsl::span buffer, + size_t& written) noexcept { written = 0; @@ -1197,11 +1175,10 @@ HRESULT ApiRoutines::ReadConsoleOutputCharacterWImpl(const SCREEN_INFORMATION& c //#define CONSOLE_GRAPHICS_BUFFER 2 //#define CONSOLE_OEMFONT_DISPLAY 4 -[[nodiscard]] -NTSTATUS ConsoleCreateScreenBuffer(std::unique_ptr& handle, - _In_ PCONSOLE_API_MSG /*Message*/, - _In_ PCD_CREATE_OBJECT_INFORMATION Information, - _In_ PCONSOLE_CREATESCREENBUFFER_MSG a) +[[nodiscard]] NTSTATUS ConsoleCreateScreenBuffer(std::unique_ptr& handle, + _In_ PCONSOLE_API_MSG /*Message*/, + _In_ PCD_CREATE_OBJECT_INFORMATION Information, + _In_ PCONSOLE_CREATESCREENBUFFER_MSG a) { Telemetry::Instance().LogApiCall(Telemetry::ApiCall::CreateConsoleScreenBuffer); const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); diff --git a/src/host/directio.h b/src/host/directio.h index 045d84d1a..e4b6a2954 100644 --- a/src/host/directio.h +++ b/src/host/directio.h @@ -21,23 +21,19 @@ Revision History: class SCREEN_INFORMATION; -[[nodiscard]] -HRESULT DoSrvPrivateWriteConsoleInputW(_Inout_ InputBuffer* const pInputBuffer, - _Inout_ std::deque>& events, - _Out_ size_t& eventsWritten, - const bool append) noexcept; +[[nodiscard]] HRESULT DoSrvPrivateWriteConsoleInputW(_Inout_ InputBuffer* const pInputBuffer, + _Inout_ std::deque>& events, + _Out_ size_t& eventsWritten, + const bool append) noexcept; -[[nodiscard]] -NTSTATUS ConsoleCreateScreenBuffer(std::unique_ptr& handle, - _In_ PCONSOLE_API_MSG Message, - _In_ PCD_CREATE_OBJECT_INFORMATION Information, - _In_ PCONSOLE_CREATESCREENBUFFER_MSG a); +[[nodiscard]] NTSTATUS ConsoleCreateScreenBuffer(std::unique_ptr& handle, + _In_ PCONSOLE_API_MSG Message, + _In_ PCD_CREATE_OBJECT_INFORMATION Information, + _In_ PCONSOLE_CREATESCREENBUFFER_MSG a); -[[nodiscard]] -NTSTATUS DoSrvPrivatePrependConsoleInput(_Inout_ InputBuffer* const pInputBuffer, - _Inout_ std::deque>& events, - _Out_ size_t& eventsWritten); +[[nodiscard]] NTSTATUS DoSrvPrivatePrependConsoleInput(_Inout_ InputBuffer* const pInputBuffer, + _Inout_ std::deque>& events, + _Out_ size_t& eventsWritten); -[[nodiscard]] -NTSTATUS DoSrvPrivateWriteConsoleControlInput(_Inout_ InputBuffer* const pInputBuffer, - _In_ KeyEvent key); +[[nodiscard]] NTSTATUS DoSrvPrivateWriteConsoleControlInput(_Inout_ InputBuffer* const pInputBuffer, + _In_ KeyEvent key); diff --git a/src/host/exe/resource.h b/src/host/exe/resource.h index c578529e2..7d34af61b 100644 --- a/src/host/exe/resource.h +++ b/src/host/exe/resource.h @@ -3,12 +3,12 @@ // Used by Host.EXE.rc #include "..\\resource.h" // Next default values for new objects -// +// #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 103 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1001 -#define _APS_NEXT_SYMED_VALUE 101 +#define _APS_NEXT_RESOURCE_VALUE 103 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 #endif #endif diff --git a/src/host/exemain.cpp b/src/host/exemain.cpp index 5fe4fbbca..c67049948 100644 --- a/src/host/exemain.cpp +++ b/src/host/exemain.cpp @@ -40,10 +40,9 @@ static bool ShouldUseConhostV2() (PBYTE)&dwValue, &cbValue); - if (ERROR_SUCCESS == lStatus && - dwType == REG_DWORD && // response is a DWORD - cbValue == sizeof(dwValue)) // response data exists + dwType == REG_DWORD && // response is a DWORD + cbValue == sizeof(dwValue)) // response data exists { // Value exists. If non-zero use v2 console. fShouldUseConhostV2 = dwValue != 0; @@ -64,8 +63,7 @@ static bool ShouldUseConhostV2() return fShouldUseConhostV2; } -[[nodiscard]] -static HRESULT ValidateServerHandle(const HANDLE handle) +[[nodiscard]] static HRESULT ValidateServerHandle(const HANDLE handle) { // Make sure this is a console file. FILE_FS_DEVICE_INFORMATION DeviceInformation; @@ -90,8 +88,7 @@ static bool ShouldUseLegacyConhost(const bool fForceV1) return fForceV1 || !ShouldUseConhostV2(); } -[[nodiscard]] -static HRESULT ActivateLegacyConhost(const HANDLE handle) +[[nodiscard]] static HRESULT ActivateLegacyConhost(const HANDLE handle) { HRESULT hr = S_OK; @@ -99,9 +96,7 @@ static HRESULT ActivateLegacyConhost(const HANDLE handle) // because there's already a count of how many total processes were launched. // Total - legacy = new console. // We expect legacy launches to be infrequent enough to not cause an issue. - TraceLoggingWrite(g_ConhostLauncherProvider, "IsLegacyLoaded", - TraceLoggingBool(true, "ConsoleLegacy"), - TraceLoggingKeyword(MICROSOFT_KEYWORD_TELEMETRY)); + TraceLoggingWrite(g_ConhostLauncherProvider, "IsLegacyLoaded", TraceLoggingBool(true, "ConsoleLegacy"), TraceLoggingKeyword(MICROSOFT_KEYWORD_TELEMETRY)); PCWSTR pszConhostDllName = L"ConhostV1.dll"; @@ -109,7 +104,7 @@ static HRESULT ActivateLegacyConhost(const HANDLE handle) wil::unique_hmodule hConhostBin(LoadLibraryExW(pszConhostDllName, NULL, LOAD_LIBRARY_SEARCH_SYSTEM32)); if (hConhostBin.get() != nullptr) { - typedef NTSTATUS(*PFNCONSOLECREATEIOTHREAD)(__in HANDLE Server); + typedef NTSTATUS (*PFNCONSOLECREATEIOTHREAD)(__in HANDLE Server); PFNCONSOLECREATEIOTHREAD pfnConsoleCreateIoThread = (PFNCONSOLECREATEIOTHREAD)GetProcAddress(hConhostBin.get(), "ConsoleCreateIoThread"); if (pfnConsoleCreateIoThread != nullptr) diff --git a/src/host/ft_host/API_AliasTests.cpp b/src/host/ft_host/API_AliasTests.cpp index 3d3dfc1e5..833159e7d 100644 --- a/src/host/ft_host/API_AliasTests.cpp +++ b/src/host/ft_host/API_AliasTests.cpp @@ -147,6 +147,5 @@ void AliasTests::TestGetConsoleAlias() dwExeName, bUnicode, bSetFirst); - } } diff --git a/src/host/ft_host/API_AliasTestsHelpers.hpp b/src/host/ft_host/API_AliasTestsHelpers.hpp index e24dea52d..bfbccc9d9 100644 --- a/src/host/ft_host/API_AliasTestsHelpers.hpp +++ b/src/host/ft_host/API_AliasTestsHelpers.hpp @@ -136,8 +136,7 @@ void TestGetConsoleAliasHelper(TCH* ptszSourceGiven, ZeroMemory(ptchTargetBuffer, cbTargetBuffer); } - auto freeTargetBuffer = wil::scope_exit([&]() - { + auto freeTargetBuffer = wil::scope_exit([&]() { if (ptchTargetBuffer != nullptr) { delete[] ptchTargetBuffer; @@ -193,10 +192,10 @@ void TestGetConsoleAliasHelper(TCH* ptszSourceGiven, // If the target isn't enough space, insufficient buffer. dwExpectedResult = cbTargetBuffer; - // For some reason, the console API *ALWAYS* says it needs enough space as if we were copying Unicode, - // even if the final result will be ANSI. - // Therefore, if we're mathing based on a char size buffer, multiple the expected result by 2. - #pragma warning(suppress:4127) // This is a constant, but conditionally compiled twice so we need the check. +// For some reason, the console API *ALWAYS* says it needs enough space as if we were copying Unicode, +// even if the final result will be ANSI. +// Therefore, if we're mathing based on a char size buffer, multiple the expected result by 2. +#pragma warning(suppress : 4127) // This is a constant, but conditionally compiled twice so we need the check. if (1 == sizeof(TCH)) { dwExpectedResult *= sizeof(wchar_t); diff --git a/src/host/ft_host/API_BufferTests.cpp b/src/host/ft_host/API_BufferTests.cpp index aebad2234..706dda1e0 100644 --- a/src/host/ft_host/API_BufferTests.cpp +++ b/src/host/ft_host/API_BufferTests.cpp @@ -26,7 +26,7 @@ class BufferTests BEGIN_TEST_METHOD(TestWritingInactiveScreenBuffer) TEST_METHOD_PROPERTY(L"Data:UseVtOutput", L"{true, false}") END_TEST_METHOD() - + TEST_METHOD(ScrollLargeBufferPerformance); TEST_METHOD(ChafaGifPerformance); @@ -97,7 +97,6 @@ void BufferTests::TestWritingInactiveScreenBuffer() VERIFY_WIN32_BOOL_SUCCEEDED(ReadConsoleOutputCharacterW(handle, alternativeBuffer.get(), gsl::narrow(alternative.size()), { 0, 0 }, &read)); VERIFY_ARE_EQUAL(alternative.size(), read); VERIFY_ARE_EQUAL(String(alternative.data()), String(alternativeBuffer.get(), gsl::narrow(alternative.size()))); - } void BufferTests::ScrollLargeBufferPerformance() @@ -127,8 +126,7 @@ void BufferTests::ScrollLargeBufferPerformance() // Set this to false to scroll the entire buffer. The issue will disappear! const auto ScrollOnlyInvisibleArea = true; - const SMALL_RECT Rect - { + const SMALL_RECT Rect{ 0, 0, Info.dwSize.X - 1, @@ -148,7 +146,7 @@ void BufferTests::ScrollLargeBufferPerformance() const auto delta = std::chrono::duration_cast(std::chrono::steady_clock::now() - now).count(); SetConsoleCursorPosition(Out, { 0, Info.dwSize.Y - 1 }); - Log::Comment(String().Format(L"%d calls took %d ms. Avg %d ms per call", count, delta, delta/count)); + Log::Comment(String().Format(L"%d calls took %d ms. Avg %d ms per call", count, delta, delta / count)); } void BufferTests::ChafaGifPerformance() @@ -166,7 +164,7 @@ void BufferTests::ChafaGifPerformance() Info.dwSize.Y = 9999; SetConsoleScreenBufferSize(Out, Info.dwSize); - SetConsoleCursorPosition(Out, { 0}); + SetConsoleCursorPosition(Out, { 0 }); DWORD Mode = 0; GetConsoleMode(Out, &Mode); @@ -176,11 +174,11 @@ void BufferTests::ChafaGifPerformance() SetConsoleOutputCP(CP_UTF8); // Taken from: https://blog.kowalczyk.info/article/zy/Embedding-binary-resources-on-Windows.html - HGLOBAL res_handle = NULL; - HRSRC res; - char * res_data; - DWORD res_size; - + HGLOBAL res_handle = NULL; + HRSRC res; + char* res_data; + DWORD res_size; + // NOTE: providing g_hInstance is important, NULL might not work HMODULE hModule = (HMODULE)&__ImageBase; @@ -207,7 +205,7 @@ void BufferTests::ChafaGifPerformance() for (DWORD pos = 0; pos < res_size; pos += 1000) { DWORD written = 0; - WriteConsoleA(Out, res_data + pos, min(1000, res_size-pos), &written, nullptr); + WriteConsoleA(Out, res_data + pos, min(1000, res_size - pos), &written, nullptr); count++; } diff --git a/src/host/ft_host/API_DimensionsTests.cpp b/src/host/ft_host/API_DimensionsTests.cpp index 16f695c60..357eb2dcb 100644 --- a/src/host/ft_host/API_DimensionsTests.cpp +++ b/src/host/ft_host/API_DimensionsTests.cpp @@ -171,9 +171,9 @@ void TestSetConsoleWindowInfoHelper(bool const bAbsolute, ConvertAbsoluteToRelative(bAbsolute, &srTest, srOriginalViewport); Log::Comment(NoThrowString().Format(L"Abs:%s Original:%s Viewport:%s", - bAbsolute ? L"True" : L"False", - VerifyOutputTraits::ToString(*srOriginalViewport).ToCStrWithFallbackTo(L"Fail To Display SMALL_RECT"), - VerifyOutputTraits::ToString(srTest).ToCStrWithFallbackTo(L"Fail To Display SMALL_RECT"))); + bAbsolute ? L"True" : L"False", + VerifyOutputTraits::ToString(*srOriginalViewport).ToCStrWithFallbackTo(L"Fail To Display SMALL_RECT"), + VerifyOutputTraits::ToString(srTest).ToCStrWithFallbackTo(L"Fail To Display SMALL_RECT"))); if (bExpectedResult) { @@ -285,7 +285,6 @@ void DimensionsTests::TestSetConsoleScreenBufferSize() Log::Comment(L"Adjusting Y dimension"); } - CONSOLE_SCREEN_BUFFER_INFO sbi = { 0 }; VERIFY_WIN32_BOOL_SUCCEEDED(GetConsoleScreenBufferInfo(Common::_hConsole, &sbi), L"Get initial buffer/window information."); @@ -338,7 +337,8 @@ void DimensionsTests::TestZeroSizedConsoleScreenBuffers() const BOOL fSucceeded = SetConsoleScreenBufferSize(Common::_hConsole, rgTestCoords[i]); VERIFY_IS_FALSE(!!fSucceeded, NoThrowString().Format(L"Setting zero console size should always fail (x: %d y:%d)", - rgTestCoords[i].X, rgTestCoords[i].Y)); + rgTestCoords[i].X, + rgTestCoords[i].Y)); VERIFY_ARE_EQUAL((DWORD)ERROR_INVALID_PARAMETER, GetLastError()); } } @@ -396,7 +396,6 @@ void DimensionsTests::TestSetConsoleScreenBufferInfoEx() sbiex.dwSize.Y = MAXSHORT; VERIFY_WIN32_BOOL_FAILED(SetConsoleScreenBufferInfoEx(Common::_hConsole, &sbiex), L"Try MAX by MAX viewport size."); - // Fill the entire structure with new data and set sbiex.dwSize.X = 200; sbiex.dwSize.Y = 5555; diff --git a/src/host/ft_host/API_FileTests.cpp b/src/host/ft_host/API_FileTests.cpp index 3f3c431f9..18da6911d 100644 --- a/src/host/ft_host/API_FileTests.cpp +++ b/src/host/ft_host/API_FileTests.cpp @@ -7,8 +7,8 @@ #include -using WEX::TestExecution::TestData; using WEX::Logging::Log; +using WEX::TestExecution::TestData; using namespace WEX::Common; // This class is intended to test: @@ -275,7 +275,6 @@ void FileTests::TestWriteFileProcessed() VERIFY_ARE_EQUAL(String(pszReadBackExpected), String(pszReadBack.get()), L"Verify text matches what we expected to be written into the buffer."); } - // 2. Test backspace (\x8) { pszTest = "yx\x8"; @@ -455,7 +454,8 @@ void FileTests::TestWriteFileVTProcessing() COORD const coordZero = { 0 }; VERIFY_ARE_EQUAL(coordZero, csbiexOriginal.dwCursorPosition, L"Cursor should be at 0,0 in fresh buffer."); - PCSTR pszTestString = "\x1b" "[14m"; + PCSTR pszTestString = "\x1b" + "[14m"; DWORD const cchTest = (DWORD)strlen(pszTestString); CONSOLE_SCREEN_BUFFER_INFOEX csbiexBefore = { 0 }; @@ -798,7 +798,7 @@ void FileTests::TestReadFileLineSync() // // DWORD dwRead = 0; // VERIFY_WIN32_BOOL_SUCCEEDED(ReadFile(hIn, &ch, 1, nullptr, &overlapped), L"Read file was dispatched successfully."); -// +// // std::array handles; // handles[0] = _cancellationEvent; // handles[1] = overlapped.hEvent; diff --git a/src/host/ft_host/API_FontTests.cpp b/src/host/ft_host/API_FontTests.cpp index fd260f342..254e3a849 100644 --- a/src/host/ft_host/API_FontTests.cpp +++ b/src/host/ft_host/API_FontTests.cpp @@ -7,7 +7,7 @@ using namespace WEX::TestExecution; using namespace WEX::Common; using WEX::Logging::Log; -static const COORD c_coordZero = {0,0}; +static const COORD c_coordZero = { 0, 0 }; static const PCWSTR pwszLongFontPath = L"%WINDIR%\\Fonts\\ltype.ttf"; @@ -78,7 +78,7 @@ void FontTests::TestCurrentFontAPIsInvalid() if (strOperation == L"Get") { - CONSOLE_FONT_INFO cfi = {0}; + CONSOLE_FONT_INFO cfi = { 0 }; if (bUseValidOutputHandle) { @@ -91,12 +91,12 @@ void FontTests::TestCurrentFontAPIsInvalid() } else if (strOperation == L"GetEx") { - CONSOLE_FONT_INFOEX cfie = {0}; + CONSOLE_FONT_INFOEX cfie = { 0 }; VERIFY_WIN32_BOOL_FAILED(OneCoreDelay::GetCurrentConsoleFontEx(hConsoleOutput, (BOOL)bMaximumWindow, &cfie)); } else if (strOperation == L"SetEx") { - CONSOLE_FONT_INFOEX cfie = {0}; + CONSOLE_FONT_INFOEX cfie = { 0 }; VERIFY_WIN32_BOOL_FAILED(OneCoreDelay::SetCurrentConsoleFontEx(hConsoleOutput, (BOOL)bMaximumWindow, &cfie)); } else @@ -129,7 +129,7 @@ void FontTests::TestGetFontSizeLargeIndexInvalid() void FontTests::TestSetConsoleFontNegativeSize() { const HANDLE hConsoleOutput = GetStdOutputHandle(); - CONSOLE_FONT_INFOEX cfie = {0}; + CONSOLE_FONT_INFOEX cfie = { 0 }; cfie.cbSize = sizeof(cfie); VERIFY_WIN32_BOOL_SUCCEEDED(OneCoreDelay::GetCurrentConsoleFontEx(hConsoleOutput, FALSE, &cfie)); cfie.dwFontSize.X = -4; @@ -147,11 +147,11 @@ void FontTests::TestFontScenario() const HANDLE hConsoleOutput = GetStdOutputHandle(); Log::Comment(L"1. Ensure that the various GET APIs for font information align with each other."); - CONSOLE_FONT_INFOEX cfie = {0}; + CONSOLE_FONT_INFOEX cfie = { 0 }; cfie.cbSize = sizeof(cfie); VERIFY_WIN32_BOOL_SUCCEEDED(OneCoreDelay::GetCurrentConsoleFontEx(hConsoleOutput, FALSE, &cfie)); - CONSOLE_FONT_INFO cfi = {0}; + CONSOLE_FONT_INFO cfi = { 0 }; VERIFY_WIN32_BOOL_SUCCEEDED(OneCoreDelay::GetCurrentConsoleFont(hConsoleOutput, FALSE, &cfi)); VERIFY_ARE_EQUAL(cfi.nFont, cfie.nFont, L"Ensure regular and Ex APIs return same nFont"); @@ -164,14 +164,14 @@ void FontTests::TestFontScenario() // --------------------- Log::Comment(L"2. Ensure that our font settings round-trip appropriately through the Ex APIs"); - CONSOLE_FONT_INFOEX cfieSet = {0}; + CONSOLE_FONT_INFOEX cfieSet = { 0 }; cfieSet.cbSize = sizeof(cfieSet); cfieSet.dwFontSize.Y = 12; VERIFY_SUCCEEDED(StringCchCopy(cfieSet.FaceName, ARRAYSIZE(cfieSet.FaceName), L"Lucida Console")); VERIFY_WIN32_BOOL_SUCCEEDED(OneCoreDelay::SetCurrentConsoleFontEx(hConsoleOutput, FALSE, &cfieSet)); - CONSOLE_FONT_INFOEX cfiePost = {0}; + CONSOLE_FONT_INFOEX cfiePost = { 0 }; cfiePost.cbSize = sizeof(cfiePost); VERIFY_WIN32_BOOL_SUCCEEDED(OneCoreDelay::GetCurrentConsoleFontEx(hConsoleOutput, FALSE, &cfiePost)); diff --git a/src/host/ft_host/API_InputTests.cpp b/src/host/ft_host/API_InputTests.cpp index 9254824e7..0a146a821 100644 --- a/src/host/ft_host/API_InputTests.cpp +++ b/src/host/ft_host/API_InputTests.cpp @@ -36,8 +36,9 @@ class InputTests TEST_CLASS_SETUP(TestSetup); TEST_CLASS_CLEANUP(TestCleanup); - TEST_METHOD(TestGetMouseButtonsValid); // note: GetNumberOfConsoleMouseButtons crashes with nullptr, so there's no - // negative test + // note: GetNumberOfConsoleMouseButtons crashes with nullptr, so there's no negative test + TEST_METHOD(TestGetMouseButtonsValid); + TEST_METHOD(TestInputScenario); TEST_METHOD(TestFlushValid); TEST_METHOD(TestFlushInvalid); @@ -108,7 +109,7 @@ void InputTests::TestGetMouseButtonsValid() void GenerateAndWriteInputRecords(const HANDLE hConsoleInput, const UINT cRecordsToGenerate, - _Out_writes_(cRecs) INPUT_RECORD *prgRecs, + _Out_writes_(cRecs) INPUT_RECORD* prgRecs, const DWORD cRecs, _Out_ PDWORD pdwWritten) { @@ -134,13 +135,13 @@ void InputTests::TestInputScenario() HANDLE hConsoleInput = GetStdInputHandle(); DWORD nWrittenEvents = (DWORD)-1; - INPUT_RECORD rgInputRecords[NUMBER_OF_SCENARIO_INPUTS] = {0}; + INPUT_RECORD rgInputRecords[NUMBER_OF_SCENARIO_INPUTS] = { 0 }; GenerateAndWriteInputRecords(hConsoleInput, NUMBER_OF_SCENARIO_INPUTS, rgInputRecords, ARRAYSIZE(rgInputRecords), &nWrittenEvents); VerifyNumberOfInputRecords(hConsoleInput, ARRAYSIZE(rgInputRecords)); Log::Comment(L"Peeking events"); - INPUT_RECORD rgPeekedRecords[NUMBER_OF_SCENARIO_INPUTS] = {0}; + INPUT_RECORD rgPeekedRecords[NUMBER_OF_SCENARIO_INPUTS] = { 0 }; DWORD nPeekedEvents = (DWORD)-1; VERIFY_WIN32_BOOL_SUCCEEDED(PeekConsoleInput(hConsoleInput, rgPeekedRecords, ARRAYSIZE(rgPeekedRecords), &nPeekedEvents)); VERIFY_ARE_EQUAL(nPeekedEvents, nWrittenEvents, L"We should be able to peek at all of the records we've written"); @@ -158,11 +159,11 @@ void InputTests::TestInputScenario() { const bool fIsLastIteration = (iIteration + 1) > (NUMBER_OF_SCENARIO_INPUTS / READ_BATCH); Log::Comment(String().Format(L"Reading inputs (iteration %d/%d)%s", - iIteration+1, + iIteration + 1, cIterations, fIsLastIteration ? L" (last one)" : L"")); - INPUT_RECORD rgReadRecords[READ_BATCH] = {0}; + INPUT_RECORD rgReadRecords[READ_BATCH] = { 0 }; DWORD nReadEvents = (DWORD)-1; VERIFY_WIN32_BOOL_SUCCEEDED(ReadConsoleInput(hConsoleInput, rgReadRecords, ARRAYSIZE(rgReadRecords), &nReadEvents)); @@ -176,7 +177,7 @@ void InputTests::TestInputScenario() VERIFY_ARE_EQUAL(nReadEvents, dwExpectedEventsRead); for (UINT iReadRecord = 0; iReadRecord < nReadEvents; iReadRecord++) { - const UINT iInputRecord = iReadRecord+(iIteration*READ_BATCH); + const UINT iInputRecord = iReadRecord + (iIteration * READ_BATCH); VERIFY_ARE_EQUAL(rgReadRecords[iReadRecord], rgInputRecords[iInputRecord], String().Format(L"verify record %d", iInputRecord)); @@ -185,7 +186,7 @@ void InputTests::TestInputScenario() DWORD nInputEventsAfterRead = (DWORD)-1; VERIFY_WIN32_BOOL_SUCCEEDED(GetNumberOfConsoleInputEvents(hConsoleInput, &nInputEventsAfterRead)); - DWORD dwExpectedEventsAfterRead = (NUMBER_OF_SCENARIO_INPUTS - (READ_BATCH*(iIteration+1))); + DWORD dwExpectedEventsAfterRead = (NUMBER_OF_SCENARIO_INPUTS - (READ_BATCH * (iIteration + 1))); if (fIsLastIteration) { dwExpectedEventsAfterRead = 0; @@ -202,7 +203,7 @@ void InputTests::TestFlushValid() HANDLE hConsoleInput = GetStdInputHandle(); DWORD nWrittenEvents = (DWORD)-1; - INPUT_RECORD rgInputRecords[NUMBER_OF_SCENARIO_INPUTS] = {0}; + INPUT_RECORD rgInputRecords[NUMBER_OF_SCENARIO_INPUTS] = { 0 }; GenerateAndWriteInputRecords(hConsoleInput, NUMBER_OF_SCENARIO_INPUTS, rgInputRecords, ARRAYSIZE(rgInputRecords), &nWrittenEvents); VerifyNumberOfInputRecords(hConsoleInput, ARRAYSIZE(rgInputRecords)); @@ -231,13 +232,13 @@ void InputTests::TestPeekConsoleInvalid() VERIFY_ARE_EQUAL(nPeeked, (DWORD)0); DWORD nWritten = (DWORD)-1; - INPUT_RECORD ir = {0}; + INPUT_RECORD ir = { 0 }; GenerateAndWriteInputRecords(hConsoleInput, 1, &ir, 1, &nWritten); VerifyNumberOfInputRecords(hConsoleInput, 1); nPeeked = (DWORD)-1; - INPUT_RECORD irPeeked = {0}; + INPUT_RECORD irPeeked = { 0 }; VERIFY_WIN32_BOOL_SUCCEEDED(PeekConsoleInput(hConsoleInput, &irPeeked, 0, &nPeeked)); VERIFY_ARE_EQUAL(nPeeked, (DWORD)0, L"Verify that an empty array doesn't cause peeks to get written"); @@ -262,7 +263,7 @@ void InputTests::TestReadConsoleInvalid() HANDLE hConsoleInput = GetStdInputHandle(); DWORD nWritten = (DWORD)-1; - INPUT_RECORD irWrite = {0}; + INPUT_RECORD irWrite = { 0 }; GenerateAndWriteInputRecords(hConsoleInput, 1, &irWrite, 1, &nWritten); VerifyNumberOfInputRecords(hConsoleInput, 1); @@ -270,7 +271,7 @@ void InputTests::TestReadConsoleInvalid() VERIFY_WIN32_BOOL_SUCCEEDED(ReadConsoleInput(hConsoleInput, nullptr, 0, &nRead)); VERIFY_ARE_EQUAL(nRead, (DWORD)0); - INPUT_RECORD irRead = {0}; + INPUT_RECORD irRead = { 0 }; nRead = (DWORD)-1; VERIFY_WIN32_BOOL_SUCCEEDED(ReadConsoleInput(hConsoleInput, &irRead, 0, &nRead)); VERIFY_ARE_EQUAL(nRead, (DWORD)0); @@ -296,7 +297,7 @@ void InputTests::TestWriteConsoleInvalid() VERIFY_ARE_EQUAL(nWrite, (DWORD)0); nWrite = (DWORD)-1; - INPUT_RECORD irWrite = {0}; + INPUT_RECORD irWrite = { 0 }; VERIFY_WIN32_BOOL_SUCCEEDED(WriteConsoleInput(hConsoleInput, &irWrite, 0, &nWrite)); VERIFY_ARE_EQUAL(nWrite, (DWORD)0); } @@ -349,7 +350,6 @@ void InputTests::TestReadConsolePasswordScenario() FlushConsoleInputBuffer(hIn); WriteConsoleInputW(hIn, irBuffer.get(), cBuffer, &dwWritten); - // Press "enter" key on the window to signify the user pressing enter at the end of the password. VERIFY_WIN32_BOOL_SUCCEEDED_RETURN(PostMessageW(GetConsoleWindow(), WM_KEYDOWN, VK_RETURN, 0)); @@ -440,9 +440,10 @@ void TestMouseWheelReadConsoleInputHelper(const UINT msg, const DWORD dwEventFla WPARAM wParam = 0; short sKeyState = 0; short sWheelDelta = -WHEEL_DELTA; // scroll down is negative, up is positive. - wParam = ((sWheelDelta << 16) | sKeyState) & 0xFFFFFFFF; // we only use the lower 32-bits (in case of 64-bit system) + // we only use the lower 32-bits (in case of 64-bit system) + wParam = ((sWheelDelta << 16) | sKeyState) & 0xFFFFFFFF; - // LPARAM is positioning information. We don't care so we'll leave it 0x0 + // LPARAM is positioning information. We don't care so we'll leave it 0x0 LPARAM lParam = 0; Log::Comment(L"Send scroll down message into console window queue."); @@ -452,8 +453,7 @@ void TestMouseWheelReadConsoleInputHelper(const UINT msg, const DWORD dwEventFla DWORD dwAvailable = 0; VERIFY_WIN32_BOOL_SUCCEEDED(GetNumberOfConsoleInputEvents(hConsoleInput, &dwAvailable), L"Retrieve number of events in queue."); - VERIFY_ARE_EQUAL(dwExpectedEvents, dwAvailable, - NoThrowString().Format(L"We expected %i event from our scroll message.", dwExpectedEvents)); + VERIFY_ARE_EQUAL(dwExpectedEvents, dwAvailable, NoThrowString().Format(L"We expected %i event from our scroll message.", dwExpectedEvents)); INPUT_RECORD ir; DWORD dwRead = 0; @@ -464,8 +464,9 @@ void TestMouseWheelReadConsoleInputHelper(const UINT msg, const DWORD dwEventFla Log::Comment(L"Verify the event is what we expected. We only verify the fields relevant to this test."); VERIFY_ARE_EQUAL(MOUSE_EVENT, ir.EventType); - VERIFY_ARE_EQUAL((DWORD)wParam, ir.Event.MouseEvent.dwButtonState); // hard cast OK. only using lower 32-bits (see above) - // Don't care about ctrl key state. Can be messed with by caps lock/numlock state. Not checking this. + // hard cast OK. only using lower 32-bits (see above) + VERIFY_ARE_EQUAL((DWORD)wParam, ir.Event.MouseEvent.dwButtonState); + // Don't care about ctrl key state. Can be messed with by caps lock/numlock state. Not checking this. VERIFY_ARE_EQUAL(dwEventFlagsExpected, ir.Event.MouseEvent.dwEventFlags); // Don't care about mouse position for ensuring scroll message went through. } @@ -607,7 +608,7 @@ void InputTests::TestVtInputGeneration() DWORD dwWritten = (DWORD)-1; DWORD dwRead = (DWORD)-1; - INPUT_RECORD rgInputRecords[64] = {0}; + INPUT_RECORD rgInputRecords[64] = { 0 }; Log::Comment(L"First make sure that an arrow keydown is not translated in not-VT mode"); @@ -632,7 +633,6 @@ void InputTests::TestVtInputGeneration() VERIFY_ARE_EQUAL(rgInputRecords[0].Event.KeyEvent.bKeyDown, TRUE); VERIFY_ARE_EQUAL(rgInputRecords[0].Event.KeyEvent.wVirtualKeyCode, VK_UP); - Log::Comment(L"Now, enable VT Input and make sure that a vt sequence comes out the other side."); dwMode = WI_SetFlag(dwMode, ENABLE_VIRTUAL_TERMINAL_INPUT); diff --git a/src/host/ft_host/API_ModeTests.cpp b/src/host/ft_host/API_ModeTests.cpp index 4b0cae429..2f7110926 100644 --- a/src/host/ft_host/API_ModeTests.cpp +++ b/src/host/ft_host/API_ModeTests.cpp @@ -46,7 +46,7 @@ void ModeTests::TestGetConsoleModeInvalid() BEGIN_TEST_METHOD_PROPERTIES() TEST_METHOD_PROPERTY(L"IsPerfTest", L"true") END_TEST_METHOD_PROPERTIES() - + DWORD dwConsoleMode = (DWORD)-1; VERIFY_WIN32_BOOL_FAILED(GetConsoleMode(INVALID_HANDLE_VALUE, &dwConsoleMode)); VERIFY_ARE_EQUAL(dwConsoleMode, (DWORD)-1); diff --git a/src/host/ft_host/API_OutputTests.cpp b/src/host/ft_host/API_OutputTests.cpp index 621698247..803932ef5 100644 --- a/src/host/ft_host/API_OutputTests.cpp +++ b/src/host/ft_host/API_OutputTests.cpp @@ -202,7 +202,7 @@ void OutputTests::WriteConsoleOutputWOutsideBuffer() void OutputTests::WriteConsoleOutputWWithClipping() { SetVerifyOutput vf(VerifyOutputSettings::LogOnlyFailures); - + // Get output buffer information. const auto consoleOutputHandle = GetStdOutputHandle(); @@ -389,7 +389,7 @@ void OutputTests::WriteConsoleOutputCharacterWRunoff() VERIFY_WIN32_BOOL_SUCCEEDED(GetConsoleScreenBufferInfoEx(consoleOutputHandle, &sbiex)); const auto bufferSize = sbiex.dwSize; - COORD target{ bufferSize.X - 1, bufferSize.Y - 1}; + COORD target{ bufferSize.X - 1, bufferSize.Y - 1 }; const std::wstring text = L"hello"; DWORD charsWritten = 0; @@ -454,11 +454,10 @@ void OutputTests::WriteConsoleOutputAttributeCheckerTest() const DWORD size = width * height; std::unique_ptr attrs = std::make_unique(size); - std::generate(attrs.get(), attrs.get() + size, [=]() - { - static int i = 0; - return i++ % 2 == 0 ? red : green; - }); + std::generate(attrs.get(), attrs.get() + size, [=]() { + static int i = 0; + return i++ % 2 == 0 ? red : green; + }); // write text const COORD coord{ 0, 0 }; @@ -498,12 +497,11 @@ void OutputTests::WriteBackspaceTest() // Get output buffer information. const auto hOut = GetStdOutputHandle(); Log::Comment(NoThrowString().Format( - L"Outputing \"\\b \\b\" should behave the same as \"\b\", \" \", \"\b\" in seperate WriteConsoleW calls." - )); + L"Outputing \"\\b \\b\" should behave the same as \"\b\", \" \", \"\b\" in seperate WriteConsoleW calls.")); DWORD n = 0; - CONSOLE_SCREEN_BUFFER_INFO csbi = {0}; - COORD c = {0, 0}; + CONSOLE_SCREEN_BUFFER_INFO csbi = { 0 }; + COORD c = { 0, 0 }; VERIFY_SUCCEEDED(SetConsoleCursorPosition(hOut, c)); VERIFY_SUCCEEDED(WriteConsoleW(hOut, L"GoodX", 5, &n, nullptr)); @@ -536,7 +534,6 @@ void OutputTests::WriteBackspaceTest() VERIFY_SUCCEEDED(GetConsoleScreenBufferInfo(hOut, &csbi)); VERIFY_ARE_EQUAL(csbi.dwCursorPosition.X, 3); VERIFY_ARE_EQUAL(csbi.dwCursorPosition.Y, 1); - } void OutputTests::BasicReadConsoleOutputATest() @@ -1000,7 +997,8 @@ void OutputTests::ReadConsoleOutputWPartialUserBuffer() } // Send "Select All", then spawn a thread to hit ESC a moment later. -static void WinPtyTestStartSelection() { +static void WinPtyTestStartSelection() +{ const HWND hwnd = GetConsoleWindow(); const int SC_CONSOLE_SELECT_ALL = 0xFFF5; SendMessage(hwnd, WM_SYSCOMMAND, SC_CONSOLE_SELECT_ALL, 0); @@ -1011,23 +1009,31 @@ static void WinPtyTestStartSelection() { press_escape.detach(); } -template +template static void WinPtyDoWriteTest( - const wchar_t *api_name, - T *api_ptr, - bool use_selection) { + const wchar_t* api_name, + T* api_ptr, + bool use_selection) +{ if (use_selection) WinPtyTestStartSelection(); char buf[] = "1234567890567890567890567890\n"; DWORD actual = 0; const BOOL ret = api_ptr( GetStdHandle(STD_OUTPUT_HANDLE), - buf, static_cast(strlen(buf)), &actual, NULL); + buf, + static_cast(strlen(buf)), + &actual, + NULL); const DWORD last_error = GetLastError(); - VERIFY_IS_TRUE(ret && actual == strlen(buf), String().Format(L"%s: %s returned %d: actual=%u LastError=%u (%s)\n", - ((ret && actual == strlen(buf)) ? L"SUCCESS" : L"ERROR"), - api_name, ret, actual, last_error, - use_selection ? L"select" : L"no-select")); + VERIFY_IS_TRUE(ret && actual == strlen(buf), + String().Format(L"%s: %s returned %d: actual=%u LastError=%u (%s)\n", + ((ret && actual == strlen(buf)) ? L"SUCCESS" : L"ERROR"), + api_name, + ret, + actual, + last_error, + use_selection ? L"select" : L"no-select")); } void OutputTests::WinPtyWrite() @@ -1061,5 +1067,4 @@ void OutputTests::WinPtyWrite() VERIFY_FAIL(L"Unknown test type."); break; } - } diff --git a/src/host/ft_host/API_RgbColorTests.cpp b/src/host/ft_host/API_RgbColorTests.cpp index 8e1af73d2..12f40312e 100644 --- a/src/host/ft_host/API_RgbColorTests.cpp +++ b/src/host/ft_host/API_RgbColorTests.cpp @@ -7,7 +7,7 @@ using namespace WEX::Common; HANDLE g_hOut = INVALID_HANDLE_VALUE; CONSOLE_SCREEN_BUFFER_INFOEX g_sbiex_backup = { 0 }; -COORD g_cWriteSize = {16, 16}; +COORD g_cWriteSize = { 16, 16 }; const int LEGACY_MODE = 0; const int VT_SIMPLE_MODE = 1; @@ -92,11 +92,11 @@ WORD WinToVTColor(int winColor, bool isForeground) bool blue = (winColor & FOREGROUND_BLUE) > 0; bool bright = (winColor & FOREGROUND_INTENSITY) > 0; - WORD result = isForeground? 30 : 40; - result += bright? 60 : 0; - result += red? 1 : 0; - result += green? 2 : 0; - result += blue? 4 : 0; + WORD result = isForeground ? 30 : 40; + result += bright ? 60 : 0; + result += red ? 1 : 0; + result += green ? 2 : 0; + result += blue ? 4 : 0; return result; } @@ -114,7 +114,7 @@ int WinToXtermIndex(int iWinColor) bool fGreen = (iWinColor & 0x02) > 0; bool fBlue = (iWinColor & 0x01) > 0; bool fBright = (iWinColor & 0x08) > 0; - int iXtermTableEntry = (fRed? 0x1:0x0) | (fGreen? 0x2:0x0) | (fBlue? 0x4:0x0) | (fBright? 0x8:0x0); + int iXtermTableEntry = (fRed ? 0x1 : 0x0) | (fGreen ? 0x2 : 0x0) | (fBlue ? 0x4 : 0x0) | (fBright ? 0x8 : 0x0); return iXtermTableEntry; } @@ -217,7 +217,6 @@ BOOL CreateColorGrid(int iColorMode) break; default: VERIFY_ARE_EQUAL(true, false, L"Did not provide a valid color mode"); - } } switch (iColorMode) @@ -234,7 +233,6 @@ BOOL CreateColorGrid(int iColorMode) break; default: VERIFY_ARE_EQUAL(true, false, L"Did not provide a valid color mode"); - } } fSuccess = totalWritten == (1 * 16 * 16); @@ -242,7 +240,6 @@ BOOL CreateColorGrid(int iColorMode) } return fSuccess; - } BOOL CreateLegacyColorGrid() @@ -263,13 +260,13 @@ BOOL ValidateLegacyColorGrid(COORD cursorPosInitial) CHAR_INFO* rOutputBuffer = new CHAR_INFO[actualWriteSize.X * actualWriteSize.Y]; - SMALL_RECT srReadRegion = {0}; + SMALL_RECT srReadRegion = { 0 }; srReadRegion.Top = cursorPosInitial.Y; srReadRegion.Left = cursorPosInitial.X; srReadRegion.Right = srReadRegion.Left + actualWriteSize.X; srReadRegion.Bottom = srReadRegion.Top + actualWriteSize.Y; - BOOL fSuccess = ReadConsoleOutput(g_hOut, rOutputBuffer, actualWriteSize, {0}, &srReadRegion); + BOOL fSuccess = ReadConsoleOutput(g_hOut, rOutputBuffer, actualWriteSize, { 0 }, &srReadRegion); VERIFY_WIN32_BOOL_SUCCEEDED(fSuccess, L"Read the output back"); if (fSuccess) { @@ -281,7 +278,7 @@ BOOL ValidateLegacyColorGrid(COORD cursorPosInitial) WORD wExpected = MakeAttribute(fg, bg); VERIFY_ARE_EQUAL(pInfo->Attributes, wExpected, NoThrowString().Format(L"fg, bg = (%d,%d)", fg, bg)); fSuccess &= pInfo->Attributes == wExpected; - pInfo+=1;// We wrote one character each time + pInfo += 1; // We wrote one character each time } } } @@ -298,13 +295,13 @@ BOOL Validate256GridToLegacy(COORD cursorPosInitial) CHAR_INFO* rOutputBuffer = new CHAR_INFO[actualWriteSize.X * actualWriteSize.Y]; - SMALL_RECT srReadRegion = {0}; + SMALL_RECT srReadRegion = { 0 }; srReadRegion.Top = cursorPosInitial.Y; srReadRegion.Left = cursorPosInitial.X; srReadRegion.Right = srReadRegion.Left + actualWriteSize.X; srReadRegion.Bottom = srReadRegion.Top + actualWriteSize.Y; - BOOL fSuccess = ReadConsoleOutput(g_hOut, rOutputBuffer, actualWriteSize, {0}, &srReadRegion); + BOOL fSuccess = ReadConsoleOutput(g_hOut, rOutputBuffer, actualWriteSize, { 0 }, &srReadRegion); VERIFY_WIN32_BOOL_SUCCEEDED(fSuccess, L"Read the output back"); if (fSuccess) { @@ -358,8 +355,6 @@ BOOL Validate256GridToLegacy(COORD cursorPosInitial) VERIFY_ARE_EQUAL(GetGridAttrs(15, 14, rOutputBuffer, actualWriteSize), MakeAttribute(0xF, 0xF)); VERIFY_ARE_EQUAL(GetGridAttrs(15, 15, rOutputBuffer, actualWriteSize), MakeAttribute(0xF, 0xF)); - - } delete[] rOutputBuffer; return fSuccess; diff --git a/src/host/ft_host/API_TitleTests.cpp b/src/host/ft_host/API_TitleTests.cpp index 5cc35e92e..6dda4fc64 100644 --- a/src/host/ft_host/API_TitleTests.cpp +++ b/src/host/ft_host/API_TitleTests.cpp @@ -71,7 +71,7 @@ void TestGetConsoleTitleAPrepExpectedHelper(_In_reads_(cchTitle) const char* con // Prep expected data if (cchTryToRead >= cchTitle - 1) { - VERIFY_SUCCEEDED(StringCchCopyNA(chReadExpected, cchReadExpected, chTitle, cchTryToRead)); // Copy as much room as we said we had leaving space for null terminator + VERIFY_SUCCEEDED(StringCchCopyNA(chReadExpected, cchReadExpected, chTitle, cchTryToRead)); // Copy as much room as we said we had leaving space for null terminator if (cchTryToRead == cchTitle - 1) { @@ -82,7 +82,6 @@ void TestGetConsoleTitleAPrepExpectedHelper(_In_reads_(cchTitle) const char* con { chReadExpected[0] = '\0'; } - } void TestGetConsoleTitleWPrepExpectedHelper(_In_reads_(cchTitle) const wchar_t* const wchTitle, @@ -143,7 +142,7 @@ void TestGetConsoleTitleWVerifyHelper(_Inout_updates_(cchReadBuffer) wchar_t* co const size_t cchTryToRead, const DWORD dwExpectedRetVal, const DWORD dwExpectedLastError, - _In_reads_(cchExpected) const wchar_t* const wchReadExpected, + _In_reads_(cchExpected) const wchar_t* const wchReadExpected, const size_t cchExpected) { VERIFY_ARE_EQUAL(cchExpected, cchReadBuffer); @@ -258,7 +257,6 @@ void TitleTests::TestGetConsoleTitleA() TestGetConsoleTitleAVerifyHelper(nullptr, 0, 0, 0, S_OK, nullptr, 0); } - void TitleTests::TestGetConsoleTitleW() { const wchar_t* const wszTestTitle = L"TestTitle"; diff --git a/src/host/ft_host/CJK_DbcsTests.cpp b/src/host/ft_host/CJK_DbcsTests.cpp index bdc0ddb25..b82514ab9 100644 --- a/src/host/ft_host/CJK_DbcsTests.cpp +++ b/src/host/ft_host/CJK_DbcsTests.cpp @@ -10,8 +10,8 @@ #define ENGLISH_US_CP 437u #define JAPANESE_CP 932u -using WEX::TestExecution::TestData; using WEX::Logging::Log; +using WEX::TestExecution::TestData; using namespace WEX::Common; namespace DbcsWriteRead @@ -44,15 +44,21 @@ namespace DbcsWriteRead _Out_ HANDLE* const phOut, _Out_ WORD* const pwAttributes); - void SendOutput(const HANDLE hOut, _In_ unsigned int const uiCodePage, - const WriteMode WriteMode, const bool fIsUnicode, - _In_ PCSTR pszTestString, const WORD wAttr); + void SendOutput(const HANDLE hOut, + _In_ unsigned int const uiCodePage, + const WriteMode WriteMode, + const bool fIsUnicode, + _In_ PCSTR pszTestString, + const WORD wAttr); void RetrieveOutput(const HANDLE hOut, - const DbcsWriteRead::ReadMode ReadMode, const bool fReadUnicode, - _Out_writes_(cChars) CHAR_INFO* const rgChars, const SHORT cChars); + const DbcsWriteRead::ReadMode ReadMode, + const bool fReadUnicode, + _Out_writes_(cChars) CHAR_INFO* const rgChars, + const SHORT cChars); - void Verify(_In_reads_(cExpected) CHAR_INFO* const rgExpected, const size_t cExpected, + void Verify(_In_reads_(cExpected) CHAR_INFO* const rgExpected, + const size_t cExpected, _In_reads_(cExpected) CHAR_INFO* const rgActual); void PrepExpected(_In_ unsigned int const uiCodePage, @@ -89,7 +95,6 @@ namespace DbcsWriteRead _Inout_updates_all_(cExpectedNeeded) CHAR_INFO* const rgciExpected, const size_t cExpectedNeeded); - namespace PrepPattern { // There are 14 different patterns that result from the various combinations of our APIs. @@ -360,11 +365,13 @@ bool DbcsWriteRead::Setup(_In_ unsigned int uiCodePage, return true; } -void DbcsWriteRead::SendOutput(const HANDLE hOut, _In_ unsigned int const uiCodePage, - const DbcsWriteRead::WriteMode WriteMode, const bool fIsUnicode, - _In_ PCSTR pszTestString, const WORD wAttr) +void DbcsWriteRead::SendOutput(const HANDLE hOut, + _In_ unsigned int const uiCodePage, + const DbcsWriteRead::WriteMode WriteMode, + const bool fIsUnicode, + _In_ PCSTR pszTestString, + const WORD wAttr) { - // DBCS is very dependent on knowing the byte length in the original codepage of the input text. // Save off the original length of the string so we know what its A length was. SHORT const cTestString = (SHORT)strlen(pszTestString); @@ -1393,7 +1400,6 @@ void DbcsWriteRead::PrepPattern::ACoverAttrSpacePaddedDedupeTruncatedW(_In_ unsi pciExpected[i].Attributes |= COMMON_LVB_TRAILING_BYTE; fIsNextTrailing = false; } - } for (; i < cExpected; i++) @@ -1704,8 +1710,10 @@ void DbcsWriteRead::PrepExpected(_In_ unsigned int const uiCodePage, } void DbcsWriteRead::RetrieveOutput(const HANDLE hOut, - const DbcsWriteRead::ReadMode ReadMode, const bool fReadUnicode, - _Out_writes_(cChars) CHAR_INFO* const rgChars, const SHORT cChars) + const DbcsWriteRead::ReadMode ReadMode, + const bool fReadUnicode, + _Out_writes_(cChars) CHAR_INFO* const rgChars, + const SHORT cChars) { COORD coordBufferTarget = { 0 }; @@ -1785,7 +1793,8 @@ void DbcsWriteRead::RetrieveOutput(const HANDLE hOut, } } -void DbcsWriteRead::Verify(_In_reads_(cExpected) CHAR_INFO* const rgExpected, const size_t cExpected, +void DbcsWriteRead::Verify(_In_reads_(cExpected) CHAR_INFO* const rgExpected, + const size_t cExpected, _In_reads_(cExpected) CHAR_INFO* const rgActual) { // We will walk through for the number of CHAR_INFOs expected. @@ -1955,7 +1964,6 @@ void DbcsTests::TestDbcsWriteRead() fReadInUnicode); Log::Comment(testInfo); - } // This test covers bisect-prevention handling. This is the behavior where a double-wide character will not be spliced @@ -2252,8 +2260,8 @@ struct MultibyteInputData PCSTR pszExpectedText; }; -const MultibyteInputData MultibyteTestDataSet[] = -{ +// clang-format off +const MultibyteInputData MultibyteTestDataSet[] = { { L"\x3042", "\x82\xa0" }, { L"\x3042" L"3", "\x82\xa0\x33" }, { L"3" L"\x3042", "\x33\x82\xa0" }, @@ -2261,6 +2269,7 @@ const MultibyteInputData MultibyteTestDataSet[] = { L"3" L"\x3042" L"\x3044" L"\x3042", "\x33\x82\xa0\x82\xa2\x82\xa0" }, { L"3" L"\x3042" L"\x3044" L"\x3042" L"\x3044", "\x33\x82\xa0\x82\xa2\x82\xa0\x82\xa2" }, }; +// clang-format on void WriteStringToInput(HANDLE hIn, PCWSTR pwszString) { @@ -2540,5 +2549,4 @@ void DbcsTests::TestDbcsStdCoutScenario() VERIFY_WIN32_BOOL_SUCCEEDED(ReadConsoleOutputCharacterA(hOut, psReadBack.get(), cchReadBack, coordReadPos, &dwRead), L"Read back std::cout line."); VERIFY_ARE_EQUAL(cchReadBack, dwRead, L"We should have read as many characters as we expected (length of original printed line.)"); VERIFY_ARE_EQUAL(String(test), String(psReadBack.get()), L"String should match what we wrote."); - } diff --git a/src/host/ft_host/Common.cpp b/src/host/ft_host/Common.cpp index 63f73a698..6fcf491f3 100644 --- a/src/host/ft_host/Common.cpp +++ b/src/host/ft_host/Common.cpp @@ -160,7 +160,8 @@ BOOL UnadjustWindowRectEx( RECT rc; SetRectEmpty(&rc); BOOL fRc = AdjustWindowRectEx(&rc, dwStyle, fMenu, dwExStyle); - if (fRc) { + if (fRc) + { prc->left -= rc.left; prc->top -= rc.top; prc->right -= rc.right; @@ -194,10 +195,10 @@ bool Common::TestBufferSetup() // to the default output buffer at the same time. _hConsole = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, - 0 /*dwShareMode*/, - NULL /*lpSecurityAttributes*/, - CONSOLE_TEXTMODE_BUFFER, - NULL /*lpReserved*/); + 0 /*dwShareMode*/, + NULL /*lpSecurityAttributes*/, + CONSOLE_TEXTMODE_BUFFER, + NULL /*lpReserved*/); VERIFY_ARE_NOT_EQUAL(_hConsole, INVALID_HANDLE_VALUE, L"Creating our test screen buffer."); @@ -240,7 +241,7 @@ CommonV1V2Helper::CommonV1V2Helper(const ForceV2States ForceV2StateDesired) _fRestoreOnExit = false; return; } - + VERIFY_ARE_EQUAL(ERROR_SUCCESS, lstatus); Log::Comment(L"Backing up v1/v2 console state."); diff --git a/src/host/ft_host/Common.hpp b/src/host/ft_host/Common.hpp index f5c0022b6..8b6aba5de 100644 --- a/src/host/ft_host/Common.hpp +++ b/src/host/ft_host/Common.hpp @@ -57,11 +57,9 @@ bool CheckLastError(HRESULT hr, PCWSTR pwszFunc); bool CheckLastError(BOOL fSuccess, PCWSTR pwszFunc); bool CheckLastError(HANDLE handle, PCWSTR pwszFunc); -[[nodiscard]] -bool CheckIfFileExists(_In_ PCWSTR pwszPath) noexcept; +[[nodiscard]] bool CheckIfFileExists(_In_ PCWSTR pwszPath) noexcept; -[[nodiscard]] -HRESULT ExpandPathToMutable(_In_ PCWSTR pwszPath, _Out_ wistd::unique_ptr& MutablePath) noexcept; +[[nodiscard]] HRESULT ExpandPathToMutable(_In_ PCWSTR pwszPath, _Out_ wistd::unique_ptr& MutablePath) noexcept; //http://blogs.msdn.com/b/oldnewthing/archive/2013/10/17/10457292.aspx BOOL UnadjustWindowRectEx( diff --git a/src/host/ft_host/InitTests.cpp b/src/host/ft_host/InitTests.cpp index 20ae9fce9..7bfe8a5e2 100644 --- a/src/host/ft_host/InitTests.cpp +++ b/src/host/ft_host/InitTests.cpp @@ -102,7 +102,7 @@ MODULE_SETUP(ModuleSetup) // We use regular new (not a smart pointer) and a scope exit delete because CreateProcess needs mutable space // and it'd be annoying to const_cast the smart pointer's .get() just for the sake of. PWSTR str = new WCHAR[cchNeeded]; - auto cleanStr = wil::scope_exit([&] { if (nullptr != str) { delete[] str; }}); + auto cleanStr = wil::scope_exit([&] { if (nullptr != str) { delete[] str; } }); VERIFY_SUCCEEDED_RETURN(StringCchCopyW(str, cchNeeded, (WCHAR*)value.GetBuffer())); diff --git a/src/host/ft_host/Message_KeyPressTests.cpp b/src/host/ft_host/Message_KeyPressTests.cpp index fd3ff489f..680e9b8ae 100644 --- a/src/host/ft_host/Message_KeyPressTests.cpp +++ b/src/host/ft_host/Message_KeyPressTests.cpp @@ -66,7 +66,7 @@ class KeyPressTests } Log::Comment(L"Checks that the context menu key is correctly added to the input buffer."); - Log::Comment(L"This test will fail on some keyboard layouts. Ensure you're using a QWERTY keyboard if " \ + Log::Comment(L"This test will fail on some keyboard layouts. Ensure you're using a QWERTY keyboard if " L"you're encountering a test failure here."); HWND hwnd = GetConsoleWindow(); @@ -103,13 +103,11 @@ class KeyPressTests VERIFY_ARE_EQUAL(expectedRecord, record); } - BEGIN_TEST_METHOD(TestAltGr) TEST_METHOD_PROPERTY(L"Ignore[@DevTest=true]", L"false") TEST_METHOD_PROPERTY(L"Ignore[default]", L"true") END_TEST_METHOD() - TEST_METHOD(TestCoalesceSameKeyPress) { if (!OneCoreDelay::IsSendMessageWPresent()) @@ -164,9 +162,9 @@ class KeyPressTests // VKeys for A-Z // See https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx TEST_METHOD_PROPERTY(L"Data:vKey", L"{" - "0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F," - "0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5A" - "}") + "0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F," + "0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5A" + "}") END_TEST_METHOD_PROPERTIES(); if (!OneCoreDelay::IsSendMessageWPresent()) @@ -199,14 +197,14 @@ class KeyPressTests Log::Comment(NoThrowString().Format(L"Mode:0x%x", dwInMode)); UINT vkCtrl = VK_LCONTROL; // Need this instead of VK_CONTROL - UINT uiCtrlScancode = MapVirtualKey(vkCtrl , MAPVK_VK_TO_VSC); + UINT uiCtrlScancode = MapVirtualKey(vkCtrl, MAPVK_VK_TO_VSC); // According to // KEY_KEYDOWN https://msdn.microsoft.com/en-us/library/windows/desktop/ms646280(v=vs.85).aspx // KEY_UP https://msdn.microsoft.com/en-us/library/windows/desktop/ms646281(v=vs.85).aspx - LPARAM CtrlFlags = (LOBYTE(uiCtrlScancode)<<16) | SINGLE_KEY_REPEAT; + LPARAM CtrlFlags = (LOBYTE(uiCtrlScancode) << 16) | SINGLE_KEY_REPEAT; LPARAM CtrlUpFlags = CtrlFlags | KEY_MESSAGE_UPKEY_CODE; - UINT uiScancode = MapVirtualKey(vk , MAPVK_VK_TO_VSC); + UINT uiScancode = MapVirtualKey(vk, MAPVK_VK_TO_VSC); LPARAM DownFlags = (LOBYTE(uiScancode) << 16) | SINGLE_KEY_REPEAT; LPARAM UpFlags = DownFlags | KEY_MESSAGE_UPKEY_CODE; @@ -217,10 +215,10 @@ class KeyPressTests // Don't Use PostMessage, those events come in the wrong order. // Also can't use SendInput because of the whole test window backgrounding thing. // It'd work locally, until you minimize the window. - SendMessage(hwnd, WM_KEYDOWN, vkCtrl, CtrlFlags); - SendMessage(hwnd, WM_KEYDOWN, vk, DownFlags); - SendMessage(hwnd, WM_KEYUP, vk, UpFlags); - SendMessage(hwnd, WM_KEYUP, vkCtrl, CtrlUpFlags); + SendMessage(hwnd, WM_KEYDOWN, vkCtrl, CtrlFlags); + SendMessage(hwnd, WM_KEYDOWN, vk, DownFlags); + SendMessage(hwnd, WM_KEYUP, vk, UpFlags); + SendMessage(hwnd, WM_KEYUP, vkCtrl, CtrlUpFlags); Sleep(50); @@ -240,23 +238,22 @@ class KeyPressTests INPUT_RECORD rc = inputBuffer[i]; switch (rc.EventType) { - case KEY_EVENT: - { - Log::Comment(NoThrowString().Format( - L"Down: %d Repeat: %d KeyCode: 0x%x ScanCode: 0x%x Char: %c (0x%x) KeyState: 0x%x", - rc.Event.KeyEvent.bKeyDown, - rc.Event.KeyEvent.wRepeatCount, - rc.Event.KeyEvent.wVirtualKeyCode, - rc.Event.KeyEvent.wVirtualScanCode, - rc.Event.KeyEvent.uChar.UnicodeChar != 0 ? rc.Event.KeyEvent.uChar.UnicodeChar : ' ', - rc.Event.KeyEvent.uChar.UnicodeChar, - rc.Event.KeyEvent.dwControlKeyState - )); + case KEY_EVENT: + { + Log::Comment(NoThrowString().Format( + L"Down: %d Repeat: %d KeyCode: 0x%x ScanCode: 0x%x Char: %c (0x%x) KeyState: 0x%x", + rc.Event.KeyEvent.bKeyDown, + rc.Event.KeyEvent.wRepeatCount, + rc.Event.KeyEvent.wVirtualKeyCode, + rc.Event.KeyEvent.wVirtualScanCode, + rc.Event.KeyEvent.uChar.UnicodeChar != 0 ? rc.Event.KeyEvent.uChar.UnicodeChar : ' ', + rc.Event.KeyEvent.uChar.UnicodeChar, + rc.Event.KeyEvent.dwControlKeyState)); - break; - } - default: - Log::Comment(NoThrowString().Format(L"Another event type was found.")); + break; + } + default: + Log::Comment(NoThrowString().Format(L"Another event type was found.")); } } VERIFY_ARE_EQUAL(events, 4u); @@ -292,19 +289,19 @@ class KeyPressTests // KEY_KEYDOWN https://msdn.microsoft.com/en-us/library/windows/desktop/ms646280(v=vs.85).aspx // KEY_UP https://msdn.microsoft.com/en-us/library/windows/desktop/ms646281(v=vs.85).aspx const UINT vsc = MapVirtualKey(VK_F11, MAPVK_VK_TO_VSC); - const LPARAM F11Flags = (LOBYTE(vsc)<<16) | SINGLE_KEY_REPEAT; + const LPARAM F11Flags = (LOBYTE(vsc) << 16) | SINGLE_KEY_REPEAT; const LPARAM F11UpFlags = F11Flags | KEY_MESSAGE_UPKEY_CODE; // Send F11 key down and up. lParam is VirtualScanCode and RepeatCount - SendMessage(hwnd, WM_KEYDOWN, VK_F11, F11Flags ); - SendMessage(hwnd, WM_KEYUP, VK_F11, F11UpFlags ); + SendMessage(hwnd, WM_KEYDOWN, VK_F11, F11Flags); + SendMessage(hwnd, WM_KEYUP, VK_F11, F11UpFlags); LONG maxStyle = GetWindowLongW(hwnd, GWL_STYLE); LONG maxExStyle = GetWindowLongW(hwnd, GWL_EXSTYLE); // Send F11 key down and up. lParam is VirtualScanCode and RepeatCount - SendMessage(hwnd, WM_KEYDOWN, VK_F11, F11Flags ); - SendMessage(hwnd, WM_KEYUP, VK_F11, F11UpFlags ); + SendMessage(hwnd, WM_KEYDOWN, VK_F11, F11Flags); + SendMessage(hwnd, WM_KEYUP, VK_F11, F11UpFlags); LONG newStyle = GetWindowLongW(hwnd, GWL_STYLE); LONG newExStyle = GetWindowLongW(hwnd, GWL_EXSTYLE); diff --git a/src/host/ft_host/OneCoreDelay.cpp b/src/host/ft_host/OneCoreDelay.cpp index f01bbc9aa..796ab30dc 100644 --- a/src/host/ft_host/OneCoreDelay.cpp +++ b/src/host/ft_host/OneCoreDelay.cpp @@ -5,9 +5,7 @@ #include "OneCoreDelay.hpp" -BOOLEAN -__stdcall -OneCoreDelay::IsIsWindowPresent() +BOOLEAN __stdcall OneCoreDelay::IsIsWindowPresent() { #ifdef __INSIDE_WINDOWS return ::IsIsWindowPresent(); @@ -16,9 +14,7 @@ OneCoreDelay::IsIsWindowPresent() #endif } -BOOLEAN -__stdcall -OneCoreDelay::IsGetSystemMetricsPresent() +BOOLEAN __stdcall OneCoreDelay::IsGetSystemMetricsPresent() { #ifdef __INSIDE_WINDOWS return ::IsGetSystemMetricsPresent(); @@ -27,9 +23,7 @@ OneCoreDelay::IsGetSystemMetricsPresent() #endif } -BOOLEAN -__stdcall -OneCoreDelay::IsPostMessageWPresent() +BOOLEAN __stdcall OneCoreDelay::IsPostMessageWPresent() { #ifdef __INSIDE_WINDOWS return ::IsPostMessageWPresent(); @@ -38,9 +32,7 @@ OneCoreDelay::IsPostMessageWPresent() #endif } -BOOLEAN -__stdcall -OneCoreDelay::IsSendMessageWPresent() +BOOLEAN __stdcall OneCoreDelay::IsSendMessageWPresent() { #ifdef __INSIDE_WINDOWS return ::IsSendMessageWPresent(); @@ -56,7 +48,7 @@ HMODULE GetUser32() { _hUser32 = LoadLibraryExW(L"user32.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); } - + return _hUser32; } @@ -67,298 +59,273 @@ HMODULE GetKernel32() { _hKernel32 = LoadLibraryExW(L"kernel32.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); } - + return _hKernel32; } -BOOL -APIENTRY -OneCoreDelay::AddConsoleAliasA( +BOOL APIENTRY OneCoreDelay::AddConsoleAliasA( _In_ LPSTR Source, _In_ LPSTR Target, _In_ LPSTR ExeName) { HMODULE h = GetKernel32(); - + if (h != nullptr) { - typedef BOOL(WINAPI *PfnAddConsoleAliasA)(LPSTR Source, LPSTR Target, LPSTR ExeName); - + typedef BOOL(WINAPI * PfnAddConsoleAliasA)(LPSTR Source, LPSTR Target, LPSTR ExeName); + static PfnAddConsoleAliasA pfn = nullptr; - + if (pfn == nullptr) { pfn = (PfnAddConsoleAliasA)GetProcAddress(h, "AddConsoleAliasA"); } - + if (pfn != nullptr) { return pfn(Source, Target, ExeName); } } - + return FALSE; } -BOOL -APIENTRY -OneCoreDelay::AddConsoleAliasW( +BOOL APIENTRY OneCoreDelay::AddConsoleAliasW( _In_ LPWSTR Source, _In_ LPWSTR Target, _In_ LPWSTR ExeName) { HMODULE h = GetKernel32(); - + if (h != nullptr) { - typedef BOOL(WINAPI *PfnAddConsoleAliasW)(LPWSTR Source, LPWSTR Target, LPWSTR ExeName); - + typedef BOOL(WINAPI * PfnAddConsoleAliasW)(LPWSTR Source, LPWSTR Target, LPWSTR ExeName); + static PfnAddConsoleAliasW pfn = nullptr; - + if (pfn == nullptr) { pfn = (PfnAddConsoleAliasW)GetProcAddress(h, "AddConsoleAliasW"); } - + if (pfn != nullptr) { return pfn(Source, Target, ExeName); } } - + return FALSE; } -DWORD -APIENTRY -OneCoreDelay::GetConsoleAliasA( +DWORD APIENTRY OneCoreDelay::GetConsoleAliasA( _In_ LPSTR Source, _Out_writes_(TargetBufferLength) LPSTR TargetBuffer, _In_ DWORD TargetBufferLength, _In_ LPSTR ExeName) - { - HMODULE h = GetKernel32(); - +{ + HMODULE h = GetKernel32(); + if (h != nullptr) { - typedef BOOL(WINAPI *PfnGetConsoleAliasA)(LPSTR Source, LPSTR TargetBuffer, DWORD TargetBufferLength, LPSTR ExeName); - + typedef BOOL(WINAPI * PfnGetConsoleAliasA)(LPSTR Source, LPSTR TargetBuffer, DWORD TargetBufferLength, LPSTR ExeName); + static PfnGetConsoleAliasA pfn = nullptr; - + if (pfn == nullptr) { pfn = (PfnGetConsoleAliasA)GetProcAddress(h, "GetConsoleAliasA"); } - + if (pfn != nullptr) { return pfn(Source, TargetBuffer, TargetBufferLength, ExeName); } } - + return FALSE; - } - -DWORD -APIENTRY -OneCoreDelay::GetConsoleAliasW( +} + +DWORD APIENTRY OneCoreDelay::GetConsoleAliasW( _In_ LPWSTR Source, _Out_writes_(TargetBufferLength) LPWSTR TargetBuffer, _In_ DWORD TargetBufferLength, _In_ LPWSTR ExeName) - { - HMODULE h = GetKernel32(); - +{ + HMODULE h = GetKernel32(); + if (h != nullptr) { - typedef BOOL(WINAPI *PfnGetConsoleAliasW)(LPWSTR Source, LPWSTR TargetBuffer,DWORD TargetBufferLength, LPWSTR ExeName); - + typedef BOOL(WINAPI * PfnGetConsoleAliasW)(LPWSTR Source, LPWSTR TargetBuffer, DWORD TargetBufferLength, LPWSTR ExeName); + static PfnGetConsoleAliasW pfn = nullptr; - + if (pfn == nullptr) { pfn = (PfnGetConsoleAliasW)GetProcAddress(h, "GetConsoleAliasW"); } - + if (pfn != nullptr) { return pfn(Source, TargetBuffer, TargetBufferLength, ExeName); } } - - return FALSE; - } -BOOL -WINAPI -OneCoreDelay::GetCurrentConsoleFont( + return FALSE; +} + +BOOL WINAPI OneCoreDelay::GetCurrentConsoleFont( _In_ HANDLE hConsoleOutput, _In_ BOOL bMaximumWindow, - _Out_ PCONSOLE_FONT_INFO lpConsoleCurrentFont - ) - { - HMODULE h = GetKernel32(); - + _Out_ PCONSOLE_FONT_INFO lpConsoleCurrentFont) +{ + HMODULE h = GetKernel32(); + if (h != nullptr) { - typedef BOOL(WINAPI *PfnGetCurrentConsoleFont)(HANDLE hConsoleOutput, BOOL bMaximumWindow, PCONSOLE_FONT_INFO lpConsoleCurrentFont); - + typedef BOOL(WINAPI * PfnGetCurrentConsoleFont)(HANDLE hConsoleOutput, BOOL bMaximumWindow, PCONSOLE_FONT_INFO lpConsoleCurrentFont); + static PfnGetCurrentConsoleFont pfn = nullptr; - + if (pfn == nullptr) { pfn = (PfnGetCurrentConsoleFont)GetProcAddress(h, "GetCurrentConsoleFont"); } - + if (pfn != nullptr) { return pfn(hConsoleOutput, bMaximumWindow, lpConsoleCurrentFont); } } - - return FALSE; - } -BOOL -WINAPI -OneCoreDelay::GetCurrentConsoleFontEx( + return FALSE; +} + +BOOL WINAPI OneCoreDelay::GetCurrentConsoleFontEx( _In_ HANDLE hConsoleOutput, _In_ BOOL bMaximumWindow, _Out_ PCONSOLE_FONT_INFOEX lpConsoleCurrentFontEx) - { - HMODULE h = GetKernel32(); - +{ + HMODULE h = GetKernel32(); + if (h != nullptr) { - typedef BOOL(WINAPI *PfnGetCurrentConsoleFontEx)(HANDLE hConsoleOutput, BOOL bMaximumWindow, PCONSOLE_FONT_INFOEX lpConsoleCurrentFontEx); - + typedef BOOL(WINAPI * PfnGetCurrentConsoleFontEx)(HANDLE hConsoleOutput, BOOL bMaximumWindow, PCONSOLE_FONT_INFOEX lpConsoleCurrentFontEx); + static PfnGetCurrentConsoleFontEx pfn = nullptr; - + if (pfn == nullptr) { pfn = (PfnGetCurrentConsoleFontEx)GetProcAddress(h, "GetCurrentConsoleFontEx"); } - + if (pfn != nullptr) { return pfn(hConsoleOutput, bMaximumWindow, lpConsoleCurrentFontEx); } } - - return FALSE; - } -BOOL -WINAPI -OneCoreDelay::SetCurrentConsoleFontEx( + return FALSE; +} + +BOOL WINAPI OneCoreDelay::SetCurrentConsoleFontEx( _In_ HANDLE hConsoleOutput, _In_ BOOL bMaximumWindow, _In_ PCONSOLE_FONT_INFOEX lpConsoleCurrentFontEx) - { - HMODULE h = GetKernel32(); - +{ + HMODULE h = GetKernel32(); + if (h != nullptr) { - typedef BOOL(WINAPI *PfnSetCurrentConsoleFontEx)(HANDLE hConsoleOutput, BOOL bMaximumWindow, PCONSOLE_FONT_INFOEX lpConsoleCurrentFontEx); - + typedef BOOL(WINAPI * PfnSetCurrentConsoleFontEx)(HANDLE hConsoleOutput, BOOL bMaximumWindow, PCONSOLE_FONT_INFOEX lpConsoleCurrentFontEx); + static PfnSetCurrentConsoleFontEx pfn = nullptr; - + if (pfn == nullptr) { pfn = (PfnSetCurrentConsoleFontEx)GetProcAddress(h, "SetCurrentConsoleFontEx"); } - + if (pfn != nullptr) { return pfn(hConsoleOutput, bMaximumWindow, lpConsoleCurrentFontEx); } } - - return FALSE; - } -COORD -WINAPI -OneCoreDelay::GetConsoleFontSize( + return FALSE; +} + +COORD WINAPI OneCoreDelay::GetConsoleFontSize( _In_ HANDLE hConsoleOutput, - _In_ DWORD nFont - ) - { - HMODULE h = GetKernel32(); - + _In_ DWORD nFont) +{ + HMODULE h = GetKernel32(); + if (h != nullptr) { - typedef COORD(WINAPI *PfnGetConsoleFontSize)(HANDLE hConsoleOutput, DWORD nFont); - + typedef COORD(WINAPI * PfnGetConsoleFontSize)(HANDLE hConsoleOutput, DWORD nFont); + static PfnGetConsoleFontSize pfn = nullptr; - + if (pfn == nullptr) { pfn = (PfnGetConsoleFontSize)GetProcAddress(h, "GetConsoleFontSize"); } - + if (pfn != nullptr) { return pfn(hConsoleOutput, nFont); } } - - return {0}; - } - -BOOL -WINAPI -OneCoreDelay::GetNumberOfConsoleMouseButtons( - _Out_ LPDWORD lpNumberOfMouseButtons - ) - { - HMODULE h = GetKernel32(); - + + return { 0 }; +} + +BOOL WINAPI OneCoreDelay::GetNumberOfConsoleMouseButtons( + _Out_ LPDWORD lpNumberOfMouseButtons) +{ + HMODULE h = GetKernel32(); + if (h != nullptr) { - typedef BOOL(WINAPI *PfnGetNumberOfConsoleMouseButtons)(LPDWORD lpNumberOfMouseButtons); - + typedef BOOL(WINAPI * PfnGetNumberOfConsoleMouseButtons)(LPDWORD lpNumberOfMouseButtons); + static PfnGetNumberOfConsoleMouseButtons pfn = nullptr; - + if (pfn == nullptr) { pfn = (PfnGetNumberOfConsoleMouseButtons)GetProcAddress(h, "GetNumberOfConsoleMouseButtons"); } - + if (pfn != nullptr) { return pfn(lpNumberOfMouseButtons); } } - + return FALSE; - } - -HMENU -WINAPI -OneCoreDelay::GetMenu( +} + +HMENU WINAPI OneCoreDelay::GetMenu( _In_ HWND hWnd) - { - HMODULE h = GetUser32(); - +{ + HMODULE h = GetUser32(); + if (h != nullptr) { - typedef HMENU(WINAPI *PfnGetMenu)(HWND hWnd); - + typedef HMENU(WINAPI * PfnGetMenu)(HWND hWnd); + static PfnGetMenu pfn = nullptr; - + if (pfn == nullptr) { pfn = (PfnGetMenu)GetProcAddress(h, "GetMenu"); } - + if (pfn != nullptr) { return pfn(hWnd); } } - + return nullptr; - } - - +} diff --git a/src/host/ft_host/OneCoreDelay.hpp b/src/host/ft_host/OneCoreDelay.hpp index 01c2faa29..a15c5461a 100644 --- a/src/host/ft_host/OneCoreDelay.hpp +++ b/src/host/ft_host/OneCoreDelay.hpp @@ -22,89 +22,82 @@ Revision History: namespace OneCoreDelay { BOOLEAN - __stdcall - IsIsWindowPresent(); + __stdcall IsIsWindowPresent(); BOOLEAN - __stdcall - IsGetSystemMetricsPresent(); + __stdcall IsGetSystemMetricsPresent(); BOOLEAN - __stdcall - IsPostMessageWPresent(); + __stdcall IsPostMessageWPresent(); BOOLEAN - __stdcall - IsSendMessageWPresent(); + __stdcall IsSendMessageWPresent(); -BOOL -APIENTRY -AddConsoleAliasA( - _In_ LPSTR Source, - _In_ LPSTR Target, - _In_ LPSTR ExeName); + BOOL + APIENTRY + AddConsoleAliasA( + _In_ LPSTR Source, + _In_ LPSTR Target, + _In_ LPSTR ExeName); -BOOL -APIENTRY -AddConsoleAliasW( - _In_ LPWSTR Source, - _In_ LPWSTR Target, - _In_ LPWSTR ExeName); + BOOL + APIENTRY + AddConsoleAliasW( + _In_ LPWSTR Source, + _In_ LPWSTR Target, + _In_ LPWSTR ExeName); -DWORD -APIENTRY -GetConsoleAliasA( - _In_ LPSTR Source, - _Out_writes_(TargetBufferLength) LPSTR TargetBuffer, - _In_ DWORD TargetBufferLength, - _In_ LPSTR ExeName); - -DWORD -APIENTRY -GetConsoleAliasW( - _In_ LPWSTR Source, - _Out_writes_(TargetBufferLength) LPWSTR TargetBuffer, - _In_ DWORD TargetBufferLength, - _In_ LPWSTR ExeName); + DWORD + APIENTRY + GetConsoleAliasA( + _In_ LPSTR Source, + _Out_writes_(TargetBufferLength) LPSTR TargetBuffer, + _In_ DWORD TargetBufferLength, + _In_ LPSTR ExeName); -BOOL -WINAPI -GetCurrentConsoleFont( - _In_ HANDLE hConsoleOutput, - _In_ BOOL bMaximumWindow, - _Out_ PCONSOLE_FONT_INFO lpConsoleCurrentFont - ); + DWORD + APIENTRY + GetConsoleAliasW( + _In_ LPWSTR Source, + _Out_writes_(TargetBufferLength) LPWSTR TargetBuffer, + _In_ DWORD TargetBufferLength, + _In_ LPWSTR ExeName); -BOOL -WINAPI -GetCurrentConsoleFontEx( - _In_ HANDLE hConsoleOutput, - _In_ BOOL bMaximumWindow, - _Out_ PCONSOLE_FONT_INFOEX lpConsoleCurrentFontEx); + BOOL + WINAPI + GetCurrentConsoleFont( + _In_ HANDLE hConsoleOutput, + _In_ BOOL bMaximumWindow, + _Out_ PCONSOLE_FONT_INFO lpConsoleCurrentFont); -BOOL -WINAPI -SetCurrentConsoleFontEx( - _In_ HANDLE hConsoleOutput, - _In_ BOOL bMaximumWindow, - _In_ PCONSOLE_FONT_INFOEX lpConsoleCurrentFontEx); + BOOL + WINAPI + GetCurrentConsoleFontEx( + _In_ HANDLE hConsoleOutput, + _In_ BOOL bMaximumWindow, + _Out_ PCONSOLE_FONT_INFOEX lpConsoleCurrentFontEx); + + BOOL + WINAPI + SetCurrentConsoleFontEx( + _In_ HANDLE hConsoleOutput, + _In_ BOOL bMaximumWindow, + _In_ PCONSOLE_FONT_INFOEX lpConsoleCurrentFontEx); + + COORD + WINAPI + GetConsoleFontSize( + _In_ HANDLE hConsoleOutput, + _In_ DWORD nFont); + + BOOL + WINAPI + GetNumberOfConsoleMouseButtons( + _Out_ LPDWORD lpNumberOfMouseButtons); + + HMENU + WINAPI + GetMenu( + _In_ HWND hWnd); -COORD -WINAPI -GetConsoleFontSize( - _In_ HANDLE hConsoleOutput, - _In_ DWORD nFont - ); - -BOOL -WINAPI -GetNumberOfConsoleMouseButtons( - _Out_ LPDWORD lpNumberOfMouseButtons - ); - -HMENU -WINAPI -GetMenu( - _In_ HWND hWnd); - }; diff --git a/src/host/ft_host/precomp.h b/src/host/ft_host/precomp.h index 0fdc2bbb9..e24c1720b 100644 --- a/src/host/ft_host/precomp.h +++ b/src/host/ft_host/precomp.h @@ -21,8 +21,8 @@ #include #endif -#define CM_SET_KEY_STATE (WM_USER+18) -#define CM_SET_KEYBOARD_LAYOUT (WM_USER+19) +#define CM_SET_KEY_STATE (WM_USER + 18) +#define CM_SET_KEYBOARD_LAYOUT (WM_USER + 19) #include "OneCoreDelay.hpp" diff --git a/src/host/ft_integrity/IntegrityTest.cpp b/src/host/ft_integrity/IntegrityTest.cpp index 3be3783c3..c29f08357 100644 --- a/src/host/ft_integrity/IntegrityTest.cpp +++ b/src/host/ft_integrity/IntegrityTest.cpp @@ -46,15 +46,15 @@ static void s_RunViaCreateProcess(_In_ PCWSTR pwszExePath) LOG_OUTPUT(L"Launching '%s'", cmdlineMutable.get()); THROW_IF_WIN32_BOOL_FALSE(CreateProcessW(nullptr, - cmdlineMutable.get(), - nullptr, - nullptr, - TRUE, - 0, - nullptr, - nullptr, - &si, - &pi)); + cmdlineMutable.get(), + nullptr, + nullptr, + TRUE, + 0, + nullptr, + nullptr, + &si, + &pi)); WaitForSingleObject(pi.hProcess, INFINITE); } @@ -67,7 +67,7 @@ static void s_SetConIntegrityLow() // First assemble with WinRT strings including the Test Deployment Directory C:\data\test\bin which can vary. auto commandLine = ref new String(L"%WINDIR%\\system32\\icacls.exe ") + - TAEFHelper::GetTestDeploymentDirectory() + ref new String(L"conintegrity.exe /setintegritylevel low"); + TAEFHelper::GetTestDeploymentDirectory() + ref new String(L"conintegrity.exe /setintegritylevel low"); // Now call our helper to munge the environment strings then run it and wait for exit. s_RunViaCreateProcess(commandLine->Data()); @@ -113,11 +113,11 @@ bool IntegrityTest::ClassSetup() #if defined(_X86_) auto vclibPackage = DeploymentHelper::AddPackageIfNotPresent(testDeploymentDir + ref new String(L"Microsoft.VCLibs.x86.14.00.appx")); -#elif defined (_AMD64_) +#elif defined(_AMD64_) auto vclibPackage = DeploymentHelper::AddPackageIfNotPresent(testDeploymentDir + ref new String(L"Microsoft.VCLibs.x64.14.00.appx")); -#elif defined (_ARM_) +#elif defined(_ARM_) auto vclibPackage = DeploymentHelper::AddPackageIfNotPresent(testDeploymentDir + ref new String(L"Microsoft.VCLibs.arm.14.00.appx")); -#elif defined (_ARM64_) +#elif defined(_ARM64_) auto vclibPackage = DeploymentHelper::AddPackageIfNotPresent(testDeploymentDir + ref new String(L"Microsoft.VCLibs.arm64.14.00.appx")); #else #error Unknown architecture for test. @@ -186,8 +186,7 @@ void IntegrityTest::_RunUWPConIntegrityViaTile() // on OneCore-derived Windows SKUs. // Example: RCOW;1;0 = ReadConsoleOutputW returning TRUE and a GetLastError() of 0. // Please see conintegrity.exe and conintegrityuwp.exe for how they are formed. -static PCWSTR _rgpwszExpectedSuccess[] = -{ +static PCWSTR _rgpwszExpectedSuccess[] = { L"RCOW;1;0", L"RCOA;1;0", L"RCOCW;1;0", @@ -197,8 +196,7 @@ static PCWSTR _rgpwszExpectedSuccess[] = L"WCIW;1;0" }; -static PCWSTR _rgpwszExpectedFail[] = -{ +static PCWSTR _rgpwszExpectedFail[] = { L"RCOW;0;5", L"RCOA;0;5", L"RCOCW;0;5", @@ -318,7 +316,7 @@ PCWSTR IntegrityTest::s_GetMyIntegrityLevel() THROW_IF_FAILED(wil::GetTokenInformationNoThrow(tokenLabel, GetCurrentProcessToken())); dwIntegrityLevel = *GetSidSubAuthority(tokenLabel->Label.Sid, - (DWORD)(UCHAR)(*GetSidSubAuthorityCount(tokenLabel->Label.Sid) - 1)); + (DWORD)(UCHAR)(*GetSidSubAuthorityCount(tokenLabel->Label.Sid) - 1)); switch (dwIntegrityLevel) { diff --git a/src/host/ft_integrity/IntegrityTest.hpp b/src/host/ft_integrity/IntegrityTest.hpp index 99b707407..9e4102c50 100644 --- a/src/host/ft_integrity/IntegrityTest.hpp +++ b/src/host/ft_integrity/IntegrityTest.hpp @@ -17,36 +17,36 @@ public: BEGIN_TEST_CLASS(IntegrityTest) // We need each method to start it in its own console. TEST_CLASS_PROPERTY(L"IsolationLevel", L"Method") - END_TEST_CLASS() + END_TEST_CLASS() - TEST_CLASS_SETUP(ClassSetup) - TEST_CLASS_CLEANUP(ClassCleanup) + TEST_CLASS_SETUP(ClassSetup) + TEST_CLASS_CLEANUP(ClassCleanup) - BEGIN_TEST_METHOD(TestLaunchLowILFromHigh) + BEGIN_TEST_METHOD(TestLaunchLowILFromHigh) TEST_METHOD_PROPERTY(L"RunAs", L"ElevatedUserOrSystem") - END_TEST_METHOD() + END_TEST_METHOD() - BEGIN_TEST_METHOD(TestLaunchLowILFromMedium) + BEGIN_TEST_METHOD(TestLaunchLowILFromMedium) TEST_METHOD_PROPERTY(L"RunAs", L"RestrictedUser") - END_TEST_METHOD() + END_TEST_METHOD() - BEGIN_TEST_METHOD(TestLaunchAppFromHigh) + BEGIN_TEST_METHOD(TestLaunchAppFromHigh) TEST_METHOD_PROPERTY(L"RunAs", L"ElevatedUserOrSystem") - END_TEST_METHOD() + END_TEST_METHOD() - BEGIN_TEST_METHOD(TestLaunchAppFromMedium) + BEGIN_TEST_METHOD(TestLaunchAppFromMedium) TEST_METHOD_PROPERTY(L"RunAs", L"RestrictedUser") - END_TEST_METHOD() + END_TEST_METHOD() - BEGIN_TEST_METHOD(TestLaunchAppAlone) + BEGIN_TEST_METHOD(TestLaunchAppAlone) TEST_METHOD_PROPERTY(L"RunAs", L"RestrictedUser") - END_TEST_METHOD() + END_TEST_METHOD() + + static PCWSTR s_GetMyIntegrityLevel(); + static void s_LogMyIntegrityLevel(PCWSTR WhoAmI); - static PCWSTR s_GetMyIntegrityLevel(); - static void s_LogMyIntegrityLevel(PCWSTR WhoAmI); - private: - Platform::String^ _appAumid; + Platform::String ^ _appAumid; void _RunWin32ConIntegrityLowHelper(); void _RunUWPConIntegrityAppHelper(); diff --git a/src/host/getset.cpp b/src/host/getset.cpp index 35e510f6f..3606bd093 100644 --- a/src/host/getset.cpp +++ b/src/host/getset.cpp @@ -83,8 +83,7 @@ void ApiRoutines::GetConsoleOutputModeImpl(SCREEN_INFORMATION& context, ULONG& m // - event - The count of events in the queue // Return Value: // - S_OK or math failure. -[[nodiscard]] -HRESULT ApiRoutines::GetNumberOfConsoleInputEventsImpl(const InputBuffer& context, ULONG& events) noexcept +[[nodiscard]] HRESULT ApiRoutines::GetNumberOfConsoleInputEventsImpl(const InputBuffer& context, ULONG& events) noexcept { try { @@ -209,10 +208,9 @@ void ApiRoutines::GetNumberOfConsoleMouseButtonsImpl(ULONG& buttons) noexcept // - size - The X by Y pixel size of the font // Return Value: // - S_OK, E_INVALIDARG or code from thrown exception -[[nodiscard]] -HRESULT ApiRoutines::GetConsoleFontSizeImpl(const SCREEN_INFORMATION& context, - const DWORD index, - COORD& size) noexcept +[[nodiscard]] HRESULT ApiRoutines::GetConsoleFontSizeImpl(const SCREEN_INFORMATION& context, + const DWORD index, + COORD& size) noexcept { try { @@ -243,10 +241,9 @@ HRESULT ApiRoutines::GetConsoleFontSizeImpl(const SCREEN_INFORMATION& context, // - consoleFontInfoEx - structure containing font information like size, family, weight, etc. // Return Value: // - S_OK, string copy failure code or code from thrown exception -[[nodiscard]] -HRESULT ApiRoutines::GetCurrentConsoleFontExImpl(const SCREEN_INFORMATION& context, - const bool isForMaximumWindowSize, - CONSOLE_FONT_INFOEX& consoleFontInfoEx) noexcept +[[nodiscard]] HRESULT ApiRoutines::GetCurrentConsoleFontExImpl(const SCREEN_INFORMATION& context, + const bool isForMaximumWindowSize, + CONSOLE_FONT_INFOEX& consoleFontInfoEx) noexcept { try { @@ -287,10 +284,9 @@ HRESULT ApiRoutines::GetCurrentConsoleFontExImpl(const SCREEN_INFORMATION& conte // - consoleFontInfoEx - structure containing font information like size, family, weight, etc. // Return Value: // - S_OK, string copy failure code or code from thrown exception -[[nodiscard]] -HRESULT ApiRoutines::SetCurrentConsoleFontExImpl(IConsoleOutputObject& context, - const bool /*isForMaximumWindowSize*/, - const CONSOLE_FONT_INFOEX& consoleFontInfoEx) noexcept +[[nodiscard]] HRESULT ApiRoutines::SetCurrentConsoleFontExImpl(IConsoleOutputObject& context, + const bool /*isForMaximumWindowSize*/, + const CONSOLE_FONT_INFOEX& consoleFontInfoEx) noexcept { try { @@ -324,8 +320,7 @@ HRESULT ApiRoutines::SetCurrentConsoleFontExImpl(IConsoleOutputObject& context, // - mode - flags that change behavior of the buffer // Return Value: // - S_OK, E_INVALIDARG, or failure code from thrown exception -[[nodiscard]] -HRESULT ApiRoutines::SetConsoleInputModeImpl(InputBuffer& context, const ULONG mode) noexcept +[[nodiscard]] HRESULT ApiRoutines::SetConsoleInputModeImpl(InputBuffer& context, const ULONG mode) noexcept { try { @@ -386,8 +381,7 @@ HRESULT ApiRoutines::SetConsoleInputModeImpl(InputBuffer& context, const ULONG m // - mode - flags that change behavior of the buffer // Return Value: // - S_OK, E_INVALIDARG, or failure code from thrown exception -[[nodiscard]] -HRESULT ApiRoutines::SetConsoleOutputModeImpl(SCREEN_INFORMATION& context, const ULONG mode) noexcept +[[nodiscard]] HRESULT ApiRoutines::SetConsoleOutputModeImpl(SCREEN_INFORMATION& context, const ULONG mode) noexcept { try { @@ -405,7 +399,8 @@ HRESULT ApiRoutines::SetConsoleOutputModeImpl(SCREEN_INFORMATION& context, const screenInfo.OutputMode = dwNewMode; // if we're moving from VT on->off - if (WI_IsFlagClear(dwNewMode, ENABLE_VIRTUAL_TERMINAL_PROCESSING) && WI_IsFlagSet(dwOldMode, ENABLE_VIRTUAL_TERMINAL_PROCESSING)) + if (WI_IsFlagClear(dwNewMode, ENABLE_VIRTUAL_TERMINAL_PROCESSING) && + WI_IsFlagSet(dwOldMode, ENABLE_VIRTUAL_TERMINAL_PROCESSING)) { // jiggle the handle screenInfo.GetStateMachine().ResetState(); @@ -426,7 +421,7 @@ HRESULT ApiRoutines::SetConsoleOutputModeImpl(SCREEN_INFORMATION& context, const // but only do this if we're not in conpty mode. if (!gci.IsInVtIoMode() && (WI_IsFlagSet(dwNewMode, ENABLE_VIRTUAL_TERMINAL_PROCESSING) != WI_IsFlagSet(dwOldMode, ENABLE_VIRTUAL_TERMINAL_PROCESSING) || - WI_IsFlagSet(dwNewMode, ENABLE_LVB_GRID_WORLDWIDE) != WI_IsFlagSet(dwOldMode, ENABLE_LVB_GRID_WORLDWIDE)) ) + WI_IsFlagSet(dwNewMode, ENABLE_LVB_GRID_WORLDWIDE) != WI_IsFlagSet(dwOldMode, ENABLE_LVB_GRID_WORLDWIDE))) { auto* pRender = ServiceLocator::LocateGlobals().pRender; if (pRender) @@ -499,9 +494,8 @@ void ApiRoutines::GetLargestConsoleWindowSizeImpl(const SCREEN_INFORMATION& cont // - size - size in character rows and columns // Return Value: // - S_OK, E_INVALIDARG, or failure code from thrown exception -[[nodiscard]] -HRESULT ApiRoutines::SetConsoleScreenBufferSizeImpl(SCREEN_INFORMATION& context, - const COORD size) noexcept +[[nodiscard]] HRESULT ApiRoutines::SetConsoleScreenBufferSizeImpl(SCREEN_INFORMATION& context, + const COORD size) noexcept { try { @@ -515,11 +509,13 @@ HRESULT ApiRoutines::SetConsoleScreenBufferSizeImpl(SCREEN_INFORMATION& context, if (!ServiceLocator::LocateGlobals().IsHeadless()) { COORD const coordMin = screenInfo.GetMinWindowSizeInCharacters(); + // clang-format off // Make sure requested screen buffer size isn't smaller than the window. RETURN_HR_IF(E_INVALIDARG, (size.X < screenInfo.GetViewport().Width() || size.Y < screenInfo.GetViewport().Height() || size.Y < coordMin.Y || size.X < coordMin.X)); + // clang-format on } // Ensure the requested size isn't larger than we can handle in our data type. @@ -544,16 +540,17 @@ HRESULT ApiRoutines::SetConsoleScreenBufferSizeImpl(SCREEN_INFORMATION& context, // - data - metadata information structure like buffer size, viewport size, colors, and more. // Return Value: // - S_OK, E_INVALIDARG, or failure code from thrown exception -[[nodiscard]] -HRESULT ApiRoutines::SetConsoleScreenBufferInfoExImpl(SCREEN_INFORMATION& context, - const CONSOLE_SCREEN_BUFFER_INFOEX& data) noexcept +[[nodiscard]] HRESULT ApiRoutines::SetConsoleScreenBufferInfoExImpl(SCREEN_INFORMATION& context, + const CONSOLE_SCREEN_BUFFER_INFOEX& data) noexcept { try { + // clang-format off RETURN_HR_IF(E_INVALIDARG, (data.dwSize.X == 0 || data.dwSize.Y == 0 || data.dwSize.X == SHRT_MAX || data.dwSize.Y == SHRT_MAX)); + // clang-format on LockConsole(); auto Unlock = wil::scope_exit([&] { UnlockConsole(); }); @@ -625,9 +622,8 @@ HRESULT ApiRoutines::SetConsoleScreenBufferInfoExImpl(SCREEN_INFORMATION& contex // - position - The X/Y (row/column) position in the buffer to place the cursor // Return Value: // - S_OK, E_INVALIDARG, or failure code from thrown exception -[[nodiscard]] -HRESULT ApiRoutines::SetConsoleCursorPositionImpl(SCREEN_INFORMATION& context, - const COORD position) noexcept +[[nodiscard]] HRESULT ApiRoutines::SetConsoleCursorPositionImpl(SCREEN_INFORMATION& context, + const COORD position) noexcept { try { @@ -637,10 +633,12 @@ HRESULT ApiRoutines::SetConsoleCursorPositionImpl(SCREEN_INFORMATION& context, CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); const COORD coordScreenBufferSize = context.GetBufferSize().Dimensions(); + // clang-format off RETURN_HR_IF(E_INVALIDARG, (position.X >= coordScreenBufferSize.X || position.Y >= coordScreenBufferSize.Y || position.X < 0 || position.Y < 0)); + // clang-format on // MSFT: 15813316 - Try to use this SetCursorPosition call to inherit the cursor position. RETURN_IF_FAILED(gci.GetVtIo()->SetCursorPosition(position)); @@ -688,10 +686,9 @@ HRESULT ApiRoutines::SetConsoleCursorPositionImpl(SCREEN_INFORMATION& context, // - isVisible - Whether or not the cursor should be displayed // Return Value: // - S_OK, E_INVALIDARG, or failure code from thrown exception -[[nodiscard]] -HRESULT ApiRoutines::SetConsoleCursorInfoImpl(SCREEN_INFORMATION& context, - const ULONG size, - const bool isVisible) noexcept +[[nodiscard]] HRESULT ApiRoutines::SetConsoleCursorInfoImpl(SCREEN_INFORMATION& context, + const ULONG size, + const bool isVisible) noexcept { try { @@ -717,10 +714,9 @@ HRESULT ApiRoutines::SetConsoleCursorInfoImpl(SCREEN_INFORMATION& context, // - windowRect - Updated viewport rectangle information // Return Value: // - S_OK, E_INVALIDARG, or failure code from thrown exception -[[nodiscard]] -HRESULT ApiRoutines::SetConsoleWindowInfoImpl(SCREEN_INFORMATION& context, - const bool isAbsolute, - const SMALL_RECT& windowRect) noexcept +[[nodiscard]] HRESULT ApiRoutines::SetConsoleWindowInfoImpl(SCREEN_INFORMATION& context, + const bool isAbsolute, + const SMALL_RECT& windowRect) noexcept { try { @@ -754,7 +750,6 @@ HRESULT ApiRoutines::SetConsoleWindowInfoImpl(SCREEN_INFORMATION& context, { COORD const coordMax = context.GetMaxWindowSizeInCharacters(); RETURN_HR_IF(E_INVALIDARG, (NewWindowSize.X > coordMax.X || NewWindowSize.Y > coordMax.Y)); - } else if (g.getConsoleInformation().IsInVtIoMode()) { @@ -786,13 +781,12 @@ HRESULT ApiRoutines::SetConsoleWindowInfoImpl(SCREEN_INFORMATION& context, // - fillAttribute - Fills in the region left behind when the source is "lifted" out of its original location. The color to use. // Return Value: // - S_OK, E_INVALIDARG, or failure code from thrown exception -[[nodiscard]] -HRESULT ApiRoutines::ScrollConsoleScreenBufferAImpl(SCREEN_INFORMATION& context, - const SMALL_RECT& source, - const COORD target, - std::optional clip, - const char fillCharacter, - const WORD fillAttribute) noexcept +[[nodiscard]] HRESULT ApiRoutines::ScrollConsoleScreenBufferAImpl(SCREEN_INFORMATION& context, + const SMALL_RECT& source, + const COORD target, + std::optional clip, + const char fillCharacter, + const WORD fillAttribute) noexcept { try { @@ -814,20 +808,18 @@ HRESULT ApiRoutines::ScrollConsoleScreenBufferAImpl(SCREEN_INFORMATION& context, // - fillAttribute - Fills in the region left behind when the source is "lifted" out of its original location. The color to use. // Return Value: // - S_OK, E_INVALIDARG, or failure code from thrown exception -[[nodiscard]] -HRESULT ApiRoutines::ScrollConsoleScreenBufferWImpl(SCREEN_INFORMATION& context, - const SMALL_RECT& source, - const COORD target, - std::optional clip, - const wchar_t fillCharacter, - const WORD fillAttribute) noexcept +[[nodiscard]] HRESULT ApiRoutines::ScrollConsoleScreenBufferWImpl(SCREEN_INFORMATION& context, + const SMALL_RECT& source, + const COORD target, + std::optional clip, + const wchar_t fillCharacter, + const WORD fillAttribute) noexcept { try { LockConsole(); auto Unlock = wil::scope_exit([&] { UnlockConsole(); }); - TextAttribute useThisAttr(fillAttribute); // Here we're being a little clever - similar to FillConsoleOutputAttributeImpl @@ -868,9 +860,8 @@ HRESULT ApiRoutines::ScrollConsoleScreenBufferWImpl(SCREEN_INFORMATION& context, // - attribute - Color information // Return Value: // - S_OK, E_INVALIDARG, or failure code from thrown exception -[[nodiscard]] -HRESULT ApiRoutines::SetConsoleTextAttributeImpl(SCREEN_INFORMATION& context, - const WORD attribute) noexcept +[[nodiscard]] HRESULT ApiRoutines::SetConsoleTextAttributeImpl(SCREEN_INFORMATION& context, + const WORD attribute) noexcept { CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); try @@ -980,8 +971,7 @@ void DoSrvPrivateBoldText(SCREEN_INFORMATION& screenInfo, const bool bolded) // - codepage - The codepage // Return Value: // - S_OK, E_INVALIDARG, or failure code from thrown exception -[[nodiscard]] -HRESULT ApiRoutines::SetConsoleOutputCodePageImpl(const ULONG codepage) noexcept +[[nodiscard]] HRESULT ApiRoutines::SetConsoleOutputCodePageImpl(const ULONG codepage) noexcept { try { @@ -1012,8 +1002,7 @@ HRESULT ApiRoutines::SetConsoleOutputCodePageImpl(const ULONG codepage) noexcept // - codepage - The codepage // Return Value: // - S_OK, E_INVALIDARG, or failure code from thrown exception -[[nodiscard]] -HRESULT ApiRoutines::SetConsoleInputCodePageImpl(const ULONG codepage) noexcept +[[nodiscard]] HRESULT ApiRoutines::SetConsoleInputCodePageImpl(const ULONG codepage) noexcept { try { @@ -1199,10 +1188,9 @@ void ApiRoutines::GetConsoleDisplayModeImpl(ULONG& flags) noexcept // NOTE: // - This was in private.c, but turns out to be a public API: // - See: http://msdn.microsoft.com/en-us/library/windows/desktop/ms686028(v=vs.85).aspx -[[nodiscard]] -HRESULT ApiRoutines::SetConsoleDisplayModeImpl(SCREEN_INFORMATION& context, - const ULONG flags, - COORD& newSize) noexcept +[[nodiscard]] HRESULT ApiRoutines::SetConsoleDisplayModeImpl(SCREEN_INFORMATION& context, + const ULONG flags, + COORD& newSize) noexcept { try { @@ -1213,7 +1201,7 @@ HRESULT ApiRoutines::SetConsoleDisplayModeImpl(SCREEN_INFORMATION& context, { auto Unlock = wil::scope_exit([&] { UnlockConsole(); }); - SCREEN_INFORMATION& screenInfo = context.GetActiveBuffer(); + SCREEN_INFORMATION& screenInfo = context.GetActiveBuffer(); newSize = screenInfo.GetBufferSize().Dimensions(); RETURN_HR_IF(E_INVALIDARG, !(screenInfo.IsActiveScreenBuffer())); @@ -1251,8 +1239,7 @@ HRESULT ApiRoutines::SetConsoleDisplayModeImpl(SCREEN_INFORMATION& context, // - fApplicationMode - set to true to enable Application Mode Input, false for Numeric Mode Input. // Return value: // - True if handled successfully. False otherwise. -[[nodiscard]] -NTSTATUS DoSrvPrivateSetCursorKeysMode(_In_ bool fApplicationMode) +[[nodiscard]] NTSTATUS DoSrvPrivateSetCursorKeysMode(_In_ bool fApplicationMode) { CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); if (gci.pInputBuffer == nullptr) @@ -1270,8 +1257,7 @@ NTSTATUS DoSrvPrivateSetCursorKeysMode(_In_ bool fApplicationMode) // - fApplicationMode - set to true to enable Application Mode Input, false for Numeric Mode Input. // Return value: // - True if handled successfully. False otherwise. -[[nodiscard]] -NTSTATUS DoSrvPrivateSetKeypadMode(_In_ bool fApplicationMode) +[[nodiscard]] NTSTATUS DoSrvPrivateSetKeypadMode(_In_ bool fApplicationMode) { CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); if (gci.pInputBuffer == nullptr) @@ -1319,8 +1305,7 @@ void DoSrvPrivateAllowCursorBlinking(SCREEN_INFORMATION& screenInfo, const bool // left and right margins in the future. // Return value: // - True if handled successfully. False otherwise. -[[nodiscard]] -NTSTATUS DoSrvPrivateSetScrollingRegion(SCREEN_INFORMATION& screenInfo, const SMALL_RECT* const psrScrollMargins) +[[nodiscard]] NTSTATUS DoSrvPrivateSetScrollingRegion(SCREEN_INFORMATION& screenInfo, const SMALL_RECT* const psrScrollMargins) { NTSTATUS Status = STATUS_SUCCESS; @@ -1346,8 +1331,7 @@ NTSTATUS DoSrvPrivateSetScrollingRegion(SCREEN_INFORMATION& screenInfo, const SM // - screenInfo - a pointer to the screen buffer that should perform the reverse line feed // Return value: // - True if handled successfully. False otherwise. -[[nodiscard]] -NTSTATUS DoSrvPrivateReverseLineFeed(SCREEN_INFORMATION& screenInfo) +[[nodiscard]] NTSTATUS DoSrvPrivateReverseLineFeed(SCREEN_INFORMATION& screenInfo) { NTSTATUS Status = STATUS_SUCCESS; @@ -1409,8 +1393,7 @@ NTSTATUS DoSrvPrivateReverseLineFeed(SCREEN_INFORMATION& screenInfo) // - lines - The number of lines to move the cursor. Up is negative, down positive. // Return value: // - S_OK if handled successfully. Otherwise an appropriate HRESULT for failing to clamp. -[[nodiscard]] -HRESULT DoSrvMoveCursorVertically(SCREEN_INFORMATION& screenInfo, const short lines) +[[nodiscard]] HRESULT DoSrvMoveCursorVertically(SCREEN_INFORMATION& screenInfo, const short lines) { auto& cursor = screenInfo.GetActiveBuffer().GetTextBuffer().GetCursor(); const int currentCursorY = cursor.GetPosition().Y; @@ -1447,8 +1430,7 @@ HRESULT DoSrvMoveCursorVertically(SCREEN_INFORMATION& screenInfo, const short li // - screenInfo - a reference to the screen buffer that should use an alternate buffer // Return value: // - True if handled successfully. False otherwise. -[[nodiscard]] -NTSTATUS DoSrvPrivateUseAlternateScreenBuffer(SCREEN_INFORMATION& screenInfo) +[[nodiscard]] NTSTATUS DoSrvPrivateUseAlternateScreenBuffer(SCREEN_INFORMATION& screenInfo) { return screenInfo.GetActiveBuffer().UseAlternateScreenBuffer(); } @@ -1472,8 +1454,7 @@ void DoSrvPrivateUseMainScreenBuffer(SCREEN_INFORMATION& screenInfo) // // Return value: // - STATUS_SUCCESS if handled successfully. Otherwise, an appropriate status code indicating the error. -[[nodiscard]] -NTSTATUS DoSrvPrivateHorizontalTabSet() +[[nodiscard]] NTSTATUS DoSrvPrivateHorizontalTabSet() { CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); SCREEN_INFORMATION& _screenBuffer = gci.GetActiveOutputBuffer().GetActiveBuffer(); @@ -1497,8 +1478,7 @@ NTSTATUS DoSrvPrivateHorizontalTabSet() // fForward - whether to tab forward or backwards // Return value: // - STATUS_SUCCESS if handled successfully. Otherwise, an appropriate status code indicating the error. -[[nodiscard]] -NTSTATUS DoPrivateTabHelper(const SHORT sNumTabs, _In_ bool fForward) +[[nodiscard]] NTSTATUS DoPrivateTabHelper(const SHORT sNumTabs, _In_ bool fForward) { CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); SCREEN_INFORMATION& _screenBuffer = gci.GetActiveOutputBuffer().GetActiveBuffer(); @@ -1526,8 +1506,7 @@ NTSTATUS DoPrivateTabHelper(const SHORT sNumTabs, _In_ bool fForward) // - sNumTabs - The number of tabs to perform. // Return value: // - STATUS_SUCCESS if handled successfully. Otherwise, an appropriate status code indicating the error. -[[nodiscard]] -NTSTATUS DoSrvPrivateForwardTab(const SHORT sNumTabs) +[[nodiscard]] NTSTATUS DoSrvPrivateForwardTab(const SHORT sNumTabs) { return DoPrivateTabHelper(sNumTabs, true); } @@ -1539,8 +1518,7 @@ NTSTATUS DoSrvPrivateForwardTab(const SHORT sNumTabs) // - sNumTabs - The number of tabs to perform. // Return value: // - STATUS_SUCCESS if handled successfully. Otherwise, an appropriate status code indicating the error. -[[nodiscard]] -NTSTATUS DoSrvPrivateBackwardsTab(const SHORT sNumTabs) +[[nodiscard]] NTSTATUS DoSrvPrivateBackwardsTab(const SHORT sNumTabs) { return DoPrivateTabHelper(sNumTabs, false); } @@ -1646,8 +1624,7 @@ void DoSrvPrivateEnableAlternateScroll(const bool fEnable) // The ScreenBuffer to perform the erase on. // Return value: // - STATUS_SUCCESS if we succeeded, otherwise the NTSTATUS version of the failure. -[[nodiscard]] -NTSTATUS DoSrvPrivateEraseAll(SCREEN_INFORMATION& screenInfo) +[[nodiscard]] NTSTATUS DoSrvPrivateEraseAll(SCREEN_INFORMATION& screenInfo) { return NTSTATUS_FROM_HRESULT(screenInfo.GetActiveBuffer().VtEraseAll()); } @@ -1674,8 +1651,7 @@ void DoSrvSetCursorColor(SCREEN_INFORMATION& screenInfo, // - pwAttributes - Pointer to space that will receive color attributes data // Return Value: // - STATUS_SUCCESS if we succeeded or STATUS_INVALID_PARAMETER for bad params (nullptr). -[[nodiscard]] -NTSTATUS DoSrvPrivateGetConsoleScreenBufferAttributes(_In_ const SCREEN_INFORMATION& screenInfo, _Out_ WORD* const pwAttributes) +[[nodiscard]] NTSTATUS DoSrvPrivateGetConsoleScreenBufferAttributes(_In_ const SCREEN_INFORMATION& screenInfo, _Out_ WORD* const pwAttributes) { NTSTATUS Status = STATUS_SUCCESS; @@ -1720,11 +1696,10 @@ void DoSrvPrivateRefreshWindow(_In_ const SCREEN_INFORMATION& screenInfo) // - isOriginal - If true, gets the title when we booted up. If false, gets whatever it is set to right now. // Return Value: // - S_OK, E_INVALIDARG, or failure code from thrown exception -[[nodiscard]] -HRESULT GetConsoleTitleWImplHelper(std::optional> title, - size_t& written, - size_t& needed, - const bool isOriginal) noexcept +[[nodiscard]] HRESULT GetConsoleTitleWImplHelper(std::optional> title, + size_t& written, + size_t& needed, + const bool isOriginal) noexcept { try { @@ -1784,11 +1759,10 @@ HRESULT GetConsoleTitleWImplHelper(std::optional> title, // Return Value: // - S_OK, E_INVALIDARG, or failure code from thrown exception -[[nodiscard]] -HRESULT GetConsoleTitleAImplHelper(gsl::span title, - size_t& written, - size_t& needed, - const bool isOriginal) noexcept +[[nodiscard]] HRESULT GetConsoleTitleAImplHelper(gsl::span title, + size_t& written, + size_t& needed, + const bool isOriginal) noexcept { try { @@ -1834,7 +1808,6 @@ HRESULT GetConsoleTitleAImplHelper(gsl::span title, // Copy safely to output buffer HRESULT const hr = StringCchCopyNA(title.data(), title.size(), converted.data(), converted.size()); - // Insufficient buffer is allowed. If we return a partial string, that's still OK by historical/compat standards. // Just say how much we managed to return. if (SUCCEEDED(hr) || STRSAFE_E_INSUFFICIENT_BUFFER == hr) @@ -1863,7 +1836,6 @@ HRESULT GetConsoleTitleAImplHelper(gsl::span title, return S_OK; } CATCH_RETURN(); - } // Routine Description: @@ -1875,10 +1847,9 @@ HRESULT GetConsoleTitleAImplHelper(gsl::span title, // - needed - The number of characters we would need to completely write out the title. // Return Value: // - S_OK, E_INVALIDARG, or failure code from thrown exception -[[nodiscard]] -HRESULT ApiRoutines::GetConsoleTitleAImpl(gsl::span title, - size_t& written, - size_t& needed) noexcept +[[nodiscard]] HRESULT ApiRoutines::GetConsoleTitleAImpl(gsl::span title, + size_t& written, + size_t& needed) noexcept { try { @@ -1899,10 +1870,9 @@ HRESULT ApiRoutines::GetConsoleTitleAImpl(gsl::span title, // - needed - The number of characters we would need to completely write out the title. // Return Value: // - S_OK, E_INVALIDARG, or failure code from thrown exception -[[nodiscard]] -HRESULT ApiRoutines::GetConsoleTitleWImpl(gsl::span title, - size_t& written, - size_t& needed) noexcept +[[nodiscard]] HRESULT ApiRoutines::GetConsoleTitleWImpl(gsl::span title, + size_t& written, + size_t& needed) noexcept { try { @@ -1923,10 +1893,9 @@ HRESULT ApiRoutines::GetConsoleTitleWImpl(gsl::span title, // - needed - The number of characters we would need to completely write out the title. // Return Value: // - S_OK, E_INVALIDARG, or failure code from thrown exception -[[nodiscard]] -HRESULT ApiRoutines::GetConsoleOriginalTitleAImpl(gsl::span title, - size_t& written, - size_t& needed) noexcept +[[nodiscard]] HRESULT ApiRoutines::GetConsoleOriginalTitleAImpl(gsl::span title, + size_t& written, + size_t& needed) noexcept { try { @@ -1947,10 +1916,9 @@ HRESULT ApiRoutines::GetConsoleOriginalTitleAImpl(gsl::span title, // - needed - The number of characters we would need to completely write out the title. // Return Value: // - S_OK, E_INVALIDARG, or failure code from thrown exception -[[nodiscard]] -HRESULT ApiRoutines::GetConsoleOriginalTitleWImpl(gsl::span title, - size_t& written, - size_t& needed) noexcept +[[nodiscard]] HRESULT ApiRoutines::GetConsoleOriginalTitleWImpl(gsl::span title, + size_t& written, + size_t& needed) noexcept { try { @@ -1968,8 +1936,7 @@ HRESULT ApiRoutines::GetConsoleOriginalTitleWImpl(gsl::span title, // - title - The new title to store and display on the console window. // Return Value: // - S_OK, E_INVALIDARG, or failure code from thrown exception -[[nodiscard]] -HRESULT ApiRoutines::SetConsoleTitleAImpl(const std::string_view title) noexcept +[[nodiscard]] HRESULT ApiRoutines::SetConsoleTitleAImpl(const std::string_view title) noexcept { const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); @@ -1988,8 +1955,7 @@ HRESULT ApiRoutines::SetConsoleTitleAImpl(const std::string_view title) noexcept // - title - The new title to store and display on the console window. // Return Value: // - S_OK, E_INVALIDARG, or failure code from thrown exception -[[nodiscard]] -HRESULT ApiRoutines::SetConsoleTitleWImpl(const std::wstring_view title) noexcept +[[nodiscard]] HRESULT ApiRoutines::SetConsoleTitleWImpl(const std::wstring_view title) noexcept { LockConsole(); auto Unlock = wil::scope_exit([&] { UnlockConsole(); }); @@ -1997,8 +1963,7 @@ HRESULT ApiRoutines::SetConsoleTitleWImpl(const std::wstring_view title) noexcep return DoSrvSetConsoleTitleW(title); } -[[nodiscard]] -HRESULT DoSrvSetConsoleTitleW(const std::wstring_view title) noexcept +[[nodiscard]] HRESULT DoSrvSetConsoleTitleW(const std::wstring_view title) noexcept { CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); @@ -2036,8 +2001,7 @@ HRESULT DoSrvSetConsoleTitleW(const std::wstring_view title) noexcept // // Return value: // - STATUS_SUCCESS if we succeeded, otherwise the NTSTATUS version of the failure. -[[nodiscard]] -NTSTATUS DoSrvPrivateSuppressResizeRepaint() +[[nodiscard]] NTSTATUS DoSrvPrivateSuppressResizeRepaint() { CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); FAIL_FAST_IF(!(gci.IsInVtIoMode())); @@ -2148,8 +2112,7 @@ void DoSrvPrivateMoveToBottom(SCREEN_INFORMATION& screenInfo) // Notes: // Does not take a buffer parameter. The color table for a console and for // terminals as well is global, not per-screen-buffer. -[[nodiscard]] -HRESULT DoSrvPrivateSetColorTableEntry(const short index, const COLORREF value) noexcept +[[nodiscard]] HRESULT DoSrvPrivateSetColorTableEntry(const short index, const COLORREF value) noexcept { RETURN_HR_IF(E_INVALIDARG, index >= 256); try @@ -2169,7 +2132,6 @@ HRESULT DoSrvPrivateSetColorTableEntry(const short index, const COLORREF value) return S_OK; } CATCH_RETURN(); - } // Method Description: @@ -2178,8 +2140,7 @@ HRESULT DoSrvPrivateSetColorTableEntry(const short index, const COLORREF value) // - value: the new RGB value to use, as a COLORREF, format 0x00BBGGRR. // Return Value: // - S_OK -[[nodiscard]] -HRESULT DoSrvPrivateSetDefaultForegroundColor(const COLORREF value) noexcept +[[nodiscard]] HRESULT DoSrvPrivateSetDefaultForegroundColor(const COLORREF value) noexcept { try { @@ -2206,8 +2167,7 @@ HRESULT DoSrvPrivateSetDefaultForegroundColor(const COLORREF value) noexcept // - value: the new RGB value to use, as a COLORREF, format 0x00BBGGRR. // Return Value: // - S_OK -[[nodiscard]] -HRESULT DoSrvPrivateSetDefaultBackgroundColor(const COLORREF value) noexcept +[[nodiscard]] HRESULT DoSrvPrivateSetDefaultBackgroundColor(const COLORREF value) noexcept { try { diff --git a/src/host/getset.h b/src/host/getset.h index 22784375e..129bb8cd1 100644 --- a/src/host/getset.h +++ b/src/host/getset.h @@ -18,7 +18,6 @@ Revision History: #include "../inc/conattrs.hpp" class SCREEN_INFORMATION; - void DoSrvPrivateSetLegacyAttributes(SCREEN_INFORMATION& screenInfo, const WORD Attribute, const bool fForeground, @@ -27,31 +26,22 @@ void DoSrvPrivateSetLegacyAttributes(SCREEN_INFORMATION& screenInfo, void DoSrvPrivateSetDefaultAttributes(SCREEN_INFORMATION& screenInfo, const bool fForeground, const bool fBackground); -[[nodiscard]] -NTSTATUS DoSrvPrivateSetCursorKeysMode(_In_ bool fApplicationMode); -[[nodiscard]] -NTSTATUS DoSrvPrivateSetKeypadMode(_In_ bool fApplicationMode); +[[nodiscard]] NTSTATUS DoSrvPrivateSetCursorKeysMode(_In_ bool fApplicationMode); +[[nodiscard]] NTSTATUS DoSrvPrivateSetKeypadMode(_In_ bool fApplicationMode); void DoSrvPrivateShowCursor(SCREEN_INFORMATION& screenInfo, const bool show) noexcept; void DoSrvPrivateAllowCursorBlinking(SCREEN_INFORMATION& screenInfo, const bool fEnable); -[[nodiscard]] -NTSTATUS DoSrvPrivateSetScrollingRegion(SCREEN_INFORMATION& screenInfo, const SMALL_RECT* const psrScrollMargins); -[[nodiscard]] -NTSTATUS DoSrvPrivateReverseLineFeed(SCREEN_INFORMATION& screenInfo); -[[nodiscard]] -HRESULT DoSrvMoveCursorVertically(SCREEN_INFORMATION& screenInfo, const short lines); +[[nodiscard]] NTSTATUS DoSrvPrivateSetScrollingRegion(SCREEN_INFORMATION& screenInfo, const SMALL_RECT* const psrScrollMargins); +[[nodiscard]] NTSTATUS DoSrvPrivateReverseLineFeed(SCREEN_INFORMATION& screenInfo); +[[nodiscard]] HRESULT DoSrvMoveCursorVertically(SCREEN_INFORMATION& screenInfo, const short lines); -[[nodiscard]] -NTSTATUS DoSrvPrivateUseAlternateScreenBuffer(SCREEN_INFORMATION& screenInfo); -void DoSrvPrivateUseMainScreenBuffer(SCREEN_INFORMATION& screenInfo); +[[nodiscard]] NTSTATUS DoSrvPrivateUseAlternateScreenBuffer(SCREEN_INFORMATION& screenInfo); +void DoSrvPrivateUseMainScreenBuffer(SCREEN_INFORMATION& screenInfo); -[[nodiscard]] -NTSTATUS DoSrvPrivateHorizontalTabSet(); -[[nodiscard]] -NTSTATUS DoSrvPrivateForwardTab(const SHORT sNumTabs); -[[nodiscard]] -NTSTATUS DoSrvPrivateBackwardsTab(const SHORT sNumTabs); +[[nodiscard]] NTSTATUS DoSrvPrivateHorizontalTabSet(); +[[nodiscard]] NTSTATUS DoSrvPrivateForwardTab(const SHORT sNumTabs); +[[nodiscard]] NTSTATUS DoSrvPrivateBackwardsTab(const SHORT sNumTabs); void DoSrvPrivateTabClear(const bool fClearAll); void DoSrvPrivateEnableVT200MouseMode(const bool fEnable); @@ -70,24 +60,21 @@ void DoSrvPrivateSetConsoleRGBTextAttribute(SCREEN_INFORMATION& screenInfo, void DoSrvPrivateBoldText(SCREEN_INFORMATION& screenInfo, const bool bolded); -[[nodiscard]] -NTSTATUS DoSrvPrivateEraseAll(SCREEN_INFORMATION& screenInfo); +[[nodiscard]] NTSTATUS DoSrvPrivateEraseAll(SCREEN_INFORMATION& screenInfo); void DoSrvSetCursorStyle(SCREEN_INFORMATION& screenInfo, const CursorType cursorType); void DoSrvSetCursorColor(SCREEN_INFORMATION& screenInfo, const COLORREF cursorColor); -[[nodiscard]] -NTSTATUS DoSrvPrivateGetConsoleScreenBufferAttributes(const SCREEN_INFORMATION& screenInfo, - _Out_ WORD* const pwAttributes); +[[nodiscard]] NTSTATUS DoSrvPrivateGetConsoleScreenBufferAttributes(const SCREEN_INFORMATION& screenInfo, + _Out_ WORD* const pwAttributes); void DoSrvPrivateRefreshWindow(const SCREEN_INFORMATION& screenInfo); void DoSrvGetConsoleOutputCodePage(_Out_ unsigned int* const pCodePage); -[[nodiscard]] -NTSTATUS DoSrvPrivateSuppressResizeRepaint(); +[[nodiscard]] NTSTATUS DoSrvPrivateSuppressResizeRepaint(); void DoSrvIsConsolePty(_Out_ bool* const pIsPty); @@ -97,11 +84,8 @@ void DoSrvPrivateInsertLines(const unsigned int count); void DoSrvPrivateMoveToBottom(SCREEN_INFORMATION& screenInfo); -[[nodiscard]] -HRESULT DoSrvPrivateSetColorTableEntry(const short index, const COLORREF value) noexcept; +[[nodiscard]] HRESULT DoSrvPrivateSetColorTableEntry(const short index, const COLORREF value) noexcept; -[[nodiscard]] -HRESULT DoSrvPrivateSetDefaultForegroundColor(const COLORREF value) noexcept; +[[nodiscard]] HRESULT DoSrvPrivateSetDefaultForegroundColor(const COLORREF value) noexcept; -[[nodiscard]] -HRESULT DoSrvPrivateSetDefaultBackgroundColor(const COLORREF value) noexcept; +[[nodiscard]] HRESULT DoSrvPrivateSetDefaultBackgroundColor(const COLORREF value) noexcept; diff --git a/src/host/history.cpp b/src/host/history.cpp index 99b470a17..1acf028f0 100644 --- a/src/host/history.cpp +++ b/src/host/history.cpp @@ -90,9 +90,8 @@ void CommandHistory::_Reset() WI_SetFlag(Flags, CLE_RESET); } -[[nodiscard]] -HRESULT CommandHistory::Add(const std::wstring_view newCommand, - const bool suppressDuplicates) +[[nodiscard]] HRESULT CommandHistory::Add(const std::wstring_view newCommand, + const bool suppressDuplicates) { RETURN_HR_IF(E_OUTOFMEMORY, _maxCommands == 0); FAIL_FAST_IF(WI_IsFlagClear(Flags, CLE_ALLOCATED)); @@ -106,8 +105,10 @@ HRESULT CommandHistory::Add(const std::wstring_view newCommand, { if (_commands.size() == 0 || _commands.back().size() != newCommand.size() || - !std::equal(_commands.back().cbegin(), _commands.back().cbegin() + newCommand.size(), - newCommand.cbegin(), newCommand.cend())) + !std::equal(_commands.back().cbegin(), + _commands.back().cbegin() + newCommand.size(), + newCommand.cbegin(), + newCommand.cend())) { std::wstring reuse{}; @@ -141,8 +142,10 @@ HRESULT CommandHistory::Add(const std::wstring_view newCommand, if (LastDisplayed == -1 || _commands.at(LastDisplayed).size() != newCommand.size() || - !std::equal(_commands.at(LastDisplayed).cbegin(), _commands.at(LastDisplayed).cbegin() + newCommand.size(), - newCommand.cbegin(), newCommand.cend())) + !std::equal(_commands.at(LastDisplayed).cbegin(), + _commands.at(LastDisplayed).cbegin() + newCommand.size(), + newCommand.cbegin(), + newCommand.cend())) { _Reset(); } @@ -165,10 +168,9 @@ std::wstring_view CommandHistory::GetNth(const SHORT index) const return {}; } -[[nodiscard]] -HRESULT CommandHistory::RetrieveNth(const SHORT index, - gsl::span buffer, - size_t& commandSize) +[[nodiscard]] HRESULT CommandHistory::RetrieveNth(const SHORT index, + gsl::span buffer, + size_t& commandSize) { LastDisplayed = index; @@ -193,10 +195,9 @@ HRESULT CommandHistory::RetrieveNth(const SHORT index, CATCH_RETURN(); } -[[nodiscard]] -HRESULT CommandHistory::Retrieve(const SearchDirection searchDirection, - const gsl::span buffer, - size_t& commandSize) +[[nodiscard]] HRESULT CommandHistory::Retrieve(const SearchDirection searchDirection, + const gsl::span buffer, + size_t& commandSize) { FAIL_FAST_IF(!(WI_IsFlagSet(Flags, CLE_ALLOCATED))); @@ -383,7 +384,6 @@ CommandHistory* CommandHistory::s_Allocate(const std::wstring_view appName, cons break; } } - } // If the app name doesn't match, copy in the new app name and free the old commands. @@ -499,14 +499,12 @@ std::wstring CommandHistory::Remove(const SHORT iDel) return {}; } - // Routine Description: // - this routine finds the most recent command that starts with the letters already in the current command. it returns the array index (no mod needed). -[[nodiscard]] -bool CommandHistory::FindMatchingCommand(const std::wstring_view givenCommand, - const SHORT startingIndex, - SHORT& indexFound, - const MatchOptions options) +[[nodiscard]] bool CommandHistory::FindMatchingCommand(const std::wstring_view givenCommand, + const SHORT startingIndex, + SHORT& indexFound, + const MatchOptions options) { indexFound = startingIndex; @@ -536,8 +534,10 @@ bool CommandHistory::FindMatchingCommand(const std::wstring_view givenCommand, const auto& storedCommand = _commands.at(indexFound); if ((WI_IsFlagClear(options, MatchOptions::ExactMatch) && (givenCommand.size() <= storedCommand.size())) || (givenCommand.size() == storedCommand.size())) { - if (std::equal(storedCommand.begin(), storedCommand.begin() + givenCommand.size(), - givenCommand.begin(), givenCommand.end(), + if (std::equal(storedCommand.begin(), + storedCommand.begin() + givenCommand.size(), + givenCommand.begin(), + givenCommand.end(), CaseInsensitiveEquality)) { return true; diff --git a/src/host/history.h b/src/host/history.h index 64afda8f2..481c2fdcf 100644 --- a/src/host/history.h +++ b/src/host/history.h @@ -14,7 +14,7 @@ Abstract: // CommandHistory Flags #define CLE_ALLOCATED 0x00000001 -#define CLE_RESET 0x00000002 +#define CLE_RESET 0x00000002 class CommandHistory { @@ -46,19 +46,16 @@ public: const MatchOptions options); bool IsAppNameMatch(const std::wstring_view other) const; - [[nodiscard]] - HRESULT Add(const std::wstring_view command, - const bool suppressDuplicates); + [[nodiscard]] HRESULT Add(const std::wstring_view command, + const bool suppressDuplicates); - [[nodiscard]] - HRESULT Retrieve(const SearchDirection searchDirection, - const gsl::span buffer, - size_t& commandSize); + [[nodiscard]] HRESULT Retrieve(const SearchDirection searchDirection, + const gsl::span buffer, + size_t& commandSize); - [[nodiscard]] - HRESULT RetrieveNth(const SHORT index, - const gsl::span buffer, - size_t& commandSize); + [[nodiscard]] HRESULT RetrieveNth(const SHORT index, + const gsl::span buffer, + size_t& commandSize); size_t GetNumberOfCommands() const; std::wstring_view GetNth(const SHORT index) const; @@ -86,7 +83,6 @@ private: void _Dec(SHORT& ind) const; void _Inc(SHORT& ind) const; - std::vector _commands; SHORT _maxCommands; diff --git a/src/host/init.cpp b/src/host/init.cpp index 98ac57fbc..4d3c32709 100644 --- a/src/host/init.cpp +++ b/src/host/init.cpp @@ -13,7 +13,7 @@ void InitSideBySide(_Out_writes_(ScratchBufferSize) PWSTR ScratchBuffer, __range(MAX_PATH, MAX_PATH) DWORD ScratchBufferSize) { ACTCTXW actctx = { 0 }; - + // Account for the fact that sidebyside stuff happens in CreateProcess // but conhost is run with RtlCreateUserProcess. @@ -98,8 +98,7 @@ void InitEnvironmentVariables() { LPCWSTR szRegValue; LPCWSTR szVariable; - } EnvProgFiles[] = - { + } EnvProgFiles[] = { { L"ProgramFilesDir", L"ProgramFiles" }, { L"CommonFilesDir", L"CommonProgramFiles" }, #if BUILD_WOW64_ENABLED diff --git a/src/host/input.cpp b/src/host/input.cpp index 3b1e1f3ac..ff4b1980f 100644 --- a/src/host/input.cpp +++ b/src/host/input.cpp @@ -34,16 +34,16 @@ BOOL IsSystemKey(const WORD wVirtualKeyCode) { switch (wVirtualKeyCode) { - case VK_SHIFT: - case VK_CONTROL: - case VK_MENU: - case VK_PAUSE: - case VK_CAPITAL: - case VK_LWIN: - case VK_RWIN: - case VK_NUMLOCK: - case VK_SCROLL: - return TRUE; + case VK_SHIFT: + case VK_CONTROL: + case VK_MENU: + case VK_PAUSE: + case VK_CAPITAL: + case VK_LWIN: + case VK_RWIN: + case VK_NUMLOCK: + case VK_SCROLL: + return TRUE; } return FALSE; } @@ -128,7 +128,6 @@ void HandleGenericKeyEvent(_In_ KeyEvent keyEvent, const bool generateBreak) } } - // Check for ctrl-break. else if (keyEvent.GetVirtualKeyCode() == VK_CANCEL) { @@ -170,7 +169,7 @@ void HandleGenericKeyEvent(_In_ KeyEvent keyEvent, const bool generateBreak) EventsWritten = gci.pInputBuffer->Write(std::make_unique(keyEvent)); } } - catch(...) + catch (...) { LOG_HR(wil::ResultFromCaughtException()); } @@ -216,7 +215,6 @@ void HandleMenuEvent(const DWORD wParam) { RIPMSG0(RIP_WARNING, "PutInputInBuffer: EventsWritten != 1, 1 expected"); } - } catch (...) { @@ -229,17 +227,17 @@ void HandleCtrlEvent(const DWORD EventType) CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); switch (EventType) { - case CTRL_C_EVENT: - gci.CtrlFlags |= CONSOLE_CTRL_C_FLAG; - break; - case CTRL_BREAK_EVENT: - gci.CtrlFlags |= CONSOLE_CTRL_BREAK_FLAG; - break; - case CTRL_CLOSE_EVENT: - gci.CtrlFlags |= CONSOLE_CTRL_CLOSE_FLAG; - break; - default: - RIPMSG1(RIP_ERROR, "Invalid EventType: 0x%x", EventType); + case CTRL_C_EVENT: + gci.CtrlFlags |= CONSOLE_CTRL_C_FLAG; + break; + case CTRL_BREAK_EVENT: + gci.CtrlFlags |= CONSOLE_CTRL_BREAK_FLAG; + break; + case CTRL_CLOSE_EVENT: + gci.CtrlFlags |= CONSOLE_CTRL_CLOSE_FLAG; + break; + default: + RIPMSG1(RIP_ERROR, "Invalid EventType: 0x%x", EventType); } } @@ -260,11 +258,11 @@ void ProcessCtrlEvents() size_t cProcessHandleList; HRESULT hr = gci.ProcessHandleList - .GetTerminationRecordsByGroupId(LimitingProcessId, - WI_IsFlagSet(gci.CtrlFlags, - CONSOLE_CTRL_CLOSE_FLAG), - &rgProcessHandleList, - &cProcessHandleList); + .GetTerminationRecordsByGroupId(LimitingProcessId, + WI_IsFlagSet(gci.CtrlFlags, + CONSOLE_CTRL_CLOSE_FLAG), + &rgProcessHandleList, + &cProcessHandleList); if (FAILED(hr) || cProcessHandleList == 0) { @@ -289,29 +287,28 @@ void ProcessCtrlEvents() // CONSOLE_CTRL_LOGOFF_FLAG // CONSOLE_CTRL_SHUTDOWN_FLAG - DWORD EventType = (DWORD) - 1; + DWORD EventType = (DWORD)-1; switch (CtrlFlags & (CONSOLE_CTRL_CLOSE_FLAG | CONSOLE_CTRL_BREAK_FLAG | CONSOLE_CTRL_C_FLAG | CONSOLE_CTRL_LOGOFF_FLAG | CONSOLE_CTRL_SHUTDOWN_FLAG)) { + case CONSOLE_CTRL_CLOSE_FLAG: + EventType = CTRL_CLOSE_EVENT; + break; - case CONSOLE_CTRL_CLOSE_FLAG: - EventType = CTRL_CLOSE_EVENT; - break; + case CONSOLE_CTRL_BREAK_FLAG: + EventType = CTRL_BREAK_EVENT; + break; - case CONSOLE_CTRL_BREAK_FLAG: - EventType = CTRL_BREAK_EVENT; - break; + case CONSOLE_CTRL_C_FLAG: + EventType = CTRL_C_EVENT; + break; - case CONSOLE_CTRL_C_FLAG: - EventType = CTRL_C_EVENT; - break; + case CONSOLE_CTRL_LOGOFF_FLAG: + EventType = CTRL_LOGOFF_EVENT; + break; - case CONSOLE_CTRL_LOGOFF_FLAG: - EventType = CTRL_LOGOFF_EVENT; - break; - - case CONSOLE_CTRL_SHUTDOWN_FLAG: - EventType = CTRL_SHUTDOWN_EVENT; - break; + case CONSOLE_CTRL_SHUTDOWN_FLAG: + EventType = CTRL_SHUTDOWN_EVENT; + break; } NTSTATUS Status = STATUS_SUCCESS; @@ -329,10 +326,11 @@ void ProcessCtrlEvents() if (NT_SUCCESS(Status)) { Status = ServiceLocator::LocateConsoleControl() - ->EndTask((HANDLE)rgProcessHandleList[i].dwProcessID, - EventType, - CtrlFlags); - if (rgProcessHandleList[i].hProcess == nullptr) { + ->EndTask((HANDLE)rgProcessHandleList[i].dwProcessID, + EventType, + CtrlFlags); + if (rgProcessHandleList[i].hProcess == nullptr) + { Status = STATUS_SUCCESS; } } diff --git a/src/host/input.h b/src/host/input.h index 27b77f505..a40bc0751 100644 --- a/src/host/input.h +++ b/src/host/input.h @@ -61,7 +61,7 @@ private: #define TAB_SIZE 8 #define TAB_MASK (TAB_SIZE - 1) // WHY IS THIS NOT POSITION % TAB_SIZE?! -#define NUMBER_OF_SPACES_IN_TAB(POSITION) (TAB_SIZE - ((POSITION) & TAB_MASK)) +#define NUMBER_OF_SPACES_IN_TAB(POSITION) (TAB_SIZE - ((POSITION)&TAB_MASK)) // these values are related to GetKeyboardState #define KEY_PRESSED 0x8000 diff --git a/src/host/inputBuffer.cpp b/src/host/inputBuffer.cpp index f613b5898..cea74a370 100644 --- a/src/host/inputBuffer.cpp +++ b/src/host/inputBuffer.cpp @@ -212,8 +212,7 @@ void InputBuffer::Flush() // - The console lock must be held when calling this routine. void InputBuffer::FlushAllButKeys() { - auto newEnd = std::remove_if(_storage.begin(), _storage.end(), [](const std::unique_ptr& event) - { + auto newEnd = std::remove_if(_storage.begin(), _storage.end(), [](const std::unique_ptr& event) { return event->EventType() != InputEventType::KeyEvent; }); _storage.erase(newEnd, _storage.end()); @@ -236,13 +235,12 @@ void InputBuffer::FlushAllButKeys() // - STATUS_SUCCESS if records were read into the client buffer and everything is OK. // - CONSOLE_STATUS_WAIT if there weren't enough records to satisfy the request (and waits are allowed) // - otherwise a suitable memory/math/string error in NTSTATUS form. -[[nodiscard]] -NTSTATUS InputBuffer::Read(_Out_ std::deque>& OutEvents, - const size_t AmountToRead, - const bool Peek, - const bool WaitForData, - const bool Unicode, - const bool Stream) +[[nodiscard]] NTSTATUS InputBuffer::Read(_Out_ std::deque>& OutEvents, + const size_t AmountToRead, + const bool Peek, + const bool WaitForData, + const bool Unicode, + const bool Stream) { try { @@ -302,12 +300,11 @@ NTSTATUS InputBuffer::Read(_Out_ std::deque>& OutEv // - STATUS_SUCCESS if records were read into the client buffer and everything is OK. // - CONSOLE_STATUS_WAIT if there weren't enough records to satisfy the request (and waits are allowed) // - otherwise a suitable memory/math/string error in NTSTATUS form. -[[nodiscard]] -NTSTATUS InputBuffer::Read(_Out_ std::unique_ptr& outEvent, - const bool Peek, - const bool WaitForData, - const bool Unicode, - const bool Stream) +[[nodiscard]] NTSTATUS InputBuffer::Read(_Out_ std::unique_ptr& outEvent, + const bool Peek, + const bool WaitForData, + const bool Unicode, + const bool Stream) { NTSTATUS Status; try @@ -423,7 +420,7 @@ void InputBuffer::_ReadBuffer(_Out_ std::deque>& ou readEvents.back()->EventType() == InputEventType::KeyEvent && _storage.front()->EventType() == InputEventType::KeyEvent && _CanCoalesce(static_cast(*readEvents.back()), - static_cast(*_storage.front()))) + static_cast(*_storage.front()))) { KeyEvent& keyEvent = static_cast(*_storage.front()); keyEvent.SetRepeatCount(keyEvent.GetRepeatCount() + 1); @@ -608,7 +605,7 @@ void InputBuffer::_WriteBuffer(_Inout_ std::deque>& const size_t initialInEventsSize = inEvents.size(); const bool vtInputMode = IsInVirtualTerminalInputMode(); - while(!inEvents.empty()) + while (!inEvents.empty()) { // Pop the next event. // If we're in vt mode, try and handle it with the vt input module. @@ -735,8 +732,8 @@ bool InputBuffer::_CanCoalesce(const KeyEvent& a, const KeyEvent& b) const noexc } // other key events check else if (a.GetVirtualScanCode() == b.GetVirtualScanCode() && - a.GetCharData() == b.GetCharData() && - a.GetActiveModifierKeys() == b.GetActiveModifierKeys()) + a.GetCharData() == b.GetCharData() && + a.GetActiveModifierKeys() == b.GetActiveModifierKeys()) { return true; } diff --git a/src/host/inputBuffer.hpp b/src/host/inputBuffer.hpp index 9a38a06d2..b6da61d55 100644 --- a/src/host/inputBuffer.hpp +++ b/src/host/inputBuffer.hpp @@ -33,7 +33,7 @@ class InputBuffer final : public ConsoleObjectHeader public: DWORD InputMode; ConsoleWaitQueue WaitQueue; // formerly ReadWaitQueue - bool fInComposition; // specifies if there's an ongoing text composition + bool fInComposition; // specifies if there's an ongoing text composition InputBuffer(); ~InputBuffer(); @@ -55,21 +55,18 @@ public: void Flush(); void FlushAllButKeys(); - [[nodiscard]] - NTSTATUS Read(_Out_ std::deque>& OutEvents, - const size_t AmountToRead, - const bool Peek, - const bool WaitForData, - const bool Unicode, - const bool Stream); - - [[nodiscard]] - NTSTATUS Read(_Out_ std::unique_ptr& inEvent, - const bool Peek, - const bool WaitForData, - const bool Unicode, - const bool Stream); + [[nodiscard]] NTSTATUS Read(_Out_ std::deque>& OutEvents, + const size_t AmountToRead, + const bool Peek, + const bool WaitForData, + const bool Unicode, + const bool Stream); + [[nodiscard]] NTSTATUS Read(_Out_ std::unique_ptr& inEvent, + const bool Peek, + const bool WaitForData, + const bool Unicode, + const bool Stream); size_t Prepend(_Inout_ std::deque>& inEvents); diff --git a/src/host/inputReadHandleData.cpp b/src/host/inputReadHandleData.cpp index 670042e42..505461688 100644 --- a/src/host/inputReadHandleData.cpp +++ b/src/host/inputReadHandleData.cpp @@ -7,7 +7,7 @@ INPUT_READ_HANDLE_DATA::INPUT_READ_HANDLE_DATA() : _isInputPending{ false }, - _isMultilineInput{ false }, + _isMultilineInput{ false }, _readCount{ 0 }, _buffer{} { diff --git a/src/host/inputReadHandleData.h b/src/host/inputReadHandleData.h index efa86722f..353ff5c8e 100644 --- a/src/host/inputReadHandleData.h +++ b/src/host/inputReadHandleData.h @@ -18,8 +18,7 @@ Revision History: - Adapted from original items in handle.h --*/ - -#pragma once +#pragma once class INPUT_READ_HANDLE_DATA { @@ -47,7 +46,6 @@ public: std::wstring_view GetPendingInput() const; private: - bool _isInputPending; bool _isMultilineInput; diff --git a/src/host/misc.cpp b/src/host/misc.cpp index e53f5b84c..0793c9f23 100644 --- a/src/host/misc.cpp +++ b/src/host/misc.cpp @@ -13,11 +13,11 @@ #pragma hdrstop -#define CHAR_NULL ((char)0) +#define CHAR_NULL ((char)0) using Microsoft::Console::Interactivity::ServiceLocator; -WCHAR CharToWchar(_In_reads_(cch) const char * const pch, const UINT cch) +WCHAR CharToWchar(_In_reads_(cch) const char* const pch, const UINT cch) { const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); WCHAR wc = L'\0'; @@ -78,7 +78,7 @@ void SetConsoleCPInfo(const BOOL fOutput) // Return Value: // - TRUE - Bisected character. // - FALSE - Correctly. -BOOL CheckBisectStringW(_In_reads_bytes_(cBytes) const WCHAR * pwchBuffer, +BOOL CheckBisectStringW(_In_reads_bytes_(cBytes) const WCHAR* pwchBuffer, _In_ size_t cWords, _In_ size_t cBytes) noexcept { @@ -120,7 +120,7 @@ BOOL CheckBisectStringW(_In_reads_bytes_(cBytes) const WCHAR * pwchBuffer, // - TRUE - Bisected character. // - FALSE - Correctly. BOOL CheckBisectProcessW(const SCREEN_INFORMATION& ScreenInfo, - _In_reads_bytes_(cBytes) const WCHAR * pwchBuffer, + _In_reads_bytes_(cBytes) const WCHAR* pwchBuffer, _In_ size_t cWords, _In_ size_t cBytes, _In_ SHORT sOriginalXPosition, @@ -161,37 +161,37 @@ BOOL CheckBisectProcessW(const SCREEN_INFORMATION& ScreenInfo, pwchBuffer++; switch (Char) { - case UNICODE_BELL: - if (fEcho) - goto CtrlChar; - break; - case UNICODE_BACKSPACE: - case UNICODE_LINEFEED: - case UNICODE_CARRIAGERETURN: - break; - case UNICODE_TAB: + case UNICODE_BELL: + if (fEcho) + goto CtrlChar; + break; + case UNICODE_BACKSPACE: + case UNICODE_LINEFEED: + case UNICODE_CARRIAGERETURN: + break; + case UNICODE_TAB: + { + size_t TabSize = NUMBER_OF_SPACES_IN_TAB(sOriginalXPosition); + sOriginalXPosition = (SHORT)(sOriginalXPosition + TabSize); + if (cBytes < TabSize) + return TRUE; + cBytes -= TabSize; + break; + } + default: + if (fEcho) { - size_t TabSize = NUMBER_OF_SPACES_IN_TAB(sOriginalXPosition); - sOriginalXPosition = (SHORT)(sOriginalXPosition + TabSize); - if (cBytes < TabSize) + CtrlChar: + if (cBytes < 2) return TRUE; - cBytes -= TabSize; - break; + cBytes -= 2; + sOriginalXPosition += 2; + } + else + { + cBytes--; + sOriginalXPosition++; } - default: - if (fEcho) - { - CtrlChar: - if (cBytes < 2) - return TRUE; - cBytes -= 2; - sOriginalXPosition += 2; - } - else - { - cBytes--; - sOriginalXPosition++; - } } } } @@ -203,7 +203,6 @@ BOOL CheckBisectProcessW(const SCREEN_INFORMATION& ScreenInfo, } } - // Routine Description: // - Converts all key events in the deque to the oem char data and adds // them back to events. @@ -259,22 +258,24 @@ void SplitToOem(std::deque>& events) // Return Value: // - Returns the number characters written to pchTarget, or 0 on failure int ConvertToOem(const UINT uiCodePage, - _In_reads_(cchSource) const WCHAR * const pwchSource, + _In_reads_(cchSource) const WCHAR* const pwchSource, const UINT cchSource, - _Out_writes_(cchTarget) CHAR * const pchTarget, + _Out_writes_(cchTarget) CHAR* const pchTarget, const UINT cchTarget) noexcept { - FAIL_FAST_IF(!(pwchSource != (LPWSTR) pchTarget)); + FAIL_FAST_IF(!(pwchSource != (LPWSTR)pchTarget)); DBGCHARS(("ConvertToOem U->%d %.*ls\n", uiCodePage, cchSource > 10 ? 10 : cchSource, pwchSource)); - #pragma prefast(suppress:__WARNING_W2A_BEST_FIT, "WC_NO_BEST_FIT_CHARS doesn't work in many codepages. Retain old behavior.") + // clang-format off +#pragma prefast(suppress: __WARNING_W2A_BEST_FIT, "WC_NO_BEST_FIT_CHARS doesn't work in many codepages. Retain old behavior.") + // clang-format on return LOG_IF_WIN32_BOOL_FALSE(WideCharToMultiByte(uiCodePage, 0, pwchSource, cchSource, pchTarget, cchTarget, nullptr, nullptr)); } // Data in the output buffer is the true unicode value. int ConvertInputToUnicode(const UINT uiCodePage, - _In_reads_(cchSource) const CHAR * const pchSource, + _In_reads_(cchSource) const CHAR* const pchSource, const UINT cchSource, - _Out_writes_(cchTarget) WCHAR * const pwchTarget, + _Out_writes_(cchTarget) WCHAR* const pwchTarget, const UINT cchTarget) noexcept { DBGCHARS(("ConvertInputToUnicode %d->U %.*s\n", uiCodePage, cchSource > 10 ? 10 : cchSource, pchSource)); @@ -284,9 +285,9 @@ int ConvertInputToUnicode(const UINT uiCodePage, // Output data is always translated via the ansi codepage so glyph translation works. int ConvertOutputToUnicode(_In_ UINT uiCodePage, - _In_reads_(cchSource) const CHAR * const pchSource, + _In_reads_(cchSource) const CHAR* const pchSource, _In_ UINT cchSource, - _Out_writes_(cchTarget) WCHAR *pwchTarget, + _Out_writes_(cchTarget) WCHAR* pwchTarget, _In_ UINT cchTarget) noexcept { FAIL_FAST_IF(!(cchTarget > 0)); diff --git a/src/host/misc.h b/src/host/misc.h index c4598d645..f598894ac 100644 --- a/src/host/misc.h +++ b/src/host/misc.h @@ -24,39 +24,38 @@ Revision History: #include #include -WCHAR CharToWchar(_In_reads_(cch) const char * const pch, const UINT cch); +WCHAR CharToWchar(_In_reads_(cch) const char* const pch, const UINT cch); void SetConsoleCPInfo(const BOOL fOutput); -BOOL CheckBisectStringW(_In_reads_bytes_(cBytes) const WCHAR * pwchBuffer, +BOOL CheckBisectStringW(_In_reads_bytes_(cBytes) const WCHAR* pwchBuffer, _In_ size_t cWords, _In_ size_t cBytes) noexcept; BOOL CheckBisectProcessW(const SCREEN_INFORMATION& ScreenInfo, - _In_reads_bytes_(cBytes) const WCHAR * pwchBuffer, + _In_reads_bytes_(cBytes) const WCHAR* pwchBuffer, _In_ size_t cWords, _In_ size_t cBytes, _In_ SHORT sOriginalXPosition, _In_ BOOL fEcho); int ConvertToOem(const UINT uiCodePage, - _In_reads_(cchSource) const WCHAR * const pwchSource, + _In_reads_(cchSource) const WCHAR* const pwchSource, const UINT cchSource, - _Out_writes_(cchTarget) CHAR * const pchTarget, + _Out_writes_(cchTarget) CHAR* const pchTarget, const UINT cchTarget) noexcept; void SplitToOem(std::deque>& events); int ConvertInputToUnicode(const UINT uiCodePage, - _In_reads_(cchSource) const CHAR * const pchSource, + _In_reads_(cchSource) const CHAR* const pchSource, const UINT cchSource, - _Out_writes_(cchTarget) WCHAR * const pwchTarget, + _Out_writes_(cchTarget) WCHAR* const pwchTarget, const UINT cchTarget) noexcept; - int ConvertOutputToUnicode(_In_ UINT uiCodePage, - _In_reads_(cchSource) const CHAR * const pchSource, + _In_reads_(cchSource) const CHAR* const pchSource, _In_ UINT cchSource, - _Out_writes_(cchTarget) WCHAR *pwchTarget, + _Out_writes_(cchTarget) WCHAR* pwchTarget, _In_ UINT cchTarget) noexcept; bool DoBuffersOverlap(const BYTE* const pBufferA, diff --git a/src/host/ntprivapi.cpp b/src/host/ntprivapi.cpp index 5a889e7f3..8a2471fb9 100644 --- a/src/host/ntprivapi.cpp +++ b/src/host/ntprivapi.cpp @@ -5,8 +5,7 @@ #include "NtPrivApi.hpp" -[[nodiscard]] -NTSTATUS NtPrivApi::s_GetProcessParentId(_Inout_ PULONG ProcessId) +[[nodiscard]] NTSTATUS NtPrivApi::s_GetProcessParentId(_Inout_ PULONG ProcessId) { // TODO: Get Parent current not really available without winternl + NtQueryInformationProcess. http://osgvsowi/8394495 OBJECT_ATTRIBUTES oa; @@ -38,17 +37,16 @@ NTSTATUS NtPrivApi::s_GetProcessParentId(_Inout_ PULONG ProcessId) return STATUS_SUCCESS; } -[[nodiscard]] -NTSTATUS NtPrivApi::s_NtOpenProcess(_Out_ PHANDLE ProcessHandle, - _In_ ACCESS_MASK DesiredAccess, - _In_ POBJECT_ATTRIBUTES ObjectAttributes, - _In_opt_ PCLIENT_ID ClientId) +[[nodiscard]] NTSTATUS NtPrivApi::s_NtOpenProcess(_Out_ PHANDLE ProcessHandle, + _In_ ACCESS_MASK DesiredAccess, + _In_ POBJECT_ATTRIBUTES ObjectAttributes, + _In_opt_ PCLIENT_ID ClientId) { HMODULE hNtDll = _Instance()._hNtDll; if (hNtDll != nullptr) { - typedef NTSTATUS(*PfnNtOpenProcess)(HANDLE ProcessHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, PCLIENT_ID ClientId); + typedef NTSTATUS (*PfnNtOpenProcess)(HANDLE ProcessHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, PCLIENT_ID ClientId); static PfnNtOpenProcess pfn = (PfnNtOpenProcess)GetProcAddress(hNtDll, "NtOpenProcess"); @@ -61,18 +59,17 @@ NTSTATUS NtPrivApi::s_NtOpenProcess(_Out_ PHANDLE ProcessHandle, return STATUS_UNSUCCESSFUL; } -[[nodiscard]] -NTSTATUS NtPrivApi::s_NtQueryInformationProcess(_In_ HANDLE ProcessHandle, - _In_ PROCESSINFOCLASS ProcessInformationClass, - _Out_ PVOID ProcessInformation, - _In_ ULONG ProcessInformationLength, - _Out_opt_ PULONG ReturnLength) +[[nodiscard]] NTSTATUS NtPrivApi::s_NtQueryInformationProcess(_In_ HANDLE ProcessHandle, + _In_ PROCESSINFOCLASS ProcessInformationClass, + _Out_ PVOID ProcessInformation, + _In_ ULONG ProcessInformationLength, + _Out_opt_ PULONG ReturnLength) { HMODULE hNtDll = _Instance()._hNtDll; if (hNtDll != nullptr) { - typedef NTSTATUS(*PfnNtQueryInformationProcess)(HANDLE ProcessHandle, PROCESSINFOCLASS ProcessInformationClass, PVOID ProcessInformation, ULONG ProcessInformationLength, PULONG ReturnLength); + typedef NTSTATUS (*PfnNtQueryInformationProcess)(HANDLE ProcessHandle, PROCESSINFOCLASS ProcessInformationClass, PVOID ProcessInformation, ULONG ProcessInformationLength, PULONG ReturnLength); static PfnNtQueryInformationProcess pfn = (PfnNtQueryInformationProcess)GetProcAddress(hNtDll, "NtQueryInformationProcess"); @@ -85,14 +82,13 @@ NTSTATUS NtPrivApi::s_NtQueryInformationProcess(_In_ HANDLE ProcessHandle, return STATUS_UNSUCCESSFUL; } -[[nodiscard]] -NTSTATUS NtPrivApi::s_NtClose(_In_ HANDLE Handle) +[[nodiscard]] NTSTATUS NtPrivApi::s_NtClose(_In_ HANDLE Handle) { HMODULE hNtDll = _Instance()._hNtDll; if (hNtDll != nullptr) { - typedef NTSTATUS(*PfnNtClose)(HANDLE Handle); + typedef NTSTATUS (*PfnNtClose)(HANDLE Handle); static PfnNtClose pfn = (PfnNtClose)GetProcAddress(hNtDll, "NtClose"); diff --git a/src/host/ntprivapi.hpp b/src/host/ntprivapi.hpp index f9554dfd9..ee5b9ed3f 100644 --- a/src/host/ntprivapi.hpp +++ b/src/host/ntprivapi.hpp @@ -17,7 +17,8 @@ Author(s): // From winternl.h -typedef enum _PROCESSINFOCLASS { +typedef enum _PROCESSINFOCLASS +{ ProcessBasicInformation = 0, ProcessDebugPort = 7, ProcessWow64Information = 26, @@ -25,41 +26,38 @@ typedef enum _PROCESSINFOCLASS { ProcessBreakOnTermination = 29 } PROCESSINFOCLASS; -typedef struct _PROCESS_BASIC_INFORMATION { +typedef struct _PROCESS_BASIC_INFORMATION +{ PVOID Reserved1; PVOID PebBaseAddress; PVOID Reserved2[2]; ULONG_PTR UniqueProcessId; ULONG_PTR Reserved3; } PROCESS_BASIC_INFORMATION; -typedef PROCESS_BASIC_INFORMATION *PPROCESS_BASIC_INFORMATION; +typedef PROCESS_BASIC_INFORMATION* PPROCESS_BASIC_INFORMATION; // end From winternl.h class NtPrivApi sealed { public: - [[nodiscard]] - static NTSTATUS s_GetProcessParentId(_Inout_ PULONG ProcessId); + [[nodiscard]] static NTSTATUS s_GetProcessParentId(_Inout_ PULONG ProcessId); ~NtPrivApi(); private: - [[nodiscard]] - static NTSTATUS s_NtOpenProcess(_Out_ PHANDLE ProcessHandle, - _In_ ACCESS_MASK DesiredAccess, - _In_ POBJECT_ATTRIBUTES ObjectAttributes, - _In_opt_ PCLIENT_ID ClientId); + [[nodiscard]] static NTSTATUS s_NtOpenProcess(_Out_ PHANDLE ProcessHandle, + _In_ ACCESS_MASK DesiredAccess, + _In_ POBJECT_ATTRIBUTES ObjectAttributes, + _In_opt_ PCLIENT_ID ClientId); - [[nodiscard]] - static NTSTATUS s_NtQueryInformationProcess(_In_ HANDLE ProcessHandle, - _In_ PROCESSINFOCLASS ProcessInformationClass, - _Out_ PVOID ProcessInformation, - _In_ ULONG ProcessInformationLength, - _Out_opt_ PULONG ReturnLength); + [[nodiscard]] static NTSTATUS s_NtQueryInformationProcess(_In_ HANDLE ProcessHandle, + _In_ PROCESSINFOCLASS ProcessInformationClass, + _Out_ PVOID ProcessInformation, + _In_ ULONG ProcessInformationLength, + _Out_opt_ PULONG ReturnLength); - [[nodiscard]] - static NTSTATUS s_NtClose(_In_ HANDLE Handle); + [[nodiscard]] static NTSTATUS s_NtClose(_In_ HANDLE Handle); static NtPrivApi& _Instance(); HMODULE _hNtDll; diff --git a/src/host/output.cpp b/src/host/output.cpp index 869c8bb53..de3a2b66f 100644 --- a/src/host/output.cpp +++ b/src/host/output.cpp @@ -21,8 +21,7 @@ using namespace Microsoft::Console::Interactivity; // This routine figures out what parameters to pass to CreateScreenBuffer based on the data from STARTUPINFO and the // registry defaults, and then calls CreateScreenBuffer. -[[nodiscard]] -NTSTATUS DoCreateScreenBuffer() +[[nodiscard]] NTSTATUS DoCreateScreenBuffer() { CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); @@ -272,7 +271,7 @@ static void _ScrollScreen(SCREEN_INFORMATION& screenInfo, const Viewport& source { if (screenInfo.IsActiveScreenBuffer()) { - IAccessibilityNotifier *pNotifier = ServiceLocator::LocateAccessibilityNotifier(); + IAccessibilityNotifier* pNotifier = ServiceLocator::LocateAccessibilityNotifier(); if (pNotifier != nullptr) { pNotifier->NotifyConsoleUpdateScrollEvent(target.Origin().X - source.Left(), target.Origin().Y - source.RightInclusive()); @@ -306,7 +305,7 @@ bool StreamScrollRegion(SCREEN_INFORMATION& screenInfo) COORD coordDelta = { 0 }; coordDelta.Y = -1; - IAccessibilityNotifier *pNotifier = ServiceLocator::LocateAccessibilityNotifier(); + IAccessibilityNotifier* pNotifier = ServiceLocator::LocateAccessibilityNotifier(); if (pNotifier) { // Notify accessibility that a scroll has occurred. diff --git a/src/host/output.h b/src/host/output.h index feea70685..8c0a46517 100644 --- a/src/host/output.h +++ b/src/host/output.h @@ -24,8 +24,7 @@ Revision History: void ScreenBufferSizeChange(const COORD coordNewSize); -[[nodiscard]] -NTSTATUS DoCreateScreenBuffer(); +[[nodiscard]] NTSTATUS DoCreateScreenBuffer(); std::vector ReadOutputAttributes(const SCREEN_INFORMATION& screenInfo, const COORD coordRead, @@ -36,8 +35,8 @@ std::wstring ReadOutputStringW(const SCREEN_INFORMATION& screenInfo, const size_t amountToRead); std::string ReadOutputStringA(const SCREEN_INFORMATION& screenInfo, - const COORD coordRead, - const size_t amountToRead); + const COORD coordRead, + const size_t amountToRead); void ScrollRegion(SCREEN_INFORMATION& screenInfo, const SMALL_RECT scrollRect, diff --git a/src/host/outputStream.cpp b/src/host/outputStream.cpp index 17f0e31fe..9f1211ce9 100644 --- a/src/host/outputStream.cpp +++ b/src/host/outputStream.cpp @@ -94,7 +94,6 @@ ConhostInternalGetSet::ConhostInternalGetSet(_In_ IIoProvider& io) : { } - // Routine Description: // - Connects the GetConsoleScreenBufferInfoEx API call directly into our Driver Message servicing call inside Conhost.exe // Arguments: @@ -768,7 +767,7 @@ BOOL ConhostInternalGetSet::PrivateSetColorTableEntry(const short index, const C // - Connects the PrivateSetDefaultForeground call directly into our Driver Message servicing // call inside Conhost.exe // Arguments: -// - value: the new RGB value to use, as a COLORREF, format 0x00BBGGRR. +// - value: the new RGB value to use, as a COLORREF, format 0x00BBGGRR. // Return Value: // - TRUE if successful (see DoSrvPrivateSetDefaultForegroundColor). FALSE otherwise. BOOL ConhostInternalGetSet::PrivateSetDefaultForeground(const COLORREF value) const noexcept diff --git a/src/host/outputStream.hpp b/src/host/outputStream.hpp index b87d10082..cc626e054 100644 --- a/src/host/outputStream.hpp +++ b/src/host/outputStream.hpp @@ -32,8 +32,7 @@ public: void PrintString(const wchar_t* const rgwch, const size_t cch) override; void Execute(const wchar_t wch) override; - [[nodiscard]] - NTSTATUS GetResult() { return _ntstatus; }; + [[nodiscard]] NTSTATUS GetResult() { return _ntstatus; }; private: void _DefaultCase(const wchar_t wch); @@ -45,7 +44,6 @@ private: #include "..\terminal\adapter\conGetSet.hpp" - // The ConhostInternalGetSet is for the Conhost process to call the entrypoints for its own Get/Set APIs. // Normally, these APIs are accessible from the outside of the conhost process (like by the process being "hosted") through // the kernelbase/32 exposed public APIs and routed by the console driver (condrv) to this console host. @@ -64,10 +62,12 @@ public: BOOL GetConsoleCursorInfo(_In_ CONSOLE_CURSOR_INFO* const pConsoleCursorInfo) const override; BOOL SetConsoleCursorInfo(const CONSOLE_CURSOR_INFO* const pConsoleCursorInfo) override; - BOOL FillConsoleOutputCharacterW(const WCHAR wch, const DWORD nLength, + BOOL FillConsoleOutputCharacterW(const WCHAR wch, + const DWORD nLength, const COORD dwWriteCoord, size_t& numberOfCharsWritten) noexcept override; - BOOL FillConsoleOutputAttribute(const WORD wAttribute, const DWORD nLength, + BOOL FillConsoleOutputAttribute(const WORD wAttribute, + const DWORD nLength, const COORD dwWriteCoord, size_t& numberOfAttrsWritten) noexcept override; @@ -90,7 +90,7 @@ public: BOOL PrivateBoldText(const bool bolded) override; BOOL PrivateWriteConsoleInputW(_Inout_ std::deque>& events, - _Out_ size_t& eventsWritten) override; + _Out_ size_t& eventsWritten) override; BOOL ScrollConsoleScreenBufferW(const SMALL_RECT* pScrollRectangle, _In_opt_ const SMALL_RECT* pClipRectangle, diff --git a/src/host/popup.cpp b/src/host/popup.cpp index 5467fbbc8..7979fa5d8 100644 --- a/src/host/popup.cpp +++ b/src/host/popup.cpp @@ -253,8 +253,8 @@ COORD Popup::_CalculateSize(const SCREEN_INFORMATION& screenInfo, const COORD pr { // determine popup dimensions COORD size = proposedSize; - size.X += 2; // add borders - size.Y += 2; // add borders + size.X += 2; // add borders + size.Y += 2; // add borders const COORD viewportSize = screenInfo.GetViewport().Dimensions(); @@ -333,8 +333,7 @@ void Popup::SetUserInputFunction(UserInputFunction function) noexcept // - wch - on completion, the char read from the user // Return Value: // - relevant NTSTATUS -[[nodiscard]] -NTSTATUS Popup::_getUserInput(COOKED_READ_DATA& cookedReadData, bool& popupKey, DWORD& modifiers, wchar_t& wch) noexcept +[[nodiscard]] NTSTATUS Popup::_getUserInput(COOKED_READ_DATA& cookedReadData, bool& popupKey, DWORD& modifiers, wchar_t& wch) noexcept { return _userInputFunction(cookedReadData, popupKey, modifiers, wch); } @@ -347,11 +346,10 @@ NTSTATUS Popup::_getUserInput(COOKED_READ_DATA& cookedReadData, bool& popupKey, // - wch - on completion, the char read from the user // Return Value: // - relevant NTSTATUS -[[nodiscard]] -NTSTATUS Popup::_getUserInputInternal(COOKED_READ_DATA& cookedReadData, - bool& popupKey, - DWORD& modifiers, - wchar_t& wch) noexcept +[[nodiscard]] NTSTATUS Popup::_getUserInputInternal(COOKED_READ_DATA& cookedReadData, + bool& popupKey, + DWORD& modifiers, + wchar_t& wch) noexcept { InputBuffer* const pInputBuffer = cookedReadData.GetInputBuffer(); NTSTATUS Status = GetChar(pInputBuffer, diff --git a/src/host/popup.h b/src/host/popup.h index d8ddf437d..9e007d459 100644 --- a/src/host/popup.h +++ b/src/host/popup.h @@ -24,22 +24,18 @@ Revision History: #include "screenInfo.hpp" #include "readDataCooked.hpp" - #define MINIMUM_COMMAND_PROMPT_SIZE 5 - class CommandHistory; class Popup { public: - using UserInputFunction = std::function; Popup(SCREEN_INFORMATION& screenInfo, const COORD proposedSize); virtual ~Popup(); - [[nodiscard]] - virtual NTSTATUS Process(COOKED_READ_DATA& cookedReadData) noexcept = 0; + [[nodiscard]] virtual NTSTATUS Process(COOKED_READ_DATA& cookedReadData) noexcept = 0; void Draw(); @@ -66,15 +62,13 @@ protected: friend class CommandListPopupTests; #endif - [[nodiscard]] - NTSTATUS _getUserInput(COOKED_READ_DATA& cookedReadData, bool& popupKey, DWORD& modifiers, wchar_t& wch) noexcept; + [[nodiscard]] NTSTATUS _getUserInput(COOKED_READ_DATA& cookedReadData, bool& popupKey, DWORD& modifiers, wchar_t& wch) noexcept; void _DrawPrompt(const UINT id); virtual void _DrawContent() = 0; - - SMALL_RECT _region; // region popup occupies + SMALL_RECT _region; // region popup occupies SCREEN_INFORMATION& _screenInfo; - TextAttribute _attributes; // text attributes + TextAttribute _attributes; // text attributes private: COORD _CalculateSize(const SCREEN_INFORMATION& screenInfo, const COORD proposedSize); @@ -82,11 +76,10 @@ private: void _DrawBorder(); - [[nodiscard]] - static NTSTATUS _getUserInputInternal(COOKED_READ_DATA& cookedReadData, - bool& popupKey, - DWORD& modifiers, - wchar_t& wch) noexcept; + [[nodiscard]] static NTSTATUS _getUserInputInternal(COOKED_READ_DATA& cookedReadData, + bool& popupKey, + DWORD& modifiers, + wchar_t& wch) noexcept; OutputCellRect _oldContents; // contains data under popup COORD _oldScreenSize; diff --git a/src/host/precomp.h b/src/host/precomp.h index 9c5d40fe4..ed00242ba 100644 --- a/src/host/precomp.h +++ b/src/host/precomp.h @@ -27,7 +27,7 @@ Abstract: // This includes support libraries from the CRT, STL, WIL, and GSL #include "LibraryIncludes.h" -#define SCREEN_BUFFER_POINTER(X,Y,XSIZE,CELLSIZE) (((XSIZE * (Y)) + (X)) * (ULONG)CELLSIZE) +#define SCREEN_BUFFER_POINTER(X, Y, XSIZE, CELLSIZE) (((XSIZE * (Y)) + (X)) * (ULONG)CELLSIZE) #include #include @@ -51,7 +51,7 @@ Abstract: #include "conv.h" #pragma prefast(push) -#pragma prefast(disable:26071, "Range violation in Intsafe. Not ours.") +#pragma prefast(disable : 26071, "Range violation in Intsafe. Not ours.") #define ENABLE_INTSAFE_SIGNED_FUNCTIONS // Only unsigned intsafe math/casts available without this def #include #pragma prefast(pop) @@ -80,8 +80,8 @@ TRACELOGGING_DECLARE_PROVIDER(g_hConhostV2EventTraceProvider); #define CON_BUILD_PUBLIC #ifdef CON_BUILD_PUBLIC - #define CON_USERPRIVAPI_INDIRECT - #define CON_DPIAPI_INDIRECT +#define CON_USERPRIVAPI_INDIRECT +#define CON_DPIAPI_INDIRECT #endif #include "..\inc\contsf.h" @@ -89,8 +89,7 @@ TRACELOGGING_DECLARE_PROVIDER(g_hConhostV2EventTraceProvider); #include "..\inc\conattrs.hpp" // TODO: MSFT 9355094 Find a better way of doing this. http://osgvsowi/9355094 -[[nodiscard]] -inline NTSTATUS NTSTATUS_FROM_HRESULT(HRESULT hr) +[[nodiscard]] inline NTSTATUS NTSTATUS_FROM_HRESULT(HRESULT hr) { return NTSTATUS_FROM_WIN32(HRESULT_CODE(hr)); } diff --git a/src/host/readData.hpp b/src/host/readData.hpp index c9cc3acad..41471cae2 100644 --- a/src/host/readData.hpp +++ b/src/host/readData.hpp @@ -34,7 +34,7 @@ public: ReadData(const ReadData&) = delete; ReadData(ReadData&&); ReadData& operator=(const ReadData&) & = delete; - ReadData& operator=(ReadData &&) & = delete; + ReadData& operator=(ReadData&&) & = delete; virtual bool Notify(const WaitTerminationReason TerminationReason, const bool fIsUnicode, @@ -52,8 +52,9 @@ public: ReadData() : IWaitRoutine(ReplyDataType::Read), _pInputBuffer{ nullptr }, - _pInputReadHandleData{ nullptr} - {} + _pInputReadHandleData{ nullptr } + { + } #endif protected: InputBuffer* _pInputBuffer; diff --git a/src/host/readDataCooked.cpp b/src/host/readDataCooked.cpp index ae1d6deca..7263655bb 100644 --- a/src/host/readDataCooked.cpp +++ b/src/host/readDataCooked.cpp @@ -51,8 +51,7 @@ COOKED_READ_DATA::COOKED_READ_DATA(_In_ InputBuffer* const pInputBuffer, _In_ ULONG CtrlWakeupMask, _In_ CommandHistory* CommandHistory, const std::wstring_view exeName, - const std::string_view initialData -) : + const std::string_view initialData) : ReadData(pInputBuffer, pInputReadHandleData), _screenInfo{ screenInfo }, _bytesRead{ 0 }, @@ -78,9 +77,9 @@ COOKED_READ_DATA::COOKED_READ_DATA(_In_ InputBuffer* const pInputBuffer, { #ifndef UNIT_TESTING THROW_IF_FAILED(screenInfo.GetMainBuffer().AllocateIoHandle(ConsoleHandleData::HandleType::Output, - GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE, - _tempHandle)); + GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, + _tempHandle)); #endif // to emulate OS/2 KbdStringIn, we read into our own big buffer @@ -290,7 +289,6 @@ void COOKED_READ_DATA::Erase() noexcept _bytesRead = 0; _currentPosition = 0; _visibleCharCount = 0; - } // Routine Description: @@ -437,10 +435,9 @@ bool COOKED_READ_DATA::AtEol() const noexcept // - numBytes - On in, the number of bytes available in the client // buffer. On out, the number of bytes consumed in the client buffer. // - controlKeyState - For some types of reads, this is the modifier key state with the last button press. -[[nodiscard]] -HRESULT COOKED_READ_DATA::Read(const bool isUnicode, - size_t& numBytes, - ULONG& controlKeyState) noexcept +[[nodiscard]] HRESULT COOKED_READ_DATA::Read(const bool isUnicode, + size_t& numBytes, + ULONG& controlKeyState) noexcept { controlKeyState = 0; @@ -530,14 +527,14 @@ bool COOKED_READ_DATA::ProcessInput(const wchar_t wchOrig, { NumToWrite = sizeof(WCHAR); status = WriteCharsLegacy(_screenInfo, - _backupLimit, - _bufPtr, - &wch, - &NumToWrite, - &NumSpaces, - _originalCursorPosition.X, - WC_DESTRUCTIVE_BACKSPACE | WC_KEEP_CURSOR_VISIBLE | WC_ECHO, - &ScrollY); + _backupLimit, + _bufPtr, + &wch, + &NumToWrite, + &NumSpaces, + _originalCursorPosition.X, + WC_DESTRUCTIVE_BACKSPACE | WC_KEEP_CURSOR_VISIBLE | WC_ECHO, + &ScrollY); if (NT_SUCCESS(status)) { _originalCursorPosition.Y += ScrollY; @@ -552,7 +549,9 @@ bool COOKED_READ_DATA::ProcessInput(const wchar_t wchOrig, if (wch == UNICODE_BACKSPACE && _processedInput) { _bytesRead -= sizeof(WCHAR); - #pragma prefast(suppress:__WARNING_POTENTIAL_BUFFER_OVERFLOW_HIGH_PRIORITY, "This access is fine") + // clang-format off +#pragma prefast(suppress: __WARNING_POTENTIAL_BUFFER_OVERFLOW_HIGH_PRIORITY, "This access is fine") + // clang-format on *_bufPtr = (WCHAR)' '; _bufPtr -= 1; _currentPosition -= 1; @@ -596,7 +595,6 @@ bool COOKED_READ_DATA::ProcessInput(const wchar_t wchOrig, if (_bufPtr != _backupLimit) { - fStartFromDelim = IsWordDelim(_bufPtr[-1]); bool loop = true; @@ -611,14 +609,14 @@ bool COOKED_READ_DATA::ProcessInput(const wchar_t wchOrig, { NumToWrite = sizeof(WCHAR); status = WriteCharsLegacy(_screenInfo, - _backupLimit, - _bufPtr, - &wch, - &NumToWrite, - nullptr, - _originalCursorPosition.X, - WC_DESTRUCTIVE_BACKSPACE | WC_KEEP_CURSOR_VISIBLE | WC_ECHO, - nullptr); + _backupLimit, + _bufPtr, + &wch, + &NumToWrite, + nullptr, + _originalCursorPosition.X, + WC_DESTRUCTIVE_BACKSPACE | WC_KEEP_CURSOR_VISIBLE | WC_ECHO, + nullptr); if (!NT_SUCCESS(status)) { RIPMSG1(RIP_WARNING, "WriteCharsLegacy failed %x", status); @@ -710,7 +708,9 @@ bool COOKED_READ_DATA::ProcessInput(const wchar_t wchOrig, CursorPosition.X = (SHORT)(CursorPosition.X + NumSpaces); // clear the current command line from the screen -#pragma prefast(suppress:__WARNING_BUFFER_OVERFLOW, "Not sure why prefast doesn't like this call.") + // clang-format off +#pragma prefast(suppress: __WARNING_BUFFER_OVERFLOW, "Not sure why prefast doesn't like this call.") + // clang-format on DeleteCommandLine(*this, FALSE); // write the new command line to the screen @@ -744,7 +744,8 @@ bool COOKED_READ_DATA::ProcessInput(const wchar_t wchOrig, _backupLimit, _currentPosition + 1, sScreenBufferSizeX - _originalCursorPosition.X, - _originalCursorPosition.X, TRUE)) + _originalCursorPosition.X, + TRUE)) { if (CursorPosition.X == (sScreenBufferSizeX - 1)) { @@ -835,7 +836,6 @@ size_t COOKED_READ_DATA::Write(const std::wstring_view wstr) _currentPosition += charsInserted; _bytesRead += bytesInserted; - if (IsEchoInput()) { size_t NumSpaces = 0; @@ -899,7 +899,7 @@ void COOKED_READ_DATA::SavePendingInput(const size_t index, const bool multiline { INPUT_READ_HANDLE_DATA& inputReadHandleData = *GetInputReadHandleData(); const std::wstring_view pending{ _backupLimit + index, - BytesRead() / sizeof(wchar_t) - index}; + BytesRead() / sizeof(wchar_t) - index }; if (multiline) { inputReadHandleData.SaveMultilinePendingInput(pending); @@ -918,8 +918,7 @@ void COOKED_READ_DATA::SavePendingInput(const size_t index, const bool multiline // buffer. On out, the number of bytes consumed in the client buffer. // Return Value: // - Status code that indicates success, wait, etc. -[[nodiscard]] -NTSTATUS COOKED_READ_DATA::_readCharInputLoop(const bool isUnicode, size_t& numBytes) noexcept +[[nodiscard]] NTSTATUS COOKED_READ_DATA::_readCharInputLoop(const bool isUnicode, size_t& numBytes) noexcept { NTSTATUS Status = STATUS_SUCCESS; @@ -1001,8 +1000,7 @@ NTSTATUS COOKED_READ_DATA::_readCharInputLoop(const bool isUnicode, size_t& numB // - controlKeyState - For some types of reads, this is the modifier key state with the last button press. // Return Value: // - Status code that indicates success, out of memory, etc. -[[nodiscard]] -NTSTATUS COOKED_READ_DATA::_handlePostCharInputLoop(const bool isUnicode, size_t& numBytes, ULONG& controlKeyState) noexcept +[[nodiscard]] NTSTATUS COOKED_READ_DATA::_handlePostCharInputLoop(const bool isUnicode, size_t& numBytes, ULONG& controlKeyState) noexcept { DWORD LineCount = 1; @@ -1029,7 +1027,7 @@ NTSTATUS COOKED_READ_DATA::_handlePostCharInputLoop(const bool isUnicode, size_t // add to command line recall list if we have a history list. CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); LOG_IF_FAILED(_commandHistory->Add({ _backupLimit, StringLength / sizeof(wchar_t) }, - WI_IsFlagSet(gci.Flags, CONSOLE_HISTORY_NODUP))); + WI_IsFlagSet(gci.Flags, CONSOLE_HISTORY_NODUP))); } // check for alias @@ -1061,14 +1059,16 @@ NTSTATUS COOKED_READ_DATA::_handlePostCharInputLoop(const bool isUnicode, size_t NumBytes = 0; for (Tmp = _backupLimit; - *Tmp != UNICODE_LINEFEED && _userBufferSize / sizeof(WCHAR) > NumBytes; - Tmp++) + *Tmp != UNICODE_LINEFEED && _userBufferSize / sizeof(WCHAR) > NumBytes; + Tmp++) { NumBytes += IsGlyphFullWidth(*Tmp) ? 2 : 1; } } -#pragma prefast(suppress:__WARNING_BUFFER_OVERFLOW, "LineCount > 1 means there's a UNICODE_LINEFEED") + // clang-format off +#pragma prefast(suppress: __WARNING_BUFFER_OVERFLOW, "LineCount > 1 means there's a UNICODE_LINEFEED") + // clang-format on for (Tmp = _backupLimit; *Tmp != UNICODE_LINEFEED; Tmp++) { FAIL_FAST_IF(!(Tmp < (_backupLimit + _bytesRead))); @@ -1094,8 +1094,8 @@ NTSTATUS COOKED_READ_DATA::_handlePostCharInputLoop(const bool isUnicode, size_t NumBytes = 0; size_t NumToWrite = _bytesRead; for (Tmp = _backupLimit; - NumToWrite && _userBufferSize / sizeof(WCHAR) > NumBytes; - Tmp++, NumToWrite -= sizeof(WCHAR)) + NumToWrite && _userBufferSize / sizeof(WCHAR) > NumBytes; + Tmp++, NumToWrite -= sizeof(WCHAR)) { NumBytes += IsGlyphFullWidth(*Tmp) ? 2 : 1; } @@ -1141,8 +1141,8 @@ NTSTATUS COOKED_READ_DATA::_handlePostCharInputLoop(const bool isUnicode, size_t NumBytes = 0; size_t NumToWrite = _bytesRead; for (Tmp = _backupLimit; - NumToWrite && _userBufferSize / sizeof(WCHAR) > NumBytes; - Tmp++, NumToWrite -= sizeof(WCHAR)) + NumToWrite && _userBufferSize / sizeof(WCHAR) > NumBytes; + Tmp++, NumToWrite -= sizeof(WCHAR)) { NumBytes += IsGlyphFullWidth(*Tmp) ? 2 : 1; } @@ -1174,17 +1174,16 @@ NTSTATUS COOKED_READ_DATA::_handlePostCharInputLoop(const bool isUnicode, size_t std::unique_ptr partialEvent; numBytes = TranslateUnicodeToOem(_userBuffer, - gsl::narrow(numBytes / sizeof(wchar_t)), - tempBuffer.get(), - gsl::narrow(NumBytes), - partialEvent); + gsl::narrow(numBytes / sizeof(wchar_t)), + tempBuffer.get(), + gsl::narrow(NumBytes), + partialEvent); if (partialEvent.get()) { GetInputBuffer()->StoreReadPartialByteSequence(std::move(partialEvent)); } - if (numBytes > _userBufferSize) { return STATUS_BUFFER_OVERFLOW; diff --git a/src/host/readDataCooked.hpp b/src/host/readDataCooked.hpp index d261c1124..5080de5d3 100644 --- a/src/host/readDataCooked.hpp +++ b/src/host/readDataCooked.hpp @@ -62,10 +62,9 @@ public: void ProcessAliases(DWORD& lineCount); - [[nodiscard]] - HRESULT Read(const bool isUnicode, - size_t& numBytes, - ULONG& controlKeyState) noexcept; + [[nodiscard]] HRESULT Read(const bool isUnicode, + size_t& numBytes, + ULONG& controlKeyState) noexcept; bool ProcessInput(const wchar_t wch, const DWORD keyState, @@ -107,7 +106,6 @@ public: size_t SavePromptToUserBuffer(const size_t cch); void SavePendingInput(const size_t cch, const bool multiline); - #if UNIT_TESTING friend class CommandLineTests; friend class CopyToCharPopupTests; @@ -121,14 +119,14 @@ private: size_t _bytesRead; // insertion position into the buffer (where the conceptual prompt cursor is) - size_t _currentPosition; // char position, not byte position + size_t _currentPosition; // char position, not byte position wchar_t* _bufPtr; // current position to insert chars at // should be const. the first char of the buffer wchar_t* _backupLimit; - size_t _userBufferSize; // doubled size in ansi case + size_t _userBufferSize; // doubled size in ansi case wchar_t* _userBuffer; size_t* _pdwNumBytes; @@ -156,9 +154,7 @@ private: bool _insertMode; bool _unicode; - [[nodiscard]] - NTSTATUS _readCharInputLoop(const bool isUnicode, size_t& numBytes) noexcept; + [[nodiscard]] NTSTATUS _readCharInputLoop(const bool isUnicode, size_t& numBytes) noexcept; - [[nodiscard]] - NTSTATUS _handlePostCharInputLoop(const bool isUnicode, size_t& numBytes, ULONG& controlKeyState) noexcept; + [[nodiscard]] NTSTATUS _handlePostCharInputLoop(const bool isUnicode, size_t& numBytes, ULONG& controlKeyState) noexcept; }; diff --git a/src/host/readDataDirect.cpp b/src/host/readDataDirect.cpp index 4a130c013..f47d32b92 100644 --- a/src/host/readDataDirect.cpp +++ b/src/host/readDataDirect.cpp @@ -29,7 +29,7 @@ DirectReadData::DirectReadData(_In_ InputBuffer* const pInputBuffer, ReadData(pInputBuffer, pInputReadHandleData), _eventReadCount{ eventReadCount }, _partialEvents{ std::move(partialEvents) }, - _outEvents{ } + _outEvents{} { } diff --git a/src/host/readDataDirect.hpp b/src/host/readDataDirect.hpp index 925d53e19..26006db53 100644 --- a/src/host/readDataDirect.hpp +++ b/src/host/readDataDirect.hpp @@ -28,7 +28,6 @@ Revision History: #include #include - class DirectReadData final : public ReadData { public: diff --git a/src/host/readDataRaw.cpp b/src/host/readDataRaw.cpp index 349632836..708efdc52 100644 --- a/src/host/readDataRaw.cpp +++ b/src/host/readDataRaw.cpp @@ -40,7 +40,6 @@ RAW_READ_DATA::RAW_READ_DATA(_In_ InputBuffer* const pInputBuffer, // - Decrements count of readers waiting on the given handle. RAW_READ_DATA::~RAW_READ_DATA() { - } // Routine Description: @@ -84,7 +83,6 @@ bool RAW_READ_DATA::Notify(const WaitTerminationReason TerminationReason, *pReplyStatus = STATUS_SUCCESS; *pControlKeyState = 0; - *pNumBytes = 0; size_t NumBytes = 0; diff --git a/src/host/registry.cpp b/src/host/registry.cpp index 920421537..94885b29f 100644 --- a/src/host/registry.cpp +++ b/src/host/registry.cpp @@ -19,12 +19,10 @@ using Microsoft::Console::Interactivity::ServiceLocator; Registry::Registry(_In_ Settings* const pSettings) : _pSettings(pSettings) { - } Registry::~Registry() { - } // Routine Description: @@ -53,7 +51,7 @@ void Registry::GetEditKeys(_In_opt_ HKEY hConsoleKey) const CONSOLE_REGISTRY_ALLOW_ALTF4_CLOSE, sizeof(dwValue), REG_DWORD, - (PBYTE)& dwValue, + (PBYTE)&dwValue, nullptr); if (NT_SUCCESS(Status) && dwValue <= 1) { @@ -144,7 +142,6 @@ void Registry::_LoadMappedProperties(_In_reads_(cPropertyMappings) const Registr case RegistrySerialization::_RegPropertyType::Byte: case RegistrySerialization::_RegPropertyType::Coordinate: { - Status = RegistrySerialization::s_LoadRegDword(hKey, pPropMap, _pSettings); break; } @@ -276,7 +273,7 @@ void Registry::LoadFromRegistry(_In_ PCWSTR const pwszConsoleTitle) CONSOLE_REGISTRY_CODEPAGE, sizeof(dwValue), REG_DWORD, - (PBYTE)& dwValue, + (PBYTE)&dwValue, nullptr); if (NT_SUCCESS(Status)) { @@ -309,7 +306,7 @@ void Registry::LoadFromRegistry(_In_ PCWSTR const pwszConsoleTitle) awchBuffer, sizeof(dwValue), REG_DWORD, - (PBYTE)& dwValue, + (PBYTE)&dwValue, nullptr); if (NT_SUCCESS(Status)) { diff --git a/src/host/registry.hpp b/src/host/registry.hpp index 6b89f70ae..a6de5791d 100644 --- a/src/host/registry.hpp +++ b/src/host/registry.hpp @@ -30,13 +30,12 @@ public: void LoadDefaultFromRegistry(); void LoadFromRegistry(_In_ PCWSTR const pwszConsoleTitle); - void GetEditKeys(_In_opt_ HKEY hConsoleKey) const; + private: void _LoadMappedProperties(_In_reads_(cPropertyMappings) const RegistrySerialization::RegPropertyMap* const rgPropertyMappings, const size_t cPropertyMappings, const HKEY hKey); - Settings* const _pSettings; }; diff --git a/src/host/renderData.hpp b/src/host/renderData.hpp index 70469de55..359d4348f 100644 --- a/src/host/renderData.hpp +++ b/src/host/renderData.hpp @@ -46,5 +46,4 @@ public: void LockConsole() noexcept override; void UnlockConsole() noexcept override; - }; diff --git a/src/host/renderFontDefaults.cpp b/src/host/renderFontDefaults.cpp index 176c29f57..64592c769 100644 --- a/src/host/renderFontDefaults.cpp +++ b/src/host/renderFontDefaults.cpp @@ -17,10 +17,9 @@ RenderFontDefaults::~RenderFontDefaults() LOG_IF_FAILED(TrueTypeFontList::s_Destroy()); } -[[nodiscard]] -HRESULT RenderFontDefaults::RetrieveDefaultFontNameForCodepage(const UINT uiCodePage, - _Out_writes_(cchFaceName) PWSTR pwszFaceName, - const size_t cchFaceName) +[[nodiscard]] HRESULT RenderFontDefaults::RetrieveDefaultFontNameForCodepage(const UINT uiCodePage, + _Out_writes_(cchFaceName) PWSTR pwszFaceName, + const size_t cchFaceName) { NTSTATUS status = TrueTypeFontList::s_SearchByCodePage(uiCodePage, pwszFaceName, cchFaceName); return HRESULT_FROM_NT(status); diff --git a/src/host/renderFontDefaults.hpp b/src/host/renderFontDefaults.hpp index 2fc4bbd06..4ab09a97f 100644 --- a/src/host/renderFontDefaults.hpp +++ b/src/host/renderFontDefaults.hpp @@ -22,8 +22,7 @@ public: RenderFontDefaults(); ~RenderFontDefaults(); - [[nodiscard]] - HRESULT RetrieveDefaultFontNameForCodepage(const UINT uiCodePage, - _Out_writes_(cchFaceName) PWSTR pwszFaceName, - const size_t cchFaceName); + [[nodiscard]] HRESULT RetrieveDefaultFontNameForCodepage(const UINT uiCodePage, + _Out_writes_(cchFaceName) PWSTR pwszFaceName, + const size_t cchFaceName); }; diff --git a/src/host/resource.h b/src/host/resource.h index bc6c5a660..f81be52a8 100644 --- a/src/host/resource.h +++ b/src/host/resource.h @@ -15,6 +15,8 @@ Author(s): #pragma once +// clang-format off + // Fusion Application Manifest #define IDR_SYSTEM_MANIFEST 100 @@ -48,3 +50,5 @@ Author(s): #define ID_CONSOLE_FINDCASE 602 #define ID_CONSOLE_FINDUP 603 #define ID_CONSOLE_FINDDOWN 604 + +// clang-format on diff --git a/src/host/screenInfo.cpp b/src/host/screenInfo.cpp index 814ccdb07..83cb08097 100644 --- a/src/host/screenInfo.cpp +++ b/src/host/screenInfo.cpp @@ -19,10 +19,7 @@ #include "../types/inc/convert.hpp" - #pragma hdrstop -#pragma region Construct/Destruct - using namespace Microsoft::Console; using namespace Microsoft::Console::Types; @@ -30,9 +27,11 @@ using namespace Microsoft::Console::Render; using namespace Microsoft::Console::Interactivity; using namespace Microsoft::Console::VirtualTerminal; +#pragma region Construct_Destruct + SCREEN_INFORMATION::SCREEN_INFORMATION( - _In_ IWindowMetrics *pMetrics, - _In_ IAccessibilityNotifier *pNotifier, + _In_ IWindowMetrics* pMetrics, + _In_ IAccessibilityNotifier* pNotifier, const TextAttribute popupAttributes, const FontInfo fontInfo) : OutputMode{ ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT }, @@ -49,7 +48,7 @@ SCREEN_INFORMATION::SCREEN_INFORMATION( _pConsoleWindowMetrics{ pMetrics }, _pAccessibilityNotifier{ pNotifier }, _stateMachine{ nullptr }, - _scrollMargins{ Viewport::FromCoord({0}) }, + _scrollMargins{ Viewport::FromCoord({ 0 }) }, _viewport(Viewport::Empty()), _psiAlternateBuffer{ nullptr }, _psiMainBuffer{ nullptr }, @@ -96,23 +95,22 @@ SCREEN_INFORMATION::~SCREEN_INFORMATION() // - nFont - the initial font to generate text with. // - dwScreenBufferSize - the initial size of the screen buffer (in rows/columns). // Return Value: -[[nodiscard]] -NTSTATUS SCREEN_INFORMATION::CreateInstance(_In_ COORD coordWindowSize, - const FontInfo fontInfo, - _In_ COORD coordScreenBufferSize, - const TextAttribute defaultAttributes, - const TextAttribute popupAttributes, - const UINT uiCursorSize, - _Outptr_ SCREEN_INFORMATION** const ppScreen) +[[nodiscard]] NTSTATUS SCREEN_INFORMATION::CreateInstance(_In_ COORD coordWindowSize, + const FontInfo fontInfo, + _In_ COORD coordScreenBufferSize, + const TextAttribute defaultAttributes, + const TextAttribute popupAttributes, + const UINT uiCursorSize, + _Outptr_ SCREEN_INFORMATION** const ppScreen) { *ppScreen = nullptr; try { - IWindowMetrics *pMetrics = ServiceLocator::LocateWindowMetrics(); + IWindowMetrics* pMetrics = ServiceLocator::LocateWindowMetrics(); THROW_IF_NULL_ALLOC(pMetrics); - IAccessibilityNotifier *pNotifier = ServiceLocator::LocateAccessibilityNotifier(); + IAccessibilityNotifier* pNotifier = ServiceLocator::LocateAccessibilityNotifier(); THROW_IF_NULL_ALLOC(pNotifier); SCREEN_INFORMATION* const pScreen = new SCREEN_INFORMATION(pMetrics, pNotifier, popupAttributes, fontInfo); @@ -173,7 +171,7 @@ Viewport SCREEN_INFORMATION::GetTerminalBufferSize() const Viewport v = _textBuffer->GetSize(); if (gci.IsTerminalScrolling() && v.Height() > _virtualBottom) { - v = Viewport::FromDimensions({0, 0}, v.Width(), _virtualBottom+1); + v = Viewport::FromDimensions({ 0, 0 }, v.Width(), _virtualBottom + 1); } return v; } @@ -268,8 +266,7 @@ void SCREEN_INFORMATION::s_RemoveScreenBuffer(_In_ SCREEN_INFORMATION* const pSc #pragma region Output State Machine -[[nodiscard]] -NTSTATUS SCREEN_INFORMATION::_InitializeOutputStateMachine() +[[nodiscard]] NTSTATUS SCREEN_INFORMATION::_InitializeOutputStateMachine() { try { @@ -545,10 +542,9 @@ void SCREEN_INFORMATION::RefreshFontWithRenderer() // Hand the handle to our internal structure to the font change trigger in case it updates it based on what's appropriate. if (ServiceLocator::LocateGlobals().pRender != nullptr) { - ServiceLocator::LocateGlobals().pRender - ->TriggerFontChange(ServiceLocator::LocateGlobals().dpi, - GetDesiredFont(), - GetCurrentFont()); + ServiceLocator::LocateGlobals().pRender->TriggerFontChange(ServiceLocator::LocateGlobals().dpi, + GetDesiredFont(), + GetCurrentFont()); NotifyGlyphWidthFontChanged(); } @@ -632,7 +628,7 @@ void SCREEN_INFORMATION::NotifyAccessibilityEventing(const short sStartX, #pragma endregion -#pragma region UI/Refresh +#pragma region UI_Refresh VOID SCREEN_INFORMATION::UpdateScrollBars() { @@ -744,10 +740,9 @@ void SCREEN_INFORMATION::SetViewportSize(const COORD* const pcoordSize) // Return Value: // - STATUS_INVALID_PARAMETER if the new viewport would be outside the buffer, // else STATUS_SUCCESS -[[nodiscard]] -NTSTATUS SCREEN_INFORMATION::SetViewportOrigin(const bool fAbsolute, - const COORD coordWindowOrigin, - const bool updateBottom) +[[nodiscard]] NTSTATUS SCREEN_INFORMATION::SetViewportOrigin(const bool fAbsolute, + const COORD coordWindowOrigin, + const bool updateBottom) { // calculate window size COORD WindowSize = _viewport.Dimensions(); @@ -905,7 +900,7 @@ void SCREEN_INFORMATION::ProcessResizeWindow(const RECT* const prcClientNew, #pragma endregion -#pragma region Support/Calculation +#pragma region Support_Calculation // Routine Description: // - This helper converts client pixel areas into the number of characters that could fit into the client window. @@ -916,10 +911,9 @@ void SCREEN_INFORMATION::ProcessResizeWindow(const RECT* const prcClientNew, // - pcoordClientNewCharacters - The maximum number of characters X by Y that can be displayed in the window with the given backing buffer. // Return Value: // - S_OK if math was successful. Check with SUCCEEDED/FAILED macro. -[[nodiscard]] -HRESULT SCREEN_INFORMATION::_AdjustScreenBufferHelper(const RECT* const prcClientNew, - const COORD coordBufferOld, - _Out_ COORD* const pcoordClientNewCharacters) +[[nodiscard]] HRESULT SCREEN_INFORMATION::_AdjustScreenBufferHelper(const RECT* const prcClientNew, + const COORD coordBufferOld, + _Out_ COORD* const pcoordClientNewCharacters) { // Get the font size ready. COORD const coordFontSize = GetScreenFontSize(); @@ -965,8 +959,7 @@ HRESULT SCREEN_INFORMATION::_AdjustScreenBufferHelper(const RECT* const prcClien // - prcClientNew - Client rectangle in pixels after this update // Return Value: // - appropriate HRESULT -[[nodiscard]] -HRESULT SCREEN_INFORMATION::_AdjustScreenBuffer(const RECT* const prcClientNew) +[[nodiscard]] HRESULT SCREEN_INFORMATION::_AdjustScreenBuffer(const RECT* const prcClientNew) { const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); // Prepare the buffer sizes. @@ -1245,7 +1238,7 @@ void SCREEN_INFORMATION::_InternalSetViewportSize(const COORD* const pcoordSize, { const short newTop = static_cast(std::max(0, _virtualBottom - (newViewport.Height() - 1))); - newViewport = Viewport::FromDimensions(COORD({newViewport.Left(), newTop}), newViewport.Dimensions()); + newViewport = Viewport::FromDimensions(COORD({ newViewport.Left(), newTop }), newViewport.Dimensions()); } _viewport = newViewport; @@ -1278,9 +1271,9 @@ void SCREEN_INFORMATION::_AdjustViewportSize(const RECT* const prcClientNew, // will change. In this case especially, users expect the top left // to stay in place and the bottom right to adapt. bool const fResizeFromLeft = prcClientNew->left != prcClientOld->left && - prcClientNew->right == prcClientOld->right; + prcClientNew->right == prcClientOld->right; bool const fResizeFromTop = prcClientNew->top != prcClientOld->top && - prcClientNew->bottom == prcClientOld->bottom; + prcClientNew->bottom == prcClientOld->bottom; const Viewport oldViewport = Viewport(_viewport); @@ -1400,8 +1393,7 @@ bool SCREEN_INFORMATION::IsMaximizedY() const // - Coordinates of the new screen size // Return Value: // - Success if successful. Invalid parameter if screen buffer size is unexpected. No memory if allocation failed. -[[nodiscard]] -NTSTATUS SCREEN_INFORMATION::ResizeWithReflow(const COORD coordNewScreenSize) +[[nodiscard]] NTSTATUS SCREEN_INFORMATION::ResizeWithReflow(const COORD coordNewScreenSize) { if ((USHORT)coordNewScreenSize.X >= SHORT_MAX || (USHORT)coordNewScreenSize.Y >= SHORT_MAX) { @@ -1653,8 +1645,7 @@ NTSTATUS SCREEN_INFORMATION::ResizeWithReflow(const COORD coordNewScreenSize) // - coordNewScreenSize - new size of screen. // Return Value: // - Success if successful. Invalid parameter if screen buffer size is unexpected. No memory if allocation failed. -[[nodiscard]] -NTSTATUS SCREEN_INFORMATION::ResizeTraditional(const COORD coordNewScreenSize) +[[nodiscard]] NTSTATUS SCREEN_INFORMATION::ResizeTraditional(const COORD coordNewScreenSize) { return NTSTATUS_FROM_HRESULT(_textBuffer->ResizeTraditional(coordNewScreenSize)); } @@ -1667,9 +1658,8 @@ NTSTATUS SCREEN_INFORMATION::ResizeTraditional(const COORD coordNewScreenSize) // - DoScrollBarUpdate - indicates whether to update scroll bars at the end // Return Value: // - Success if successful. Invalid parameter if screen buffer size is unexpected. No memory if allocation failed. -[[nodiscard]] -NTSTATUS SCREEN_INFORMATION::ResizeScreenBuffer(const COORD coordNewScreenSize, - const bool fDoScrollBarUpdate) +[[nodiscard]] NTSTATUS SCREEN_INFORMATION::ResizeScreenBuffer(const COORD coordNewScreenSize, + const bool fDoScrollBarUpdate) { // If the size hasn't actually changed, do nothing. if (coordNewScreenSize == GetBufferSize().Dimensions()) @@ -1831,7 +1821,7 @@ void SCREEN_INFORMATION::SetCursorType(const CursorType Type, const bool setMain // - DoubleCursor - should we indicated non-normal mode // Return Value: // - None -void SCREEN_INFORMATION::SetCursorDBMode(const bool DoubleCursor) +void SCREEN_INFORMATION::SetCursorDBMode(const bool DoubleCursor) { Cursor& cursor = _textBuffer->GetCursor(); @@ -1855,8 +1845,7 @@ void SCREEN_INFORMATION::SetCursorDBMode(const bool DoubleCursor) // - TurnOn - true if cursor should be left on, false if should be left off // Return Value: // - Status -[[nodiscard]] -NTSTATUS SCREEN_INFORMATION::SetCursorPosition(const COORD Position, const bool TurnOn) +[[nodiscard]] NTSTATUS SCREEN_INFORMATION::SetCursorPosition(const COORD Position, const bool TurnOn) { const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); Cursor& cursor = _textBuffer->GetCursor(); @@ -2010,8 +1999,7 @@ const SCREEN_INFORMATION& SCREEN_INFORMATION::GetMainBuffer() const // - ppsiNewScreenBuffer - a pointer to recieve the newly created buffer. // Return value: // - STATUS_SUCCESS if handled successfully. Otherwise, an approriate status code indicating the error. -[[nodiscard]] -NTSTATUS SCREEN_INFORMATION::_CreateAltBuffer(_Out_ SCREEN_INFORMATION** const ppsiNewScreenBuffer) +[[nodiscard]] NTSTATUS SCREEN_INFORMATION::_CreateAltBuffer(_Out_ SCREEN_INFORMATION** const ppsiNewScreenBuffer) { // Create new screen buffer. COORD WindowSize = _viewport.Dimensions(); @@ -2055,8 +2043,7 @@ NTSTATUS SCREEN_INFORMATION::_CreateAltBuffer(_Out_ SCREEN_INFORMATION** const p // - None // Return value: // - STATUS_SUCCESS if handled successfully. Otherwise, an approriate status code indicating the error. -[[nodiscard]] -NTSTATUS SCREEN_INFORMATION::UseAlternateScreenBuffer() +[[nodiscard]] NTSTATUS SCREEN_INFORMATION::UseAlternateScreenBuffer() { CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); SCREEN_INFORMATION& siMain = GetMainBuffer(); @@ -2093,7 +2080,6 @@ NTSTATUS SCREEN_INFORMATION::UseAlternateScreenBuffer() // Tell the VT MouseInput handler that we're in the Alt buffer now gci.terminalMouseInput.UseAlternateScreenBuffer(); - } return Status; } @@ -2202,7 +2188,6 @@ void SCREEN_INFORMATION::ClearTabStop(const SHORT sColumn) noexcept // - COORD SCREEN_INFORMATION::GetForwardTab(const COORD cCurrCursorPos) const noexcept { - COORD cNewCursorPos = cCurrCursorPos; SHORT sWidth = GetBufferSize().RightInclusive(); if (cCurrCursorPos.X == sWidth) @@ -2353,7 +2338,6 @@ void SCREEN_INFORMATION::SetPopupAttributes(const TextAttribute& popupAttributes void SCREEN_INFORMATION::SetDefaultAttributes(const TextAttribute& attributes, const TextAttribute& popupAttributes) { - CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); const TextAttribute oldPrimaryAttributes = GetAttributes(); @@ -2463,8 +2447,7 @@ void SCREEN_INFORMATION::SetViewport(const Viewport& newViewport, // // Return value: // - S_OK if we succeeded, or another status if there was a failure. -[[nodiscard]] -HRESULT SCREEN_INFORMATION::VtEraseAll() +[[nodiscard]] HRESULT SCREEN_INFORMATION::VtEraseAll() { const COORD coordLastChar = _textBuffer->GetLastNonSpaceCharacter(); short sNewTop = coordLastChar.Y + 1; @@ -2564,7 +2547,6 @@ OutputCellRect SCREEN_INFORMATION::ReadRect(const Viewport viewport) const { *span.rbegin() = paddingCell; } - } return result; @@ -2837,7 +2819,7 @@ void SCREEN_INFORMATION::MoveToBottom() Viewport SCREEN_INFORMATION::GetVirtualViewport() const noexcept { const short newTop = _virtualBottom - _viewport.Height() + 1; - return Viewport::FromDimensions({0, newTop}, _viewport.Dimensions()); + return Viewport::FromDimensions({ 0, newTop }, _viewport.Dimensions()); } // Method Description: @@ -2933,6 +2915,6 @@ Viewport SCREEN_INFORMATION::GetScrollingRegion() const noexcept const auto margin = Viewport::FromInclusive({ buffer.Left(), marginsSet ? marginRect.Top : buffer.Top(), buffer.RightInclusive(), - marginsSet ? marginRect.Bottom : buffer.BottomInclusive()}); + marginsSet ? marginRect.Bottom : buffer.BottomInclusive() }); return margin; } diff --git a/src/host/screenInfo.hpp b/src/host/screenInfo.hpp index 19a337bbb..0a617008e 100644 --- a/src/host/screenInfo.hpp +++ b/src/host/screenInfo.hpp @@ -53,15 +53,13 @@ class ConversionAreaInfo; // forward decl window. circular reference class SCREEN_INFORMATION : public ConsoleObjectHeader, public Microsoft::Console::IIoProvider { public: - - [[nodiscard]] - static NTSTATUS CreateInstance(_In_ COORD coordWindowSize, - const FontInfo fontInfo, - _In_ COORD coordScreenBufferSize, - const TextAttribute defaultAttributes, - const TextAttribute popupAttributes, - const UINT uiCursorSize, - _Outptr_ SCREEN_INFORMATION ** const ppScreen); + [[nodiscard]] static NTSTATUS CreateInstance(_In_ COORD coordWindowSize, + const FontInfo fontInfo, + _In_ COORD coordScreenBufferSize, + const TextAttribute defaultAttributes, + const TextAttribute popupAttributes, + const UINT uiCursorSize, + _Outptr_ SCREEN_INFORMATION** const ppScreen); ~SCREEN_INFORMATION(); @@ -91,8 +89,7 @@ public: void UpdateFont(const FontInfo* const pfiNewFont); void RefreshFontWithRenderer(); - [[nodiscard]] - NTSTATUS ResizeScreenBuffer(const COORD coordNewScreenSize, const bool fDoScrollBarUpdate); + [[nodiscard]] NTSTATUS ResizeScreenBuffer(const COORD coordNewScreenSize, const bool fDoScrollBarUpdate); void NotifyAccessibilityEventing(const short sStartX, const short sStartY, const short sEndX, const short sEndY); @@ -111,8 +108,7 @@ public: void SetViewportSize(const COORD* const pcoordSize); // Forwarders to Window if we're the active buffer. - [[nodiscard]] - NTSTATUS SetViewportOrigin(const bool fAbsolute, const COORD coordWindowOrigin, const bool updateBottom); + [[nodiscard]] NTSTATUS SetViewportOrigin(const bool fAbsolute, const COORD coordWindowOrigin, const bool updateBottom); bool SendNotifyBeep() const; bool PostUpdateWindowSize() const; @@ -159,22 +155,24 @@ public: bool CursorIsDoubleWidth() const; DWORD OutputMode; - WORD ResizingWindow; // > 0 if we should ignore WM_SIZE messages + WORD ResizingWindow; // > 0 if we should ignore WM_SIZE messages short WheelDelta; short HWheelDelta; + private: std::unique_ptr _textBuffer; + public: - SCREEN_INFORMATION *Next; + SCREEN_INFORMATION* Next; BYTE WriteConsoleDbcsLeadByte[2]; BYTE FillOutDbcsLeadChar; WCHAR LineChar[6]; -#define UPPER_LEFT_CORNER 0 -#define UPPER_RIGHT_CORNER 1 -#define HORIZONTAL_LINE 2 -#define VERTICAL_LINE 3 -#define BOTTOM_LEFT_CORNER 4 +#define UPPER_LEFT_CORNER 0 +#define UPPER_RIGHT_CORNER 1 +#define HORIZONTAL_LINE 2 +#define VERTICAL_LINE 3 +#define BOTTOM_LEFT_CORNER 4 #define BOTTOM_RIGHT_CORNER 5 // non ownership pointer @@ -195,8 +193,7 @@ public: void SetCursorType(const CursorType Type, const bool setMain = false) noexcept; void SetCursorDBMode(const bool DoubleCursor); - [[nodiscard]] - NTSTATUS SetCursorPosition(const COORD Position, const bool TurnOn); + [[nodiscard]] NTSTATUS SetCursorPosition(const COORD Position, const bool TurnOn); void MakeCursorVisible(const COORD CursorPosition, const bool updateBottom = true); @@ -206,8 +203,7 @@ public: bool AreMarginsSet() const noexcept; Microsoft::Console::Types::Viewport GetScrollingRegion() const noexcept; - [[nodiscard]] - NTSTATUS UseAlternateScreenBuffer(); + [[nodiscard]] NTSTATUS UseAlternateScreenBuffer(); void UseMainScreenBuffer(); SCREEN_INFORMATION& GetMainBuffer(); @@ -232,8 +228,7 @@ public: void SetDefaultAttributes(const TextAttribute& attributes, const TextAttribute& popupAttributes); - [[nodiscard]] - HRESULT VtEraseAll(); + [[nodiscard]] HRESULT VtEraseAll(); void SetTerminalConnection(_In_ Microsoft::Console::ITerminalOutputConnection* const pTtyConnection); @@ -251,20 +246,18 @@ public: void InitializeCursorRowAttributes(); private: - SCREEN_INFORMATION(_In_ Microsoft::Console::Interactivity::IWindowMetrics *pMetrics, - _In_ Microsoft::Console::Interactivity::IAccessibilityNotifier *pNotifier, + SCREEN_INFORMATION(_In_ Microsoft::Console::Interactivity::IWindowMetrics* pMetrics, + _In_ Microsoft::Console::Interactivity::IAccessibilityNotifier* pNotifier, const TextAttribute popupAttributes, const FontInfo fontInfo); - Microsoft::Console::Interactivity::IWindowMetrics *_pConsoleWindowMetrics; - Microsoft::Console::Interactivity::IAccessibilityNotifier *_pAccessibilityNotifier; + Microsoft::Console::Interactivity::IWindowMetrics* _pConsoleWindowMetrics; + Microsoft::Console::Interactivity::IAccessibilityNotifier* _pAccessibilityNotifier; - [[nodiscard]] - HRESULT _AdjustScreenBufferHelper(const RECT* const prcClientNew, - const COORD coordBufferOld, - _Out_ COORD* const pcoordClientNewCharacters); - [[nodiscard]] - HRESULT _AdjustScreenBuffer(const RECT* const prcClientNew); + [[nodiscard]] HRESULT _AdjustScreenBufferHelper(const RECT* const prcClientNew, + const COORD coordBufferOld, + _Out_ COORD* const pcoordClientNewCharacters); + [[nodiscard]] HRESULT _AdjustScreenBuffer(const RECT* const prcClientNew); void _CalculateViewportSize(const RECT* const prcClientArea, _Out_ COORD* const pcoordSize); void _AdjustViewportSize(const RECT* const prcClientNew, const RECT* const prcClientOld, const COORD* const pcoordSize); void _InternalSetViewportSize(const COORD* const pcoordSize, const bool fResizeFromTop, const bool fResizeFromLeft); @@ -275,17 +268,13 @@ private: _Out_ bool* const pfIsHorizontalVisible, _Out_ bool* const pfIsVerticalVisible); - [[nodiscard]] - NTSTATUS ResizeWithReflow(const COORD coordnewScreenSize); - [[nodiscard]] - NTSTATUS ResizeTraditional(const COORD coordNewScreenSize); + [[nodiscard]] NTSTATUS ResizeWithReflow(const COORD coordnewScreenSize); + [[nodiscard]] NTSTATUS ResizeTraditional(const COORD coordNewScreenSize); - [[nodiscard]] - NTSTATUS _InitializeOutputStateMachine(); + [[nodiscard]] NTSTATUS _InitializeOutputStateMachine(); void _FreeOutputStateMachine(); - [[nodiscard]] - NTSTATUS _CreateAltBuffer(_Out_ SCREEN_INFORMATION** const ppsiNewScreenBuffer); + [[nodiscard]] NTSTATUS _CreateAltBuffer(_Out_ SCREEN_INFORMATION** const ppsiNewScreenBuffer); bool _IsAltBuffer() const; bool _IsInPtyMode() const; diff --git a/src/host/scrolling.cpp b/src/host/scrolling.cpp index f221f36c5..1c344b5e5 100644 --- a/src/host/scrolling.cpp +++ b/src/host/scrolling.cpp @@ -58,7 +58,7 @@ void Scrolling::s_ClearScroll() void Scrolling::s_ScrollIfNecessary(const SCREEN_INFORMATION& ScreenInfo) { - IConsoleWindow *pWindow = ServiceLocator::LocateConsoleWindow(); + IConsoleWindow* pWindow = ServiceLocator::LocateConsoleWindow(); FAIL_FAST_IF_NULL(pWindow); Selection* const pSelection = &Selection::Instance(); @@ -77,7 +77,7 @@ void Scrolling::s_ScrollIfNecessary(const SCREEN_INFORMATION& ScreenInfo) return; } - pWindow->MapPoints((LPPOINT) & ClientRect, 2); + pWindow->MapPoints((LPPOINT)&ClientRect, 2); if (!(s_IsPointInRectangle(&ClientRect, CursorPos))) { pWindow->ConvertScreenToClient(&CursorPos); @@ -202,7 +202,7 @@ void Scrolling::s_HandleMouseWheel(_In_ bool isMouseWheel, bool Scrolling::s_HandleKeyScrollingEvent(const INPUT_KEY_INFO* const pKeyInfo) { CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); - IConsoleWindow *pWindow = ServiceLocator::LocateConsoleWindow(); + IConsoleWindow* pWindow = ServiceLocator::LocateConsoleWindow(); FAIL_FAST_IF_NULL(pWindow); const WORD VirtualKeyCode = pKeyInfo->GetVirtualKey(); diff --git a/src/host/search.h b/src/host/search.h index 50ce34db5..8c47a2460 100644 --- a/src/host/search.h +++ b/src/host/search.h @@ -18,7 +18,7 @@ Revision History: #pragma once // This used to be in find.h. -#define SEARCH_STRING_LENGTH (80) +#define SEARCH_STRING_LENGTH (80) class Search final { @@ -53,7 +53,6 @@ public: std::pair GetFoundLocation() const noexcept; private: - wchar_t _ApplySensitivity(const wchar_t wch) const; bool Search::_FindNeedleInHaystackAt(const COORD pos, COORD& start, COORD& end) const; bool _CompareChars(const std::wstring_view one, const std::wstring_view two) const; diff --git a/src/host/selection.cpp b/src/host/selection.cpp index a815bf87f..6dee0d808 100644 --- a/src/host/selection.cpp +++ b/src/host/selection.cpp @@ -729,7 +729,7 @@ void Selection::SelectAll() // Check if both anchor and opposite corner are exactly the bounds of the input line const bool fAllInputSelected = ((Utils::s_CompareCoords(coordInputStart, coordOldAnchor) == 0 && Utils::s_CompareCoords(coordInputEnd, coordOldAnchorOpposite) == 0) || - (Utils::s_CompareCoords(coordInputStart, coordOldAnchorOpposite) == 0 && Utils::s_CompareCoords(coordInputEnd, coordOldAnchor) == 0)); + (Utils::s_CompareCoords(coordInputStart, coordOldAnchorOpposite) == 0 && Utils::s_CompareCoords(coordInputEnd, coordOldAnchor) == 0)); if (fIsOldSelWithinInput && !fAllInputSelected) { diff --git a/src/host/selection.hpp b/src/host/selection.hpp index 2590ac86f..aee97594f 100644 --- a/src/host/selection.hpp +++ b/src/host/selection.hpp @@ -86,10 +86,9 @@ private: static std::unique_ptr _instance; -// ------------------------------------------------------------------------------------------------------- -// input handling (selectionInput.cpp) + // ------------------------------------------------------------------------------------------------------- + // input handling (selectionInput.cpp) public: - // key handling // N.B.: This enumeration helps push up calling clipboard functions into @@ -110,8 +109,7 @@ public: void CheckAndSetAlternateSelection(); // calculation functions - [[nodiscard]] - static bool s_GetInputLineBoundaries(_Out_opt_ COORD* const pcoordInputStart, _Out_opt_ COORD* const pcoordInputEnd); + [[nodiscard]] static bool s_GetInputLineBoundaries(_Out_opt_ COORD* const pcoordInputStart, _Out_opt_ COORD* const pcoordInputEnd); void GetValidAreaBoundaries(_Out_opt_ COORD* const pcoordValidStart, _Out_opt_ COORD* const pcoordValidEnd) const; static bool s_IsWithinBoundaries(const COORD coordPosition, const COORD coordStart, const COORD coordEnd); @@ -124,9 +122,8 @@ private: const COORD coordAnchor, const COORD coordSelPoint) const; - -// ------------------------------------------------------------------------------------------------------- -// selection state (selectionState.cpp) + // ------------------------------------------------------------------------------------------------------- + // selection state (selectionState.cpp) public: bool IsKeyboardMarkSelection() const; bool IsMouseInitiatedSelection() const; diff --git a/src/host/selectionInput.cpp b/src/host/selectionInput.cpp index b08d4db94..14bc21877 100644 --- a/src/host/selectionInput.cpp +++ b/src/host/selectionInput.cpp @@ -76,7 +76,8 @@ Selection::KeySelectionEventResult Selection::HandleKeySelectionEvent(const INPU } // if in mouse selection mode and user hits a key, cancel selection - if (!IsSystemKey(wVirtualKeyCode)) { + if (!IsSystemKey(wVirtualKeyCode)) + { ClearSelection(); } } @@ -638,7 +639,7 @@ bool Selection::_HandleColorSelection(const INPUT_KEY_INFO* const pInputKeyInfo) // If it is line selection, we can assemble that across multiple lines to make a search term. // But if it is block selection and the selected area is > 1 line in height, ignore the shift because we can't search. // Also ignore if there is no current selection. - if ((fShiftPressed) && (!IsAreaSelected() || (!IsLineSelection() && (_srSelectionRect.Top != _srSelectionRect.Bottom )))) + if ((fShiftPressed) && (!IsAreaSelected() || (!IsLineSelection() && (_srSelectionRect.Top != _srSelectionRect.Bottom)))) { fShiftPressed = false; } @@ -927,7 +928,7 @@ bool Selection::_HandleMarkModeSelectionNav(const INPUT_KEY_INFO* const pInputKe return false; } -#pragma region Calculation/Support for keyboard selection +#pragma region Calculation / Support for keyboard selection // Routine Description: // - Retrieves the boundaries of the input line (first and last char positions) @@ -936,8 +937,7 @@ bool Selection::_HandleMarkModeSelectionNav(const INPUT_KEY_INFO* const pInputKe // - pcoordInputEnd - Position of the last character in the input line // Return Value: // - If true, the boundaries returned are valid. If false, they should be discarded. -[[nodiscard]] -bool Selection::s_GetInputLineBoundaries(_Out_opt_ COORD* const pcoordInputStart, _Out_opt_ COORD* const pcoordInputEnd) +[[nodiscard]] bool Selection::s_GetInputLineBoundaries(_Out_opt_ COORD* const pcoordInputStart, _Out_opt_ COORD* const pcoordInputEnd) { const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); const auto bufferSize = gci.GetActiveOutputBuffer().GetBufferSize(); diff --git a/src/host/server.h b/src/host/server.h index 820c15f93..3d85ed459 100644 --- a/src/host/server.h +++ b/src/host/server.h @@ -32,6 +32,7 @@ Revision History: #include "..\inc\IDefaultColorProvider.hpp" +// clang-format off // Flags flags #define CONSOLE_IS_ICONIC 0x00000001 #define CONSOLE_OUTPUT_SUSPENDED 0x00000002 @@ -68,6 +69,7 @@ Revision History: #define CONSOLE_INITIALIZED 0x80000000 #define CONSOLE_SUSPENDED (CONSOLE_OUTPUT_SUSPENDED) +// clang-format on class COOKED_READ_DATA; class CommandHistory; @@ -86,7 +88,7 @@ public: ConsoleProcessList ProcessHandleList; InputBuffer* pInputBuffer; - SCREEN_INFORMATION* ScreenBuffers; // singly linked list + SCREEN_INFORMATION* ScreenBuffers; // singly linked list ConsoleWaitQueue OutputQueue; DWORD Flags; @@ -97,7 +99,7 @@ public: UINT CP; UINT OutputCP; - ULONG CtrlFlags; // indicates outstanding ctrl requests + ULONG CtrlFlags; // indicates outstanding ctrl requests ULONG LimitingProcessId; CPINFO CPInfo; @@ -141,8 +143,7 @@ public: const std::wstring& GetLinkTitle() const noexcept; const std::wstring GetTitleAndPrefix() const; - [[nodiscard]] - static NTSTATUS AllocateConsole(const std::wstring_view title); + [[nodiscard]] static NTSTATUS AllocateConsole(const std::wstring_view title); // MSFT:16886775 : get rid of friends friend void SetActiveScreenBuffer(_Inout_ SCREEN_INFORMATION& screenInfo); friend class SCREEN_INFORMATION; @@ -154,17 +155,16 @@ public: RenderData renderData; private: - CRITICAL_SECTION _csConsoleLock; // serialize input and output using this + CRITICAL_SECTION _csConsoleLock; // serialize input and output using this std::wstring _Title; std::wstring _TitlePrefix; // Eg Select, Mark - things that we manually prepend to the title. std::wstring _OriginalTitle; - std::wstring _LinkTitle; // Path to .lnk file + std::wstring _LinkTitle; // Path to .lnk file SCREEN_INFORMATION* pCurrentScreenBuffer; COOKED_READ_DATA* _cookedReadData; // non-ownership pointer Microsoft::Console::VirtualTerminal::VtIo _vtIo; Microsoft::Console::CursorBlinker _blinker; - }; #define ConsoleLocked() (ServiceLocator::LocateGlobals()->getConsoleInformation()->ConsoleLock.OwningThread == NtCurrentTeb()->ClientId.UniqueThread) diff --git a/src/host/settings.cpp b/src/host/settings.cpp index 3053e4cc0..d27beb0e4 100644 --- a/src/host/settings.cpp +++ b/src/host/settings.cpp @@ -81,15 +81,12 @@ Settings::Settings() : _CursorColor = Cursor::s_InvertCursorColor; _CursorType = CursorType::Legacy; - gsl::span tableView = { _ColorTable, gsl::narrow(COLOR_TABLE_SIZE) }; gsl::span xtermTableView = { _XtermColorTable, gsl::narrow(XTERM_COLOR_TABLE_SIZE) }; ::Microsoft::Console::Utils::Initialize256ColorTable(xtermTableView); ::Microsoft::Console::Utils::InitializeCampbellColorTable(tableView); - } - // Routine Description: // - Applies hardcoded default settings that are in line with what is defined // in our Windows edition manifest (living in win32k-settings.man). @@ -247,7 +244,7 @@ void Settings::InitFromStateInfo(_In_ PCONSOLE_STATE_INFO pStateInfo) // - a CONSOLE_STATE_INFO with the current state of this settings structure. CONSOLE_STATE_INFO Settings::CreateConsoleStateInfo() const { - CONSOLE_STATE_INFO csi = {0}; + CONSOLE_STATE_INFO csi = { 0 }; csi.ScreenAttributes = _wFillAttribute; csi.PopupAttributes = _wPopupFillAttribute; csi.ScreenBufferSize = _dwScreenBufferSize; @@ -282,7 +279,6 @@ CONSOLE_STATE_INFO Settings::CreateConsoleStateInfo() const return csi; } - void Settings::Validate() { // If we were explicitly given a size in pixels from the startup info, divide by the font to turn it into characters. @@ -444,20 +440,20 @@ void Settings::SetLineSelection(const bool bLineSelection) _bLineSelection = bLineSelection; } -bool Settings::GetWrapText () const +bool Settings::GetWrapText() const { return _bWrapText; } -void Settings::SetWrapText (const bool bWrapText ) +void Settings::SetWrapText(const bool bWrapText) { _bWrapText = bWrapText; } -bool Settings::GetCtrlKeyShortcutsDisabled () const +bool Settings::GetCtrlKeyShortcutsDisabled() const { return _fCtrlKeyShortcutsDisabled; } -void Settings::SetCtrlKeyShortcutsDisabled (const bool fCtrlKeyShortcutsDisabled ) +void Settings::SetCtrlKeyShortcutsDisabled(const bool fCtrlKeyShortcutsDisabled) { _fCtrlKeyShortcutsDisabled = fCtrlKeyShortcutsDisabled; } @@ -469,7 +465,7 @@ BYTE Settings::GetWindowAlpha() const void Settings::SetWindowAlpha(const BYTE bWindowAlpha) { // if we're out of bounds, set it to 100% opacity so it appears as if nothing happened. - _bWindowAlpha = (bWindowAlpha < MIN_WINDOW_OPACITY)? BYTE_MAX : bWindowAlpha; + _bWindowAlpha = (bWindowAlpha < MIN_WINDOW_OPACITY) ? BYTE_MAX : bWindowAlpha; } DWORD Settings::GetHotKey() const @@ -774,13 +770,13 @@ WORD Settings::GenerateLegacyAttributes(const TextAttribute attributes) const // the nearest color table value for its *ground. const COLORREF rgbForeground = LookupForegroundColor(attributes); fgIndex = attributes.ForegroundIsDefault() ? - fgIndex : - static_cast(FindNearestTableIndex(rgbForeground)); + fgIndex : + static_cast(FindNearestTableIndex(rgbForeground)); const COLORREF rgbBackground = LookupBackgroundColor(attributes); bgIndex = attributes.BackgroundIsDefault() ? - bgIndex : - static_cast(FindNearestTableIndex(rgbBackground)); + bgIndex : + static_cast(FindNearestTableIndex(rgbBackground)); } // TextAttribute::GetLegacyAttributes(BYTE, BYTE) will use the legacy value diff --git a/src/host/settings.hpp b/src/host/settings.hpp index d16f2ac1a..9a0c91e97 100644 --- a/src/host/settings.hpp +++ b/src/host/settings.hpp @@ -73,11 +73,11 @@ public: bool GetLineSelection() const; void SetLineSelection(const bool bLineSelection); - bool GetWrapText () const; - void SetWrapText (const bool bWrapText ); + bool GetWrapText() const; + void SetWrapText(const bool bWrapText); - bool GetCtrlKeyShortcutsDisabled () const; - void SetCtrlKeyShortcutsDisabled (const bool fCtrlKeyShortcutsDisabled ); + bool GetCtrlKeyShortcutsDisabled() const; + void SetCtrlKeyShortcutsDisabled(const bool fCtrlKeyShortcutsDisabled); BYTE GetWindowAlpha() const; void SetWindowAlpha(const BYTE bWindowAlpha); @@ -252,8 +252,6 @@ private: friend class RegistrySerialization; public: - WORD GenerateLegacyAttributes(const TextAttribute attributes) const; WORD FindNearestTableIndex(const COLORREF Color) const; - }; diff --git a/src/host/srvinit.cpp b/src/host/srvinit.cpp index faaae3101..be91304d2 100644 --- a/src/host/srvinit.cpp +++ b/src/host/srvinit.cpp @@ -31,8 +31,7 @@ using namespace Microsoft::Console::Render; const UINT CONSOLE_EVENT_FAILURE_ID = 21790; const UINT CONSOLE_LPC_PORT_FAILURE_ID = 21791; -[[nodiscard]] -HRESULT ConsoleServerInitialization(_In_ HANDLE Server, const ConsoleArguments* const args) +[[nodiscard]] HRESULT ConsoleServerInitialization(_In_ HANDLE Server, const ConsoleArguments* const args) { Globals& Globals = ServiceLocator::LocateGlobals(); @@ -86,12 +85,11 @@ static bool s_IsOnDesktop() return fIsDesktop; } -[[nodiscard]] -NTSTATUS SetUpConsole(_Inout_ Settings* pStartupSettings, - _In_ DWORD TitleLength, - _In_reads_bytes_(TitleLength) LPWSTR Title, - _In_ LPCWSTR CurDir, - _In_ LPCWSTR AppName) +[[nodiscard]] NTSTATUS SetUpConsole(_Inout_ Settings* pStartupSettings, + _In_ DWORD TitleLength, + _In_reads_bytes_(TitleLength) LPWSTR Title, + _In_ LPCWSTR CurDir, + _In_ LPCWSTR AppName) { // We will find and locate all relevant preference settings and then create the console here. // The precedence order for settings is: @@ -142,7 +140,6 @@ NTSTATUS SetUpConsole(_Inout_ Settings* pStartupSettings, } } - // 1. The settings we were passed contains STARTUPINFO structure settings to be applied last. settings.ApplyStartupInfo(pStartupSettings); @@ -152,12 +149,13 @@ NTSTATUS SetUpConsole(_Inout_ Settings* pStartupSettings, // Validate all applied settings for correctness against final rules. settings.Validate(); - // As of the graphics refactoring to library based, all fonts are now DPI aware. Scaling is performed at the Blt time for raster fonts. + // As of the graphics refactoring to library based, all fonts are now DPI aware. Scaling is + // performed at the Blt time for raster fonts. // Note that we can only declare our DPI awareness once per process launch. // Set the process's default dpi awareness context to PMv2 so that new top level windows // inherit their WM_DPICHANGED* broadcast mode (and more, like dialog scaling) from the thread. - IHighDpiApi *pHighDpiApi = ServiceLocator::LocateHighDpiApi(); + IHighDpiApi* pHighDpiApi = ServiceLocator::LocateHighDpiApi(); if (pHighDpiApi) { // N.B.: There is no high DPI support on OneCore (non-UAP) systems. @@ -181,8 +179,9 @@ NTSTATUS SetUpConsole(_Inout_ Settings* pStartupSettings, settings.SetLaunchFaceName(settings.GetFaceName(), LF_FACESIZE); } -// Allocate console will read the global ServiceLocator::LocateGlobals().getConsoleInformation for the settings we just set. - NTSTATUS Status = CONSOLE_INFORMATION::AllocateConsole({ Title, TitleLength / sizeof(wchar_t)}); + // Allocate console will read the global ServiceLocator::LocateGlobals().getConsoleInformation + // for the settings we just set. + NTSTATUS Status = CONSOLE_INFORMATION::AllocateConsole({ Title, TitleLength / sizeof(wchar_t) }); if (!NT_SUCCESS(Status)) { return Status; @@ -191,8 +190,7 @@ NTSTATUS SetUpConsole(_Inout_ Settings* pStartupSettings, return STATUS_SUCCESS; } -[[nodiscard]] -NTSTATUS RemoveConsole(_In_ ConsoleProcessHandle* ProcessData) +[[nodiscard]] NTSTATUS RemoveConsole(_In_ ConsoleProcessHandle* ProcessData) { CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); LockConsole(); @@ -247,8 +245,7 @@ void ConsoleCheckDebug() #endif } -[[nodiscard]] -HRESULT ConsoleCreateIoThreadLegacy(_In_ HANDLE Server, const ConsoleArguments* const args) +[[nodiscard]] HRESULT ConsoleCreateIoThreadLegacy(_In_ HANDLE Server, const ConsoleArguments* const args) { auto& g = ServiceLocator::LocateGlobals(); RETURN_IF_FAILED(ConsoleServerInitialization(Server, args)); @@ -278,8 +275,8 @@ HRESULT ConsoleCreateIoThreadLegacy(_In_ HANDLE Server, const ConsoleArguments* return S_OK; } -#define SYSTEM_ROOT (L"%SystemRoot%") -#define SYSTEM_ROOT_LENGTH (sizeof(SYSTEM_ROOT) - sizeof(WCHAR)) +#define SYSTEM_ROOT (L"%SystemRoot%") +#define SYSTEM_ROOT_LENGTH (sizeof(SYSTEM_ROOT) - sizeof(WCHAR)) // Routine Description: // - This routine translates path characters into '_' characters because the NT registry apis do not allow the creation of keys with @@ -300,7 +297,7 @@ PWSTR TranslateConsoleTitle(_In_ PCWSTR pwszConsoleTitle, const BOOL fUnexpand, size_t cbConsoleTitle; size_t cbSystemRoot; - LPWSTR pwszSysRoot = new(std::nothrow) wchar_t[MAX_PATH]; + LPWSTR pwszSysRoot = new (std::nothrow) wchar_t[MAX_PATH]; if (nullptr != pwszSysRoot) { if (0 != GetWindowsDirectoryW(pwszSysRoot, MAX_PATH)) @@ -314,7 +311,7 @@ PWSTR TranslateConsoleTitle(_In_ PCWSTR pwszConsoleTitle, const BOOL fUnexpand, if (fUnexpand && cchConsoleTitle >= cchSystemRoot && -#pragma prefast(suppress:26018, "We've guaranteed that cchSystemRoot is equal to or smaller than cchConsoleTitle in size.") +#pragma prefast(suppress : 26018, "We've guaranteed that cchSystemRoot is equal to or smaller than cchConsoleTitle in size.") (CSTR_EQUAL == CompareStringOrdinal(pwszConsoleTitle, cchSystemRoot, pwszSysRoot, cchSystemRoot, TRUE))) { cbConsoleTitle -= cbSystemRoot; @@ -328,7 +325,7 @@ PWSTR TranslateConsoleTitle(_In_ PCWSTR pwszConsoleTitle, const BOOL fUnexpand, LPWSTR pszTranslatedConsoleTitle; const size_t cbTranslatedConsoleTitle = cbSystemRoot + cbConsoleTitle; - Tmp = pszTranslatedConsoleTitle = (PWSTR)new BYTE[cbTranslatedConsoleTitle]; + Tmp = pszTranslatedConsoleTitle = (PWSTR) new BYTE[cbTranslatedConsoleTitle]; if (pszTranslatedConsoleTitle == nullptr) { return nullptr; @@ -336,14 +333,14 @@ PWSTR TranslateConsoleTitle(_In_ PCWSTR pwszConsoleTitle, const BOOL fUnexpand, // No need to check return here -- pszTranslatedConsoleTitle is guaranteed large enough for SYSTEM_ROOT (void)StringCbCopy(pszTranslatedConsoleTitle, cbTranslatedConsoleTitle, SYSTEM_ROOT); - pszTranslatedConsoleTitle += (cbSystemRoot / sizeof(WCHAR)); // skip by characters -- not bytes + pszTranslatedConsoleTitle += (cbSystemRoot / sizeof(WCHAR)); // skip by characters -- not bytes for (UINT i = 0; i < cbConsoleTitle; i += sizeof(WCHAR)) { -#pragma prefast(suppress:26018, "We are reading the null portion of the buffer on purpose and will escape on reaching it below.") +#pragma prefast(suppress : 26018, "We are reading the null portion of the buffer on purpose and will escape on reaching it below.") if (fSubstitute && *pwszConsoleTitle == '\\') { -#pragma prefast(suppress:26019, "Console title must contain system root if this path was followed.") +#pragma prefast(suppress : 26019, "Console title must contain system root if this path was followed.") *pszTranslatedConsoleTitle++ = (WCHAR)'_'; } else @@ -365,8 +362,7 @@ PWSTR TranslateConsoleTitle(_In_ PCWSTR pwszConsoleTitle, const BOOL fUnexpand, return Tmp; } -[[nodiscard]] -NTSTATUS GetConsoleLangId(const UINT uiOutputCP, _Out_ LANGID * const pLangId) +[[nodiscard]] NTSTATUS GetConsoleLangId(const UINT uiOutputCP, _Out_ LANGID* const pLangId) { NTSTATUS Status = STATUS_NOT_SUPPORTED; @@ -423,8 +419,7 @@ NTSTATUS GetConsoleLangId(const UINT uiOutputCP, _Out_ LANGID * const pLangId) return Status; } -[[nodiscard]] -HRESULT ApiRoutines::GetConsoleLangIdImpl(LANGID& langId) noexcept +[[nodiscard]] HRESULT ApiRoutines::GetConsoleLangIdImpl(LANGID& langId) noexcept { try { @@ -448,8 +443,7 @@ HRESULT ApiRoutines::GetConsoleLangIdImpl(LANGID& langId) noexcept // - Cac - Receives the connection information. // Return Value: // - NTSTATUS indicating if the connection information was successfully initialized. -[[nodiscard]] -NTSTATUS ConsoleInitializeConnectInfo(_In_ PCONSOLE_API_MSG Message, _Out_ PCONSOLE_API_CONNECTINFO Cac) +[[nodiscard]] NTSTATUS ConsoleInitializeConnectInfo(_In_ PCONSOLE_API_MSG Message, _Out_ PCONSOLE_API_CONNECTINFO Cac) { CONSOLE_SERVER_MSG Data = { 0 }; // Try to receive the data sent by the client. @@ -496,8 +490,7 @@ NTSTATUS ConsoleInitializeConnectInfo(_In_ PCONSOLE_API_MSG Message, _Out_ PCONS return STATUS_SUCCESS; } -[[nodiscard]] -NTSTATUS ConsoleAllocateConsole(PCONSOLE_API_CONNECTINFO p) +[[nodiscard]] NTSTATUS ConsoleAllocateConsole(PCONSOLE_API_CONNECTINFO p) { // AllocConsole is outside our codebase, but we should be able to mostly track the call here. Telemetry::Instance().LogApiCall(Telemetry::ApiCall::AllocConsole); @@ -535,19 +528,17 @@ NTSTATUS ConsoleAllocateConsole(PCONSOLE_API_CONNECTINFO p) // should we be unable to figure out its width another way. auto pfn = std::bind(&Renderer::IsGlyphWideByFont, static_cast(g.pRender), std::placeholders::_1); SetGlyphWidthFallback(pfn); - } catch (...) { Status = NTSTATUS_FROM_HRESULT(wil::ResultFromCaughtException()); } - if (NT_SUCCESS(Status) && p->WindowVisible) { HANDLE Thread = nullptr; - IConsoleInputThread *pNewThread = nullptr; + IConsoleInputThread* pNewThread = nullptr; LOG_IF_FAILED(ServiceLocator::CreateConsoleInputThread(&pNewThread)); FAIL_FAST_IF_NULL(pNewThread); @@ -578,7 +569,6 @@ NTSTATUS ConsoleAllocateConsole(PCONSOLE_API_CONNECTINFO p) Status = STATUS_SUCCESS; } - // If we're not headless, we'll make a real window. // Allow UI Access to the real window but not the little // fake window we would make in headless mode. diff --git a/src/host/srvinit.h b/src/host/srvinit.h index dd3902518..b660d63ed 100644 --- a/src/host/srvinit.h +++ b/src/host/srvinit.h @@ -18,16 +18,12 @@ Revision History: #include "conserv.h" -[[nodiscard]] -NTSTATUS GetConsoleLangId(const UINT uiOutputCP, _Out_ LANGID * const pLangId); +[[nodiscard]] NTSTATUS GetConsoleLangId(const UINT uiOutputCP, _Out_ LANGID* const pLangId); PWSTR TranslateConsoleTitle(_In_ PCWSTR pwszConsoleTitle, const BOOL fUnexpand, const BOOL fSubstitute); -[[nodiscard]] -NTSTATUS ConsoleInitializeConnectInfo(_In_ PCONSOLE_API_MSG Message, _Out_ PCONSOLE_API_CONNECTINFO Cac); -[[nodiscard]] -NTSTATUS ConsoleAllocateConsole(PCONSOLE_API_CONNECTINFO p); -[[nodiscard]] -NTSTATUS RemoveConsole(_In_ ConsoleProcessHandle* ProcessData); +[[nodiscard]] NTSTATUS ConsoleInitializeConnectInfo(_In_ PCONSOLE_API_MSG Message, _Out_ PCONSOLE_API_CONNECTINFO Cac); +[[nodiscard]] NTSTATUS ConsoleAllocateConsole(PCONSOLE_API_CONNECTINFO p); +[[nodiscard]] NTSTATUS RemoveConsole(_In_ ConsoleProcessHandle* ProcessData); void ConsoleCheckDebug(); diff --git a/src/host/stream.cpp b/src/host/stream.cpp index 90409153c..7682d8a24 100644 --- a/src/host/stream.cpp +++ b/src/host/stream.cpp @@ -35,13 +35,12 @@ using Microsoft::Console::Interactivity::ServiceLocator; // arrow key. // Return Value: // - STATUS_SUCCESS on success or a relevant error code on failure. -[[nodiscard]] -NTSTATUS GetChar(_Inout_ InputBuffer* const pInputBuffer, - _Out_ wchar_t* const pwchOut, - const bool Wait, - _Out_opt_ bool* const pCommandLineEditingKeys, - _Out_opt_ bool* const pPopupKeys, - _Out_opt_ DWORD* const pdwKeyState) noexcept +[[nodiscard]] NTSTATUS GetChar(_Inout_ InputBuffer* const pInputBuffer, + _Out_ wchar_t* const pwchOut, + const bool Wait, + _Out_opt_ bool* const pCommandLineEditingKeys, + _Out_opt_ bool* const pPopupKeys, + _Out_opt_ DWORD* const pdwKeyState) noexcept { if (nullptr != pCommandLineEditingKeys) { @@ -129,9 +128,9 @@ NTSTATUS GetChar(_Inout_ InputBuffer* const pInputBuffer, } // Ignore Escape and Newline chars else if (keyEvent->IsKeyDown() && - (WI_IsFlagSet(pInputBuffer->InputMode, ENABLE_VIRTUAL_TERMINAL_INPUT) || - (keyEvent->GetVirtualKeyCode() != VK_ESCAPE && - keyEvent->GetCharData() != UNICODE_LINEFEED))) + (WI_IsFlagSet(pInputBuffer->InputMode, ENABLE_VIRTUAL_TERMINAL_INPUT) || + (keyEvent->GetVirtualKeyCode() != VK_ESCAPE && + keyEvent->GetCharData() != UNICODE_LINEFEED))) { *pwchOut = keyEvent->GetCharData(); return STATUS_SUCCESS; @@ -184,7 +183,7 @@ NTSTATUS GetChar(_Inout_ InputBuffer* const pInputBuffer, // Routine Description: // - This routine returns the total number of screen spaces the characters up to the specified character take up. size_t RetrieveTotalNumberOfSpaces(const SHORT sOriginalCursorPositionX, - _In_reads_(ulCurrentPosition) const WCHAR * const pwchBuffer, + _In_reads_(ulCurrentPosition) const WCHAR* const pwchBuffer, _In_ size_t ulCurrentPosition) { SHORT XPosition = sOriginalCursorPositionX; @@ -221,7 +220,7 @@ size_t RetrieveTotalNumberOfSpaces(const SHORT sOriginalCursorPositionX, // Routine Description: // - This routine returns the number of screen spaces the specified character takes up. size_t RetrieveNumberOfSpaces(_In_ SHORT sOriginalCursorPositionX, - _In_reads_(ulCurrentPosition + 1) const WCHAR * const pwchBuffer, + _In_reads_(ulCurrentPosition + 1) const WCHAR* const pwchBuffer, _In_ size_t ulCurrentPosition) { WCHAR Char = pwchBuffer[ulCurrentPosition]; @@ -268,7 +267,6 @@ size_t RetrieveNumberOfSpaces(_In_ SHORT sOriginalCursorPositionX, } } - // Routine Description: // - if we have leftover input, copy as much fits into the user's // buffer and return. we may have multi line input, if a macro @@ -282,12 +280,11 @@ size_t RetrieveNumberOfSpaces(_In_ SHORT sOriginalCursorPositionX, // Return Value: // - STATUS_NO_MEMORY in low memory situation // - other relevant NTSTATUS codes -[[nodiscard]] -static NTSTATUS _ReadPendingInput(InputBuffer& inputBuffer, - gsl::span buffer, - size_t& bytesRead, - INPUT_READ_HANDLE_DATA& readHandleState, - const bool unicode) +[[nodiscard]] static NTSTATUS _ReadPendingInput(InputBuffer& inputBuffer, + gsl::span buffer, + size_t& bytesRead, + INPUT_READ_HANDLE_DATA& readHandleState, + const bool unicode) { // TODO: MSFT: 18047766 - Correct this method to not play byte counting games. BOOL fAddDbcsLead = FALSE; @@ -340,7 +337,6 @@ static NTSTATUS _ReadPendingInput(InputBuffer& inputBuffer, } } - NumToWrite = 0; Tmp = pending.cbegin(); while (NumToWrite < pendingBytes && @@ -395,7 +391,7 @@ static NTSTATUS _ReadPendingInput(InputBuffer& inputBuffer, pendingBytes -= NumToWrite; if (pendingBytes != 0) { - std::wstring_view remainingPending{ pending.data() + (NumToWrite / sizeof(wchar_t)) , pendingBytes / sizeof(wchar_t) }; + std::wstring_view remainingPending{ pending.data() + (NumToWrite / sizeof(wchar_t)), pendingBytes / sizeof(wchar_t) }; readHandleState.UpdatePending(remainingPending); } else @@ -420,7 +416,9 @@ static NTSTATUS _ReadPendingInput(InputBuffer& inputBuffer, inputBuffer.StoreReadPartialByteSequence(std::move(partialEvent)); } -#pragma prefast(suppress:__WARNING_POTENTIAL_BUFFER_OVERFLOW_HIGH_PRIORITY, "This access is fine but prefast can't follow it, evidently") + // clang-format off +#pragma prefast(suppress: __WARNING_POTENTIAL_BUFFER_OVERFLOW_HIGH_PRIORITY, "This access is fine but prefast can't follow it, evidently") + // clang-format on memmove(pBuffer, tempBuffer.get(), NumToWrite); if (fAddDbcsLead) @@ -457,18 +455,17 @@ static NTSTATUS _ReadPendingInput(InputBuffer& inputBuffer, // - STATUS_UNSUCCESSFUL if not able to access current screen buffer // - STATUS_NO_MEMORY in low memory situation // - other relevant HRESULT codes -[[nodiscard]] -static HRESULT _ReadLineInput(InputBuffer& inputBuffer, - const HANDLE processData, - gsl::span buffer, - size_t& bytesRead, - DWORD& controlKeyState, - const std::string_view initialData, - const DWORD ctrlWakeupMask, - INPUT_READ_HANDLE_DATA& readHandleState, - const std::wstring_view exeName, - const bool unicode, - std::unique_ptr& waiter) noexcept +[[nodiscard]] static HRESULT _ReadLineInput(InputBuffer& inputBuffer, + const HANDLE processData, + gsl::span buffer, + size_t& bytesRead, + DWORD& controlKeyState, + const std::string_view initialData, + const DWORD ctrlWakeupMask, + INPUT_READ_HANDLE_DATA& readHandleState, + const std::wstring_view exeName, + const bool unicode, + std::unique_ptr& waiter) noexcept { CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); RETURN_HR_IF(E_FAIL, !gci.HasActiveOutputBuffer()); @@ -525,15 +522,13 @@ static HRESULT _ReadLineInput(InputBuffer& inputBuffer, // populated. // - STATUS_SUCCESS on success // - Other NTSTATUS codes as necessary -[[nodiscard]] -static NTSTATUS _ReadCharacterInput(InputBuffer& inputBuffer, - gsl::span buffer, - size_t& bytesRead, - INPUT_READ_HANDLE_DATA& readHandleState, - const bool unicode, - std::unique_ptr& waiter) +[[nodiscard]] static NTSTATUS _ReadCharacterInput(InputBuffer& inputBuffer, + gsl::span buffer, + size_t& bytesRead, + INPUT_READ_HANDLE_DATA& readHandleState, + const bool unicode, + std::unique_ptr& waiter) { - size_t NumToWrite = 0; bool addDbcsLead = false; NTSTATUS Status = STATUS_SUCCESS; @@ -642,7 +637,7 @@ static NTSTATUS _ReadCharacterInput(InputBuffer& inputBuffer, inputBuffer.StoreReadPartialByteSequence(std::move(partialEvent)); } -#pragma prefast(suppress:26053 26015, "PREfast claims read overflow. *pReadByteCount is the exact size of tempBuffer as allocated above.") +#pragma prefast(suppress : 26053 26015, "PREfast claims read overflow. *pReadByteCount is the exact size of tempBuffer as allocated above.") memmove(pBuffer, tempBuffer.get(), bytesRead); if (addDbcsLead) @@ -686,18 +681,17 @@ static NTSTATUS _ReadCharacterInput(InputBuffer& inputBuffer, // populated. // - STATUS_SUCCESS on success // - Other NSTATUS codes as necessary -[[nodiscard]] -NTSTATUS DoReadConsole(InputBuffer& inputBuffer, - const HANDLE processData, - gsl::span buffer, - size_t& bytesRead, - ULONG& controlKeyState, - const std::string_view initialData, - const DWORD ctrlWakeupMask, - INPUT_READ_HANDLE_DATA& readHandleState, - const std::wstring_view exeName, - const bool unicode, - std::unique_ptr& waiter) noexcept +[[nodiscard]] NTSTATUS DoReadConsole(InputBuffer& inputBuffer, + const HANDLE processData, + gsl::span buffer, + size_t& bytesRead, + ULONG& controlKeyState, + const std::string_view initialData, + const DWORD ctrlWakeupMask, + INPUT_READ_HANDLE_DATA& readHandleState, + const std::wstring_view exeName, + const bool unicode, + std::unique_ptr& waiter) noexcept { try { @@ -750,17 +744,16 @@ NTSTATUS DoReadConsole(InputBuffer& inputBuffer, CATCH_RETURN(); } -[[nodiscard]] -HRESULT ApiRoutines::ReadConsoleAImpl(IConsoleInputObject& context, - gsl::span buffer, - size_t& written, - std::unique_ptr& waiter, - const std::string_view initialData, - const std::wstring_view exeName, - INPUT_READ_HANDLE_DATA& readHandleState, - const HANDLE clientHandle, - const DWORD controlWakeupMask, - DWORD& controlKeyState) noexcept +[[nodiscard]] HRESULT ApiRoutines::ReadConsoleAImpl(IConsoleInputObject& context, + gsl::span buffer, + size_t& written, + std::unique_ptr& waiter, + const std::string_view initialData, + const std::wstring_view exeName, + INPUT_READ_HANDLE_DATA& readHandleState, + const HANDLE clientHandle, + const DWORD controlWakeupMask, + DWORD& controlKeyState) noexcept { try { @@ -779,17 +772,16 @@ HRESULT ApiRoutines::ReadConsoleAImpl(IConsoleInputObject& context, CATCH_RETURN(); } -[[nodiscard]] -HRESULT ApiRoutines::ReadConsoleWImpl(IConsoleInputObject& context, - gsl::span buffer, - size_t& written, - std::unique_ptr& waiter, - const std::string_view initialData, - const std::wstring_view exeName, - INPUT_READ_HANDLE_DATA& readHandleState, - const HANDLE clientHandle, - const DWORD controlWakeupMask, - DWORD& controlKeyState) noexcept +[[nodiscard]] HRESULT ApiRoutines::ReadConsoleWImpl(IConsoleInputObject& context, + gsl::span buffer, + size_t& written, + std::unique_ptr& waiter, + const std::string_view initialData, + const std::wstring_view exeName, + INPUT_READ_HANDLE_DATA& readHandleState, + const HANDLE clientHandle, + const DWORD controlWakeupMask, + DWORD& controlKeyState) noexcept { try { diff --git a/src/host/stream.h b/src/host/stream.h index 306c8fe05..e90a280a2 100644 --- a/src/host/stream.h +++ b/src/host/stream.h @@ -20,26 +20,25 @@ Revision History: #include "..\server\IWaitRoutine.h" #include "readData.hpp" -#define IS_CONTROL_CHAR(wch) ((wch) < L' ') +#define IS_CONTROL_CHAR(wch) ((wch) < L' ') -[[nodiscard]] -NTSTATUS GetChar(_Inout_ InputBuffer* const pInputBuffer, - _Out_ wchar_t* const pwchOut, - const bool Wait, - _Out_opt_ bool* const pCommandLineEditingKeys, - _Out_opt_ bool* const pPopupKeys, - _Out_opt_ DWORD* const pdwKeyState) noexcept; +[[nodiscard]] NTSTATUS GetChar(_Inout_ InputBuffer* const pInputBuffer, + _Out_ wchar_t* const pwchOut, + const bool Wait, + _Out_opt_ bool* const pCommandLineEditingKeys, + _Out_opt_ bool* const pPopupKeys, + _Out_opt_ DWORD* const pdwKeyState) noexcept; // Routine Description: // - This routine returns the total number of screen spaces the characters up to the specified character take up. size_t RetrieveTotalNumberOfSpaces(const SHORT sOriginalCursorPositionX, - _In_reads_(ulCurrentPosition) const WCHAR * const pwchBuffer, - const size_t ulCurrentPosition); + _In_reads_(ulCurrentPosition) const WCHAR* const pwchBuffer, + const size_t ulCurrentPosition); // Routine Description: // - This routine returns the number of screen spaces the specified character takes up. size_t RetrieveNumberOfSpaces(_In_ SHORT sOriginalCursorPositionX, - _In_reads_(ulCurrentPosition + 1) const WCHAR * const pwchBuffer, - _In_ size_t ulCurrentPosition); + _In_reads_(ulCurrentPosition + 1) const WCHAR* const pwchBuffer, + _In_ size_t ulCurrentPosition); VOID UnblockWriteConsole(const DWORD dwReason); diff --git a/src/host/telemetry.cpp b/src/host/telemetry.cpp index c4f02ae5c..ca93c8ed1 100644 --- a/src/host/telemetry.cpp +++ b/src/host/telemetry.cpp @@ -13,15 +13,15 @@ #include "..\interactivity\inc\ServiceLocator.hpp" TRACELOGGING_DEFINE_PROVIDER(g_hConhostV2EventTraceProvider, - "Microsoft.Windows.Console.Host", - // {fe1ff234-1f09-50a8-d38d-c44fab43e818} - (0xfe1ff234, 0x1f09, 0x50a8, 0xd3, 0x8d, 0xc4, 0x4f, 0xab, 0x43, 0xe8, 0x18), - TraceLoggingOptionMicrosoftTelemetry()); + "Microsoft.Windows.Console.Host", + // {fe1ff234-1f09-50a8-d38d-c44fab43e818} + (0xfe1ff234, 0x1f09, 0x50a8, 0xd3, 0x8d, 0xc4, 0x4f, 0xab, 0x43, 0xe8, 0x18), + TraceLoggingOptionMicrosoftTelemetry()); #pragma warning(push) // Disable 4351 so we can initialize the arrays to 0 without a warning. -#pragma warning(disable:4351) -Telemetry::Telemetry() - : _fpFindStringLengthAverage(0), +#pragma warning(disable : 4351) +Telemetry::Telemetry() : + _fpFindStringLengthAverage(0), _fpDirectionDownAverage(0), _fpMatchCaseAverage(0), _uiFindNextClickedTotal(0), @@ -195,15 +195,17 @@ void Telemetry::LogFindDialogNextClicked(const unsigned int uiStringLength, cons // Find dialog was closed, now send out the telemetry. void Telemetry::FindDialogClosed() { -#pragma prefast(suppress:__WARNING_NONCONST_LOCAL, "Activity can't be const, since it's set to a random value on startup.") + // clang-format off +#pragma prefast(suppress: __WARNING_NONCONST_LOCAL, "Activity can't be const, since it's set to a random value on startup.") + // clang-format on TraceLoggingWriteTagged(_activity, - "FindDialogUsed", - TraceLoggingValue(_fpFindStringLengthAverage, "StringLengthAverage"), - TraceLoggingValue(_fpDirectionDownAverage, "DirectionDownAverage"), - TraceLoggingValue(_fpMatchCaseAverage, "MatchCaseAverage"), - TraceLoggingValue(_uiFindNextClickedTotal, "FindNextButtonClickedTotal"), - TraceLoggingKeyword(MICROSOFT_KEYWORD_MEASURES), - TelemetryPrivacyDataTag(PDT_ProductAndServiceUsage)); + "FindDialogUsed", + TraceLoggingValue(_fpFindStringLengthAverage, "StringLengthAverage"), + TraceLoggingValue(_fpDirectionDownAverage, "DirectionDownAverage"), + TraceLoggingValue(_fpMatchCaseAverage, "MatchCaseAverage"), + TraceLoggingValue(_uiFindNextClickedTotal, "FindNextButtonClickedTotal"), + TraceLoggingKeyword(MICROSOFT_KEYWORD_MEASURES), + TelemetryPrivacyDataTag(PDT_ProductAndServiceUsage)); // Get ready for the next time the dialog is used. _fpFindStringLengthAverage = 0; @@ -238,7 +240,7 @@ void Telemetry::TotalCodesForPreviousProcess() // The main difference between this and the standard bsearch library call, is that if this // can't find the string, it returns the position the new string should be inserted at. This saves // us from having an additional search through the array, and improves performance. -bool Telemetry::FindProcessName(const WCHAR* pszProcessName, _Out_ size_t *iPosition) const +bool Telemetry::FindProcessName(const WCHAR* pszProcessName, _Out_ size_t* iPosition) const { int iMin = 0; int iMid = 0; @@ -302,7 +304,7 @@ void Telemetry::LogProcessConnected(const HANDLE hProcess) _rguiProcessFileNamesCount[_iProcessConnectedCurrently]++; } else if ((_uiNumberProcessFileNames < ARRAYSIZE(_rguiProcessFileNamesCount)) && - (_iProcessFileNamesNext < ARRAYSIZE(_wchProcessFileNames) - 10)) + (_iProcessFileNamesNext < ARRAYSIZE(_wchProcessFileNames) - 10)) { // Check if the MS released bash was used. MS bash is installed under windows\system32, and it's possible somebody else // could be installing their bash into that directory, but not likely. If the user first runs a non-MS bash, @@ -339,7 +341,7 @@ void Telemetry::LogProcessConnected(const HANDLE hProcess) _iProcessConnectedCurrently = _uiNumberProcessFileNames++; // Packed arrays start with a UINT16 value indicating the number of elements in the array. - BYTE *pbFileNames = reinterpret_cast(_wchProcessFileNames); + BYTE* pbFileNames = reinterpret_cast(_wchProcessFileNames); pbFileNames[0] = (BYTE)_uiNumberProcessFileNames; pbFileNames[1] = (BYTE)(_uiNumberProcessFileNames >> 8); } @@ -369,151 +371,157 @@ void Telemetry::WriteFinalTraceLog() // Send this back using "measures" since we want a good sampling of our entire userbase. time_t tEndedAt; time(&tEndedAt); -#pragma prefast(suppress:__WARNING_NONCONST_LOCAL, "Activity can't be const, since it's set to a random value on startup.") + // clang-format off +#pragma prefast(suppress: __WARNING_NONCONST_LOCAL, "Activity can't be const, since it's set to a random value on startup.") + // clang-format on TraceLoggingWriteTagged(_activity, - "SessionEnding", - TraceLoggingBool(_fBashUsed, "BashUsed"), - TraceLoggingBool(_fCtrlPgUpPgDnUsed, "CtrlPgUpPgDnUsed"), - TraceLoggingBool(_fKeyboardTextEditingUsed, "KeyboardTextEditingUsed"), - TraceLoggingBool(_fKeyboardTextSelectionUsed, "KeyboardTextSelectionUsed"), - TraceLoggingUInt32(_uiCtrlShiftCProcUsed, "CtrlShiftCProcUsed"), - TraceLoggingUInt32(_uiCtrlShiftCRawUsed, "CtrlShiftCRawUsed"), - TraceLoggingUInt32(_uiCtrlShiftVProcUsed, "CtrlShiftVProcUsed"), - TraceLoggingUInt32(_uiCtrlShiftVRawUsed, "CtrlShiftVRawUsed"), - TraceLoggingUInt32(_uiQuickEditCopyProcUsed, "QuickEditCopyProcUsed"), - TraceLoggingUInt32(_uiQuickEditCopyRawUsed, "QuickEditCopyRawUsed"), - TraceLoggingUInt32(_uiQuickEditPasteProcUsed, "QuickEditPasteProcUsed"), - TraceLoggingUInt32(_uiQuickEditPasteRawUsed, "QuickEditPasteRawUsed"), - TraceLoggingBool(gci.GetLinkTitle().length() == 0, "LaunchedFromShortcut"), - // Normally we would send out a single array containing the name and count, - // but that's difficult to do with our telemetry system, so send out two separate arrays. - // Casting to UINT should be fine, since our array size is only 2K. - TraceLoggingPackedField(_wchProcessFileNames, static_cast(sizeof(WCHAR) * _iProcessFileNamesNext), TlgInUNICODESTRING | TlgInVcount, "ProcessesConnected"), - TraceLoggingUInt32Array(_rguiProcessFileNamesCount, _uiNumberProcessFileNames, "ProcessesConnectedCount"), - TraceLoggingUInt32Array(_rguiProcessFileNamesCodesCount, _uiNumberProcessFileNames, "ProcessesConnectedCodesCount"), - TraceLoggingUInt32Array(_rguiProcessFileNamesFailedCodesCount, _uiNumberProcessFileNames, "ProcessesConnectedFailedCodesCount"), - TraceLoggingUInt32Array(_rguiProcessFileNamesFailedOutsideCodesCount, _uiNumberProcessFileNames, "ProcessesConnectedFailedOutsideCount"), - // Send back both starting and ending times separately instead just usage time (ending - starting). - // This can help us determine if they were using multiple consoles at the same time. - TraceLoggingInt32(static_cast(_tStartedAt), "StartedUsingAtSeconds"), - TraceLoggingInt32(static_cast(tEndedAt), "EndedUsingAtSeconds"), - TraceLoggingUInt32(_uiColorSelectionUsed, "ColorSelectionUsed"), - TraceLoggingKeyword(MICROSOFT_KEYWORD_MEASURES), - TelemetryPrivacyDataTag(PDT_ProductAndServiceUsage)); + "SessionEnding", + TraceLoggingBool(_fBashUsed, "BashUsed"), + TraceLoggingBool(_fCtrlPgUpPgDnUsed, "CtrlPgUpPgDnUsed"), + TraceLoggingBool(_fKeyboardTextEditingUsed, "KeyboardTextEditingUsed"), + TraceLoggingBool(_fKeyboardTextSelectionUsed, "KeyboardTextSelectionUsed"), + TraceLoggingUInt32(_uiCtrlShiftCProcUsed, "CtrlShiftCProcUsed"), + TraceLoggingUInt32(_uiCtrlShiftCRawUsed, "CtrlShiftCRawUsed"), + TraceLoggingUInt32(_uiCtrlShiftVProcUsed, "CtrlShiftVProcUsed"), + TraceLoggingUInt32(_uiCtrlShiftVRawUsed, "CtrlShiftVRawUsed"), + TraceLoggingUInt32(_uiQuickEditCopyProcUsed, "QuickEditCopyProcUsed"), + TraceLoggingUInt32(_uiQuickEditCopyRawUsed, "QuickEditCopyRawUsed"), + TraceLoggingUInt32(_uiQuickEditPasteProcUsed, "QuickEditPasteProcUsed"), + TraceLoggingUInt32(_uiQuickEditPasteRawUsed, "QuickEditPasteRawUsed"), + TraceLoggingBool(gci.GetLinkTitle().length() == 0, "LaunchedFromShortcut"), + // Normally we would send out a single array containing the name and count, + // but that's difficult to do with our telemetry system, so send out two separate arrays. + // Casting to UINT should be fine, since our array size is only 2K. + TraceLoggingPackedField(_wchProcessFileNames, static_cast(sizeof(WCHAR) * _iProcessFileNamesNext), TlgInUNICODESTRING | TlgInVcount, "ProcessesConnected"), + TraceLoggingUInt32Array(_rguiProcessFileNamesCount, _uiNumberProcessFileNames, "ProcessesConnectedCount"), + TraceLoggingUInt32Array(_rguiProcessFileNamesCodesCount, _uiNumberProcessFileNames, "ProcessesConnectedCodesCount"), + TraceLoggingUInt32Array(_rguiProcessFileNamesFailedCodesCount, _uiNumberProcessFileNames, "ProcessesConnectedFailedCodesCount"), + TraceLoggingUInt32Array(_rguiProcessFileNamesFailedOutsideCodesCount, _uiNumberProcessFileNames, "ProcessesConnectedFailedOutsideCount"), + // Send back both starting and ending times separately instead just usage time (ending - starting). + // This can help us determine if they were using multiple consoles at the same time. + TraceLoggingInt32(static_cast(_tStartedAt), "StartedUsingAtSeconds"), + TraceLoggingInt32(static_cast(tEndedAt), "EndedUsingAtSeconds"), + TraceLoggingUInt32(_uiColorSelectionUsed, "ColorSelectionUsed"), + TraceLoggingKeyword(MICROSOFT_KEYWORD_MEASURES), + TelemetryPrivacyDataTag(PDT_ProductAndServiceUsage)); // Always send this back. We could only send this back when they click "OK" in the settings dialog, but sending it // back every time should give us a good idea of their current, final settings, and not just only when they change a setting. -#pragma prefast(suppress:__WARNING_NONCONST_LOCAL, "Activity can't be const, since it's set to a random value on startup.") + // clang-format off +#pragma prefast(suppress: __WARNING_NONCONST_LOCAL, "Activity can't be const, since it's set to a random value on startup.") + // clang-format on TraceLoggingWriteTagged(_activity, - "Settings", - TraceLoggingBool(gci.GetAutoPosition(), "AutoPosition"), - TraceLoggingBool(gci.GetHistoryNoDup(), "HistoryNoDuplicates"), - TraceLoggingBool(gci.GetInsertMode(), "InsertMode"), - TraceLoggingBool(gci.GetLineSelection(), "LineSelection"), - TraceLoggingBool(gci.GetQuickEdit(), "QuickEdit"), - TraceLoggingValue(gci.GetWindowAlpha(), "WindowAlpha"), - TraceLoggingBool(gci.GetWrapText(), "WrapText"), - TraceLoggingUInt32Array((UINT32 const*)gci.GetColorTable(), (UINT16)gci.GetColorTableSize(), "ColorTable"), - TraceLoggingValue(gci.CP, "CodePageInput"), - TraceLoggingValue(gci.OutputCP, "CodePageOutput"), - TraceLoggingValue(gci.GetFontSize().X, "FontSizeX"), - TraceLoggingValue(gci.GetFontSize().Y, "FontSizeY"), - TraceLoggingValue(gci.GetHotKey(), "HotKey"), - TraceLoggingValue(gci.GetScreenBufferSize().X, "ScreenBufferSizeX"), - TraceLoggingValue(gci.GetScreenBufferSize().Y, "ScreenBufferSizeY"), - TraceLoggingValue(gci.GetStartupFlags(), "StartupFlags"), - TraceLoggingValue(gci.GetVirtTermLevel(), "VirtualTerminalLevel"), - TraceLoggingValue(gci.GetWindowSize().X, "WindowSizeX"), - TraceLoggingValue(gci.GetWindowSize().Y, "WindowSizeY"), - TraceLoggingValue(gci.GetWindowOrigin().X, "WindowOriginX"), - TraceLoggingValue(gci.GetWindowOrigin().Y, "WindowOriginY"), - TraceLoggingValue(gci.GetFaceName(), "FontName"), - TraceLoggingBool(gci.IsAltF4CloseAllowed(), "AllowAltF4Close"), - TraceLoggingBool(gci.GetCtrlKeyShortcutsDisabled(), "ControlKeyShortcutsDisabled"), - TraceLoggingBool(gci.GetEnableColorSelection(), "EnabledColorSelection"), - TraceLoggingBool(gci.GetFilterOnPaste(), "FilterOnPaste"), - TraceLoggingBool(gci.GetTrimLeadingZeros(), "TrimLeadingZeros"), - TraceLoggingValue(gci.GetLaunchFaceName(), "LaunchFontName"), - TraceLoggingValue(CommandHistory::s_CountOfHistories(), "CommandHistoriesNumber"), - TraceLoggingValue(gci.GetCodePage(), "CodePage"), - TraceLoggingValue(gci.GetCursorSize(), "CursorSize"), - TraceLoggingValue(gci.GetFontFamily(), "FontFamily"), - TraceLoggingValue(gci.GetFontWeight(), "FontWeight"), - TraceLoggingValue(gci.GetHistoryBufferSize(), "HistoryBufferSize"), - TraceLoggingValue(gci.GetNumberOfHistoryBuffers(), "HistoryBuffersNumber"), - TraceLoggingValue(gci.GetScrollScale(), "ScrollScale"), - TraceLoggingValue(gci.GetFillAttribute(), "FillAttribute"), - TraceLoggingValue(gci.GetPopupFillAttribute(), "PopupFillAttribute"), - TraceLoggingValue(gci.GetShowWindow(), "ShowWindow"), - TraceLoggingKeyword(MICROSOFT_KEYWORD_MEASURES), - TelemetryPrivacyDataTag(PDT_ProductAndServiceUsage)); + "Settings", + TraceLoggingBool(gci.GetAutoPosition(), "AutoPosition"), + TraceLoggingBool(gci.GetHistoryNoDup(), "HistoryNoDuplicates"), + TraceLoggingBool(gci.GetInsertMode(), "InsertMode"), + TraceLoggingBool(gci.GetLineSelection(), "LineSelection"), + TraceLoggingBool(gci.GetQuickEdit(), "QuickEdit"), + TraceLoggingValue(gci.GetWindowAlpha(), "WindowAlpha"), + TraceLoggingBool(gci.GetWrapText(), "WrapText"), + TraceLoggingUInt32Array((UINT32 const*)gci.GetColorTable(), (UINT16)gci.GetColorTableSize(), "ColorTable"), + TraceLoggingValue(gci.CP, "CodePageInput"), + TraceLoggingValue(gci.OutputCP, "CodePageOutput"), + TraceLoggingValue(gci.GetFontSize().X, "FontSizeX"), + TraceLoggingValue(gci.GetFontSize().Y, "FontSizeY"), + TraceLoggingValue(gci.GetHotKey(), "HotKey"), + TraceLoggingValue(gci.GetScreenBufferSize().X, "ScreenBufferSizeX"), + TraceLoggingValue(gci.GetScreenBufferSize().Y, "ScreenBufferSizeY"), + TraceLoggingValue(gci.GetStartupFlags(), "StartupFlags"), + TraceLoggingValue(gci.GetVirtTermLevel(), "VirtualTerminalLevel"), + TraceLoggingValue(gci.GetWindowSize().X, "WindowSizeX"), + TraceLoggingValue(gci.GetWindowSize().Y, "WindowSizeY"), + TraceLoggingValue(gci.GetWindowOrigin().X, "WindowOriginX"), + TraceLoggingValue(gci.GetWindowOrigin().Y, "WindowOriginY"), + TraceLoggingValue(gci.GetFaceName(), "FontName"), + TraceLoggingBool(gci.IsAltF4CloseAllowed(), "AllowAltF4Close"), + TraceLoggingBool(gci.GetCtrlKeyShortcutsDisabled(), "ControlKeyShortcutsDisabled"), + TraceLoggingBool(gci.GetEnableColorSelection(), "EnabledColorSelection"), + TraceLoggingBool(gci.GetFilterOnPaste(), "FilterOnPaste"), + TraceLoggingBool(gci.GetTrimLeadingZeros(), "TrimLeadingZeros"), + TraceLoggingValue(gci.GetLaunchFaceName(), "LaunchFontName"), + TraceLoggingValue(CommandHistory::s_CountOfHistories(), "CommandHistoriesNumber"), + TraceLoggingValue(gci.GetCodePage(), "CodePage"), + TraceLoggingValue(gci.GetCursorSize(), "CursorSize"), + TraceLoggingValue(gci.GetFontFamily(), "FontFamily"), + TraceLoggingValue(gci.GetFontWeight(), "FontWeight"), + TraceLoggingValue(gci.GetHistoryBufferSize(), "HistoryBufferSize"), + TraceLoggingValue(gci.GetNumberOfHistoryBuffers(), "HistoryBuffersNumber"), + TraceLoggingValue(gci.GetScrollScale(), "ScrollScale"), + TraceLoggingValue(gci.GetFillAttribute(), "FillAttribute"), + TraceLoggingValue(gci.GetPopupFillAttribute(), "PopupFillAttribute"), + TraceLoggingValue(gci.GetShowWindow(), "ShowWindow"), + TraceLoggingKeyword(MICROSOFT_KEYWORD_MEASURES), + TelemetryPrivacyDataTag(PDT_ProductAndServiceUsage)); static_assert(sizeof(UINT32) == sizeof(*gci.GetColorTable()), "gci.GetColorTable()"); // I could use the TraceLoggingUIntArray, but then we would have to know the order of the enums on the backend. // So just log each enum count separately with its string representation which makes it more human readable. -#pragma prefast(suppress:__WARNING_NONCONST_LOCAL, "Activity can't be const, since it's set to a random value on startup.") + // clang-format off +#pragma prefast(suppress: __WARNING_NONCONST_LOCAL, "Activity can't be const, since it's set to a random value on startup.") + // clang-format on TraceLoggingWriteTagged(_activity, - "ApiUsed", - TraceLoggingUInt32(_rguiTimesApiUsed[AddConsoleAlias], "AddConsoleAlias"), - TraceLoggingUInt32(_rguiTimesApiUsed[AllocConsole], "AllocConsole"), - TraceLoggingUInt32(_rguiTimesApiUsed[AttachConsole], "AttachConsole"), - TraceLoggingUInt32(_rguiTimesApiUsed[CreateConsoleScreenBuffer], "CreateConsoleScreenBuffer"), - TraceLoggingUInt32(_rguiTimesApiUsed[GenerateConsoleCtrlEvent], "GenerateConsoleCtrlEvent"), - TraceLoggingUInt32(_rguiTimesApiUsed[FillConsoleOutputAttribute], "FillConsoleOutputAttribute"), - TraceLoggingUInt32(_rguiTimesApiUsed[FillConsoleOutputCharacter], "FillConsoleOutputCharacter"), - TraceLoggingUInt32(_rguiTimesApiUsed[FlushConsoleInputBuffer], "FlushConsoleInputBuffer"), - TraceLoggingUInt32(_rguiTimesApiUsed[FreeConsole], "FreeConsole"), - TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleAlias], "GetConsoleAlias"), - TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleAliases], "GetConsoleAliases"), - TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleAliasExesLength], "GetConsoleAliasExesLength"), - TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleAliasesLength], "GetConsoleAliasesLength"), - TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleAliasExes], "GetConsoleAliasExes"), - TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleCP], "GetConsoleCP"), - TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleCursorInfo], "GetConsoleCursorInfo"), - TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleDisplayMode], "GetConsoleDisplayMode"), - TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleFontSize], "GetConsoleFontSize"), - TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleHistoryInfo], "GetConsoleHistoryInfo"), - TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleLangId], "GetConsoleLangId"), - TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleMode], "GetConsoleMode"), - TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleOriginalTitle], "GetConsoleOriginalTitle"), - TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleOutputCP], "GetConsoleOutputCP"), - TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleProcessList], "GetConsoleProcessList"), - TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleScreenBufferInfoEx], "GetConsoleScreenBufferInfoEx"), - TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleSelectionInfo], "GetConsoleSelectionInfo"), - TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleTitle], "GetConsoleTitle"), - TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleWindow], "GetConsoleWindow"), - TraceLoggingUInt32(_rguiTimesApiUsed[GetCurrentConsoleFontEx], "GetCurrentConsoleFontEx"), - TraceLoggingUInt32(_rguiTimesApiUsed[GetLargestConsoleWindowSize], "GetLargestConsoleWindowSize"), - TraceLoggingUInt32(_rguiTimesApiUsed[GetNumberOfConsoleInputEvents], "GetNumberOfConsoleInputEvents"), - TraceLoggingUInt32(_rguiTimesApiUsed[GetNumberOfConsoleMouseButtons], "GetNumberOfConsoleMouseButtons"), - TraceLoggingUInt32(_rguiTimesApiUsed[PeekConsoleInput], "PeekConsoleInput"), - TraceLoggingUInt32(_rguiTimesApiUsed[ReadConsole], "ReadConsole"), - TraceLoggingUInt32(_rguiTimesApiUsed[ReadConsoleInput], "ReadConsoleInput"), - TraceLoggingUInt32(_rguiTimesApiUsed[ReadConsoleOutput], "ReadConsoleOutput"), - TraceLoggingUInt32(_rguiTimesApiUsed[ReadConsoleOutputAttribute], "ReadConsoleOutputAttribute"), - TraceLoggingUInt32(_rguiTimesApiUsed[ReadConsoleOutputCharacter], "ReadConsoleOutputCharacter"), - TraceLoggingUInt32(_rguiTimesApiUsed[ScrollConsoleScreenBuffer], "ScrollConsoleScreenBuffer"), - TraceLoggingUInt32(_rguiTimesApiUsed[SetConsoleActiveScreenBuffer], "SetConsoleActiveScreenBuffer"), - TraceLoggingUInt32(_rguiTimesApiUsed[SetConsoleCP], "SetConsoleCP"), - TraceLoggingUInt32(_rguiTimesApiUsed[SetConsoleCursorInfo], "SetConsoleCursorInfo"), - TraceLoggingUInt32(_rguiTimesApiUsed[SetConsoleCursorPosition], "SetConsoleCursorPosition"), - TraceLoggingUInt32(_rguiTimesApiUsed[SetConsoleDisplayMode], "SetConsoleDisplayMode"), - TraceLoggingUInt32(_rguiTimesApiUsed[SetConsoleHistoryInfo], "SetConsoleHistoryInfo"), - TraceLoggingUInt32(_rguiTimesApiUsed[SetConsoleMode], "SetConsoleMode"), - TraceLoggingUInt32(_rguiTimesApiUsed[SetConsoleOutputCP], "SetConsoleOutputCP"), - TraceLoggingUInt32(_rguiTimesApiUsed[SetConsoleScreenBufferInfoEx], "SetConsoleScreenBufferInfoEx"), - TraceLoggingUInt32(_rguiTimesApiUsed[SetConsoleScreenBufferSize], "SetConsoleScreenBufferSize"), - TraceLoggingUInt32(_rguiTimesApiUsed[SetConsoleTextAttribute], "SetConsoleTextAttribute"), - TraceLoggingUInt32(_rguiTimesApiUsed[SetConsoleTitle], "SetConsoleTitle"), - TraceLoggingUInt32(_rguiTimesApiUsed[SetConsoleWindowInfo], "SetConsoleWindowInfo"), - TraceLoggingUInt32(_rguiTimesApiUsed[SetCurrentConsoleFontEx], "SetCurrentConsoleFontEx"), - TraceLoggingUInt32(_rguiTimesApiUsed[WriteConsole], "WriteConsole"), - TraceLoggingUInt32(_rguiTimesApiUsed[WriteConsoleInput], "WriteConsoleInput"), - TraceLoggingUInt32(_rguiTimesApiUsed[WriteConsoleOutput], "WriteConsoleOutput"), - TraceLoggingUInt32(_rguiTimesApiUsed[WriteConsoleOutputAttribute], "WriteConsoleOutputAttribute"), - TraceLoggingUInt32(_rguiTimesApiUsed[WriteConsoleOutputCharacter], "WriteConsoleOutputCharacter"), - TraceLoggingKeyword(MICROSOFT_KEYWORD_MEASURES), - TelemetryPrivacyDataTag(PDT_ProductAndServiceUsage)); + "ApiUsed", + TraceLoggingUInt32(_rguiTimesApiUsed[AddConsoleAlias], "AddConsoleAlias"), + TraceLoggingUInt32(_rguiTimesApiUsed[AllocConsole], "AllocConsole"), + TraceLoggingUInt32(_rguiTimesApiUsed[AttachConsole], "AttachConsole"), + TraceLoggingUInt32(_rguiTimesApiUsed[CreateConsoleScreenBuffer], "CreateConsoleScreenBuffer"), + TraceLoggingUInt32(_rguiTimesApiUsed[GenerateConsoleCtrlEvent], "GenerateConsoleCtrlEvent"), + TraceLoggingUInt32(_rguiTimesApiUsed[FillConsoleOutputAttribute], "FillConsoleOutputAttribute"), + TraceLoggingUInt32(_rguiTimesApiUsed[FillConsoleOutputCharacter], "FillConsoleOutputCharacter"), + TraceLoggingUInt32(_rguiTimesApiUsed[FlushConsoleInputBuffer], "FlushConsoleInputBuffer"), + TraceLoggingUInt32(_rguiTimesApiUsed[FreeConsole], "FreeConsole"), + TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleAlias], "GetConsoleAlias"), + TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleAliases], "GetConsoleAliases"), + TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleAliasExesLength], "GetConsoleAliasExesLength"), + TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleAliasesLength], "GetConsoleAliasesLength"), + TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleAliasExes], "GetConsoleAliasExes"), + TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleCP], "GetConsoleCP"), + TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleCursorInfo], "GetConsoleCursorInfo"), + TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleDisplayMode], "GetConsoleDisplayMode"), + TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleFontSize], "GetConsoleFontSize"), + TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleHistoryInfo], "GetConsoleHistoryInfo"), + TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleLangId], "GetConsoleLangId"), + TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleMode], "GetConsoleMode"), + TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleOriginalTitle], "GetConsoleOriginalTitle"), + TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleOutputCP], "GetConsoleOutputCP"), + TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleProcessList], "GetConsoleProcessList"), + TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleScreenBufferInfoEx], "GetConsoleScreenBufferInfoEx"), + TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleSelectionInfo], "GetConsoleSelectionInfo"), + TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleTitle], "GetConsoleTitle"), + TraceLoggingUInt32(_rguiTimesApiUsed[GetConsoleWindow], "GetConsoleWindow"), + TraceLoggingUInt32(_rguiTimesApiUsed[GetCurrentConsoleFontEx], "GetCurrentConsoleFontEx"), + TraceLoggingUInt32(_rguiTimesApiUsed[GetLargestConsoleWindowSize], "GetLargestConsoleWindowSize"), + TraceLoggingUInt32(_rguiTimesApiUsed[GetNumberOfConsoleInputEvents], "GetNumberOfConsoleInputEvents"), + TraceLoggingUInt32(_rguiTimesApiUsed[GetNumberOfConsoleMouseButtons], "GetNumberOfConsoleMouseButtons"), + TraceLoggingUInt32(_rguiTimesApiUsed[PeekConsoleInput], "PeekConsoleInput"), + TraceLoggingUInt32(_rguiTimesApiUsed[ReadConsole], "ReadConsole"), + TraceLoggingUInt32(_rguiTimesApiUsed[ReadConsoleInput], "ReadConsoleInput"), + TraceLoggingUInt32(_rguiTimesApiUsed[ReadConsoleOutput], "ReadConsoleOutput"), + TraceLoggingUInt32(_rguiTimesApiUsed[ReadConsoleOutputAttribute], "ReadConsoleOutputAttribute"), + TraceLoggingUInt32(_rguiTimesApiUsed[ReadConsoleOutputCharacter], "ReadConsoleOutputCharacter"), + TraceLoggingUInt32(_rguiTimesApiUsed[ScrollConsoleScreenBuffer], "ScrollConsoleScreenBuffer"), + TraceLoggingUInt32(_rguiTimesApiUsed[SetConsoleActiveScreenBuffer], "SetConsoleActiveScreenBuffer"), + TraceLoggingUInt32(_rguiTimesApiUsed[SetConsoleCP], "SetConsoleCP"), + TraceLoggingUInt32(_rguiTimesApiUsed[SetConsoleCursorInfo], "SetConsoleCursorInfo"), + TraceLoggingUInt32(_rguiTimesApiUsed[SetConsoleCursorPosition], "SetConsoleCursorPosition"), + TraceLoggingUInt32(_rguiTimesApiUsed[SetConsoleDisplayMode], "SetConsoleDisplayMode"), + TraceLoggingUInt32(_rguiTimesApiUsed[SetConsoleHistoryInfo], "SetConsoleHistoryInfo"), + TraceLoggingUInt32(_rguiTimesApiUsed[SetConsoleMode], "SetConsoleMode"), + TraceLoggingUInt32(_rguiTimesApiUsed[SetConsoleOutputCP], "SetConsoleOutputCP"), + TraceLoggingUInt32(_rguiTimesApiUsed[SetConsoleScreenBufferInfoEx], "SetConsoleScreenBufferInfoEx"), + TraceLoggingUInt32(_rguiTimesApiUsed[SetConsoleScreenBufferSize], "SetConsoleScreenBufferSize"), + TraceLoggingUInt32(_rguiTimesApiUsed[SetConsoleTextAttribute], "SetConsoleTextAttribute"), + TraceLoggingUInt32(_rguiTimesApiUsed[SetConsoleTitle], "SetConsoleTitle"), + TraceLoggingUInt32(_rguiTimesApiUsed[SetConsoleWindowInfo], "SetConsoleWindowInfo"), + TraceLoggingUInt32(_rguiTimesApiUsed[SetCurrentConsoleFontEx], "SetCurrentConsoleFontEx"), + TraceLoggingUInt32(_rguiTimesApiUsed[WriteConsole], "WriteConsole"), + TraceLoggingUInt32(_rguiTimesApiUsed[WriteConsoleInput], "WriteConsoleInput"), + TraceLoggingUInt32(_rguiTimesApiUsed[WriteConsoleOutput], "WriteConsoleOutput"), + TraceLoggingUInt32(_rguiTimesApiUsed[WriteConsoleOutputAttribute], "WriteConsoleOutputAttribute"), + TraceLoggingUInt32(_rguiTimesApiUsed[WriteConsoleOutputCharacter], "WriteConsoleOutputCharacter"), + TraceLoggingKeyword(MICROSOFT_KEYWORD_MEASURES), + TelemetryPrivacyDataTag(PDT_ProductAndServiceUsage)); for (int n = 0; n < ARRAYSIZE(_rguiTimesApiUsedAnsi); n++) { @@ -522,30 +530,32 @@ void Telemetry::WriteFinalTraceLog() // Ansi specific API's are used less, so check if we have anything to send back. // Also breaking it up into a separate TraceLoggingWriteTagged fixes a compilation warning that // the heap is too small. -#pragma prefast(suppress:__WARNING_NONCONST_LOCAL, "Activity can't be const, since it's set to a random value on startup.") + // clang-format off +#pragma prefast(suppress: __WARNING_NONCONST_LOCAL, "Activity can't be const, since it's set to a random value on startup.") + // clang-format on TraceLoggingWriteTagged(_activity, - "ApiAnsiUsed", - TraceLoggingUInt32(_rguiTimesApiUsedAnsi[AddConsoleAlias], "AddConsoleAlias"), - TraceLoggingUInt32(_rguiTimesApiUsedAnsi[FillConsoleOutputCharacter], "FillConsoleOutputCharacter"), - TraceLoggingUInt32(_rguiTimesApiUsedAnsi[GetConsoleAlias], "GetConsoleAlias"), - TraceLoggingUInt32(_rguiTimesApiUsedAnsi[GetConsoleAliases], "GetConsoleAliases"), - TraceLoggingUInt32(_rguiTimesApiUsedAnsi[GetConsoleAliasesLength], "GetConsoleAliasesLength"), - TraceLoggingUInt32(_rguiTimesApiUsedAnsi[GetConsoleAliasExes], "GetConsoleAliasExes"), - TraceLoggingUInt32(_rguiTimesApiUsedAnsi[GetConsoleAliasExesLength], "GetConsoleAliasExesLength"), - TraceLoggingUInt32(_rguiTimesApiUsedAnsi[GetConsoleOriginalTitle], "GetConsoleOriginalTitle"), - TraceLoggingUInt32(_rguiTimesApiUsedAnsi[GetConsoleTitle], "GetConsoleTitle"), - TraceLoggingUInt32(_rguiTimesApiUsedAnsi[PeekConsoleInput], "PeekConsoleInput"), - TraceLoggingUInt32(_rguiTimesApiUsedAnsi[ReadConsole], "ReadConsole"), - TraceLoggingUInt32(_rguiTimesApiUsedAnsi[ReadConsoleInput], "ReadConsoleInput"), - TraceLoggingUInt32(_rguiTimesApiUsedAnsi[ReadConsoleOutput], "ReadConsoleOutput"), - TraceLoggingUInt32(_rguiTimesApiUsedAnsi[ReadConsoleOutputCharacter], "ReadConsoleOutputCharacter"), - TraceLoggingUInt32(_rguiTimesApiUsedAnsi[SetConsoleTitle], "SetConsoleTitle"), - TraceLoggingUInt32(_rguiTimesApiUsedAnsi[WriteConsole], "WriteConsole"), - TraceLoggingUInt32(_rguiTimesApiUsedAnsi[WriteConsoleInput], "WriteConsoleInput"), - TraceLoggingUInt32(_rguiTimesApiUsedAnsi[WriteConsoleOutput], "WriteConsoleOutput"), - TraceLoggingUInt32(_rguiTimesApiUsedAnsi[WriteConsoleOutputCharacter], "WriteConsoleOutputCharacter"), - TraceLoggingKeyword(MICROSOFT_KEYWORD_MEASURES), - TelemetryPrivacyDataTag(PDT_ProductAndServiceUsage)); + "ApiAnsiUsed", + TraceLoggingUInt32(_rguiTimesApiUsedAnsi[AddConsoleAlias], "AddConsoleAlias"), + TraceLoggingUInt32(_rguiTimesApiUsedAnsi[FillConsoleOutputCharacter], "FillConsoleOutputCharacter"), + TraceLoggingUInt32(_rguiTimesApiUsedAnsi[GetConsoleAlias], "GetConsoleAlias"), + TraceLoggingUInt32(_rguiTimesApiUsedAnsi[GetConsoleAliases], "GetConsoleAliases"), + TraceLoggingUInt32(_rguiTimesApiUsedAnsi[GetConsoleAliasesLength], "GetConsoleAliasesLength"), + TraceLoggingUInt32(_rguiTimesApiUsedAnsi[GetConsoleAliasExes], "GetConsoleAliasExes"), + TraceLoggingUInt32(_rguiTimesApiUsedAnsi[GetConsoleAliasExesLength], "GetConsoleAliasExesLength"), + TraceLoggingUInt32(_rguiTimesApiUsedAnsi[GetConsoleOriginalTitle], "GetConsoleOriginalTitle"), + TraceLoggingUInt32(_rguiTimesApiUsedAnsi[GetConsoleTitle], "GetConsoleTitle"), + TraceLoggingUInt32(_rguiTimesApiUsedAnsi[PeekConsoleInput], "PeekConsoleInput"), + TraceLoggingUInt32(_rguiTimesApiUsedAnsi[ReadConsole], "ReadConsole"), + TraceLoggingUInt32(_rguiTimesApiUsedAnsi[ReadConsoleInput], "ReadConsoleInput"), + TraceLoggingUInt32(_rguiTimesApiUsedAnsi[ReadConsoleOutput], "ReadConsoleOutput"), + TraceLoggingUInt32(_rguiTimesApiUsedAnsi[ReadConsoleOutputCharacter], "ReadConsoleOutputCharacter"), + TraceLoggingUInt32(_rguiTimesApiUsedAnsi[SetConsoleTitle], "SetConsoleTitle"), + TraceLoggingUInt32(_rguiTimesApiUsedAnsi[WriteConsole], "WriteConsole"), + TraceLoggingUInt32(_rguiTimesApiUsedAnsi[WriteConsoleInput], "WriteConsoleInput"), + TraceLoggingUInt32(_rguiTimesApiUsedAnsi[WriteConsoleOutput], "WriteConsoleOutput"), + TraceLoggingUInt32(_rguiTimesApiUsedAnsi[WriteConsoleOutputCharacter], "WriteConsoleOutputCharacter"), + TraceLoggingKeyword(MICROSOFT_KEYWORD_MEASURES), + TelemetryPrivacyDataTag(PDT_ProductAndServiceUsage)); break; } } @@ -569,9 +579,11 @@ void Telemetry::LogRipMessage(_In_z_ const char* pszMessage, ...) const if (cCharsWritten > 0) { -#pragma prefast(suppress:__WARNING_NONCONST_LOCAL, "Activity can't be const, since it's set to a random value on startup.") + // clang-format off +#pragma prefast(suppress: __WARNING_NONCONST_LOCAL, "Activity can't be const, since it's set to a random value on startup.") + // clang-format on TraceLoggingWriteTagged(_activity, - "RipMessage", - TraceLoggingString(szMessageEvaluated, "Message")); + "RipMessage", + TraceLoggingString(szMessageEvaluated, "Message")); } } diff --git a/src/host/telemetry.hpp b/src/host/telemetry.hpp index cb9b3af58..8d8d617a7 100644 --- a/src/host/telemetry.hpp +++ b/src/host/telemetry.hpp @@ -130,7 +130,7 @@ private: Telemetry(Telemetry const&); void operator=(Telemetry const&); - bool FindProcessName(const WCHAR* pszProcessName, _Out_ size_t *iPosition) const; + bool FindProcessName(const WCHAR* pszProcessName, _Out_ size_t* iPosition) const; void TotalCodesForPreviousProcess(); static const int c_iMaxProcessesConnected = 100; @@ -143,7 +143,7 @@ private: unsigned int _uiFindNextClickedTotal; unsigned int _uiColorSelectionUsed; time_t _tStartedAt; - WCHAR const * const c_pwszBashExeName = L"bash.exe"; + WCHAR const* const c_pwszBashExeName = L"bash.exe"; // The current recommendation is to keep telemetry events 4KB or less, so let's keep our array at less than 2KB (1000 * 2 bytes). WCHAR _wchProcessFileNames[1000]; diff --git a/src/host/tracing.cpp b/src/host/tracing.cpp index 1f3ec9686..4b80090ae 100644 --- a/src/host/tracing.cpp +++ b/src/host/tracing.cpp @@ -32,7 +32,6 @@ DEFINE_ENUM_FLAG_OPERATORS(TraceKeywords); Tracing::Tracing(std::function onExit) : _onExit(onExit) { - } // Routine Description: @@ -54,37 +53,44 @@ Tracing::~Tracing() // will be stored for use in the stop event. // - traceName - The name of the API call to list in the trace details // Return Value: -// - An object for the caller to hold until the API call is complete. +// - An object for the caller to hold until the API call is complete. // Then destroy it to signal that the call is over so the stop trace can be written. Tracing Tracing::s_TraceApiCall(const NTSTATUS& result, PCSTR traceName) { - TraceLoggingWrite(g_hConhostV2EventTraceProvider, "ApiCall", - TraceLoggingString(traceName, "ApiName"), - TraceLoggingOpcode(WINEVENT_OPCODE_START), - TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::API)); + // clang-format off + TraceLoggingWrite( + g_hConhostV2EventTraceProvider, + "ApiCall", + TraceLoggingString(traceName, "ApiName"), + TraceLoggingOpcode(WINEVENT_OPCODE_START), + TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), + TraceLoggingKeyword(TraceKeywords::API)); return Tracing([traceName, &result] { - TraceLoggingWrite(g_hConhostV2EventTraceProvider, "ApiCall", - TraceLoggingString(traceName, "ApiName"), - TraceLoggingHResult(result, "Result"), - TraceLoggingOpcode(WINEVENT_OPCODE_STOP), - TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::API)); + TraceLoggingWrite( + g_hConhostV2EventTraceProvider, + "ApiCall", + TraceLoggingString(traceName, "ApiName"), + TraceLoggingHResult(result, "Result"), + TraceLoggingOpcode(WINEVENT_OPCODE_STOP), + TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), + TraceLoggingKeyword(TraceKeywords::API)); }); + // clang-format on } ULONG Tracing::s_ulDebugFlag = 0x0; void Tracing::s_TraceApi(const NTSTATUS status, const CONSOLE_GETLARGESTWINDOWSIZE_MSG* const a) { - TraceLoggingWrite(g_hConhostV2EventTraceProvider, "API_GetLargestWindowSize", + TraceLoggingWrite( + g_hConhostV2EventTraceProvider, + "API_GetLargestWindowSize", TraceLoggingHexInt32(status, "ResultCode"), TraceLoggingInt32(a->Size.X, "MaxWindowWidthInChars"), TraceLoggingInt32(a->Size.Y, "MaxWindowHeightInChars"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::API) - ); + TraceLoggingKeyword(TraceKeywords::API)); } void Tracing::s_TraceApi(const NTSTATUS status, const CONSOLE_SCREENBUFFERINFO_MSG* const a, const bool fSet) @@ -94,7 +100,9 @@ void Tracing::s_TraceApi(const NTSTATUS status, const CONSOLE_SCREENBUFFERINFO_M if (fSet) { - TraceLoggingWrite(g_hConhostV2EventTraceProvider, "API_SetConsoleScreenBufferInfo", + TraceLoggingWrite( + g_hConhostV2EventTraceProvider, + "API_SetConsoleScreenBufferInfo", TraceLoggingHexInt32(status, "ResultCode"), TraceLoggingInt32(a->Size.X, "BufferWidthInChars"), TraceLoggingInt32(a->Size.Y, "BufferHeightInChars"), @@ -103,12 +111,13 @@ void Tracing::s_TraceApi(const NTSTATUS status, const CONSOLE_SCREENBUFFERINFO_M TraceLoggingInt32(a->MaximumWindowSize.X, "MaxWindowWidthInChars"), TraceLoggingInt32(a->MaximumWindowSize.Y, "MaxWindowHeightInChars"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::API) - ); + TraceLoggingKeyword(TraceKeywords::API)); } else { - TraceLoggingWrite(g_hConhostV2EventTraceProvider, "API_GetConsoleScreenBufferInfo", + TraceLoggingWrite( + g_hConhostV2EventTraceProvider, + "API_GetConsoleScreenBufferInfo", TraceLoggingHexInt32(status, "ResultCode"), TraceLoggingInt32(a->Size.X, "BufferWidthInChars"), TraceLoggingInt32(a->Size.Y, "BufferHeightInChars"), @@ -117,25 +126,27 @@ void Tracing::s_TraceApi(const NTSTATUS status, const CONSOLE_SCREENBUFFERINFO_M TraceLoggingInt32(a->MaximumWindowSize.X, "MaxWindowWidthInChars"), TraceLoggingInt32(a->MaximumWindowSize.Y, "MaxWindowHeightInChars"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::API) - ); + TraceLoggingKeyword(TraceKeywords::API)); } } void Tracing::s_TraceApi(const NTSTATUS status, const CONSOLE_SETSCREENBUFFERSIZE_MSG* const a) { - TraceLoggingWrite(g_hConhostV2EventTraceProvider, "API_SetConsoleScreenBufferSize", + TraceLoggingWrite( + g_hConhostV2EventTraceProvider, + "API_SetConsoleScreenBufferSize", TraceLoggingHexInt32(status, "ResultCode"), TraceLoggingInt32(a->Size.X, "BufferWidthInChars"), TraceLoggingInt32(a->Size.Y, "BufferHeightInChars"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::API) - ); + TraceLoggingKeyword(TraceKeywords::API)); } void Tracing::s_TraceApi(const NTSTATUS status, const CONSOLE_SETWINDOWINFO_MSG* const a) { - TraceLoggingWrite(g_hConhostV2EventTraceProvider, "API_SetConsoleWindowInfo", + TraceLoggingWrite( + g_hConhostV2EventTraceProvider, + "API_SetConsoleWindowInfo", TraceLoggingHexInt32(status, "ResultCode"), TraceLoggingBool(a->Absolute, "IsWindowRectAbsolute"), TraceLoggingInt32(a->Window.Left, "WindowRectLeft"), @@ -143,39 +154,44 @@ void Tracing::s_TraceApi(const NTSTATUS status, const CONSOLE_SETWINDOWINFO_MSG* TraceLoggingInt32(a->Window.Top, "WindowRectTop"), TraceLoggingInt32(a->Window.Bottom, "WindowRectBottom"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::API) - ); + TraceLoggingKeyword(TraceKeywords::API)); } void Tracing::s_TraceApi(_In_ const void* const buffer, const CONSOLE_WRITECONSOLE_MSG* const a) { + // clang-format off if (a->Unicode) { const wchar_t* const buf = static_cast(buffer); - TraceLoggingWrite(g_hConhostV2EventTraceProvider, "API_WriteConsole", + TraceLoggingWrite( + g_hConhostV2EventTraceProvider, + "API_WriteConsole", TraceLoggingBoolean(a->Unicode, "Unicode"), TraceLoggingUInt32(a->NumBytes, "NumBytes"), TraceLoggingCountedWideString(buf, static_cast(a->NumBytes / sizeof(wchar_t)), "input buffer"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::API) - ); + TraceLoggingKeyword(TraceKeywords::API)); } else { const char* const buf = static_cast(buffer); - TraceLoggingWrite(g_hConhostV2EventTraceProvider, "API_WriteConsole", + TraceLoggingWrite( + g_hConhostV2EventTraceProvider, + "API_WriteConsole", TraceLoggingBoolean(a->Unicode, "Unicode"), TraceLoggingUInt32(a->NumBytes, "NumBytes"), TraceLoggingCountedString(buf, static_cast(a->NumBytes / sizeof(char)), "input buffer"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::API) - ); + TraceLoggingKeyword(TraceKeywords::API)); } + // clang-format on } void Tracing::s_TraceApi(const CONSOLE_SCREENBUFFERINFO_MSG* const a) { - TraceLoggingWrite(g_hConhostV2EventTraceProvider, "API_GetConsoleScreenBufferInfo", + TraceLoggingWrite( + g_hConhostV2EventTraceProvider, + "API_GetConsoleScreenBufferInfo", TraceLoggingInt16(a->Size.X, "Size.X"), TraceLoggingInt16(a->Size.Y, "Size.Y"), TraceLoggingInt16(a->CursorPosition.X, "CursorPosition.X"), @@ -191,52 +207,55 @@ void Tracing::s_TraceApi(const CONSOLE_SCREENBUFFERINFO_MSG* const a) TraceLoggingBoolean(a->FullscreenSupported, "FullscreenSupported"), TraceLoggingHexUInt32FixedArray((UINT32 const*)a->ColorTable, _countof(a->ColorTable), "ColorTable"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::API) - ); + TraceLoggingKeyword(TraceKeywords::API)); static_assert(sizeof(UINT32) == sizeof(*a->ColorTable), "a->ColorTable"); } void Tracing::s_TraceApi(const CONSOLE_MODE_MSG* const a, const std::wstring& handleType) { - TraceLoggingWrite(g_hConhostV2EventTraceProvider, "API_GetConsoleMode", + TraceLoggingWrite( + g_hConhostV2EventTraceProvider, + "API_GetConsoleMode", TraceLoggingHexUInt32(a->Mode, "Mode"), TraceLoggingWideString(handleType.c_str(), "Handle type"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::API) - ); + TraceLoggingKeyword(TraceKeywords::API)); } void Tracing::s_TraceApi(const CONSOLE_SETTEXTATTRIBUTE_MSG* const a) { - TraceLoggingWrite(g_hConhostV2EventTraceProvider, "API_SetConsoleTextAttribute", + TraceLoggingWrite( + g_hConhostV2EventTraceProvider, + "API_SetConsoleTextAttribute", TraceLoggingHexUInt16(a->Attributes, "Attributes"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::API) - ); + TraceLoggingKeyword(TraceKeywords::API)); } void Tracing::s_TraceApi(const CONSOLE_WRITECONSOLEOUTPUTSTRING_MSG* const a) { - TraceLoggingWrite(g_hConhostV2EventTraceProvider, "API_WriteConsoleOutput", + TraceLoggingWrite( + g_hConhostV2EventTraceProvider, + "API_WriteConsoleOutput", TraceLoggingInt16(a->WriteCoord.X, "WriteCoord.X"), TraceLoggingInt16(a->WriteCoord.Y, "WriteCoord.Y"), TraceLoggingHexUInt32(a->StringType, "StringType"), TraceLoggingUInt32(a->NumRecords, "NumRecords"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::API) - ); + TraceLoggingKeyword(TraceKeywords::API)); } void Tracing::s_TraceWindowViewport(const Microsoft::Console::Types::Viewport& viewport) { - TraceLoggingWrite(g_hConhostV2EventTraceProvider, "WindowViewport", + TraceLoggingWrite( + g_hConhostV2EventTraceProvider, + "WindowViewport", TraceLoggingInt32(viewport.Height(), "ViewHeight"), TraceLoggingInt32(viewport.Width(), "ViewWidth"), TraceLoggingInt32(viewport.Top(), "OriginTop"), TraceLoggingInt32(viewport.Left(), "OriginLeft"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::General) - ); + TraceLoggingKeyword(TraceKeywords::General)); } void Tracing::s_TraceChars(_In_z_ const char* pszMessage, ...) @@ -247,11 +266,12 @@ void Tracing::s_TraceChars(_In_z_ const char* pszMessage, ...) vsprintf_s(szBuffer, ARRAYSIZE(szBuffer), pszMessage, args); va_end(args); - TraceLoggingWrite(g_hConhostV2EventTraceProvider, "CharsTrace", + TraceLoggingWrite( + g_hConhostV2EventTraceProvider, + "CharsTrace", TraceLoggingString(szBuffer), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::Chars) - ); + TraceLoggingKeyword(TraceKeywords::Chars)); if (s_ulDebugFlag & TraceKeywords::Chars) { @@ -267,11 +287,12 @@ void Tracing::s_TraceOutput(_In_z_ const char* pszMessage, ...) vsprintf_s(szBuffer, ARRAYSIZE(szBuffer), pszMessage, args); va_end(args); - TraceLoggingWrite(g_hConhostV2EventTraceProvider, "OutputTrace", + TraceLoggingWrite( + g_hConhostV2EventTraceProvider, + "OutputTrace", TraceLoggingString(szBuffer), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::Output) - ); + TraceLoggingKeyword(TraceKeywords::Output)); if (s_ulDebugFlag & TraceKeywords::Output) { @@ -402,8 +423,7 @@ void Tracing::s_TraceUia(const UiaTextRange* const range, "UiaTextRange::Constructor", TraceLoggingValue(id, "_id"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; } case UiaTextRangeTracing::ApiCall::AddRef: @@ -415,8 +435,7 @@ void Tracing::s_TraceUia(const UiaTextRange* const range, TraceLoggingValue(end, "_end"), TraceLoggingValue(degenerate, "_degenerate"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case UiaTextRangeTracing::ApiCall::Release: TraceLoggingWrite( @@ -427,8 +446,7 @@ void Tracing::s_TraceUia(const UiaTextRange* const range, TraceLoggingValue(end, "_end"), TraceLoggingValue(degenerate, "_degenerate"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case UiaTextRangeTracing::ApiCall::QueryInterface: TraceLoggingWrite( @@ -439,8 +457,7 @@ void Tracing::s_TraceUia(const UiaTextRange* const range, TraceLoggingValue(end, "_end"), TraceLoggingValue(degenerate, "_degenerate"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case UiaTextRangeTracing::ApiCall::Clone: { @@ -458,8 +475,7 @@ void Tracing::s_TraceUia(const UiaTextRange* const range, TraceLoggingValue(degenerate, "_degenerate"), TraceLoggingValue(cloneId, "clone's _id"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; } case UiaTextRangeTracing::ApiCall::Compare: @@ -475,8 +491,7 @@ void Tracing::s_TraceUia(const UiaTextRange* const range, TraceLoggingValue(msg->OtherId, "Other's Id"), TraceLoggingValue(msg->Equal, "Equal"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; } case UiaTextRangeTracing::ApiCall::CompareEndpoints: @@ -496,8 +511,7 @@ void Tracing::s_TraceUia(const UiaTextRange* const range, TraceLoggingValue(pTargetEndpoint, "targetEndpoint"), TraceLoggingValue(msg->Result, "Result"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; } case UiaTextRangeTracing::ApiCall::ExpandToEnclosingUnit: @@ -515,8 +529,7 @@ void Tracing::s_TraceUia(const UiaTextRange* const range, TraceLoggingValue(msg->OriginalStart, "Original Start"), TraceLoggingValue(msg->OriginalEnd, "Original End"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; } case UiaTextRangeTracing::ApiCall::FindAttribute: @@ -528,8 +541,7 @@ void Tracing::s_TraceUia(const UiaTextRange* const range, TraceLoggingValue(end, "_end"), TraceLoggingValue(degenerate, "_degenerate"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case UiaTextRangeTracing::ApiCall::FindText: TraceLoggingWrite( @@ -540,8 +552,7 @@ void Tracing::s_TraceUia(const UiaTextRange* const range, TraceLoggingValue(end, "_end"), TraceLoggingValue(degenerate, "_degenerate"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case UiaTextRangeTracing::ApiCall::GetAttributeValue: TraceLoggingWrite( @@ -552,8 +563,7 @@ void Tracing::s_TraceUia(const UiaTextRange* const range, TraceLoggingValue(end, "_end"), TraceLoggingValue(degenerate, "_degenerate"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case UiaTextRangeTracing::ApiCall::GetBoundingRectangles: TraceLoggingWrite( @@ -564,8 +574,7 @@ void Tracing::s_TraceUia(const UiaTextRange* const range, TraceLoggingValue(end, "_end"), TraceLoggingValue(degenerate, "_degenerate"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case UiaTextRangeTracing::ApiCall::GetEnclosingElement: TraceLoggingWrite( @@ -576,8 +585,7 @@ void Tracing::s_TraceUia(const UiaTextRange* const range, TraceLoggingValue(end, "_end"), TraceLoggingValue(degenerate, "_degenerate"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case UiaTextRangeTracing::ApiCall::GetText: { @@ -591,8 +599,7 @@ void Tracing::s_TraceUia(const UiaTextRange* const range, TraceLoggingValue(degenerate, "_degenerate"), TraceLoggingValue(msg->Text, "Text"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; } case UiaTextRangeTracing::ApiCall::Move: @@ -612,8 +619,7 @@ void Tracing::s_TraceUia(const UiaTextRange* const range, TraceLoggingValue(msg->RequestedCount, "Requested Count"), TraceLoggingValue(msg->MovedCount, "Moved Count"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; } case UiaTextRangeTracing::ApiCall::MoveEndpointByUnit: @@ -635,8 +641,7 @@ void Tracing::s_TraceUia(const UiaTextRange* const range, TraceLoggingValue(msg->RequestedCount, "Requested Count"), TraceLoggingValue(msg->MovedCount, "Moved Count"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; } case UiaTextRangeTracing::ApiCall::MoveEndpointByRange: @@ -657,8 +662,7 @@ void Tracing::s_TraceUia(const UiaTextRange* const range, TraceLoggingValue(pTargetEndpoint, "targetEndpoint"), TraceLoggingValue(msg->OtherId, "Other's _id"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; } case UiaTextRangeTracing::ApiCall::Select: @@ -670,8 +674,7 @@ void Tracing::s_TraceUia(const UiaTextRange* const range, TraceLoggingValue(end, "_end"), TraceLoggingValue(degenerate, "_degenerate"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case UiaTextRangeTracing::ApiCall::AddToSelection: TraceLoggingWrite( @@ -682,8 +685,7 @@ void Tracing::s_TraceUia(const UiaTextRange* const range, TraceLoggingValue(end, "_end"), TraceLoggingValue(degenerate, "_degenerate"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case UiaTextRangeTracing::ApiCall::RemoveFromSelection: TraceLoggingWrite( @@ -694,8 +696,7 @@ void Tracing::s_TraceUia(const UiaTextRange* const range, TraceLoggingValue(end, "_end"), TraceLoggingValue(degenerate, "_degenerate"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case UiaTextRangeTracing::ApiCall::ScrollIntoView: { @@ -709,8 +710,7 @@ void Tracing::s_TraceUia(const UiaTextRange* const range, TraceLoggingValue(degenerate, "_degenerate"), TraceLoggingValue(msg->AlignToTop, "alignToTop"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; } case UiaTextRangeTracing::ApiCall::GetChildren: @@ -722,8 +722,7 @@ void Tracing::s_TraceUia(const UiaTextRange* const range, TraceLoggingValue(end, "_end"), TraceLoggingValue(degenerate, "_degenerate"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; default: break; @@ -741,8 +740,7 @@ void Tracing::s_TraceUia(const ScreenInfoUiaProvider* const /*pProvider*/, g_hConhostV2EventTraceProvider, "ScreenInfoUiaProvider::Constructor", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case ScreenInfoUiaProviderTracing::ApiCall::Signal: { @@ -754,8 +752,7 @@ void Tracing::s_TraceUia(const ScreenInfoUiaProvider* const /*pProvider*/, TraceLoggingValue(msg->Signal), TraceLoggingValue(signalName, "Event Name"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; } case ScreenInfoUiaProviderTracing::ApiCall::AddRef: @@ -763,56 +760,49 @@ void Tracing::s_TraceUia(const ScreenInfoUiaProvider* const /*pProvider*/, g_hConhostV2EventTraceProvider, "ScreenInfoUiaProvider::AddRef", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case ScreenInfoUiaProviderTracing::ApiCall::Release: TraceLoggingWrite( g_hConhostV2EventTraceProvider, "ScreenInfoUiaProvider::Release", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case ScreenInfoUiaProviderTracing::ApiCall::QueryInterface: TraceLoggingWrite( g_hConhostV2EventTraceProvider, "ScreenInfoUiaProvider::QueryInterface", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case ScreenInfoUiaProviderTracing::ApiCall::GetProviderOptions: TraceLoggingWrite( g_hConhostV2EventTraceProvider, "ScreenInfoUiaProvider::GetProviderOptions", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case ScreenInfoUiaProviderTracing::ApiCall::GetPatternProvider: TraceLoggingWrite( g_hConhostV2EventTraceProvider, "ScreenInfoUiaProvider::GetPatternProvider", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case ScreenInfoUiaProviderTracing::ApiCall::GetPropertyValue: TraceLoggingWrite( g_hConhostV2EventTraceProvider, "ScreenInfoUiaProvider::GetPropertyValue", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case ScreenInfoUiaProviderTracing::ApiCall::GetHostRawElementProvider: TraceLoggingWrite( g_hConhostV2EventTraceProvider, "ScreenInfoUiaProvider::GetHostRawElementProvider", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case ScreenInfoUiaProviderTracing::ApiCall::Navigate: { @@ -823,8 +813,7 @@ void Tracing::s_TraceUia(const ScreenInfoUiaProvider* const /*pProvider*/, "ScreenInfoUiaProvider::Navigate", TraceLoggingValue(direction, "direction"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; } case ScreenInfoUiaProviderTracing::ApiCall::GetRuntimeId: @@ -832,88 +821,77 @@ void Tracing::s_TraceUia(const ScreenInfoUiaProvider* const /*pProvider*/, g_hConhostV2EventTraceProvider, "ScreenInfoUiaProvider::GetRuntimeId", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case ScreenInfoUiaProviderTracing::ApiCall::GetBoundingRectangle: TraceLoggingWrite( g_hConhostV2EventTraceProvider, "ScreenInfoUiaProvider::GetBoundingRectangles", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case ScreenInfoUiaProviderTracing::ApiCall::GetEmbeddedFragmentRoots: TraceLoggingWrite( g_hConhostV2EventTraceProvider, "ScreenInfoUiaProvider::GetEmbeddedFragmentRoots", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case ScreenInfoUiaProviderTracing::ApiCall::SetFocus: TraceLoggingWrite( g_hConhostV2EventTraceProvider, "ScreenInfoUiaProvider::SetFocus", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case ScreenInfoUiaProviderTracing::ApiCall::GetFragmentRoot: TraceLoggingWrite( g_hConhostV2EventTraceProvider, "ScreenInfoUiaProvider::GetFragmentRoot", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case ScreenInfoUiaProviderTracing::ApiCall::GetSelection: TraceLoggingWrite( g_hConhostV2EventTraceProvider, "ScreenInfoUiaProvider::GetSelection", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case ScreenInfoUiaProviderTracing::ApiCall::GetVisibleRanges: TraceLoggingWrite( g_hConhostV2EventTraceProvider, "ScreenInfoUiaProvider::GetVisibleRanges", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case ScreenInfoUiaProviderTracing::ApiCall::RangeFromChild: TraceLoggingWrite( g_hConhostV2EventTraceProvider, "ScreenInfoUiaProvider::RangeFromChild", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case ScreenInfoUiaProviderTracing::ApiCall::RangeFromPoint: TraceLoggingWrite( g_hConhostV2EventTraceProvider, "ScreenInfoUiaProvider::RangeFromPoint", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case ScreenInfoUiaProviderTracing::ApiCall::GetDocumentRange: TraceLoggingWrite( g_hConhostV2EventTraceProvider, "ScreenInfoUiaProvider::GetDocumentRange", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case ScreenInfoUiaProviderTracing::ApiCall::GetSupportedTextSelection: TraceLoggingWrite( g_hConhostV2EventTraceProvider, "ScreenInfoUiaProvider::GetSupportedTextSelection", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; default: break; @@ -931,8 +909,7 @@ void Tracing::s_TraceUia(const WindowUiaProvider* const /*pProvider*/, g_hConhostV2EventTraceProvider, "WindowUiaProvider::Create", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case WindowUiaProviderTracing::ApiCall::Signal: { @@ -944,8 +921,7 @@ void Tracing::s_TraceUia(const WindowUiaProvider* const /*pProvider*/, TraceLoggingValue(msg->Signal, "Signal"), TraceLoggingValue(eventName, "Signal Name"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; } case WindowUiaProviderTracing::ApiCall::AddRef: @@ -953,56 +929,49 @@ void Tracing::s_TraceUia(const WindowUiaProvider* const /*pProvider*/, g_hConhostV2EventTraceProvider, "WindowUiaProvider::AddRef", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case WindowUiaProviderTracing::ApiCall::Release: TraceLoggingWrite( g_hConhostV2EventTraceProvider, "WindowUiaProvider::Release", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case WindowUiaProviderTracing::ApiCall::QueryInterface: TraceLoggingWrite( g_hConhostV2EventTraceProvider, "WindowUiaProvider::QueryInterface", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case WindowUiaProviderTracing::ApiCall::GetProviderOptions: TraceLoggingWrite( g_hConhostV2EventTraceProvider, "WindowUiaProvider::GetProviderOptions", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case WindowUiaProviderTracing::ApiCall::GetPatternProvider: TraceLoggingWrite( g_hConhostV2EventTraceProvider, "WindowUiaProvider::GetPatternProvider", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case WindowUiaProviderTracing::ApiCall::GetPropertyValue: TraceLoggingWrite( g_hConhostV2EventTraceProvider, "WindowUiaProvider::GetPropertyValue", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case WindowUiaProviderTracing::ApiCall::GetHostRawElementProvider: TraceLoggingWrite( g_hConhostV2EventTraceProvider, "WindowUiaProvider::GetHostRawElementProvider", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case WindowUiaProviderTracing::ApiCall::Navigate: { @@ -1013,8 +982,7 @@ void Tracing::s_TraceUia(const WindowUiaProvider* const /*pProvider*/, "WindowUiaProvider::Navigate", TraceLoggingValue(direction, "direction"), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; } case WindowUiaProviderTracing::ApiCall::GetRuntimeId: @@ -1022,56 +990,49 @@ void Tracing::s_TraceUia(const WindowUiaProvider* const /*pProvider*/, g_hConhostV2EventTraceProvider, "WindowUiaProvider::GetRuntimeId", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case WindowUiaProviderTracing::ApiCall::GetBoundingRectangle: TraceLoggingWrite( g_hConhostV2EventTraceProvider, "WindowUiaProvider::GetBoundingRectangle", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case WindowUiaProviderTracing::ApiCall::GetEmbeddedFragmentRoots: TraceLoggingWrite( g_hConhostV2EventTraceProvider, "WindowUiaProvider::GetEmbeddedFragmentRoots", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case WindowUiaProviderTracing::ApiCall::SetFocus: TraceLoggingWrite( g_hConhostV2EventTraceProvider, "WindowUiaProvider::SetFocus", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case WindowUiaProviderTracing::ApiCall::GetFragmentRoot: TraceLoggingWrite( g_hConhostV2EventTraceProvider, "WindowUiaProvider::GetFragmentRoot", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case WindowUiaProviderTracing::ApiCall::ElementProviderFromPoint: TraceLoggingWrite( g_hConhostV2EventTraceProvider, "WindowUiaProvider::ElementProviderFromPoint", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; case WindowUiaProviderTracing::ApiCall::GetFocus: TraceLoggingWrite( g_hConhostV2EventTraceProvider, "WindowUiaProvider::GetFocus", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingKeyword(TraceKeywords::UIA) - ); + TraceLoggingKeyword(TraceKeywords::UIA)); break; default: break; diff --git a/src/host/tracing.hpp b/src/host/tracing.hpp index cb3f2b66d..32c441f45 100644 --- a/src/host/tracing.hpp +++ b/src/host/tracing.hpp @@ -47,8 +47,14 @@ namespace Microsoft::Console::Interactivity::Win32 } #if DBG -#define DBGCHARS(_params_) { Tracing::s_TraceChars _params_ ; } -#define DBGOUTPUT(_params_) { Tracing::s_TraceOutput _params_ ; } +#define DBGCHARS(_params_) \ + { \ + Tracing::s_TraceChars _params_; \ + } +#define DBGOUTPUT(_params_) \ + { \ + Tracing::s_TraceOutput _params_; \ + } #else #define DBGCHARS(_params_) #define DBGOUTPUT(_params_) diff --git a/src/host/ut_host/AliasTests.cpp b/src/host/ut_host/AliasTests.cpp index c6f07480d..befc8067e 100644 --- a/src/host/ut_host/AliasTests.cpp +++ b/src/host/ut_host/AliasTests.cpp @@ -64,7 +64,8 @@ class AliasTests TEST_METHOD_PROPERTY(L"Data:exeName", L"{test.exe}") TEST_METHOD_PROPERTY(L"Data:aliasName", L"{foo}") TEST_METHOD_PROPERTY(L"Data:originalString", L"{ foo one two three four five six seven eight nine ten eleven twelve }") - TEST_METHOD_PROPERTY(L"Data:targetExpectedPair", L"{" // Each of these is a human-generated test of macro before and after. + TEST_METHOD_PROPERTY(L"Data:targetExpectedPair", + L"{" // Each of these is a human-generated test of macro before and after. L"bar=bar%," // The character % will be turned into an \r\n L"bar $1=bar one%," L"bar $2=bar two%," @@ -92,10 +93,10 @@ class AliasTests L"IEndInA$=IEndInA$%," // Ending in a $ is copied through. L"megamix $7$Gfun $1 $b test $9 $L $2.txt$tall$$the$$things $*$tat$g$gonce.log=megamix seven>fun one | test nine < two.txt%all$$the$$things one two three four five six seven eight nine ten eleven twelve%at>>once.log%" L"}") - END_TEST_METHOD_PROPERTIES() + END_TEST_METHOD_PROPERTIES() - // Get test parameters - String exeName; + // Get test parameters + String exeName; VERIFY_SUCCEEDED(TestData::TryGetValue(L"exeName", exeName)); String aliasName; @@ -318,7 +319,6 @@ class AliasTests std::wstring target(L"someTarget"); Alias::s_TestAddAlias(exe, source, target); - Alias::s_MatchAndCopyAliasLegacy(pwszSource, cbSource, rgwchTarget.get(), @@ -374,7 +374,8 @@ class AliasTests TEST_METHOD(TrimTrailing) { BEGIN_TEST_METHOD_PROPERTIES() - TEST_METHOD_PROPERTY(L"Data:targetExpectedPair", L"{" + TEST_METHOD_PROPERTY(L"Data:targetExpectedPair", + L"{" L"bar%=bar," // The character % will be turned into an \r\n L"bar=bar" L"}") @@ -430,10 +431,11 @@ class AliasTests TEST_METHOD(GetArgString) { BEGIN_TEST_METHOD_PROPERTIES() - TEST_METHOD_PROPERTY(L"Data:targetExpectedPair", L"{" - L"alias arg1 arg2 arg3=arg1 arg2 arg3," - L"aliasOnly=" - L"}") + TEST_METHOD_PROPERTY(L"Data:targetExpectedPair", + L"{" + L"alias arg1 arg2 arg3=arg1 arg2 arg3," + L"aliasOnly=" + L"}") END_TEST_METHOD_PROPERTIES() std::wstring target; @@ -448,7 +450,8 @@ class AliasTests TEST_METHOD(NumberedArgMacro) { BEGIN_TEST_METHOD_PROPERTIES() - TEST_METHOD_PROPERTY(L"Data:targetExpectedPair", L"{" + TEST_METHOD_PROPERTY(L"Data:targetExpectedPair", + L"{" L"1=one," L"2=two," L"3=three," @@ -493,7 +496,8 @@ class AliasTests TEST_METHOD(WildcardArgMacro) { BEGIN_TEST_METHOD_PROPERTIES() - TEST_METHOD_PROPERTY(L"Data:targetExpectedPair", L"{" + TEST_METHOD_PROPERTY(L"Data:targetExpectedPair", + L"{" L"*=one two three," L"A=," L"0=," @@ -519,7 +523,8 @@ class AliasTests TEST_METHOD(InputRedirMacro) { BEGIN_TEST_METHOD_PROPERTIES() - TEST_METHOD_PROPERTY(L"Data:targetExpectedPair", L"{" + TEST_METHOD_PROPERTY(L"Data:targetExpectedPair", + L"{" L"L=<," L"l=<," L"A=," @@ -545,7 +550,8 @@ class AliasTests TEST_METHOD(OutputRedirMacro) { BEGIN_TEST_METHOD_PROPERTIES() - TEST_METHOD_PROPERTY(L"Data:targetExpectedPair", L"{" + TEST_METHOD_PROPERTY(L"Data:targetExpectedPair", + L"{" L"G=>," L"g=>," L"A=," @@ -571,7 +577,8 @@ class AliasTests TEST_METHOD(PipeRedirMacro) { BEGIN_TEST_METHOD_PROPERTIES() - TEST_METHOD_PROPERTY(L"Data:targetExpectedPair", L"{" + TEST_METHOD_PROPERTY(L"Data:targetExpectedPair", + L"{" L"B=|," L"b=|," L"A=," @@ -597,7 +604,8 @@ class AliasTests TEST_METHOD(NextCommandMacro) { BEGIN_TEST_METHOD_PROPERTIES() - TEST_METHOD_PROPERTY(L"Data:targetExpectedPair", L"{" + TEST_METHOD_PROPERTY(L"Data:targetExpectedPair", + L"{" L"T=%," L"t=%," L"A=," diff --git a/src/host/ut_host/ApiRoutinesTests.cpp b/src/host/ut_host/ApiRoutinesTests.cpp index 170240699..a8e425882 100644 --- a/src/host/ut_host/ApiRoutinesTests.cpp +++ b/src/host/ut_host/ApiRoutinesTests.cpp @@ -149,9 +149,9 @@ class ApiRoutinesTests { Log::Comment(L"Turn on insert mode with cooked read data."); m_state->PrepareReadHandle(); - auto cleanupReadHandle = wil::scope_exit([&](){ m_state->CleanupReadHandle(); }); + auto cleanupReadHandle = wil::scope_exit([&]() { m_state->CleanupReadHandle(); }); m_state->PrepareCookedReadData(); - auto cleanupCookedRead = wil::scope_exit([&](){ m_state->CleanupCookedReadData(); }); + auto cleanupCookedRead = wil::scope_exit([&]() { m_state->CleanupCookedReadData(); }); PrepVerifySetConsoleInputModeImpl(0); Log::Comment(L"Success code should result from setting valid flags."); @@ -595,7 +595,7 @@ class ApiRoutinesTests { BEGIN_TEST_METHOD_PROPERTIES() TEST_METHOD_PROPERTY(L"data:checkClipped", L"{false, true}") - END_TEST_METHOD_PROPERTIES(); + END_TEST_METHOD_PROPERTIES(); bool checkClipped; VERIFY_SUCCEEDED(TestData::TryGetValue(L"checkClipped", checkClipped), L"Get whether or not we should check all the options using a clipping rectangle."); @@ -660,7 +660,7 @@ class ApiRoutinesTests // for scrolling left and right, we're going to clip to only modify the top half of the buffer COORD clipRectDimensions = bufferSize.Dimensions(); clipRectDimensions.Y /= 2; - + clipViewport = Viewport::FromDimensions({ 0, 0 }, clipRectDimensions); clipRectangle = clipViewport.value().ToInclusive(); } diff --git a/src/host/ut_host/AttrRowTests.cpp b/src/host/ut_host/AttrRowTests.cpp index 7a1881efe..78366327a 100644 --- a/src/host/ut_host/AttrRowTests.cpp +++ b/src/host/ut_host/AttrRowTests.cpp @@ -16,10 +16,12 @@ using namespace WEX::Common; using namespace WEX::Logging; using namespace WEX::TestExecution; -namespace WEX { - namespace TestExecution { +namespace WEX +{ + namespace TestExecution + { template<> - class VerifyOutputTraits + class VerifyOutputTraits { public: static WEX::Common::NoThrowString ToString(const TextAttributeRun& tar) @@ -27,19 +29,18 @@ namespace WEX { return WEX::Common::NoThrowString().Format( L"Length:%d, attr:%s", tar.GetLength(), - VerifyOutputTraits::ToString(tar.GetAttributes()).GetBuffer() - ); + VerifyOutputTraits::ToString(tar.GetAttributes()).GetBuffer()); } }; template<> - class VerifyCompareTraits + class VerifyCompareTraits { public: static bool AreEqual(const TextAttributeRun& expected, const TextAttributeRun& actual) { return expected.GetAttributes() == actual.GetAttributes() && - expected.GetLength() == actual.GetLength(); + expected.GetLength() == actual.GetLength(); } static bool AreSame(const TextAttributeRun& expected, const TextAttributeRun& actual) @@ -54,7 +55,7 @@ namespace WEX { static bool IsNull(const TextAttributeRun& object) { return object.GetAttributes().IsLegacy() && object.GetAttributes().GetLegacyAttributes() == 0 && - object.GetLength() == 0; + object.GetLength() == 0; } }; } @@ -293,7 +294,6 @@ class AttrRowTests insertRow[1].SetLength(uiChar2Length); } - LogChain(L"Insert: ", insertRow); Log::Comment(NoThrowString().Format(L"At Index: %d", uiStartPos)); @@ -453,7 +453,6 @@ class AttrRowTests TEST_METHOD(TestUnpackAttrs) { - Log::Comment(L"Checking unpack of a single color for the entire length"); { const std::vector attrs{ pSingle->begin(), pSingle->end() }; diff --git a/src/host/ut_host/CharRowBaseTests.cpp b/src/host/ut_host/CharRowBaseTests.cpp index e75f2cc5c..85abc4933 100644 --- a/src/host/ut_host/CharRowBaseTests.cpp +++ b/src/host/ut_host/CharRowBaseTests.cpp @@ -19,7 +19,7 @@ class CharRowBaseTests const size_t rowWidth = 80; const Ucs2CharRow::glyph_type ucs2Glyph = L'a'; // hiragana ka U+304B - const Utf8CharRow::glyph_type utf8Glyph = { '\xE3', '\x81', '\x8B'}; + const Utf8CharRow::glyph_type utf8Glyph = { '\xE3', '\x81', '\x8B' }; const Ucs2CharRow::glyph_type ucs2DefaultGlyph = UNICODE_SPACE; const Utf8CharRow::glyph_type utf8DefaultGlyph = { UNICODE_SPACE }; @@ -27,7 +27,6 @@ class CharRowBaseTests Ucs2CharRow::string_type ucs2Text = L"Loremipsumdolorsitamet,consecteturadipiscingelit.Nullametrutrummetus.Namquiseratal"; std::vector utf8Text; - Ucs2CharRow ucs2CharRow; Utf8CharRow utf8CharRow; @@ -50,14 +49,14 @@ class CharRowBaseTests { switch (pCharRow->GetSupportedEncoding()) { - case ICharRow::SupportedEncoding::Ucs2: - static_cast(pCharRow)->GetGlyphAt(column) = ucs2Glyph; - break; - case ICharRow::SupportedEncoding::Utf8: - static_cast(pCharRow)->GetGlyphAt(column) = utf8Glyph; - break; - default: - VERIFY_IS_TRUE(false); + case ICharRow::SupportedEncoding::Ucs2: + static_cast(pCharRow)->GetGlyphAt(column) = ucs2Glyph; + break; + case ICharRow::SupportedEncoding::Utf8: + static_cast(pCharRow)->GetGlyphAt(column) = utf8Glyph; + break; + default: + VERIFY_IS_TRUE(false); } } @@ -67,28 +66,28 @@ class CharRowBaseTests VERIFY_ARE_EQUAL(attrs.size(), rowWidth); switch (pCharRow->GetSupportedEncoding()) { - case ICharRow::SupportedEncoding::Ucs2: + case ICharRow::SupportedEncoding::Ucs2: + { + auto& cells = static_cast(pCharRow)->_data; + for (size_t i = 0; i < cells.size(); ++i) { - auto& cells = static_cast(pCharRow)->_data; - for (size_t i = 0; i < cells.size(); ++i) - { - cells[i].first = ucs2Text[i]; - cells[i].second = attrs[i]; - } - break; + cells[i].first = ucs2Text[i]; + cells[i].second = attrs[i]; } - case ICharRow::SupportedEncoding::Utf8: + break; + } + case ICharRow::SupportedEncoding::Utf8: + { + auto& cells = static_cast(pCharRow)->_data; + for (size_t i = 0; i < cells.size(); ++i) { - auto& cells = static_cast(pCharRow)->_data; - for (size_t i = 0; i < cells.size(); ++i) - { - cells[i].first = utf8Text[i]; - cells[i].second = attrs[i]; - } - break; + cells[i].first = utf8Text[i]; + cells[i].second = attrs[i]; } - default: - VERIFY_IS_TRUE(false); + break; + } + default: + VERIFY_IS_TRUE(false); } } @@ -121,22 +120,22 @@ class CharRowBaseTests // check that cell data was initialized correctly switch (pCharRow->GetSupportedEncoding()) { - case ICharRow::SupportedEncoding::Ucs2: - for (auto& cell : static_cast(pCharRow)->_data) - { - VERIFY_ARE_EQUAL(cell.first, ucs2DefaultGlyph); - VERIFY_IS_TRUE(cell.second.IsSingle()); - } - break; - case ICharRow::SupportedEncoding::Utf8: - for (auto& cell : static_cast(pCharRow)->_data) - { - VERIFY_ARE_EQUAL(cell.first, utf8DefaultGlyph); - VERIFY_IS_TRUE(cell.second.IsSingle()); - } - break; - default: - VERIFY_IS_TRUE(false); + case ICharRow::SupportedEncoding::Ucs2: + for (auto& cell : static_cast(pCharRow)->_data) + { + VERIFY_ARE_EQUAL(cell.first, ucs2DefaultGlyph); + VERIFY_IS_TRUE(cell.second.IsSingle()); + } + break; + case ICharRow::SupportedEncoding::Utf8: + for (auto& cell : static_cast(pCharRow)->_data) + { + VERIFY_ARE_EQUAL(cell.first, utf8DefaultGlyph); + VERIFY_IS_TRUE(cell.second.IsSingle()); + } + break; + default: + VERIFY_IS_TRUE(false); } } } @@ -165,6 +164,7 @@ class CharRowBaseTests for (ICharRow* const pCharRow : rows) { + // clang-format off std::vector, // locations to fill with characters size_t, // MeasureLeft value @@ -220,6 +220,7 @@ class CharRowBaseTests rowWidth - 2 }, }; + // clang-format on for (auto data : testData) { @@ -255,17 +256,17 @@ class CharRowBaseTests auto choice = rand() % 2; switch (choice) { - case 0: - attr.SetSingle(); - break; - case 1: - attr.SetLeading(); - break; - case 2: - attr.SetTrailing(); - break; - default: - VERIFY_IS_TRUE(false); + case 0: + attr.SetSingle(); + break; + case 1: + attr.SetLeading(); + break; + case 2: + attr.SetTrailing(); + break; + default: + VERIFY_IS_TRUE(false); } } @@ -287,40 +288,40 @@ class CharRowBaseTests switch (pCharRow->GetSupportedEncoding()) { - case ICharRow::SupportedEncoding::Ucs2: - // data not clipped should not have changed - for (size_t i = 0; i < smallSize; ++i) - { - auto cell = static_cast(pCharRow)->_data[i]; - VERIFY_ARE_EQUAL(cell.first, ucs2Text[i]); - VERIFY_ARE_EQUAL(cell.second, attrs[i]); - } - // newly added cells should be set to the defaults - for (size_t i = smallSize + 1; i < bigSize; ++i) - { - auto cell = static_cast(pCharRow)->_data[i]; - VERIFY_ARE_EQUAL(cell.first, ucs2DefaultGlyph); - VERIFY_IS_TRUE(cell.second.IsSingle()); - } - break; - case ICharRow::SupportedEncoding::Utf8: - // data not clipped should not have changed - for (size_t i = 0; i < smallSize; ++i) - { - auto cell = static_cast(pCharRow)->_data[i]; - VERIFY_ARE_EQUAL(cell.first, utf8Text[i]); - VERIFY_ARE_EQUAL(cell.second, attrs[i]); - } - // newly added cells should be set to the defaults - for (size_t i = smallSize + 1; i < bigSize; ++i) - { - auto cell = static_cast(pCharRow)->_data[i]; - VERIFY_ARE_EQUAL(cell.first, utf8DefaultGlyph); - VERIFY_IS_TRUE(cell.second.IsSingle()); - } - break; - default: - VERIFY_IS_TRUE(false); + case ICharRow::SupportedEncoding::Ucs2: + // data not clipped should not have changed + for (size_t i = 0; i < smallSize; ++i) + { + auto cell = static_cast(pCharRow)->_data[i]; + VERIFY_ARE_EQUAL(cell.first, ucs2Text[i]); + VERIFY_ARE_EQUAL(cell.second, attrs[i]); + } + // newly added cells should be set to the defaults + for (size_t i = smallSize + 1; i < bigSize; ++i) + { + auto cell = static_cast(pCharRow)->_data[i]; + VERIFY_ARE_EQUAL(cell.first, ucs2DefaultGlyph); + VERIFY_IS_TRUE(cell.second.IsSingle()); + } + break; + case ICharRow::SupportedEncoding::Utf8: + // data not clipped should not have changed + for (size_t i = 0; i < smallSize; ++i) + { + auto cell = static_cast(pCharRow)->_data[i]; + VERIFY_ARE_EQUAL(cell.first, utf8Text[i]); + VERIFY_ARE_EQUAL(cell.second, attrs[i]); + } + // newly added cells should be set to the defaults + for (size_t i = smallSize + 1; i < bigSize; ++i) + { + auto cell = static_cast(pCharRow)->_data[i]; + VERIFY_ARE_EQUAL(cell.first, utf8DefaultGlyph); + VERIFY_IS_TRUE(cell.second.IsSingle()); + } + break; + default: + VERIFY_IS_TRUE(false); } } } @@ -345,24 +346,24 @@ class CharRowBaseTests for (auto index : eraseIndices) { pCharRow->ClearCell(index); - switch(pCharRow->GetSupportedEncoding()) + switch (pCharRow->GetSupportedEncoding()) { - case ICharRow::SupportedEncoding::Ucs2: - { - auto& cell = static_cast(pCharRow)->_data[index]; - VERIFY_ARE_EQUAL(cell.first, ucs2DefaultGlyph); - VERIFY_ARE_EQUAL(cell.second, DbcsAttribute::Attribute::Single); - break; - } - case ICharRow::SupportedEncoding::Utf8: - { - auto& cell = static_cast(pCharRow)->_data[index]; - VERIFY_ARE_EQUAL(cell.first, utf8DefaultGlyph); - VERIFY_ARE_EQUAL(cell.second, DbcsAttribute::Attribute::Single); - break; - } - default: - VERIFY_IS_TRUE(false); + case ICharRow::SupportedEncoding::Ucs2: + { + auto& cell = static_cast(pCharRow)->_data[index]; + VERIFY_ARE_EQUAL(cell.first, ucs2DefaultGlyph); + VERIFY_ARE_EQUAL(cell.second, DbcsAttribute::Attribute::Single); + break; + } + case ICharRow::SupportedEncoding::Utf8: + { + auto& cell = static_cast(pCharRow)->_data[index]; + VERIFY_ARE_EQUAL(cell.first, utf8DefaultGlyph); + VERIFY_ARE_EQUAL(cell.second, DbcsAttribute::Attribute::Single); + break; + } + default: + VERIFY_IS_TRUE(false); } } } @@ -388,24 +389,24 @@ class CharRowBaseTests for (auto index : eraseIndices) { pCharRow->ClearGlyph(index); - switch(pCharRow->GetSupportedEncoding()) + switch (pCharRow->GetSupportedEncoding()) { - case ICharRow::SupportedEncoding::Ucs2: - { - auto& cell = static_cast(pCharRow)->_data[index]; - VERIFY_ARE_EQUAL(cell.first, ucs2DefaultGlyph); - VERIFY_ARE_EQUAL(cell.second, DbcsAttribute::Attribute::Leading); - break; - } - case ICharRow::SupportedEncoding::Utf8: - { - auto& cell = static_cast(pCharRow)->_data[index]; - VERIFY_ARE_EQUAL(cell.first, utf8DefaultGlyph); - VERIFY_ARE_EQUAL(cell.second, DbcsAttribute::Attribute::Leading); - break; - } - default: - VERIFY_IS_TRUE(false); + case ICharRow::SupportedEncoding::Ucs2: + { + auto& cell = static_cast(pCharRow)->_data[index]; + VERIFY_ARE_EQUAL(cell.first, ucs2DefaultGlyph); + VERIFY_ARE_EQUAL(cell.second, DbcsAttribute::Attribute::Leading); + break; + } + case ICharRow::SupportedEncoding::Utf8: + { + auto& cell = static_cast(pCharRow)->_data[index]; + VERIFY_ARE_EQUAL(cell.first, utf8DefaultGlyph); + VERIFY_ARE_EQUAL(cell.second, DbcsAttribute::Attribute::Leading); + break; + } + default: + VERIFY_IS_TRUE(false); } } } @@ -433,40 +434,40 @@ class CharRowBaseTests // fill cells with data SetCellData(pCharRow, attrs); - switch(pCharRow->GetSupportedEncoding()) + switch (pCharRow->GetSupportedEncoding()) { - case ICharRow::SupportedEncoding::Ucs2: + case ICharRow::SupportedEncoding::Ucs2: + { + Ucs2CharRow::string_type expectedText = L""; + for (size_t i = 0; i < ucs2Text.size(); ++i) { - Ucs2CharRow::string_type expectedText = L""; - for (size_t i = 0; i < ucs2Text.size(); ++i) + if (i % 2 == 0) { - if (i % 2 == 0) + expectedText += ucs2Text[i]; + } + } + VERIFY_ARE_EQUAL(expectedText, static_cast(pCharRow)->GetText()); + break; + } + case ICharRow::SupportedEncoding::Utf8: + { + Utf8CharRow::string_type expectedText = ""; + for (size_t i = 0; i < utf8Text.size(); ++i) + { + if (i % 2 == 0) + { + auto glyph = utf8Text[i]; + for (auto ch : glyph) { - expectedText += ucs2Text[i]; + expectedText += ch; } } - VERIFY_ARE_EQUAL(expectedText, static_cast(pCharRow)->GetText()); - break; } - case ICharRow::SupportedEncoding::Utf8: - { - Utf8CharRow::string_type expectedText = ""; - for (size_t i = 0; i < utf8Text.size(); ++i) - { - if (i % 2 == 0) - { - auto glyph = utf8Text[i]; - for (auto ch : glyph) - { - expectedText += ch; - } - } - } - VERIFY_ARE_EQUAL(expectedText, static_cast(pCharRow)->GetText()); - break; - } - default: - VERIFY_IS_TRUE(false); + VERIFY_ARE_EQUAL(expectedText, static_cast(pCharRow)->GetText()); + break; + } + default: + VERIFY_IS_TRUE(false); } } } @@ -482,36 +483,35 @@ class CharRowBaseTests SetCellData(pCharRow, attrs); // make sure data received from iterators matches data written - switch(pCharRow->GetSupportedEncoding()) + switch (pCharRow->GetSupportedEncoding()) { - case ICharRow::SupportedEncoding::Ucs2: + case ICharRow::SupportedEncoding::Ucs2: + { + size_t index = 0; + const Ucs2CharRow& charRow = *static_cast(pCharRow); + for (Ucs2CharRow::const_iterator it = charRow.cbegin(); it != charRow.cend(); ++it) { - size_t index = 0; - const Ucs2CharRow& charRow = *static_cast(pCharRow); - for (Ucs2CharRow::const_iterator it = charRow.cbegin(); it != charRow.cend(); ++it) - { - VERIFY_ARE_EQUAL(ucs2Text[index], it->first); - VERIFY_ARE_EQUAL(attrs[index], it->second); - ++index; - } - break; + VERIFY_ARE_EQUAL(ucs2Text[index], it->first); + VERIFY_ARE_EQUAL(attrs[index], it->second); + ++index; } - case ICharRow::SupportedEncoding::Utf8: + break; + } + case ICharRow::SupportedEncoding::Utf8: + { + size_t index = 0; + const Utf8CharRow& charRow = *static_cast(pCharRow); + for (Utf8CharRow::const_iterator it = charRow.cbegin(); it != charRow.cend(); ++it) { - size_t index = 0; - const Utf8CharRow& charRow = *static_cast(pCharRow); - for (Utf8CharRow::const_iterator it = charRow.cbegin(); it != charRow.cend(); ++it) - { - VERIFY_ARE_EQUAL(utf8Text[index], it->first); - VERIFY_ARE_EQUAL(attrs[index], it->second); - ++index; - } - break; + VERIFY_ARE_EQUAL(utf8Text[index], it->first); + VERIFY_ARE_EQUAL(attrs[index], it->second); + ++index; } - default: - VERIFY_IS_TRUE(false); + break; + } + default: + VERIFY_IS_TRUE(false); } } } - }; diff --git a/src/host/ut_host/ClipboardTests.cpp b/src/host/ut_host/ClipboardTests.cpp index 99fa9b193..689ee8428 100644 --- a/src/host/ut_host/ClipboardTests.cpp +++ b/src/host/ut_host/ClipboardTests.cpp @@ -22,7 +22,6 @@ #include "UnicodeLiteral.hpp" #include "../../inc/consoletaeftemplates.hpp" - using namespace WEX::Common; using namespace WEX::Logging; using namespace WEX::TestExecution; @@ -88,11 +87,12 @@ class ClipboardTests return Clipboard::Instance().RetrieveTextFromBuffer(screenInfo, fLineSelection, - selection).text; + selection) + .text; } #pragma prefast(push) -#pragma prefast(disable:26006, "Specifically trying to check unterminated strings in this test.") +#pragma prefast(disable : 26006, "Specifically trying to check unterminated strings in this test.") TEST_METHOD(TestRetrieveFromBuffer) { // NOTE: This test requires innate knowledge of how the common buffer text is emitted in order to test all cases @@ -131,7 +131,6 @@ class ClipboardTests // NOTE: This test requires innate knowledge of how the common buffer text is emitted in order to test all cases // Please see CommonState.hpp for information on the buffer state per row, the row contents, etc. - std::vector selection; const auto text = SetupRetrieveFromBuffers(true, selection); @@ -201,7 +200,6 @@ class ClipboardTests std::deque> events = Clipboard::Instance().TextToKeyEvents(wstr.c_str(), wstr.size()); - VERIFY_ARE_EQUAL((wstr.size() + uppercaseCount) * 2, events.size()); IInputServices* pInputServices = ServiceLocator::LocateInputServices(); VERIFY_IS_NOT_NULL(pInputServices); @@ -317,11 +315,11 @@ class ClipboardTests VERIFY_ARE_EQUAL(convertedSize, events.size()); std::deque expectedEvents; - expectedEvents.push_back({ TRUE, 1, VK_MENU, altScanCode, L'\0', LEFT_ALT_PRESSED }); - expectedEvents.push_back({ TRUE, 1, 0x66, 0x4D, L'\0', LEFT_ALT_PRESSED }); - expectedEvents.push_back({ FALSE, 1, 0x66, 0x4D, L'\0', LEFT_ALT_PRESSED }); - expectedEvents.push_back({ TRUE, 1, 0x63, 0x51, L'\0', LEFT_ALT_PRESSED }); - expectedEvents.push_back({ FALSE, 1, 0x63, 0x51, L'\0', LEFT_ALT_PRESSED }); + expectedEvents.push_back({ TRUE, 1, VK_MENU, altScanCode, L'\0', LEFT_ALT_PRESSED }); + expectedEvents.push_back({ TRUE, 1, 0x66, 0x4D, L'\0', LEFT_ALT_PRESSED }); + expectedEvents.push_back({ FALSE, 1, 0x66, 0x4D, L'\0', LEFT_ALT_PRESSED }); + expectedEvents.push_back({ TRUE, 1, 0x63, 0x51, L'\0', LEFT_ALT_PRESSED }); + expectedEvents.push_back({ FALSE, 1, 0x63, 0x51, L'\0', LEFT_ALT_PRESSED }); expectedEvents.push_back({ FALSE, 1, VK_MENU, altScanCode, wstr[0], 0 }); for (size_t i = 0; i < events.size(); ++i) @@ -330,4 +328,4 @@ class ClipboardTests VERIFY_ARE_EQUAL(expectedEvents[i], currentKeyEvent, NoThrowString().Format(L"i == %d", i)); } } - }; +}; diff --git a/src/host/ut_host/CodepointWidthDetectorTests.cpp b/src/host/ut_host/CodepointWidthDetectorTests.cpp index 4e0071781..ca8dd3373 100644 --- a/src/host/ut_host/CodepointWidthDetectorTests.cpp +++ b/src/host/ut_host/CodepointWidthDetectorTests.cpp @@ -15,8 +15,7 @@ static constexpr std::wstring_view emoji = L"\xD83E\xDD22"; // U+1F922 nauseated static constexpr std::wstring_view ambiguous = L"\x414"; // U+0414 cyrillic capital de // codepoint and utf16 encoded string -static const std::vector> testData = -{ +static const std::vector> testData = { { 0x7, L"\a", CodepointWidth::Narrow }, // BEL { 0x20, L" ", CodepointWidth::Narrow }, { 0x39, L"9", CodepointWidth::Narrow }, @@ -33,7 +32,6 @@ class CodepointWidthDetectorTests { TEST_CLASS(CodepointWidthDetectorTests); - TEST_METHOD(CodepointWidthDetectDefersMapPopulation) { CodepointWidthDetector widthDetector; @@ -120,5 +118,4 @@ class CodepointWidthDetectorTests widthDetector.NotifyFontChanged(); VERIFY_ARE_EQUAL(0u, widthDetector._fallbackCache.size()); } - }; diff --git a/src/host/ut_host/CommandLineTests.cpp b/src/host/ut_host/CommandLineTests.cpp index 81736aed6..4f089a557 100644 --- a/src/host/ut_host/CommandLineTests.cpp +++ b/src/host/ut_host/CommandLineTests.cpp @@ -11,7 +11,6 @@ #include "../cmdline.h" - using namespace WEX::Common; using namespace WEX::Logging; using namespace WEX::TestExecution; @@ -261,7 +260,6 @@ class CommandLineTests VERIFY_ARE_EQUAL(cursorPos.X, gsl::narrow(expectedCursorPos)); VERIFY_ARE_EQUAL(cookedReadData._currentPosition, expectedCursorPos); VERIFY_ARE_EQUAL(cookedReadData._bufPtr, expectedBufferPos); - } TEST_METHOD(CanMoveCursorToStartOfPrompt) diff --git a/src/host/ut_host/CommandListPopupTests.cpp b/src/host/ut_host/CommandListPopupTests.cpp index c9da3ec0b..69e999479 100644 --- a/src/host/ut_host/CommandListPopupTests.cpp +++ b/src/host/ut_host/CommandListPopupTests.cpp @@ -89,8 +89,7 @@ class CommandListPopupTests TEST_METHOD(CanDismiss) { // function to simulate user pressing escape key - Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) - { + Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) { popupKey = true; modifiers = 0; wch = VK_ESCAPE; @@ -126,8 +125,7 @@ class CommandListPopupTests TEST_METHOD(UpMovesSelection) { // function to simulate user pressing up arrow - Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) - { + Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) { static bool firstTime = true; if (firstTime) { @@ -165,8 +163,7 @@ class CommandListPopupTests TEST_METHOD(DownMovesSelection) { // function to simulate user pressing down arrow - Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) - { + Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) { static bool firstTime = true; if (firstTime) { @@ -206,8 +203,7 @@ class CommandListPopupTests TEST_METHOD(EndMovesSelectionToEnd) { // function to simulate user pressing end key - Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) - { + Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) { static bool firstTime = true; if (firstTime) { @@ -246,8 +242,7 @@ class CommandListPopupTests TEST_METHOD(HomeMovesSelectionToStart) { // function to simulate user pressing home key - Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) - { + Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) { static bool firstTime = true; if (firstTime) { @@ -284,8 +279,7 @@ class CommandListPopupTests TEST_METHOD(PageUpMovesSelection) { // function to simulate user pressing page up key - Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) - { + Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) { static bool firstTime = true; if (firstTime) { @@ -322,8 +316,7 @@ class CommandListPopupTests TEST_METHOD(PageDownMovesSelection) { // function to simulate user pressing page down key - Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) - { + Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) { static bool firstTime = true; if (firstTime) { @@ -362,8 +355,7 @@ class CommandListPopupTests TEST_METHOD(SideArrowsFillsPrompt) { // function to simulate user pressing right arrow key - Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) - { + Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) { wch = VK_RIGHT; popupKey = true; modifiers = 0; @@ -395,8 +387,7 @@ class CommandListPopupTests TEST_METHOD(CanLaunchCommandNumberPopup) { // function to simulate user pressing F9 - Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) - { + Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) { wch = VK_F9; popupKey = true; modifiers = 0; @@ -422,14 +413,12 @@ class CommandListPopupTests auto scopeExit = wil::scope_exit([&]() { commandLine.EndAllPopups(); }); VERIFY_ARE_EQUAL(popup.Process(cookedReadData), static_cast(CONSOLE_STATUS_WAIT)); VERIFY_IS_TRUE(commandLine.HasPopup()); - } TEST_METHOD(CanDeleteFromCommandHistory) { // function to simulate user pressing the delete key - Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) - { + Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) { static bool firstTime = true; if (firstTime) { @@ -466,8 +455,7 @@ class CommandListPopupTests TEST_METHOD(CanReorderHistoryUp) { // function to simulate user pressing shift + up arrow - Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) - { + Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) { static bool firstTime = true; if (firstTime) { @@ -506,8 +494,7 @@ class CommandListPopupTests TEST_METHOD(CanReorderHistoryDown) { // function to simulate user pressing the up arrow, then shift + down arrow, then escape - Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) - { + Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) { static unsigned int count = 0; if (count == 0) { diff --git a/src/host/ut_host/CommandNumberPopupTests.cpp b/src/host/ut_host/CommandNumberPopupTests.cpp index 649f4d9f6..0716e017a 100644 --- a/src/host/ut_host/CommandNumberPopupTests.cpp +++ b/src/host/ut_host/CommandNumberPopupTests.cpp @@ -13,7 +13,6 @@ #include "../CommandNumberPopup.hpp" #include "../CommandListPopup.hpp" - using namespace WEX::Common; using namespace WEX::Logging; using namespace WEX::TestExecution; @@ -69,8 +68,7 @@ class CommandNumberPopupTests TEST_METHOD(CanDismiss) { // function to simulate user pressing escape key - Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) - { + Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) { popupKey = true; wch = VK_ESCAPE; modifiers = 0; @@ -109,8 +107,7 @@ class CommandNumberPopupTests // CommanNumberPopup is the only popup that can act as a 2nd popup. make sure that it dismisses all // popups when exiting // function to simulate user pressing escape key - Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) - { + Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) { popupKey = true; wch = VK_ESCAPE; modifiers = 0; @@ -139,14 +136,12 @@ class CommandNumberPopupTests VERIFY_ARE_EQUAL(numberPopup.Process(cookedReadData), static_cast(CONSOLE_STATUS_WAIT_NO_BLOCK)); VERIFY_IS_FALSE(commandLine.HasPopup()); - } TEST_METHOD(EmptyInputCountsAsOldestHistory) { Log::Comment(L"hitting enter with no input should grab the oldest history item"); - Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) - { + Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) { popupKey = false; wch = UNICODE_CARRIAGERETURN; modifiers = 0; @@ -183,8 +178,7 @@ class CommandNumberPopupTests Popup::UserInputFunction fn = [historyIndex](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, - wchar_t& wch) - { + wchar_t& wch) { static bool needReturn = false; popupKey = false; modifiers = 0; @@ -229,8 +223,7 @@ class CommandNumberPopupTests Log::Comment(L"entering a number larger than the number of history items should grab the most recent history item"); // simulates user pressing 1, 2, 3, 4, 5, enter - Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) - { + Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) { static int num = 1; popupKey = false; modifiers = 0; diff --git a/src/host/ut_host/ConsoleArgumentsTests.cpp b/src/host/ut_host/ConsoleArgumentsTests.cpp index 8338b46ed..a8b0bd825 100644 --- a/src/host/ut_host/ConsoleArgumentsTests.cpp +++ b/src/host/ut_host/ConsoleArgumentsTests.cpp @@ -32,7 +32,6 @@ public: TEST_METHOD(HeadlessArgTests); TEST_METHOD(SignalHandleTests); TEST_METHOD(FeatureArgTests); - }; ConsoleArguments CreateAndParse(std::wstring& commandline, HANDLE hVtIn, HANDLE hVtOut) @@ -55,8 +54,8 @@ void ArgTestsRunner(LPCWSTR comment, std::wstring commandline, HANDLE hVtIn, HAN Log::Comment(comment); Log::Comment(commandline.c_str()); const ConsoleArguments actual = shouldBeSuccessful ? - CreateAndParse(commandline, hVtIn, hVtOut) : - CreateAndParseUnsuccessfully(commandline, hVtIn, hVtOut); + CreateAndParse(commandline, hVtIn, hVtOut) : + CreateAndParseUnsuccessfully(commandline, hVtIn, hVtOut); VERIFY_ARE_EQUAL(expected, actual); } @@ -82,7 +81,7 @@ void ConsoleArgumentsTests::ArgSplittingTests() true, // createServerHandle 0, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? commandline = L"conhost.exe \"this is the commandline\""; @@ -102,7 +101,7 @@ void ConsoleArgumentsTests::ArgSplittingTests() true, // createServerHandle 0, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? commandline = L"conhost.exe --headless \"--vtmode bar this is the commandline\""; @@ -122,7 +121,7 @@ void ConsoleArgumentsTests::ArgSplittingTests() true, // createServerHandle 0, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? commandline = L"conhost.exe --headless --server 0x4 this is the commandline"; @@ -142,7 +141,7 @@ void ConsoleArgumentsTests::ArgSplittingTests() false, // createServerHandle 0x4, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? commandline = L"conhost.exe --headless\t--vtmode\txterm\tthis\tis\tthe\tcommandline"; @@ -162,7 +161,7 @@ void ConsoleArgumentsTests::ArgSplittingTests() true, // createServerHandle 0, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? commandline = L"conhost.exe --headless\\ foo\\ --outpipe\\ bar\\ this\\ is\\ the\\ commandline"; @@ -182,7 +181,7 @@ void ConsoleArgumentsTests::ArgSplittingTests() true, // createServerHandle 0, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? commandline = L"conhost.exe --headless\\\tfoo\\\t--outpipe\\\tbar\\\tthis\\\tis\\\tthe\\\tcommandline"; @@ -202,7 +201,7 @@ void ConsoleArgumentsTests::ArgSplittingTests() true, // createServerHandle 0, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? commandline = L"conhost.exe --vtmode a\\\\\\\\\"b c\" d e"; @@ -222,7 +221,7 @@ void ConsoleArgumentsTests::ArgSplittingTests() true, // createServerHandle 0, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? } @@ -247,7 +246,7 @@ void ConsoleArgumentsTests::ClientCommandlineTests() true, // createServerHandle 0, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? commandline = L"conhost.exe foo"; @@ -267,7 +266,7 @@ void ConsoleArgumentsTests::ClientCommandlineTests() true, // createServerHandle 0, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? commandline = L"conhost.exe foo -- bar"; @@ -287,7 +286,7 @@ void ConsoleArgumentsTests::ClientCommandlineTests() true, // createServerHandle 0, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? commandline = L"conhost.exe --vtmode foo foo -- bar"; @@ -307,7 +306,7 @@ void ConsoleArgumentsTests::ClientCommandlineTests() true, // createServerHandle 0, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? commandline = L"conhost.exe console --vtmode foo foo -- bar"; @@ -327,7 +326,7 @@ void ConsoleArgumentsTests::ClientCommandlineTests() true, // createServerHandle 0, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? commandline = L"conhost.exe console --vtmode foo --outpipe foo -- bar"; @@ -347,7 +346,7 @@ void ConsoleArgumentsTests::ClientCommandlineTests() true, // createServerHandle 0, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? commandline = L"conhost.exe --vtmode foo -- --outpipe foo bar"; @@ -367,7 +366,7 @@ void ConsoleArgumentsTests::ClientCommandlineTests() true, // createServerHandle 0, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? commandline = L"conhost.exe --vtmode -- --headless bar"; @@ -387,7 +386,7 @@ void ConsoleArgumentsTests::ClientCommandlineTests() true, // createServerHandle 0, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? commandline = L"conhost.exe --"; @@ -407,7 +406,7 @@ void ConsoleArgumentsTests::ClientCommandlineTests() true, // createServerHandle 0, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? commandline = L"conhost.exe"; @@ -427,7 +426,7 @@ void ConsoleArgumentsTests::ClientCommandlineTests() true, // createServerHandle 0, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? } @@ -452,7 +451,7 @@ void ConsoleArgumentsTests::LegacyFormatsTests() false, // createServerHandle 4ul, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? commandline = L"conhost.exe --server 0x4"; @@ -472,7 +471,7 @@ void ConsoleArgumentsTests::LegacyFormatsTests() false, // createServerHandle 4ul, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? commandline = L"conhost.exe 0x4 0x8"; @@ -492,7 +491,7 @@ void ConsoleArgumentsTests::LegacyFormatsTests() false, // createServerHandle 4ul, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor false); // successful parse? commandline = L"conhost.exe --server 0x4 0x8"; @@ -512,7 +511,7 @@ void ConsoleArgumentsTests::LegacyFormatsTests() false, // createServerHandle 4ul, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor false); // successful parse? commandline = L"conhost.exe 0x4 --server 0x8"; @@ -532,7 +531,7 @@ void ConsoleArgumentsTests::LegacyFormatsTests() false, // createServerHandle 4ul, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor false); // successful parse? commandline = L"conhost.exe --server 0x4 --server 0x8"; @@ -552,7 +551,7 @@ void ConsoleArgumentsTests::LegacyFormatsTests() false, // createServerHandle 4ul, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor false); // successful parse? commandline = L"conhost.exe 0x4 -ForceV1"; @@ -572,7 +571,7 @@ void ConsoleArgumentsTests::LegacyFormatsTests() false, // createServerHandle 4ul, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? commandline = L"conhost.exe -ForceV1"; @@ -592,7 +591,7 @@ void ConsoleArgumentsTests::LegacyFormatsTests() true, // createServerHandle 0, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? } @@ -641,7 +640,7 @@ void ConsoleArgumentsTests::CombineVtPipeHandleTests() true, // createServerHandle 0ul, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? commandline = L"conhost.exe --vtmode telnet"; @@ -661,7 +660,7 @@ void ConsoleArgumentsTests::CombineVtPipeHandleTests() true, // createServerHandle 0ul, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? } @@ -696,8 +695,8 @@ void ConsoleArgumentsTests::InitialSizeTests() true, // createServerHandle 0ul, // serverHandle 0, // signalHandle - false ), // inheritCursor - true); // successful parse? + false), // inheritCursor + true); // successful parse? commandline = L"conhost.exe --width 120"; ArgTestsRunner(L"#2 look for a valid commandline with only width", @@ -716,7 +715,7 @@ void ConsoleArgumentsTests::InitialSizeTests() true, // createServerHandle 0ul, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? commandline = L"conhost.exe --height 30"; @@ -736,7 +735,7 @@ void ConsoleArgumentsTests::InitialSizeTests() true, // createServerHandle 0ul, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? commandline = L"conhost.exe --width 0"; @@ -756,7 +755,7 @@ void ConsoleArgumentsTests::InitialSizeTests() true, // createServerHandle 0ul, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? commandline = L"conhost.exe --width -1"; @@ -776,7 +775,7 @@ void ConsoleArgumentsTests::InitialSizeTests() true, // createServerHandle 0ul, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? commandline = L"conhost.exe --width foo"; @@ -796,7 +795,7 @@ void ConsoleArgumentsTests::InitialSizeTests() true, // createServerHandle 0ul, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor false); // successful parse? commandline = L"conhost.exe --width 2foo"; @@ -816,7 +815,7 @@ void ConsoleArgumentsTests::InitialSizeTests() true, // createServerHandle 0ul, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor false); // successful parse? commandline = L"conhost.exe --width 65535"; @@ -836,9 +835,8 @@ void ConsoleArgumentsTests::InitialSizeTests() true, // createServerHandle 0ul, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor false); // successful parse? - } void ConsoleArgumentsTests::HeadlessArgTests() @@ -862,7 +860,7 @@ void ConsoleArgumentsTests::HeadlessArgTests() true, // createServerHandle 0, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? commandline = L"conhost.exe --headless 0x4"; @@ -882,7 +880,7 @@ void ConsoleArgumentsTests::HeadlessArgTests() false, // createServerHandle 4ul, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? commandline = L"conhost.exe --headless --headless"; @@ -902,7 +900,7 @@ void ConsoleArgumentsTests::HeadlessArgTests() true, // createServerHandle 0, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? commandline = L"conhost.exe -- foo.exe --headless"; @@ -922,7 +920,7 @@ void ConsoleArgumentsTests::HeadlessArgTests() true, // createServerHandle 0, // serverHandle 0, // signalHandle - false ), // inheritCursor + false), // inheritCursor true); // successful parse? } diff --git a/src/host/ut_host/CopyFromCharPopupTests.cpp b/src/host/ut_host/CopyFromCharPopupTests.cpp index 132a42fc0..d303e7305 100644 --- a/src/host/ut_host/CopyFromCharPopupTests.cpp +++ b/src/host/ut_host/CopyFromCharPopupTests.cpp @@ -12,7 +12,6 @@ #include "../CopyFromCharPopup.hpp" - using namespace WEX::Common; using namespace WEX::Logging; using namespace WEX::TestExecution; @@ -60,8 +59,7 @@ class CopyFromCharPopupTests TEST_METHOD(CanDismiss) { // function to simulate user pressing escape key - Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) - { + Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) { popupKey = true; wch = VK_ESCAPE; modifiers = 0; @@ -94,8 +92,7 @@ class CopyFromCharPopupTests TEST_METHOD(DeleteAllWhenCharNotFound) { - Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) - { + Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) { popupKey = false; wch = L'x'; modifiers = 0; @@ -125,8 +122,7 @@ class CopyFromCharPopupTests TEST_METHOD(CanDeletePartialLine) { - Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) - { + Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) { popupKey = false; wch = L'f'; modifiers = 0; diff --git a/src/host/ut_host/CopyToCharPopupTests.cpp b/src/host/ut_host/CopyToCharPopupTests.cpp index 5e64e1c76..f6422a266 100644 --- a/src/host/ut_host/CopyToCharPopupTests.cpp +++ b/src/host/ut_host/CopyToCharPopupTests.cpp @@ -67,8 +67,7 @@ class CopyToCharPopupTests TEST_METHOD(CanDismiss) { // function to simulate user pressing escape key - Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) - { + Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) { popupKey = true; wch = VK_ESCAPE; modifiers = 0; @@ -104,8 +103,7 @@ class CopyToCharPopupTests TEST_METHOD(NothingHappensWhenCharNotFound) { // function to simulate user pressing escape key - Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) - { + Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) { popupKey = true; wch = L'x'; modifiers = 0; @@ -135,8 +133,7 @@ class CopyToCharPopupTests TEST_METHOD(CanCopyToEmptyPrompt) { // function to simulate user pressing escape key - Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) - { + Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) { popupKey = true; wch = L's'; modifiers = 0; @@ -173,8 +170,7 @@ class CopyToCharPopupTests TEST_METHOD(WontCopyTextBeforeCursor) { // function to simulate user pressing escape key - Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) - { + Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) { popupKey = true; wch = L's'; modifiers = 0; @@ -208,14 +204,12 @@ class CopyToCharPopupTests VERIFY_ARE_EQUAL(resultText, testString); // make sure that more wasn't copied VERIFY_ARE_EQUAL(buffer[testString.size()], UNICODE_SPACE); - } TEST_METHOD(CanMergeLine) { // function to simulate user pressing escape key - Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) - { + Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) { popupKey = true; wch = L's'; modifiers = 0; @@ -245,5 +239,4 @@ class CopyToCharPopupTests // make sure that more wasn't copied VERIFY_ARE_EQUAL(buffer[expectedText.size()], UNICODE_SPACE); } - }; diff --git a/src/host/ut_host/DbcsTests.cpp b/src/host/ut_host/DbcsTests.cpp index 9f260410c..e62d70e7b 100644 --- a/src/host/ut_host/DbcsTests.cpp +++ b/src/host/ut_host/DbcsTests.cpp @@ -86,6 +86,5 @@ class DbcsTests VERIFY_ARE_EQUAL(rgci[i].Attributes, 0); } } - } }; diff --git a/src/host/ut_host/HistoryTests.cpp b/src/host/ut_host/HistoryTests.cpp index f6823b492..37bedaf52 100644 --- a/src/host/ut_host/HistoryTests.cpp +++ b/src/host/ut_host/HistoryTests.cpp @@ -243,9 +243,7 @@ class HistoryTests } private: - - const std::array _manyApps = - { + const std::array _manyApps = { L"foo.exe", L"bar.exe", L"baz.exe", @@ -253,8 +251,7 @@ private: L"banana.exe" }; - const std::array _manyHistoryItems = - { + const std::array _manyHistoryItems = { L"dir", L"dir /w", L"dir /p /w", diff --git a/src/host/ut_host/InitTests.cpp b/src/host/ut_host/InitTests.cpp index f390138c5..b3e32603e 100644 --- a/src/host/ut_host/InitTests.cpp +++ b/src/host/ut_host/InitTests.cpp @@ -91,6 +91,5 @@ class InitTests { VERIFY_ARE_EQUAL(STATUS_NOT_SUPPORTED, status); } - } }; diff --git a/src/host/ut_host/InputBufferTests.cpp b/src/host/ut_host/InputBufferTests.cpp index 24398ff4d..70e44ee0a 100644 --- a/src/host/ut_host/InputBufferTests.cpp +++ b/src/host/ut_host/InputBufferTests.cpp @@ -648,5 +648,4 @@ class InputBufferTests VERIFY_ARE_EQUAL(static_cast(*inputBuffer._storage.front()).GetRepeatCount(), repeatCount); VERIFY_ARE_EQUAL(static_cast(*outEvents.front()).GetRepeatCount(), 1u); } - }; diff --git a/src/host/ut_host/OutputCellIteratorTests.cpp b/src/host/ut_host/OutputCellIteratorTests.cpp index 000e313b6..c379f06ce 100644 --- a/src/host/ut_host/OutputCellIteratorTests.cpp +++ b/src/host/ut_host/OutputCellIteratorTests.cpp @@ -413,9 +413,9 @@ class OutputCellIteratorTests for (const auto& ci : charInfos) { - auto expected = OutputCellView({&ci.Char.UnicodeChar, 1}, + auto expected = OutputCellView({ &ci.Char.UnicodeChar, 1 }, {}, - { ci.Attributes}, + { ci.Attributes }, TextAttributeBehavior::Stored); VERIFY_IS_TRUE(it); diff --git a/src/host/ut_host/PopupTestHelper.hpp b/src/host/ut_host/PopupTestHelper.hpp index 0cb8f7968..43076e031 100644 --- a/src/host/ut_host/PopupTestHelper.hpp +++ b/src/host/ut_host/PopupTestHelper.hpp @@ -14,17 +14,14 @@ Author(s): --*/ - #pragma once #include "../history.h" #include "../readDataCooked.hpp" - class PopupTestHelper final { public: - static void InitReadData(COOKED_READ_DATA& cookedReadData, wchar_t* const pBuffer, const size_t cchBuffer, @@ -84,5 +81,4 @@ public: VERIFY_SUCCEEDED(history.Add(L"~ Emily Dickinson", false)); VERIFY_ARE_EQUAL(history.GetNumberOfCommands(), 28u); } - }; diff --git a/src/host/ut_host/ScreenBufferTests.cpp b/src/host/ut_host/ScreenBufferTests.cpp index 2d2d67cd7..81aab7b35 100644 --- a/src/host/ut_host/ScreenBufferTests.cpp +++ b/src/host/ut_host/ScreenBufferTests.cpp @@ -64,13 +64,12 @@ class ScreenBufferTests gci.SetDefaultBackgroundColor(INVALID_COLOR); gci.SetFillAttribute(0x07); // DARK_WHITE on DARK_BLACK - m_state->PrepareNewTextBufferInfo(); auto& currentBuffer = gci.GetActiveOutputBuffer(); // Make sure a test hasn't left us in the alt buffer on accident VERIFY_IS_FALSE(currentBuffer._IsAltBuffer()); - VERIFY_SUCCEEDED(currentBuffer.SetViewportOrigin(true, {0, 0}, true)); - VERIFY_ARE_EQUAL(COORD({0, 0}), currentBuffer.GetTextBuffer().GetCursor().GetPosition()); + VERIFY_SUCCEEDED(currentBuffer.SetViewportOrigin(true, { 0, 0 }, true)); + VERIFY_ARE_EQUAL(COORD({ 0, 0 }), currentBuffer.GetTextBuffer().GetCursor().GetPosition()); return true; } @@ -163,7 +162,6 @@ class ScreenBufferTests TEST_METHOD(ScrollUpInMargins); TEST_METHOD(ScrollDownInMargins); - }; void ScreenBufferTests::SingleAlternateBufferCreationTest() @@ -178,7 +176,7 @@ void ScreenBufferTests::SingleAlternateBufferCreationTest() VERIFY_IS_NULL(psiOriginal->_psiMainBuffer); NTSTATUS Status = psiOriginal->UseAlternateScreenBuffer(); - if(VERIFY_IS_TRUE(NT_SUCCESS(Status))) + if (VERIFY_IS_TRUE(NT_SUCCESS(Status))) { Log::Comment(L"First alternate buffer successfully created"); SCREEN_INFORMATION* const psiFirstAlternate = &gci.GetActiveOutputBuffer(); @@ -207,12 +205,11 @@ void ScreenBufferTests::MultipleAlternateBufferCreationTest() Log::Comment( L"Testing creating one alternate buffer, then creating another " L"alternate from that first alternate, before returning to the " - L"main buffer." - ); + L"main buffer."); SCREEN_INFORMATION* const psiOriginal = &gci.GetActiveOutputBuffer(); NTSTATUS Status = psiOriginal->UseAlternateScreenBuffer(); - if(VERIFY_IS_TRUE(NT_SUCCESS(Status))) + if (VERIFY_IS_TRUE(NT_SUCCESS(Status))) { Log::Comment(L"First alternate buffer successfully created"); SCREEN_INFORMATION* const psiFirstAlternate = &gci.GetActiveOutputBuffer(); @@ -223,7 +220,7 @@ void ScreenBufferTests::MultipleAlternateBufferCreationTest() VERIFY_IS_NULL(psiFirstAlternate->_psiAlternateBuffer); Status = psiFirstAlternate->UseAlternateScreenBuffer(); - if(VERIFY_IS_TRUE(NT_SUCCESS(Status))) + if (VERIFY_IS_TRUE(NT_SUCCESS(Status))) { Log::Comment(L"Second alternate buffer successfully created"); SCREEN_INFORMATION* psiSecondAlternate = &gci.GetActiveOutputBuffer(); @@ -254,11 +251,10 @@ void ScreenBufferTests::MultipleAlternateBuffersFromMainCreationTest() Log::Comment( L"Testing creating one alternate buffer, then creating another" - L" alternate from the main, before returning to the main buffer." - ); + L" alternate from the main, before returning to the main buffer."); SCREEN_INFORMATION* const psiOriginal = &gci.GetActiveOutputBuffer(); NTSTATUS Status = psiOriginal->UseAlternateScreenBuffer(); - if(VERIFY_IS_TRUE(NT_SUCCESS(Status))) + if (VERIFY_IS_TRUE(NT_SUCCESS(Status))) { Log::Comment(L"First alternate buffer successfully created"); SCREEN_INFORMATION* const psiFirstAlternate = &gci.GetActiveOutputBuffer(); @@ -269,7 +265,7 @@ void ScreenBufferTests::MultipleAlternateBuffersFromMainCreationTest() VERIFY_IS_NULL(psiFirstAlternate->_psiAlternateBuffer); Status = psiOriginal->UseAlternateScreenBuffer(); - if(VERIFY_IS_TRUE(NT_SUCCESS(Status))) + if (VERIFY_IS_TRUE(NT_SUCCESS(Status))) { Log::Comment(L"Second alternate buffer successfully created"); SCREEN_INFORMATION* const psiSecondAlternate = &gci.GetActiveOutputBuffer(); @@ -318,12 +314,14 @@ void ScreenBufferTests::TestReverseLineFeed() VERIFY_ARE_EQUAL(viewport.Top(), 0); Log::Comment(NoThrowString().Format( L"viewport={L:%d,T:%d,R:%d,B:%d}", - viewport.Left(), viewport.Top(), viewport.RightInclusive(), viewport.BottomInclusive() - )); + viewport.Left(), + viewport.Top(), + viewport.RightInclusive(), + viewport.BottomInclusive())); //////////////////////////////////////////////////////////////////////// Log::Comment(L"Case 2: RI from top of viewport"); - cursor.SetPosition({0, 0}); + cursor.SetPosition({ 0, 0 }); stateMachine.ProcessString(L"123456789", 9); VERIFY_ARE_EQUAL(cursor.GetPosition().X, 9); VERIFY_ARE_EQUAL(cursor.GetPosition().Y, 0); @@ -337,16 +335,18 @@ void ScreenBufferTests::TestReverseLineFeed() VERIFY_ARE_EQUAL(viewport.Top(), 0); Log::Comment(NoThrowString().Format( L"viewport={L:%d,T:%d,R:%d,B:%d}", - viewport.Left(), viewport.Top(), viewport.RightInclusive(), viewport.BottomInclusive() - )); + viewport.Left(), + viewport.Top(), + viewport.RightInclusive(), + viewport.BottomInclusive())); auto c = screenInfo._textBuffer->GetLastNonSpaceCharacter(); VERIFY_ARE_EQUAL(c.Y, 2); // This is the coordinates of the second "foo" from before. //////////////////////////////////////////////////////////////////////// Log::Comment(L"Case 3: RI from top of viewport, when viewport is below top of buffer"); - cursor.SetPosition({0, 5}); - VERIFY_SUCCEEDED(screenInfo.SetViewportOrigin(true, {0, 5}, true)); + cursor.SetPosition({ 0, 5 }); + VERIFY_SUCCEEDED(screenInfo.SetViewportOrigin(true, { 0, 5 }, true)); stateMachine.ProcessString(L"ABCDEFGH", 9); VERIFY_ARE_EQUAL(cursor.GetPosition().X, 9); VERIFY_ARE_EQUAL(cursor.GetPosition().Y, 5); @@ -360,8 +360,10 @@ void ScreenBufferTests::TestReverseLineFeed() VERIFY_ARE_EQUAL(viewport.Top(), 5); Log::Comment(NoThrowString().Format( L"viewport={L:%d,T:%d,R:%d,B:%d}", - viewport.Left(), viewport.Top(), viewport.RightInclusive(), viewport.BottomInclusive() - )); + viewport.Left(), + viewport.Top(), + viewport.RightInclusive(), + viewport.BottomInclusive())); c = screenInfo._textBuffer->GetLastNonSpaceCharacter(); VERIFY_ARE_EQUAL(c.Y, 6); } @@ -656,8 +658,7 @@ void ScreenBufferTests::TestAltBufferDefaultTabStops() Log::Comment(NoThrowString().Format( L"Manually enable VT mode for the alt buffer - " - L"usually the ctor will pick this up from GCI, but not in the tests." - )); + L"usually the ctor will pick this up from GCI, but not in the tests.")); WI_SetFlag(altBuffer.OutputMode, ENABLE_VIRTUAL_TERMINAL_PROCESSING); VERIFY_IS_TRUE(WI_IsFlagSet(altBuffer.OutputMode, ENABLE_VIRTUAL_TERMINAL_PROCESSING)); @@ -670,25 +671,24 @@ void ScreenBufferTests::TestAltBufferDefaultTabStops() auto& stateMachine = altBuffer.GetStateMachine(); Log::Comment(NoThrowString().Format( - L"Tab a few times - make sure the cursor is where we expect." - )); + L"Tab a few times - make sure the cursor is where we expect.")); stateMachine.ProcessString(L"\t"); - COORD expected{8, 0}; + COORD expected{ 8, 0 }; VERIFY_ARE_EQUAL(expected, cursor.GetPosition()); stateMachine.ProcessString(L"\t"); - expected = {16, 0}; + expected = { 16, 0 }; VERIFY_ARE_EQUAL(expected, cursor.GetPosition()); stateMachine.ProcessString(L"\n"); - expected = {0, 1}; + expected = { 0, 1 }; VERIFY_ARE_EQUAL(expected, cursor.GetPosition()); altBuffer.ClearTabStops(); VERIFY_IS_FALSE(altBuffer.AreTabsSet()); stateMachine.ProcessString(L"\t"); - expected = {altBuffer.GetBufferSize().Width()-1, 1}; + expected = { altBuffer.GetBufferSize().Width() - 1, 1 }; VERIFY_ARE_EQUAL(expected, cursor.GetPosition()); @@ -710,7 +710,7 @@ void ScreenBufferTests::EraseAllTests() Log::Comment(L"Case 1: Erase a single line of text in the buffer\n"); stateMachine.ProcessString(L"foo", 3); - COORD originalRelativePosition = {3, 0}; + COORD originalRelativePosition = { 3, 0 }; VERIFY_ARE_EQUAL(si.GetViewport().Top(), 0); VERIFY_ARE_EQUAL(cursor.GetPosition(), originalRelativePosition); @@ -723,8 +723,10 @@ void ScreenBufferTests::EraseAllTests() VERIFY_ARE_EQUAL(cursor.GetPosition(), newRelativePos); Log::Comment(NoThrowString().Format( L"viewport={L:%d,T:%d,R:%d,B:%d}", - viewport.Left(), viewport.Top(), viewport.RightInclusive(), viewport.BottomInclusive() - )); + viewport.Left(), + viewport.Top(), + viewport.RightInclusive(), + viewport.BottomInclusive())); //////////////////////////////////////////////////////////////////////// Log::Comment(L"Case 2: Erase multiple lines, below the top of the buffer\n"); @@ -736,8 +738,10 @@ void ScreenBufferTests::EraseAllTests() VERIFY_ARE_EQUAL(viewport.Top(), 1); Log::Comment(NoThrowString().Format( L"viewport={L:%d,T:%d,R:%d,B:%d}", - viewport.Left(), viewport.Top(), viewport.RightInclusive(), viewport.BottomInclusive() - )); + viewport.Left(), + viewport.Top(), + viewport.RightInclusive(), + viewport.BottomInclusive())); VERIFY_SUCCEEDED(si.VtEraseAll()); viewport = si._viewport; @@ -747,15 +751,16 @@ void ScreenBufferTests::EraseAllTests() VERIFY_ARE_EQUAL(cursor.GetPosition(), newRelativePos); Log::Comment(NoThrowString().Format( L"viewport={L:%d,T:%d,R:%d,B:%d}", - viewport.Left(), viewport.Top(), viewport.RightInclusive(), viewport.BottomInclusive() - )); - + viewport.Left(), + viewport.Top(), + viewport.RightInclusive(), + viewport.BottomInclusive())); //////////////////////////////////////////////////////////////////////// Log::Comment(L"Case 3: multiple lines at the bottom of the buffer\n"); - cursor.SetPosition({0, 275}); - VERIFY_SUCCEEDED(si.SetViewportOrigin(true, {0, 220}, true)); + cursor.SetPosition({ 0, 275 }); + VERIFY_SUCCEEDED(si.SetViewportOrigin(true, { 0, 220 }, true)); stateMachine.ProcessString(L"bar\nbar\nbar", 11); viewport = si._viewport; VERIFY_ARE_EQUAL(cursor.GetPosition().X, 3); @@ -765,8 +770,10 @@ void ScreenBufferTests::EraseAllTests() Log::Comment(NoThrowString().Format( L"viewport={L:%d,T:%d,R:%d,B:%d}", - viewport.Left(), viewport.Top(), viewport.RightInclusive(), viewport.BottomInclusive() - )); + viewport.Left(), + viewport.Top(), + viewport.RightInclusive(), + viewport.BottomInclusive())); VERIFY_SUCCEEDED(si.VtEraseAll()); viewport = si._viewport; @@ -777,8 +784,10 @@ void ScreenBufferTests::EraseAllTests() VERIFY_ARE_EQUAL(cursor.GetPosition(), newRelativePos); Log::Comment(NoThrowString().Format( L"viewport={L:%d,T:%d,R:%d,B:%d}", - viewport.Left(), viewport.Top(), viewport.RightInclusive(), viewport.BottomInclusive() - )); + viewport.Left(), + viewport.Top(), + viewport.RightInclusive(), + viewport.BottomInclusive())); } void ScreenBufferTests::VtResize() @@ -806,8 +815,7 @@ void ScreenBufferTests::VtResize() Log::Comment(NoThrowString().Format( L"Write '\x1b[8;30;80t'" L" The Screen buffer height should remain unchanged, but the width should be 80 columns" - L" The viewport should be w,h=80,30" - )); + L" The viewport should be w,h=80,30")); std::wstring sequence = L"\x1b[8;30;80t"; stateMachine.ProcessString(&sequence[0], sequence.length()); @@ -830,8 +838,7 @@ void ScreenBufferTests::VtResize() Log::Comment(NoThrowString().Format( L"Write '\x1b[8;40;80t'" L" The Screen buffer height should remain unchanged, but the width should be 80 columns" - L" The viewport should be w,h=80,40" - )); + L" The viewport should be w,h=80,40")); sequence = L"\x1b[8;40;80t"; stateMachine.ProcessString(&sequence[0], sequence.length()); @@ -854,8 +861,7 @@ void ScreenBufferTests::VtResize() Log::Comment(NoThrowString().Format( L"Write '\x1b[8;40;90t'" L" The Screen buffer height should remain unchanged, but the width should be 90 columns" - L" The viewport should be w,h=90,40" - )); + L" The viewport should be w,h=90,40")); sequence = L"\x1b[8;40;90t"; stateMachine.ProcessString(&sequence[0], sequence.length()); @@ -878,8 +884,7 @@ void ScreenBufferTests::VtResize() Log::Comment(NoThrowString().Format( L"Write '\x1b[8;12;12t'" L" The Screen buffer height should remain unchanged, but the width should be 12 columns" - L" The viewport should be w,h=12,12" - )); + L" The viewport should be w,h=12,12")); sequence = L"\x1b[8;12;12t"; stateMachine.ProcessString(&sequence[0], sequence.length()); @@ -901,8 +906,7 @@ void ScreenBufferTests::VtResize() Log::Comment(NoThrowString().Format( L"Write '\x1b[8;0;0t'" - L" Nothing should change" - )); + L" Nothing should change")); sequence = L"\x1b[8;0;0t"; stateMachine.ProcessString(&sequence[0], sequence.length()); @@ -916,10 +920,8 @@ void ScreenBufferTests::VtResize() VERIFY_ARE_EQUAL(initialSbWidth, newSbWidth); VERIFY_ARE_EQUAL(initialViewHeight, newViewHeight); VERIFY_ARE_EQUAL(initialViewWidth, newViewWidth); - } - void ScreenBufferTests::VtResizeComprehensive() { // Run this test in isolation - for one reason or another, this breaks other tests. @@ -955,9 +957,10 @@ void ScreenBufferTests::VtResizeComprehensive() Log::Comment(NoThrowString().Format( L"Write '\\x1b[8;%d;%dt'" L" The viewport should be w,h=%d,%d", - expectedViewHeight, expectedViewWidth, - expectedViewWidth, expectedViewHeight - )); + expectedViewHeight, + expectedViewWidth, + expectedViewWidth, + expectedViewHeight)); std::wstring sequence = ss.str(); stateMachine.ProcessString(sequence); @@ -978,39 +981,36 @@ void ScreenBufferTests::VtSoftResetCursorPosition() const Cursor& cursor = tbi.GetCursor(); Log::Comment(NoThrowString().Format(L"Make sure the viewport is at 0,0")); - VERIFY_SUCCEEDED(si.SetViewportOrigin(true, COORD({0, 0}), true)); + VERIFY_SUCCEEDED(si.SetViewportOrigin(true, COORD({ 0, 0 }), true)); Log::Comment(NoThrowString().Format( L"Move the cursor to 2,2, then execute a soft reset.\n" - L"The cursor should not move." - )); + L"The cursor should not move.")); std::wstring seq = L"\x1b[2;2H"; stateMachine.ProcessString(&seq[0], seq.length()); - VERIFY_ARE_EQUAL( COORD({1, 1}), cursor.GetPosition()); + VERIFY_ARE_EQUAL(COORD({ 1, 1 }), cursor.GetPosition()); seq = L"\x1b[!p"; stateMachine.ProcessString(&seq[0], seq.length()); - VERIFY_ARE_EQUAL( COORD({1, 1}), cursor.GetPosition()); + VERIFY_ARE_EQUAL(COORD({ 1, 1 }), cursor.GetPosition()); Log::Comment(NoThrowString().Format( - L"Set some margins. The cursor should move home." - )); + L"Set some margins. The cursor should move home.")); seq = L"\x1b[2;10r"; stateMachine.ProcessString(&seq[0], seq.length()); - VERIFY_ARE_EQUAL( COORD({0, 0}), cursor.GetPosition()); + VERIFY_ARE_EQUAL(COORD({ 0, 0 }), cursor.GetPosition()); Log::Comment(NoThrowString().Format( L"Move the cursor to 2,2, then execute a soft reset.\n" - L"The cursor should not move, even though there are margins." - )); + L"The cursor should not move, even though there are margins.")); seq = L"\x1b[2;2H"; stateMachine.ProcessString(&seq[0], seq.length()); - VERIFY_ARE_EQUAL( COORD({1, 1}), cursor.GetPosition()); + VERIFY_ARE_EQUAL(COORD({ 1, 1 }), cursor.GetPosition()); seq = L"\x1b[!p"; stateMachine.ProcessString(&seq[0], seq.length()); - VERIFY_ARE_EQUAL( COORD({1, 1}), cursor.GetPosition()); + VERIFY_ARE_EQUAL(COORD({ 1, 1 }), cursor.GetPosition()); } void ScreenBufferTests::VtScrollMarginsNewlineColor() @@ -1022,8 +1022,8 @@ void ScreenBufferTests::VtScrollMarginsNewlineColor() Cursor& cursor = si.GetTextBuffer().GetCursor(); Log::Comment(NoThrowString().Format(L"Make sure the viewport is at 0,0")); - VERIFY_SUCCEEDED(si.SetViewportOrigin(true, COORD({0, 0}), true)); - cursor.SetPosition(COORD({0, 0})); + VERIFY_SUCCEEDED(si.SetViewportOrigin(true, COORD({ 0, 0 }), true)); + cursor.SetPosition(COORD({ 0, 0 })); const COLORREF yellow = RGB(255, 255, 0); const COLORREF magenta = RGB(255, 0, 255); @@ -1041,18 +1041,16 @@ void ScreenBufferTests::VtScrollMarginsNewlineColor() Log::Comment(NoThrowString().Format( L"Set the margins to 2, 5, then emit 10 'X\\n' strings. " - L"Each time, check that rows 0-10 have default attributes in their entire row." - )); + L"Each time, check that rows 0-10 have default attributes in their entire row.")); seq = L"\x1b[2;5r"; stateMachine.ProcessString(seq); // Make sure we clear the margins to not screw up another test. - auto clearMargins = wil::scope_exit([&]{stateMachine.ProcessString(L"\x1b[r");}); + auto clearMargins = wil::scope_exit([&] { stateMachine.ProcessString(L"\x1b[r"); }); for (int iteration = 0; iteration < 10; iteration++) { Log::Comment(NoThrowString().Format( - L"Iteration:%d", iteration - )); + L"Iteration:%d", iteration)); seq = L"X"; stateMachine.ProcessString(seq); seq = L"\n"; @@ -1062,13 +1060,11 @@ void ScreenBufferTests::VtScrollMarginsNewlineColor() Log::Comment(NoThrowString().Format( L"Cursor=%s", - VerifyOutputTraits::ToString(cursorPos).GetBuffer() - )); + VerifyOutputTraits::ToString(cursorPos).GetBuffer())); const auto viewport = si.GetViewport(); Log::Comment(NoThrowString().Format( L"Viewport=%s", - VerifyOutputTraits::ToString(viewport.ToInclusive()).GetBuffer() - )); + VerifyOutputTraits::ToString(viewport.ToInclusive()).GetBuffer())); const auto viewTop = viewport.Top(); for (int y = viewTop; y < viewTop + 10; y++) { @@ -1101,8 +1097,8 @@ void ScreenBufferTests::VtNewlinePastViewport() VERIFY_IS_TRUE(WI_IsFlagSet(si.OutputMode, ENABLE_VIRTUAL_TERMINAL_PROCESSING)); Log::Comment(NoThrowString().Format(L"Make sure the viewport is at 0,0")); - VERIFY_SUCCEEDED(si.SetViewportOrigin(true, COORD({0, 0}), true)); - cursor.SetPosition(COORD({0, 0})); + VERIFY_SUCCEEDED(si.SetViewportOrigin(true, COORD({ 0, 0 }), true)); + cursor.SetPosition(COORD({ 0, 0 })); std::wstring seq = L"\x1b[m"; stateMachine.ProcessString(seq); @@ -1110,19 +1106,17 @@ void ScreenBufferTests::VtNewlinePastViewport() stateMachine.ProcessString(seq); const TextAttribute defaultAttrs{}; - const TextAttribute expectedTwo{FOREGROUND_GREEN | FOREGROUND_INTENSITY | BACKGROUND_BLUE}; + const TextAttribute expectedTwo{ FOREGROUND_GREEN | FOREGROUND_INTENSITY | BACKGROUND_BLUE }; Log::Comment(NoThrowString().Format( - L"Move the cursor to the bottom of the viewport" - )); + L"Move the cursor to the bottom of the viewport")); const auto initialViewport = si.GetViewport(); Log::Comment(NoThrowString().Format( L"initialViewport=%s", - VerifyOutputTraits::ToString(initialViewport.ToInclusive()).GetBuffer() - )); + VerifyOutputTraits::ToString(initialViewport.ToInclusive()).GetBuffer())); - cursor.SetPosition(COORD({0, initialViewport.BottomInclusive()})); + cursor.SetPosition(COORD({ 0, initialViewport.BottomInclusive() })); seq = L"\x1b[92;44m"; // bright-green on dark-blue stateMachine.ProcessString(seq); @@ -1132,8 +1126,7 @@ void ScreenBufferTests::VtNewlinePastViewport() const auto viewport = si.GetViewport(); Log::Comment(NoThrowString().Format( L"viewport=%s", - VerifyOutputTraits::ToString(viewport.ToInclusive()).GetBuffer() - )); + VerifyOutputTraits::ToString(viewport.ToInclusive()).GetBuffer())); VERIFY_ARE_EQUAL(viewport.BottomInclusive(), cursor.GetPosition().Y); VERIFY_ARE_EQUAL(0, cursor.GetPosition().X); @@ -1171,112 +1164,99 @@ void ScreenBufferTests::VtSetColorTable() gci.SetColorTableEntry(0, RGB(0, 0, 0)); Log::Comment(NoThrowString().Format( - L"Process some valid sequences for setting the table" - )); + L"Process some valid sequences for setting the table")); std::wstring seq = L"\x1b]4;0;rgb:1/1/1\x7"; stateMachine.ProcessString(&seq[0], seq.length()); - VERIFY_ARE_EQUAL(RGB(1,1,1), gci.GetColorTableEntry(::XtermToWindowsIndex(0))); + VERIFY_ARE_EQUAL(RGB(1, 1, 1), gci.GetColorTableEntry(::XtermToWindowsIndex(0))); seq = L"\x1b]4;1;rgb:1/23/1\x7"; stateMachine.ProcessString(&seq[0], seq.length()); - VERIFY_ARE_EQUAL(RGB(1,0x23,1), gci.GetColorTableEntry(::XtermToWindowsIndex(1))); + VERIFY_ARE_EQUAL(RGB(1, 0x23, 1), gci.GetColorTableEntry(::XtermToWindowsIndex(1))); seq = L"\x1b]4;2;rgb:1/23/12\x7"; stateMachine.ProcessString(&seq[0], seq.length()); - VERIFY_ARE_EQUAL(RGB(1,0x23,0x12), gci.GetColorTableEntry(::XtermToWindowsIndex(2))); + VERIFY_ARE_EQUAL(RGB(1, 0x23, 0x12), gci.GetColorTableEntry(::XtermToWindowsIndex(2))); seq = L"\x1b]4;3;rgb:12/23/12\x7"; stateMachine.ProcessString(&seq[0], seq.length()); - VERIFY_ARE_EQUAL(RGB(0x12,0x23,0x12), gci.GetColorTableEntry(::XtermToWindowsIndex(3))); + VERIFY_ARE_EQUAL(RGB(0x12, 0x23, 0x12), gci.GetColorTableEntry(::XtermToWindowsIndex(3))); seq = L"\x1b]4;4;rgb:ff/a1/1b\x7"; stateMachine.ProcessString(&seq[0], seq.length()); - VERIFY_ARE_EQUAL(RGB(0xff,0xa1,0x1b), gci.GetColorTableEntry(::XtermToWindowsIndex(4))); + VERIFY_ARE_EQUAL(RGB(0xff, 0xa1, 0x1b), gci.GetColorTableEntry(::XtermToWindowsIndex(4))); seq = L"\x1b]4;5;rgb:ff/a1/1b\x1b\\"; stateMachine.ProcessString(&seq[0], seq.length()); - VERIFY_ARE_EQUAL(RGB(0xff,0xa1,0x1b), gci.GetColorTableEntry(::XtermToWindowsIndex(5))); + VERIFY_ARE_EQUAL(RGB(0xff, 0xa1, 0x1b), gci.GetColorTableEntry(::XtermToWindowsIndex(5))); Log::Comment(NoThrowString().Format( - L"Try a bunch of invalid sequences." - )); + L"Try a bunch of invalid sequences.")); Log::Comment(NoThrowString().Format( - L"First start by setting an entry to a known value to compare to." - )); + L"First start by setting an entry to a known value to compare to.")); seq = L"\x1b]4;5;rgb:9/9/9\x1b\\"; stateMachine.ProcessString(&seq[0], seq.length()); - VERIFY_ARE_EQUAL(RGB(9,9,9), gci.GetColorTableEntry(::XtermToWindowsIndex(5))); + VERIFY_ARE_EQUAL(RGB(9, 9, 9), gci.GetColorTableEntry(::XtermToWindowsIndex(5))); Log::Comment(NoThrowString().Format( - L"invalid: Missing the first component" - )); + L"invalid: Missing the first component")); seq = L"\x1b]4;5;rgb:/1/1\x1b\\"; stateMachine.ProcessString(&seq[0], seq.length()); - VERIFY_ARE_EQUAL(RGB(9,9,9), gci.GetColorTableEntry(::XtermToWindowsIndex(5))); + VERIFY_ARE_EQUAL(RGB(9, 9, 9), gci.GetColorTableEntry(::XtermToWindowsIndex(5))); Log::Comment(NoThrowString().Format( - L"invalid: too many characters in a component" - )); + L"invalid: too many characters in a component")); seq = L"\x1b]4;5;rgb:111/1/1\x1b\\"; stateMachine.ProcessString(&seq[0], seq.length()); - VERIFY_ARE_EQUAL(RGB(9,9,9), gci.GetColorTableEntry(::XtermToWindowsIndex(5))); + VERIFY_ARE_EQUAL(RGB(9, 9, 9), gci.GetColorTableEntry(::XtermToWindowsIndex(5))); Log::Comment(NoThrowString().Format( - L"invalid: too many componenets" - )); + L"invalid: too many componenets")); seq = L"\x1b]4;5;rgb:1/1/1/1\x1b\\"; stateMachine.ProcessString(&seq[0], seq.length()); - VERIFY_ARE_EQUAL(RGB(9,9,9), gci.GetColorTableEntry(::XtermToWindowsIndex(5))); + VERIFY_ARE_EQUAL(RGB(9, 9, 9), gci.GetColorTableEntry(::XtermToWindowsIndex(5))); Log::Comment(NoThrowString().Format( - L"invalid: no second component" - )); + L"invalid: no second component")); seq = L"\x1b]4;5;rgb:1//1\x1b\\"; stateMachine.ProcessString(&seq[0], seq.length()); - VERIFY_ARE_EQUAL(RGB(9,9,9), gci.GetColorTableEntry(::XtermToWindowsIndex(5))); + VERIFY_ARE_EQUAL(RGB(9, 9, 9), gci.GetColorTableEntry(::XtermToWindowsIndex(5))); Log::Comment(NoThrowString().Format( - L"invalid: no components" - )); + L"invalid: no components")); seq = L"\x1b]4;5;rgb://\x1b\\"; stateMachine.ProcessString(&seq[0], seq.length()); - VERIFY_ARE_EQUAL(RGB(9,9,9), gci.GetColorTableEntry(::XtermToWindowsIndex(5))); + VERIFY_ARE_EQUAL(RGB(9, 9, 9), gci.GetColorTableEntry(::XtermToWindowsIndex(5))); Log::Comment(NoThrowString().Format( - L"invalid: no third component" - )); + L"invalid: no third component")); seq = L"\x1b]4;5;rgb:1/11/\x1b\\"; stateMachine.ProcessString(&seq[0], seq.length()); - VERIFY_ARE_EQUAL(RGB(9,9,9), gci.GetColorTableEntry(::XtermToWindowsIndex(5))); + VERIFY_ARE_EQUAL(RGB(9, 9, 9), gci.GetColorTableEntry(::XtermToWindowsIndex(5))); Log::Comment(NoThrowString().Format( - L"invalid: rgbi is not a supported color space" - )); + L"invalid: rgbi is not a supported color space")); seq = L"\x1b]4;5;rgbi:1/1/1\x1b\\"; stateMachine.ProcessString(&seq[0], seq.length()); - VERIFY_ARE_EQUAL(RGB(9,9,9), gci.GetColorTableEntry(::XtermToWindowsIndex(5))); + VERIFY_ARE_EQUAL(RGB(9, 9, 9), gci.GetColorTableEntry(::XtermToWindowsIndex(5))); Log::Comment(NoThrowString().Format( - L"invalid: cmyk is not a supported color space" - )); + L"invalid: cmyk is not a supported color space")); seq = L"\x1b]4;5;cmyk:1/1/1\x1b\\"; stateMachine.ProcessString(&seq[0], seq.length()); - VERIFY_ARE_EQUAL(RGB(9,9,9), gci.GetColorTableEntry(::XtermToWindowsIndex(5))); + VERIFY_ARE_EQUAL(RGB(9, 9, 9), gci.GetColorTableEntry(::XtermToWindowsIndex(5))); Log::Comment(NoThrowString().Format( - L"invalid: no table index should do nothing" - )); + L"invalid: no table index should do nothing")); seq = L"\x1b]4;;rgb:1/1/1\x1b\\"; stateMachine.ProcessString(&seq[0], seq.length()); - VERIFY_ARE_EQUAL(RGB(9,9,9), gci.GetColorTableEntry(::XtermToWindowsIndex(5))); + VERIFY_ARE_EQUAL(RGB(9, 9, 9), gci.GetColorTableEntry(::XtermToWindowsIndex(5))); Log::Comment(NoThrowString().Format( - L"invalid: need to specify a color space" - )); + L"invalid: need to specify a color space")); seq = L"\x1b]4;5;1/1/1\x1b\\"; stateMachine.ProcessString(&seq[0], seq.length()); - VERIFY_ARE_EQUAL(RGB(9,9,9), gci.GetColorTableEntry(::XtermToWindowsIndex(5))); + VERIFY_ARE_EQUAL(RGB(9, 9, 9), gci.GetColorTableEntry(::XtermToWindowsIndex(5))); } void ScreenBufferTests::ResizeTraditionalDoesntDoubleFreeAttrRows() @@ -1338,7 +1318,6 @@ void ScreenBufferTests::ResizeCursorUnchanged() VERIFY_ARE_EQUAL(initialSize, finalSize); } - void ScreenBufferTests::ResizeAltBuffer() { CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); @@ -1349,15 +1328,13 @@ void ScreenBufferTests::ResizeAltBuffer() StateMachine& stateMachine = si.GetStateMachine(); Log::Comment(NoThrowString().Format( - L"Try resizing the alt buffer. Make sure the call doesn't stack overflow." - )); + L"Try resizing the alt buffer. Make sure the call doesn't stack overflow.")); VERIFY_IS_FALSE(si._IsAltBuffer()); const Viewport originalMainSize = Viewport(si._viewport); Log::Comment(NoThrowString().Format( - L"Switch to alt buffer" - )); + L"Switch to alt buffer")); std::wstring seq = L"\x1b[?1049h"; stateMachine.ProcessString(&seq[0], seq.length()); @@ -1370,14 +1347,12 @@ void ScreenBufferTests::ResizeAltBuffer() newSize.Y += 2; Log::Comment(NoThrowString().Format( - L"MSFT:15917333 This call shouldn't stack overflow" - )); + L"MSFT:15917333 This call shouldn't stack overflow")); psiAlt->SetViewportSize(&newSize); VERIFY_IS_TRUE(true); Log::Comment(NoThrowString().Format( - L"Switch back from buffer" - )); + L"Switch back from buffer")); seq = L"\x1b[?1049l"; stateMachine.ProcessString(&seq[0], seq.length()); VERIFY_IS_FALSE(si._IsAltBuffer()); @@ -1399,8 +1374,7 @@ void ScreenBufferTests::ResizeAltBufferGetScreenBufferInfo() Log::Comment(NoThrowString().Format( L"Switch to the alt buffer, then resize the buffer. " L"GetConsoleScreenBufferInfoEx(mainBuffer) should return the alt " - L"buffer's size, not the main buffer's size." - )); + L"buffer's size, not the main buffer's size.")); auto& g = ServiceLocator::LocateGlobals(); CONSOLE_INFORMATION& gci = g.getConsoleInformation(); @@ -1414,8 +1388,7 @@ void ScreenBufferTests::ResizeAltBufferGetScreenBufferInfo() const Viewport originalMainSize = Viewport(mainBuffer._viewport); Log::Comment(NoThrowString().Format( - L"Switch to alt buffer" - )); + L"Switch to alt buffer")); std::wstring seq = L"\x1b[?1049h"; stateMachine.ProcessString(seq); @@ -1423,7 +1396,7 @@ void ScreenBufferTests::ResizeAltBufferGetScreenBufferInfo() VERIFY_IS_NOT_NULL(mainBuffer._psiAlternateBuffer); auto& altBuffer = *(mainBuffer._psiAlternateBuffer); - auto useMain = wil::scope_exit([&]{ altBuffer.UseMainScreenBuffer(); }); + auto useMain = wil::scope_exit([&] { altBuffer.UseMainScreenBuffer(); }); COORD newBufferSize = originalMainSize.Dimensions(); newBufferSize.X += static_cast(dx); @@ -1436,7 +1409,7 @@ void ScreenBufferTests::ResizeAltBufferGetScreenBufferInfo() altBuffer.SetViewportSize(&newBufferSize); - CONSOLE_SCREEN_BUFFER_INFOEX csbiex{0}; + CONSOLE_SCREEN_BUFFER_INFOEX csbiex{ 0 }; g.api.GetConsoleScreenBufferInfoExImpl(mainBuffer, csbiex); const auto newActualMainView = mainBuffer.GetViewport(); const auto newActualAltView = altBuffer.GetViewport(); @@ -1462,28 +1435,25 @@ void ScreenBufferTests::VtEraseAllPersistCursor() const Cursor& cursor = tbi.GetCursor(); Log::Comment(NoThrowString().Format( - L"Make sure the viewport is at 0,0" - )); - VERIFY_SUCCEEDED(si.SetViewportOrigin(true, COORD({0, 0}), true)); + L"Make sure the viewport is at 0,0")); + VERIFY_SUCCEEDED(si.SetViewportOrigin(true, COORD({ 0, 0 }), true)); Log::Comment(NoThrowString().Format( L"Move the cursor to 2,2, then execute a Erase All.\n" - L"The cursor should not move relative to the viewport." - )); + L"The cursor should not move relative to the viewport.")); std::wstring seq = L"\x1b[2;2H"; stateMachine.ProcessString(&seq[0], seq.length()); - VERIFY_ARE_EQUAL( COORD({1, 1}), cursor.GetPosition()); + VERIFY_ARE_EQUAL(COORD({ 1, 1 }), cursor.GetPosition()); seq = L"\x1b[2J"; stateMachine.ProcessString(&seq[0], seq.length()); auto newViewport = si._viewport; - COORD expectedCursor = {1, 1}; + COORD expectedCursor = { 1, 1 }; newViewport.ConvertFromOrigin(&expectedCursor); VERIFY_ARE_EQUAL(expectedCursor, cursor.GetPosition()); - } void ScreenBufferTests::VtEraseAllPersistCursorFillColor() @@ -1494,14 +1464,12 @@ void ScreenBufferTests::VtEraseAllPersistCursorFillColor() StateMachine& stateMachine = si.GetStateMachine(); Log::Comment(NoThrowString().Format( - L"Make sure the viewport is at 0,0" - )); - VERIFY_SUCCEEDED(si.SetViewportOrigin(true, COORD({0, 0}), true)); + L"Make sure the viewport is at 0,0")); + VERIFY_SUCCEEDED(si.SetViewportOrigin(true, COORD({ 0, 0 }), true)); Log::Comment(NoThrowString().Format( L"Change the colors to dark_red on bright_blue, then execute a Erase All.\n" - L"The viewport should be full of dark_red on bright_blue" - )); + L"The viewport should be full of dark_red on bright_blue")); auto expectedAttr = TextAttribute(XtermToLegacy(1, 12)); std::wstring seq = L"\x1b[31;104m"; @@ -1517,12 +1485,10 @@ void ScreenBufferTests::VtEraseAllPersistCursorFillColor() auto newViewport = si._viewport; Log::Comment(NoThrowString().Format( L"new Viewport: %s", - VerifyOutputTraits::ToString(newViewport.ToInclusive()).GetBuffer() - )); + VerifyOutputTraits::ToString(newViewport.ToInclusive()).GetBuffer())); Log::Comment(NoThrowString().Format( L"Buffer Size: %s", - VerifyOutputTraits::ToString(si.GetBufferSize().ToInclusive()).GetBuffer() - )); + VerifyOutputTraits::ToString(si.GetBufferSize().ToInclusive()).GetBuffer())); auto iter = tbi.GetCellDataAt(newViewport.Origin()); auto height = newViewport.Height(); @@ -1550,7 +1516,7 @@ void ScreenBufferTests::GetWordBoundary() VERIFY_SUCCEEDED(si.GetTextBuffer().ResizeTraditional(newBufferSize)); const OutputCellIterator it(text, si.GetAttributes()); - si.Write(it, { 0,0 }); + si.Write(it, { 0, 0 }); // Now find some words in it. Log::Comment(L"Find first word from its front."); @@ -1692,7 +1658,7 @@ void ScreenBufferTests::TestAltBufferCursorState() VERIFY_IS_NULL(original._psiMainBuffer); NTSTATUS Status = original.UseAlternateScreenBuffer(); - if(VERIFY_IS_TRUE(NT_SUCCESS(Status))) + if (VERIFY_IS_TRUE(NT_SUCCESS(Status))) { Log::Comment(L"Alternate buffer successfully created"); auto& alternate = gci.GetActiveOutputBuffer(); @@ -1738,7 +1704,7 @@ void ScreenBufferTests::TestAltBufferVtDispatching() VERIFY_IS_NULL(mainBuffer._psiMainBuffer); NTSTATUS Status = mainBuffer.UseAlternateScreenBuffer(); - if(VERIFY_IS_TRUE(NT_SUCCESS(Status))) + if (VERIFY_IS_TRUE(NT_SUCCESS(Status))) { Log::Comment(L"Alternate buffer successfully created"); auto& alternate = gci.GetActiveOutputBuffer(); @@ -1761,7 +1727,7 @@ void ScreenBufferTests::TestAltBufferVtDispatching() auto& mainCursor = mainBuffer.GetTextBuffer().GetCursor(); auto& altCursor = alternate.GetTextBuffer().GetCursor(); - const COORD origin = {0, 0}; + const COORD origin = { 0, 0 }; mainCursor.SetPosition(origin); altCursor.SetPosition(origin); Log::Comment(NoThrowString().Format(L"Make sure the viewport is at 0,0")); @@ -1778,9 +1744,9 @@ void ScreenBufferTests::TestAltBufferVtDispatching() size_t seqCb = 2 * seq.size(); VERIFY_SUCCEEDED(DoWriteConsole(&seq[0], &seqCb, mainBuffer, waiter)); - VERIFY_ARE_EQUAL(COORD({0, 0}), mainCursor.GetPosition()); + VERIFY_ARE_EQUAL(COORD({ 0, 0 }), mainCursor.GetPosition()); // recall: vt coordinates are (row, column), 1-indexed - VERIFY_ARE_EQUAL(COORD({5, 4}), altCursor.GetPosition()); + VERIFY_ARE_EQUAL(COORD({ 5, 4 }), altCursor.GetPosition()); const TextAttribute expectedDefaults = gci.GetDefaultAttributes(); TextAttribute expectedRgb = expectedDefaults; @@ -1800,8 +1766,8 @@ void ScreenBufferTests::TestAltBufferVtDispatching() seqCb = 2 * seq.size(); VERIFY_SUCCEEDED(DoWriteConsole(&seq[0], &seqCb, mainBuffer, waiter)); - VERIFY_ARE_EQUAL(COORD({0, 0}), mainCursor.GetPosition()); - VERIFY_ARE_EQUAL(COORD({6, 4}), altCursor.GetPosition()); + VERIFY_ARE_EQUAL(COORD({ 0, 0 }), mainCursor.GetPosition()); + VERIFY_ARE_EQUAL(COORD({ 6, 4 }), altCursor.GetPosition()); // Recall we didn't print an 'X' to the main buffer, so there's no // char to inspect the attributes of. @@ -1824,8 +1790,8 @@ void ScreenBufferTests::SetDefaultsIndividuallyBothDefault() Cursor& cursor = si.GetTextBuffer().GetCursor(); Log::Comment(NoThrowString().Format(L"Make sure the viewport is at 0,0")); - VERIFY_SUCCEEDED(si.SetViewportOrigin(true, COORD({0, 0}), true)); - cursor.SetPosition({0, 0}); + VERIFY_SUCCEEDED(si.SetViewportOrigin(true, COORD({ 0, 0 }), true)); + cursor.SetPosition({ 0, 0 }); COLORREF magenta = RGB(255, 0, 255); COLORREF yellow = RGB(255, 255, 0); @@ -1876,15 +1842,15 @@ void ScreenBufferTests::SetDefaultsIndividuallyBothDefault() // See the log comment above for description of these values. TextAttribute expectedDefaults{}; - TextAttribute expectedTwo{FOREGROUND_GREEN | FOREGROUND_INTENSITY | BACKGROUND_BLUE}; - TextAttribute expectedThree{FOREGROUND_GREEN | FOREGROUND_INTENSITY | BACKGROUND_BLUE}; + TextAttribute expectedTwo{ FOREGROUND_GREEN | FOREGROUND_INTENSITY | BACKGROUND_BLUE }; + TextAttribute expectedThree{ FOREGROUND_GREEN | FOREGROUND_INTENSITY | BACKGROUND_BLUE }; expectedThree.SetDefaultForeground(); // Four is the same as Defaults // Five is the same as two - TextAttribute expectedSix{FOREGROUND_GREEN | FOREGROUND_INTENSITY | BACKGROUND_BLUE}; + TextAttribute expectedSix{ FOREGROUND_GREEN | FOREGROUND_INTENSITY | BACKGROUND_BLUE }; expectedSix.SetDefaultBackground(); - COORD expectedCursor{6, 0}; + COORD expectedCursor{ 6, 0 }; VERIFY_ARE_EQUAL(expectedCursor, cursor.GetPosition()); const ROW& row = tbi.GetRowByOffset(0); @@ -1905,10 +1871,10 @@ void ScreenBufferTests::SetDefaultsIndividuallyBothDefault() LOG_ATTR(attrF); VERIFY_ARE_EQUAL(false, attrA.IsLegacy()); - VERIFY_ARE_EQUAL(true, attrB.IsLegacy()); + VERIFY_ARE_EQUAL(true, attrB.IsLegacy()); VERIFY_ARE_EQUAL(false, attrC.IsLegacy()); VERIFY_ARE_EQUAL(false, attrD.IsLegacy()); - VERIFY_ARE_EQUAL(true, attrE.IsLegacy()); + VERIFY_ARE_EQUAL(true, attrE.IsLegacy()); VERIFY_ARE_EQUAL(false, attrF.IsLegacy()); VERIFY_ARE_EQUAL(expectedDefaults, attrA); @@ -1918,7 +1884,7 @@ void ScreenBufferTests::SetDefaultsIndividuallyBothDefault() VERIFY_ARE_EQUAL(expectedTwo, attrE); VERIFY_ARE_EQUAL(expectedSix, attrF); - VERIFY_ARE_EQUAL(yellow, gci.LookupForegroundColor(attrA)); + VERIFY_ARE_EQUAL(yellow, gci.LookupForegroundColor(attrA)); VERIFY_ARE_EQUAL(brightGreen, gci.LookupForegroundColor(attrB)); VERIFY_ARE_EQUAL(yellow, gci.LookupForegroundColor(attrC)); VERIFY_ARE_EQUAL(yellow, gci.LookupForegroundColor(attrD)); @@ -1944,8 +1910,8 @@ void ScreenBufferTests::SetDefaultsTogether() Cursor& cursor = si.GetTextBuffer().GetCursor(); Log::Comment(NoThrowString().Format(L"Make sure the viewport is at 0,0")); - VERIFY_SUCCEEDED(si.SetViewportOrigin(true, COORD({0, 0}), true)); - cursor.SetPosition({0, 0}); + VERIFY_SUCCEEDED(si.SetViewportOrigin(true, COORD({ 0, 0 }), true)); + cursor.SetPosition({ 0, 0 }); COLORREF magenta = RGB(255, 0, 255); COLORREF yellow = RGB(255, 255, 0); @@ -1980,7 +1946,7 @@ void ScreenBufferTests::SetDefaultsTogether() TextAttribute expectedTwo{}; expectedTwo.SetBackground(color250); - COORD expectedCursor{3, 0}; + COORD expectedCursor{ 3, 0 }; VERIFY_ARE_EQUAL(expectedCursor, cursor.GetPosition()); const ROW& row = tbi.GetRowByOffset(0); @@ -1995,14 +1961,14 @@ void ScreenBufferTests::SetDefaultsTogether() LOG_ATTR(attrC); VERIFY_ARE_EQUAL(false, attrA.IsLegacy()); - VERIFY_ARE_EQUAL(false, attrB.IsLegacy()); + VERIFY_ARE_EQUAL(false, attrB.IsLegacy()); VERIFY_ARE_EQUAL(false, attrC.IsLegacy()); VERIFY_ARE_EQUAL(expectedDefaults, attrA); VERIFY_ARE_EQUAL(expectedTwo, attrB); VERIFY_ARE_EQUAL(expectedDefaults, attrC); - VERIFY_ARE_EQUAL(yellow, gci.LookupForegroundColor(attrA)); + VERIFY_ARE_EQUAL(yellow, gci.LookupForegroundColor(attrA)); VERIFY_ARE_EQUAL(yellow, gci.LookupForegroundColor(attrB)); VERIFY_ARE_EQUAL(yellow, gci.LookupForegroundColor(attrC)); @@ -2011,7 +1977,6 @@ void ScreenBufferTests::SetDefaultsTogether() VERIFY_ARE_EQUAL(magenta, gci.LookupBackgroundColor(attrC)); } - void ScreenBufferTests::ReverseResetWithDefaultBackground() { // Tests MSFT:19694089 @@ -2022,8 +1987,8 @@ void ScreenBufferTests::ReverseResetWithDefaultBackground() Cursor& cursor = si.GetTextBuffer().GetCursor(); Log::Comment(NoThrowString().Format(L"Make sure the viewport is at 0,0")); - VERIFY_SUCCEEDED(si.SetViewportOrigin(true, COORD({0, 0}), true)); - cursor.SetPosition({0, 0}); + VERIFY_SUCCEEDED(si.SetViewportOrigin(true, COORD({ 0, 0 }), true)); + cursor.SetPosition({ 0, 0 }); COLORREF magenta = RGB(255, 0, 255); @@ -2047,12 +2012,12 @@ void ScreenBufferTests::ReverseResetWithDefaultBackground() seq = L"X"; stateMachine.ProcessString(seq); - TextAttribute expectedDefaults{gci.GetFillAttribute()}; + TextAttribute expectedDefaults{ gci.GetFillAttribute() }; expectedDefaults.SetDefaultBackground(); TextAttribute expectedReversed = expectedDefaults; expectedReversed.Invert(); - COORD expectedCursor{3, 0}; + COORD expectedCursor{ 3, 0 }; VERIFY_ARE_EQUAL(expectedCursor, cursor.GetPosition()); const ROW& row = tbi.GetRowByOffset(0); @@ -2096,8 +2061,8 @@ void ScreenBufferTests::BackspaceDefaultAttrs() Cursor& cursor = si.GetTextBuffer().GetCursor(); Log::Comment(NoThrowString().Format(L"Make sure the viewport is at 0,0")); - VERIFY_SUCCEEDED(si.SetViewportOrigin(true, COORD({0, 0}), true)); - cursor.SetPosition({0, 0}); + VERIFY_SUCCEEDED(si.SetViewportOrigin(true, COORD({ 0, 0 }), true)); + cursor.SetPosition({ 0, 0 }); COLORREF magenta = RGB(255, 0, 255); @@ -2117,7 +2082,7 @@ void ScreenBufferTests::BackspaceDefaultAttrs() TextAttribute expectedDefaults{}; expectedDefaults.SetDefaultBackground(); - COORD expectedCursor{1, 0}; + COORD expectedCursor{ 1, 0 }; VERIFY_ARE_EQUAL(expectedCursor, cursor.GetPosition()); const ROW& row = tbi.GetRowByOffset(0); @@ -2141,7 +2106,6 @@ void ScreenBufferTests::BackspaceDefaultAttrs() void ScreenBufferTests::BackspaceDefaultAttrsWriteCharsLegacy() { - BEGIN_TEST_METHOD_PROPERTIES() TEST_METHOD_PROPERTY(L"Data:writeSingly", L"{false, true}") TEST_METHOD_PROPERTY(L"Data:writeCharsLegacyMode", L"{0, 1, 2, 3, 4, 5, 6, 7}") @@ -2164,8 +2128,8 @@ void ScreenBufferTests::BackspaceDefaultAttrsWriteCharsLegacy() Cursor& cursor = si.GetTextBuffer().GetCursor(); Log::Comment(NoThrowString().Format(L"Make sure the viewport is at 0,0")); - VERIFY_SUCCEEDED(si.SetViewportOrigin(true, COORD({0, 0}), true)); - cursor.SetPosition({0, 0}); + VERIFY_SUCCEEDED(si.SetViewportOrigin(true, COORD({ 0, 0 }), true)); + cursor.SetPosition({ 0, 0 }); COLORREF magenta = RGB(255, 0, 255); @@ -2196,7 +2160,7 @@ void ScreenBufferTests::BackspaceDefaultAttrsWriteCharsLegacy() TextAttribute expectedDefaults{}; expectedDefaults.SetDefaultBackground(); - COORD expectedCursor{1, 0}; + COORD expectedCursor{ 1, 0 }; VERIFY_ARE_EQUAL(expectedCursor, cursor.GetPosition()); const ROW& row = tbi.GetRowByOffset(0); @@ -2233,8 +2197,8 @@ void ScreenBufferTests::BackspaceDefaultAttrsInPrompt() VERIFY_IS_TRUE(WI_IsFlagSet(si.OutputMode, ENABLE_VIRTUAL_TERMINAL_PROCESSING)); Log::Comment(NoThrowString().Format(L"Make sure the viewport is at 0,0")); - VERIFY_SUCCEEDED(si.SetViewportOrigin(true, COORD({0, 0}), true)); - cursor.SetPosition({0, 0}); + VERIFY_SUCCEEDED(si.SetViewportOrigin(true, COORD({ 0, 0 }), true)); + cursor.SetPosition({ 0, 0 }); COLORREF magenta = RGB(255, 0, 255); @@ -2248,8 +2212,7 @@ void ScreenBufferTests::BackspaceDefaultAttrsInPrompt() std::wstring seq = L"\x1b[m"; stateMachine.ProcessString(seq); Log::Comment(NoThrowString().Format( - L"Clear the screen - make sure the line is filled with the current attributes." - )); + L"Clear the screen - make sure the line is filled with the current attributes.")); seq = L"\x1b[2J"; stateMachine.ProcessString(seq); @@ -2261,8 +2224,7 @@ void ScreenBufferTests::BackspaceDefaultAttrsInPrompt() SetVerifyOutput settings(VerifyOutputSettings::LogOnlyFailures); Log::Comment(NoThrowString().Format( L"Make sure the row contains what we're expecting before we start." - L"It should entirely be filled with defaults" - )); + L"It should entirely be filled with defaults")); const std::vector initialAttrs{ attrRow->begin(), attrRow->end() }; for (int x = 0; x <= viewport.RightInclusive(); x++) @@ -2272,8 +2234,7 @@ void ScreenBufferTests::BackspaceDefaultAttrsInPrompt() } } Log::Comment(NoThrowString().Format( - L"Print 'XXX', move the cursor left 2, delete a character." - )); + L"Print 'XXX', move the cursor left 2, delete a character.")); seq = L"XXX"; stateMachine.ProcessString(seq); @@ -2282,8 +2243,8 @@ void ScreenBufferTests::BackspaceDefaultAttrsInPrompt() seq = L"\x1b[P"; stateMachine.ProcessString(seq); - COORD expectedCursor{1, 1}; // We're expecting y=1, because the 2J above - // should have moved the viewport down a line. + COORD expectedCursor{ 1, 1 }; // We're expecting y=1, because the 2J above + // should have moved the viewport down a line. VERIFY_ARE_EQUAL(expectedCursor, cursor.GetPosition()); const std::vector attrs{ attrRow->begin(), attrRow->end() }; @@ -2316,8 +2277,8 @@ void ScreenBufferTests::SetGlobalColorTable() Cursor& mainCursor = mainBuffer.GetTextBuffer().GetCursor(); Log::Comment(NoThrowString().Format(L"Make sure the viewport is at 0,0")); - VERIFY_SUCCEEDED(mainBuffer.SetViewportOrigin(true, COORD({0, 0}), true)); - mainCursor.SetPosition({0, 0}); + VERIFY_SUCCEEDED(mainBuffer.SetViewportOrigin(true, COORD({ 0, 0 }), true)); + mainCursor.SetPosition({ 0, 0 }); const COLORREF originalRed = gci.GetColorTableEntry(4); const COLORREF testColor = RGB(0x11, 0x22, 0x33); @@ -2327,7 +2288,7 @@ void ScreenBufferTests::SetGlobalColorTable() stateMachine.ProcessString(seq); seq = L"X"; stateMachine.ProcessString(seq); - COORD expectedCursor{1, 0}; + COORD expectedCursor{ 1, 0 }; VERIFY_ARE_EQUAL(expectedCursor, mainCursor.GetPosition()); { const ROW& row = mainBuffer.GetTextBuffer().GetRowByOffset(mainCursor.GetPosition().Y); @@ -2348,11 +2309,10 @@ void ScreenBufferTests::SetGlobalColorTable() VERIFY_IS_TRUE(WI_IsFlagSet(altBuffer.OutputMode, ENABLE_VIRTUAL_TERMINAL_PROCESSING)); Cursor& altCursor = altBuffer.GetTextBuffer().GetCursor(); - altCursor.SetPosition({0, 0}); + altCursor.SetPosition({ 0, 0 }); Log::Comment(NoThrowString().Format( - L"Print one X in red, should be the original red color" - )); + L"Print one X in red, should be the original red color")); seq = L"\x1b[41m"; stateMachine.ProcessString(seq); seq = L"X"; @@ -2371,11 +2331,10 @@ void ScreenBufferTests::SetGlobalColorTable() seq = L"\x1b]4;1;rgb:11/22/33\x07"; stateMachine.ProcessString(seq); Log::Comment(NoThrowString().Format( - L"Print another X, both should be the new \"red\" color" - )); + L"Print another X, both should be the new \"red\" color")); seq = L"X"; stateMachine.ProcessString(seq); - VERIFY_ARE_EQUAL(COORD({2, 0}), altCursor.GetPosition()); + VERIFY_ARE_EQUAL(COORD({ 2, 0 }), altCursor.GetPosition()); { const ROW& row = altBuffer.GetTextBuffer().GetRowByOffset(altCursor.GetPosition().Y); const auto attrRow = &row.GetAttrRow(); @@ -2396,11 +2355,10 @@ void ScreenBufferTests::SetGlobalColorTable() VERIFY_ARE_EQUAL(&mainBufferPostSwitch, &mainBuffer); Log::Comment(NoThrowString().Format( - L"Print another X, both should be the new \"red\" color" - )); + L"Print another X, both should be the new \"red\" color")); seq = L"X"; stateMachine.ProcessString(seq); - VERIFY_ARE_EQUAL(COORD({2, 0}), mainCursor.GetPosition()); + VERIFY_ARE_EQUAL(COORD({ 2, 0 }), mainCursor.GetPosition()); { const ROW& row = mainBuffer.GetTextBuffer().GetRowByOffset(mainCursor.GetPosition().Y); const auto attrRow = &row.GetAttrRow(); @@ -2432,8 +2390,8 @@ void ScreenBufferTests::SetColorTableThreeDigits() Cursor& mainCursor = mainBuffer.GetTextBuffer().GetCursor(); Log::Comment(NoThrowString().Format(L"Make sure the viewport is at 0,0")); - VERIFY_SUCCEEDED(mainBuffer.SetViewportOrigin(true, COORD({0, 0}), true)); - mainCursor.SetPosition({0, 0}); + VERIFY_SUCCEEDED(mainBuffer.SetViewportOrigin(true, COORD({ 0, 0 }), true)); + mainCursor.SetPosition({ 0, 0 }); const COLORREF originalRed = gci.GetColorTableEntry(123); const COLORREF testColor = RGB(0x11, 0x22, 0x33); @@ -2443,7 +2401,7 @@ void ScreenBufferTests::SetColorTableThreeDigits() stateMachine.ProcessString(seq); seq = L"X"; stateMachine.ProcessString(seq); - COORD expectedCursor{1, 0}; + COORD expectedCursor{ 1, 0 }; VERIFY_ARE_EQUAL(expectedCursor, mainCursor.GetPosition()); { const ROW& row = mainBuffer.GetTextBuffer().GetRowByOffset(mainCursor.GetPosition().Y); @@ -2464,11 +2422,10 @@ void ScreenBufferTests::SetColorTableThreeDigits() VERIFY_IS_TRUE(WI_IsFlagSet(altBuffer.OutputMode, ENABLE_VIRTUAL_TERMINAL_PROCESSING)); Cursor& altCursor = altBuffer.GetTextBuffer().GetCursor(); - altCursor.SetPosition({0, 0}); + altCursor.SetPosition({ 0, 0 }); Log::Comment(NoThrowString().Format( - L"Print one X in red, should be the original red color" - )); + L"Print one X in red, should be the original red color")); seq = L"\x1b[48;5;123m"; stateMachine.ProcessString(seq); seq = L"X"; @@ -2487,15 +2444,14 @@ void ScreenBufferTests::SetColorTableThreeDigits() seq = L"\x1b]4;123;rgb:11/22/33\x07"; stateMachine.ProcessString(seq); Log::Comment(NoThrowString().Format( - L"Print another X, it should be the new \"red\" color" - )); + L"Print another X, it should be the new \"red\" color")); // TODO MSFT:20105972 - // You shouldn't need to manually update the attributes again. seq = L"\x1b[48;5;123m"; stateMachine.ProcessString(seq); seq = L"X"; stateMachine.ProcessString(seq); - VERIFY_ARE_EQUAL(COORD({2, 0}), altCursor.GetPosition()); + VERIFY_ARE_EQUAL(COORD({ 2, 0 }), altCursor.GetPosition()); { const ROW& row = altBuffer.GetTextBuffer().GetRowByOffset(altCursor.GetPosition().Y); const auto attrRow = &row.GetAttrRow(); @@ -2505,10 +2461,8 @@ void ScreenBufferTests::SetColorTableThreeDigits() LOG_ATTR(attrB); VERIFY_ARE_EQUAL(testColor, gci.LookupBackgroundColor(attrB)); } - } - void ScreenBufferTests::SetDefaultForegroundColor() { // Setting the default foreground color should work @@ -2567,7 +2521,6 @@ void ScreenBufferTests::SetDefaultForegroundColor() VERIFY_ARE_EQUAL(originalColor, newColor); } - void ScreenBufferTests::SetDefaultBackgroundColor() { // Setting the default Background color should work @@ -2626,8 +2579,6 @@ void ScreenBufferTests::SetDefaultBackgroundColor() VERIFY_ARE_EQUAL(originalColor, newColor); } - - void ScreenBufferTests::DeleteCharsNearEndOfLine() { // Created for MSFT:19888564. @@ -2685,7 +2636,7 @@ void ScreenBufferTests::DeleteCharsNearEndOfLine() auto& mainCursor = tbi.GetCursor(); auto& mainView = mainBuffer.GetViewport(); - VERIFY_ARE_EQUAL(COORD({0, 0}), mainCursor.GetPosition()); + VERIFY_ARE_EQUAL(COORD({ 0, 0 }), mainCursor.GetPosition()); VERIFY_ARE_EQUAL(mainBuffer.GetBufferSize().Width(), mainView.Width()); VERIFY_IS_GREATER_THAN(mainView.Width(), (dx + numCharsToDelete)); @@ -2695,14 +2646,13 @@ void ScreenBufferTests::DeleteCharsNearEndOfLine() stateMachine.ProcessString(seq); } - VERIFY_ARE_EQUAL(COORD({mainView.Width() - 1, 0}), mainCursor.GetPosition()); + VERIFY_ARE_EQUAL(COORD({ mainView.Width() - 1, 0 }), mainCursor.GetPosition()); Log::Comment(NoThrowString().Format( L"row_i=[%s]", - tbi.GetRowByOffset(0).GetText().c_str() - )); + tbi.GetRowByOffset(0).GetText().c_str())); - mainCursor.SetPosition({mainView.Width() - static_cast(dx), 0}); + mainCursor.SetPosition({ mainView.Width() - static_cast(dx), 0 }); std::wstringstream ss; ss << L"\x1b[" << numCharsToDelete << L"P"; seq = ss.str(); // Delete N chars @@ -2710,10 +2660,9 @@ void ScreenBufferTests::DeleteCharsNearEndOfLine() Log::Comment(NoThrowString().Format( L"row_f=[%s]", - tbi.GetRowByOffset(0).GetText().c_str() - )); - VERIFY_ARE_EQUAL(COORD({mainView.Width() - static_cast(dx), 0}), mainCursor.GetPosition()); - auto iter = tbi.GetCellDataAt({0, 0}); + tbi.GetRowByOffset(0).GetText().c_str())); + VERIFY_ARE_EQUAL(COORD({ mainView.Width() - static_cast(dx), 0 }), mainCursor.GetPosition()); + auto iter = tbi.GetCellDataAt({ 0, 0 }); auto expectedNumSpaces = std::min(dx, numCharsToDelete); for (int x = 0; x < mainView.Width() - expectedNumSpaces; x++) { @@ -2727,14 +2676,13 @@ void ScreenBufferTests::DeleteCharsNearEndOfLine() } for (int x = mainView.Width() - expectedNumSpaces; x < mainView.Width(); x++) { - if (iter->Chars() != L"\x20" ) + if (iter->Chars() != L"\x20") { Log::Comment(NoThrowString().Format(L"character [%d] was mismatched", x)); } - VERIFY_ARE_EQUAL(L"\x20" , iter->Chars()); + VERIFY_ARE_EQUAL(L"\x20", iter->Chars()); iter++; } - } void ScreenBufferTests::DeleteCharsNearEndOfLineSimpleFirstCase() @@ -2750,25 +2698,25 @@ void ScreenBufferTests::DeleteCharsNearEndOfLineSimpleFirstCase() auto& stateMachine = si.GetStateMachine(); const auto newBufferWidth = 8; - VERIFY_SUCCEEDED(si.ResizeScreenBuffer({newBufferWidth, si.GetBufferSize().Height()}, false)); + VERIFY_SUCCEEDED(si.ResizeScreenBuffer({ newBufferWidth, si.GetBufferSize().Height() }, false)); auto& mainBuffer = gci.GetActiveOutputBuffer(); - const COORD newViewSize{newBufferWidth, mainBuffer.GetViewport().Height()}; + const COORD newViewSize{ newBufferWidth, mainBuffer.GetViewport().Height() }; mainBuffer.SetViewportSize(&newViewSize); auto& tbi = mainBuffer.GetTextBuffer(); auto& mainView = mainBuffer.GetViewport(); auto& mainCursor = tbi.GetCursor(); - VERIFY_ARE_EQUAL(COORD({0, 0}), mainCursor.GetPosition()); + VERIFY_ARE_EQUAL(COORD({ 0, 0 }), mainCursor.GetPosition()); VERIFY_ARE_EQUAL(newBufferWidth, mainView.Width()); VERIFY_ARE_EQUAL(mainBuffer.GetBufferSize().Width(), mainView.Width()); std::wstring seq = L"ABCDEFG"; stateMachine.ProcessString(seq); - VERIFY_ARE_EQUAL(COORD({7, 0}), mainCursor.GetPosition()); + VERIFY_ARE_EQUAL(COORD({ 7, 0 }), mainCursor.GetPosition()); // Place the cursor on the 'D' - mainCursor.SetPosition({3, 0}); + mainCursor.SetPosition({ 3, 0 }); Log::Comment(NoThrowString().Format(L"before=[%s]", tbi.GetRowByOffset(0).GetText().c_str())); // Delete 3 chars - [D, E, F] @@ -2780,9 +2728,9 @@ void ScreenBufferTests::DeleteCharsNearEndOfLineSimpleFirstCase() Log::Comment(NoThrowString().Format(L"after =[%s]", tbi.GetRowByOffset(0).GetText().c_str())); // Cursor shouldn't have moved - VERIFY_ARE_EQUAL(COORD({3, 0}), mainCursor.GetPosition()); + VERIFY_ARE_EQUAL(COORD({ 3, 0 }), mainCursor.GetPosition()); - auto iter = tbi.GetCellDataAt({0, 0}); + auto iter = tbi.GetCellDataAt({ 0, 0 }); VERIFY_ARE_EQUAL(L"A", iter->Chars()); iter++; VERIFY_ARE_EQUAL(L"B", iter->Chars()); @@ -2812,26 +2760,26 @@ void ScreenBufferTests::DeleteCharsNearEndOfLineSimpleSecondCase() auto& stateMachine = si.GetStateMachine(); const auto newBufferWidth = 8; - VERIFY_SUCCEEDED(si.ResizeScreenBuffer({newBufferWidth, si.GetBufferSize().Height()}, false)); + VERIFY_SUCCEEDED(si.ResizeScreenBuffer({ newBufferWidth, si.GetBufferSize().Height() }, false)); auto& mainBuffer = gci.GetActiveOutputBuffer(); - const COORD newViewSize{newBufferWidth, mainBuffer.GetViewport().Height()}; + const COORD newViewSize{ newBufferWidth, mainBuffer.GetViewport().Height() }; mainBuffer.SetViewportSize(&newViewSize); auto& tbi = mainBuffer.GetTextBuffer(); auto& mainView = mainBuffer.GetViewport(); auto& mainCursor = tbi.GetCursor(); - VERIFY_ARE_EQUAL(COORD({0, 0}), mainCursor.GetPosition()); + VERIFY_ARE_EQUAL(COORD({ 0, 0 }), mainCursor.GetPosition()); VERIFY_ARE_EQUAL(newBufferWidth, mainView.Width()); VERIFY_ARE_EQUAL(mainBuffer.GetBufferSize().Width(), mainView.Width()); std::wstring seq = L"ABCDEFG"; stateMachine.ProcessString(seq); - VERIFY_ARE_EQUAL(COORD({7, 0}), mainCursor.GetPosition()); + VERIFY_ARE_EQUAL(COORD({ 7, 0 }), mainCursor.GetPosition()); // Place the cursor on the 'C' - mainCursor.SetPosition({2, 0}); + mainCursor.SetPosition({ 2, 0 }); Log::Comment(NoThrowString().Format(L"before=[%s]", tbi.GetRowByOffset(0).GetText().c_str())); @@ -2843,9 +2791,9 @@ void ScreenBufferTests::DeleteCharsNearEndOfLineSimpleSecondCase() Log::Comment(NoThrowString().Format(L"after =[%s]", tbi.GetRowByOffset(0).GetText().c_str())); - VERIFY_ARE_EQUAL(COORD({2, 0}), mainCursor.GetPosition()); + VERIFY_ARE_EQUAL(COORD({ 2, 0 }), mainCursor.GetPosition()); - auto iter = tbi.GetCellDataAt({0, 0}); + auto iter = tbi.GetCellDataAt({ 0, 0 }); VERIFY_ARE_EQUAL(L"A", iter->Chars()); iter++; VERIFY_ARE_EQUAL(L"B", iter->Chars()); @@ -2860,7 +2808,6 @@ void ScreenBufferTests::DeleteCharsNearEndOfLineSimpleSecondCase() iter++; VERIFY_ARE_EQUAL(L"\x20", iter->Chars()); iter++; - } void ScreenBufferTests::DontResetColorsAboveVirtualBottom() @@ -2877,14 +2824,12 @@ void ScreenBufferTests::DontResetColorsAboveVirtualBottom() auto& stateMachine = si.GetStateMachine(); auto& cursor = si.GetTextBuffer().GetCursor(); - VERIFY_SUCCESS_NTSTATUS(si.SetViewportOrigin(true, {0, 1}, true)); - cursor.SetPosition({0, si.GetViewport().BottomInclusive()}); + VERIFY_SUCCESS_NTSTATUS(si.SetViewportOrigin(true, { 0, 1 }, true)); + cursor.SetPosition({ 0, si.GetViewport().BottomInclusive() }); Log::Comment(NoThrowString().Format( - L"cursor=%s", VerifyOutputTraits::ToString(cursor.GetPosition()).GetBuffer() - )); + L"cursor=%s", VerifyOutputTraits::ToString(cursor.GetPosition()).GetBuffer())); Log::Comment(NoThrowString().Format( - L"viewport=%s", VerifyOutputTraits::ToString(si.GetViewport().ToInclusive()).GetBuffer() - )); + L"viewport=%s", VerifyOutputTraits::ToString(si.GetViewport().ToInclusive()).GetBuffer())); const auto darkRed = gci.GetColorTableEntry(::XtermToWindowsIndex(1)); const auto darkBlue = gci.GetColorTableEntry(::XtermToWindowsIndex(4)); const auto darkBlack = gci.GetColorTableEntry(::XtermToWindowsIndex(0)); @@ -2895,11 +2840,9 @@ void ScreenBufferTests::DontResetColorsAboveVirtualBottom() stateMachine.ProcessString(L"X"); Log::Comment(NoThrowString().Format( - L"cursor=%s", VerifyOutputTraits::ToString(cursor.GetPosition()).GetBuffer() - )); + L"cursor=%s", VerifyOutputTraits::ToString(cursor.GetPosition()).GetBuffer())); Log::Comment(NoThrowString().Format( - L"viewport=%s", VerifyOutputTraits::ToString(si.GetViewport().ToInclusive()).GetBuffer() - )); + L"viewport=%s", VerifyOutputTraits::ToString(si.GetViewport().ToInclusive()).GetBuffer())); VERIFY_ARE_EQUAL(2, cursor.GetPosition().X); { const ROW& row = tbi.GetRowByOffset(cursor.GetPosition().Y); @@ -2917,25 +2860,21 @@ void ScreenBufferTests::DontResetColorsAboveVirtualBottom() } Log::Comment(NoThrowString().Format(L"Emulate scrolling up with the mouse")); - VERIFY_SUCCESS_NTSTATUS(si.SetViewportOrigin(true, {0, 0}, false)); + VERIFY_SUCCESS_NTSTATUS(si.SetViewportOrigin(true, { 0, 0 }, false)); Log::Comment(NoThrowString().Format( - L"cursor=%s", VerifyOutputTraits::ToString(cursor.GetPosition()).GetBuffer() - )); + L"cursor=%s", VerifyOutputTraits::ToString(cursor.GetPosition()).GetBuffer())); Log::Comment(NoThrowString().Format( - L"viewport=%s", VerifyOutputTraits::ToString(si.GetViewport().ToInclusive()).GetBuffer() - )); + L"viewport=%s", VerifyOutputTraits::ToString(si.GetViewport().ToInclusive()).GetBuffer())); VERIFY_IS_GREATER_THAN(cursor.GetPosition().Y, si.GetViewport().BottomInclusive()); stateMachine.ProcessString(L"X"); Log::Comment(NoThrowString().Format( - L"cursor=%s", VerifyOutputTraits::ToString(cursor.GetPosition()).GetBuffer() - )); + L"cursor=%s", VerifyOutputTraits::ToString(cursor.GetPosition()).GetBuffer())); Log::Comment(NoThrowString().Format( - L"viewport=%s", VerifyOutputTraits::ToString(si.GetViewport().ToInclusive()).GetBuffer() - )); + L"viewport=%s", VerifyOutputTraits::ToString(si.GetViewport().ToInclusive()).GetBuffer())); VERIFY_ARE_EQUAL(3, cursor.GetPosition().X); { @@ -2987,12 +2926,12 @@ void _CommonScrollingSetup() auto& stateMachine = si.GetStateMachine(); auto& cursor = si.GetTextBuffer().GetCursor(); const auto oldView = si.GetViewport(); - const auto view = Viewport::FromDimensions({0, 0}, {oldView.Width(), 6}); + const auto view = Viewport::FromDimensions({ 0, 0 }, { oldView.Width(), 6 }); si.SetViewport(view, true); - cursor.SetPosition({0, 0}); + cursor.SetPosition({ 0, 0 }); std::wstring seq = L"A"; stateMachine.ProcessString(seq); - cursor.SetPosition({0, 5}); + cursor.SetPosition({ 0, 5 }); seq = L"B"; stateMachine.ProcessString(seq); seq = L"\x1b[2;5r"; @@ -3002,58 +2941,52 @@ void _CommonScrollingSetup() seq = L"1\n2\n3\n4"; stateMachine.ProcessString(seq); - Log::Comment(NoThrowString().Format( - L"cursor=%s", VerifyOutputTraits::ToString(cursor.GetPosition()).GetBuffer() - )); + L"cursor=%s", VerifyOutputTraits::ToString(cursor.GetPosition()).GetBuffer())); Log::Comment(NoThrowString().Format( - L"viewport=%s", VerifyOutputTraits::ToString(si.GetViewport().ToInclusive()).GetBuffer() - )); + L"viewport=%s", VerifyOutputTraits::ToString(si.GetViewport().ToInclusive()).GetBuffer())); VERIFY_ARE_EQUAL(1, cursor.GetPosition().X); VERIFY_ARE_EQUAL(4, cursor.GetPosition().Y); { - auto iter0 = tbi.GetCellDataAt({0, 0}); - auto iter1 = tbi.GetCellDataAt({0, 1}); - auto iter2 = tbi.GetCellDataAt({0, 2}); - auto iter3 = tbi.GetCellDataAt({0, 3}); - auto iter4 = tbi.GetCellDataAt({0, 4}); - auto iter5 = tbi.GetCellDataAt({0, 5}); - VERIFY_ARE_EQUAL(L"A" , iter0->Chars()); - VERIFY_ARE_EQUAL(L"1" , iter1->Chars()); - VERIFY_ARE_EQUAL(L"2" , iter2->Chars()); - VERIFY_ARE_EQUAL(L"3" , iter3->Chars()); - VERIFY_ARE_EQUAL(L"4" , iter4->Chars()); - VERIFY_ARE_EQUAL(L"B" , iter5->Chars()); + auto iter0 = tbi.GetCellDataAt({ 0, 0 }); + auto iter1 = tbi.GetCellDataAt({ 0, 1 }); + auto iter2 = tbi.GetCellDataAt({ 0, 2 }); + auto iter3 = tbi.GetCellDataAt({ 0, 3 }); + auto iter4 = tbi.GetCellDataAt({ 0, 4 }); + auto iter5 = tbi.GetCellDataAt({ 0, 5 }); + VERIFY_ARE_EQUAL(L"A", iter0->Chars()); + VERIFY_ARE_EQUAL(L"1", iter1->Chars()); + VERIFY_ARE_EQUAL(L"2", iter2->Chars()); + VERIFY_ARE_EQUAL(L"3", iter3->Chars()); + VERIFY_ARE_EQUAL(L"4", iter4->Chars()); + VERIFY_ARE_EQUAL(L"B", iter5->Chars()); } - seq = L"\n5\n6\n7\n"; stateMachine.ProcessString(seq); Log::Comment(NoThrowString().Format( - L"cursor=%s", VerifyOutputTraits::ToString(cursor.GetPosition()).GetBuffer() - )); + L"cursor=%s", VerifyOutputTraits::ToString(cursor.GetPosition()).GetBuffer())); Log::Comment(NoThrowString().Format( - L"viewport=%s", VerifyOutputTraits::ToString(si.GetViewport().ToInclusive()).GetBuffer() - )); + L"viewport=%s", VerifyOutputTraits::ToString(si.GetViewport().ToInclusive()).GetBuffer())); VERIFY_ARE_EQUAL(0, cursor.GetPosition().X); VERIFY_ARE_EQUAL(4, cursor.GetPosition().Y); { - auto iter0 = tbi.GetCellDataAt({0, 0}); - auto iter1 = tbi.GetCellDataAt({0, 1}); - auto iter2 = tbi.GetCellDataAt({0, 2}); - auto iter3 = tbi.GetCellDataAt({0, 3}); - auto iter4 = tbi.GetCellDataAt({0, 4}); - auto iter5 = tbi.GetCellDataAt({0, 5}); - VERIFY_ARE_EQUAL(L"A" , iter0->Chars()); - VERIFY_ARE_EQUAL(L"5" , iter1->Chars()); - VERIFY_ARE_EQUAL(L"6" , iter2->Chars()); - VERIFY_ARE_EQUAL(L"7" , iter3->Chars()); + auto iter0 = tbi.GetCellDataAt({ 0, 0 }); + auto iter1 = tbi.GetCellDataAt({ 0, 1 }); + auto iter2 = tbi.GetCellDataAt({ 0, 2 }); + auto iter3 = tbi.GetCellDataAt({ 0, 3 }); + auto iter4 = tbi.GetCellDataAt({ 0, 4 }); + auto iter5 = tbi.GetCellDataAt({ 0, 5 }); + VERIFY_ARE_EQUAL(L"A", iter0->Chars()); + VERIFY_ARE_EQUAL(L"5", iter1->Chars()); + VERIFY_ARE_EQUAL(L"6", iter2->Chars()); + VERIFY_ARE_EQUAL(L"7", iter3->Chars()); // Chars() will return a single space for an empty row. - VERIFY_ARE_EQUAL(L"\x20" , iter4->Chars()); - VERIFY_ARE_EQUAL(L"B" , iter5->Chars()); + VERIFY_ARE_EQUAL(L"\x20", iter4->Chars()); + VERIFY_ARE_EQUAL(L"B", iter5->Chars()); } } @@ -3075,29 +3008,26 @@ void ScreenBufferTests::ScrollUpInMargins() stateMachine.ProcessString(seq); Log::Comment(NoThrowString().Format( - L"cursor=%s", VerifyOutputTraits::ToString(cursor.GetPosition()).GetBuffer() - )); + L"cursor=%s", VerifyOutputTraits::ToString(cursor.GetPosition()).GetBuffer())); Log::Comment(NoThrowString().Format( - L"viewport=%s", VerifyOutputTraits::ToString(si.GetViewport().ToInclusive()).GetBuffer() - )); + L"viewport=%s", VerifyOutputTraits::ToString(si.GetViewport().ToInclusive()).GetBuffer())); VERIFY_ARE_EQUAL(0, cursor.GetPosition().X); VERIFY_ARE_EQUAL(4, cursor.GetPosition().Y); { - auto iter0 = tbi.GetCellDataAt({0, 0}); - auto iter1 = tbi.GetCellDataAt({0, 1}); - auto iter2 = tbi.GetCellDataAt({0, 2}); - auto iter3 = tbi.GetCellDataAt({0, 3}); - auto iter4 = tbi.GetCellDataAt({0, 4}); - auto iter5 = tbi.GetCellDataAt({0, 5}); - VERIFY_ARE_EQUAL(L"A" , iter0->Chars()); - VERIFY_ARE_EQUAL(L"6" , iter1->Chars()); - VERIFY_ARE_EQUAL(L"7" , iter2->Chars()); - VERIFY_ARE_EQUAL(L"\x20" , iter3->Chars()); - VERIFY_ARE_EQUAL(L"\x20" , iter4->Chars()); - VERIFY_ARE_EQUAL(L"B" , iter5->Chars()); + auto iter0 = tbi.GetCellDataAt({ 0, 0 }); + auto iter1 = tbi.GetCellDataAt({ 0, 1 }); + auto iter2 = tbi.GetCellDataAt({ 0, 2 }); + auto iter3 = tbi.GetCellDataAt({ 0, 3 }); + auto iter4 = tbi.GetCellDataAt({ 0, 4 }); + auto iter5 = tbi.GetCellDataAt({ 0, 5 }); + VERIFY_ARE_EQUAL(L"A", iter0->Chars()); + VERIFY_ARE_EQUAL(L"6", iter1->Chars()); + VERIFY_ARE_EQUAL(L"7", iter2->Chars()); + VERIFY_ARE_EQUAL(L"\x20", iter3->Chars()); + VERIFY_ARE_EQUAL(L"\x20", iter4->Chars()); + VERIFY_ARE_EQUAL(L"B", iter5->Chars()); } - } void ScreenBufferTests::ScrollDownInMargins() @@ -3118,26 +3048,24 @@ void ScreenBufferTests::ScrollDownInMargins() stateMachine.ProcessString(seq); Log::Comment(NoThrowString().Format( - L"cursor=%s", VerifyOutputTraits::ToString(cursor.GetPosition()).GetBuffer() - )); + L"cursor=%s", VerifyOutputTraits::ToString(cursor.GetPosition()).GetBuffer())); Log::Comment(NoThrowString().Format( - L"viewport=%s", VerifyOutputTraits::ToString(si.GetViewport().ToInclusive()).GetBuffer() - )); + L"viewport=%s", VerifyOutputTraits::ToString(si.GetViewport().ToInclusive()).GetBuffer())); VERIFY_ARE_EQUAL(0, cursor.GetPosition().X); VERIFY_ARE_EQUAL(4, cursor.GetPosition().Y); { - auto iter0 = tbi.GetCellDataAt({0, 0}); - auto iter1 = tbi.GetCellDataAt({0, 1}); - auto iter2 = tbi.GetCellDataAt({0, 2}); - auto iter3 = tbi.GetCellDataAt({0, 3}); - auto iter4 = tbi.GetCellDataAt({0, 4}); - auto iter5 = tbi.GetCellDataAt({0, 5}); - VERIFY_ARE_EQUAL(L"A" , iter0->Chars()); + auto iter0 = tbi.GetCellDataAt({ 0, 0 }); + auto iter1 = tbi.GetCellDataAt({ 0, 1 }); + auto iter2 = tbi.GetCellDataAt({ 0, 2 }); + auto iter3 = tbi.GetCellDataAt({ 0, 3 }); + auto iter4 = tbi.GetCellDataAt({ 0, 4 }); + auto iter5 = tbi.GetCellDataAt({ 0, 5 }); + VERIFY_ARE_EQUAL(L"A", iter0->Chars()); VERIFY_ARE_EQUAL(L"\x20", iter1->Chars()); - VERIFY_ARE_EQUAL(L"5" , iter2->Chars()); - VERIFY_ARE_EQUAL(L"6" , iter3->Chars()); - VERIFY_ARE_EQUAL(L"7" , iter4->Chars()); - VERIFY_ARE_EQUAL(L"B" , iter5->Chars()); + VERIFY_ARE_EQUAL(L"5", iter2->Chars()); + VERIFY_ARE_EQUAL(L"6", iter3->Chars()); + VERIFY_ARE_EQUAL(L"7", iter4->Chars()); + VERIFY_ARE_EQUAL(L"B", iter5->Chars()); } } diff --git a/src/host/ut_host/SelectionTests.cpp b/src/host/ut_host/SelectionTests.cpp index ae93ee74c..d483217f7 100644 --- a/src/host/ut_host/SelectionTests.cpp +++ b/src/host/ut_host/SelectionTests.cpp @@ -613,5 +613,4 @@ class SelectionInputTests } while (point.Y < bufferSize.BottomInclusive()); // stop once we've advanced to a point on the bottom row of the buffer. } - }; diff --git a/src/host/ut_host/TextBufferIteratorTests.cpp b/src/host/ut_host/TextBufferIteratorTests.cpp index a7144f4e7..13630a51a 100644 --- a/src/host/ut_host/TextBufferIteratorTests.cpp +++ b/src/host/ut_host/TextBufferIteratorTests.cpp @@ -62,7 +62,7 @@ class TextBufferIteratorTests return true; } - template + template void BoolOperatorTestHelper() { const auto it = GetIterator(); @@ -78,7 +78,7 @@ class TextBufferIteratorTests TEST_METHOD(BoolOperatorText); TEST_METHOD(BoolOperatorCell); - template + template void EqualsOperatorTestHelper() { const auto it = GetIterator(); @@ -90,7 +90,7 @@ class TextBufferIteratorTests TEST_METHOD(EqualsOperatorText); TEST_METHOD(EqualsOperatorCell); - template + template void NotEqualsOperatorTestHelper() { const auto it = GetIterator(); @@ -105,7 +105,7 @@ class TextBufferIteratorTests TEST_METHOD(NotEqualsOperatorText); TEST_METHOD(NotEqualsOperatorCell); - template + template void PlusEqualsOperatorTestHelper() { auto it = GetIterator(); @@ -123,7 +123,7 @@ class TextBufferIteratorTests TEST_METHOD(PlusEqualsOperatorText); TEST_METHOD(PlusEqualsOperatorCell); - template + template void MinusEqualsOperatorTestHelper() { auto itExpected = GetIteratorWithAdvance(); @@ -141,7 +141,7 @@ class TextBufferIteratorTests TEST_METHOD(MinusEqualsOperatorText); TEST_METHOD(MinusEqualsOperatorCell); - template + template void PrefixPlusPlusOperatorTestHelper() { auto itActual = GetIterator(); @@ -158,7 +158,7 @@ class TextBufferIteratorTests TEST_METHOD(PrefixPlusPlusOperatorText); TEST_METHOD(PrefixPlusPlusOperatorCell); - template + template void PrefixMinusMinusOperatorTestHelper() { const auto itExpected = GetIteratorWithAdvance(); @@ -175,7 +175,7 @@ class TextBufferIteratorTests TEST_METHOD(PrefixMinusMinusOperatorText); TEST_METHOD(PrefixMinusMinusOperatorCell); - template + template void PostfixPlusPlusOperatorTestHelper() { auto it = GetIterator(); @@ -192,7 +192,7 @@ class TextBufferIteratorTests TEST_METHOD(PostfixPlusPlusOperatorText); TEST_METHOD(PostfixPlusPlusOperatorCell); - template + template void PostfixMinusMinusOperatorTestHelper() { const auto itExpected = GetIteratorWithAdvance(); @@ -209,7 +209,7 @@ class TextBufferIteratorTests TEST_METHOD(PostfixMinusMinusOperatorText); TEST_METHOD(PostfixMinusMinusOperatorCell); - template + template void PlusOperatorTestHelper() { auto it = GetIterator(); @@ -227,7 +227,7 @@ class TextBufferIteratorTests TEST_METHOD(PlusOperatorText); TEST_METHOD(PlusOperatorCell); - template + template void MinusOperatorTestHelper() { auto itExpected = GetIteratorWithAdvance(); @@ -245,7 +245,7 @@ class TextBufferIteratorTests TEST_METHOD(MinusOperatorText); TEST_METHOD(MinusOperatorCell); - template + template void DifferenceOperatorTestHelper() { const ptrdiff_t expected(3); @@ -266,17 +266,22 @@ class TextBufferIteratorTests TEST_METHOD(ConstructedNoLimit); TEST_METHOD(ConstructedLimits); - }; -template -T GetIterator() {} +template +T GetIterator() +{ +} -template -T GetIteratorAt(COORD at) {} +template +T GetIteratorAt(COORD at) +{ +} -template -T GetIteratorWithAdvance() {} +template +T GetIteratorWithAdvance() +{ +} template<> TextBufferCellIterator GetIteratorAt(COORD at) @@ -330,7 +335,7 @@ void TextBufferIteratorTests::BoolOperatorCell() Log::Comment(L"For cells, also check incrementing past the end."); const auto& outputBuffer = ServiceLocator::LocateGlobals().getConsoleInformation().GetActiveOutputBuffer(); const auto size = outputBuffer.GetBufferSize().Dimensions(); - TextBufferCellIterator it(outputBuffer.GetTextBuffer(), { size.X-1, size.Y-1 }); + TextBufferCellIterator it(outputBuffer.GetTextBuffer(), { size.X - 1, size.Y - 1 }); VERIFY_IS_TRUE(it); it++; VERIFY_IS_FALSE(it); @@ -487,7 +492,6 @@ void TextBufferIteratorTests::DereferenceOperatorCell() m_state->FillTextBuffer(); const auto it = GetIterator(); - const auto& outputBuffer = ServiceLocator::LocateGlobals().getConsoleInformation().GetActiveOutputBuffer(); const auto& row = outputBuffer._textBuffer->GetRowByOffset(it._pos.Y); @@ -572,13 +576,14 @@ void TextBufferIteratorTests::ConstructedLimits() VERIFY_THROWS_SPECIFIC(TextBufferCellIterator(textBuffer, { 0 }, viewport), - wil::ResultException, [](wil::ResultException& e) { return e.GetErrorCode() == E_INVALIDARG; }); + wil::ResultException, + [](wil::ResultException& e) { return e.GetErrorCode() == E_INVALIDARG; }); // Verify throws for limit not inside buffer const auto bufferSize = textBuffer.GetSize(); VERIFY_THROWS_SPECIFIC(TextBufferCellIterator(textBuffer, pos, Microsoft::Console::Types::Viewport::FromInclusive(bufferSize.ToExclusive())), - wil::ResultException, [](wil::ResultException& e) { return e.GetErrorCode() == E_INVALIDARG; }); - + wil::ResultException, + [](wil::ResultException& e) { return e.GetErrorCode() == E_INVALIDARG; }); } diff --git a/src/host/ut_host/TextBufferTests.cpp b/src/host/ut_host/TextBufferTests.cpp index 5b809fafd..4a31e4469 100644 --- a/src/host/ut_host/TextBufferTests.cpp +++ b/src/host/ut_host/TextBufferTests.cpp @@ -143,7 +143,6 @@ class TextBufferTests TEST_METHOD(ResizeTraditionalHighUnicodeColumnRemoval); TEST_METHOD(TestBurrito); - }; void TextBufferTests::TestBufferCreate() @@ -216,7 +215,6 @@ void TextBufferTests::TestDoubleBytePadFlag() VERIFY_IS_FALSE(Row.GetCharRow().WasDoubleBytePadded()); } - void TextBufferTests::DoBoundaryTest(PWCHAR const pwszInputString, short const cLength, short const cMax, @@ -343,7 +341,7 @@ void TextBufferTests::TestInsertCharacter() // ensure that the cursor moved to a new position (X or Y or both have changed) VERIFY_IS_TRUE((coordCursorBefore.X != textBuffer.GetCursor().GetPosition().X) || - (coordCursorBefore.Y != textBuffer.GetCursor().GetPosition().Y)); + (coordCursorBefore.Y != textBuffer.GetCursor().GetPosition().Y)); // the proper advancement of the cursor (e.g. which position it goes to) is validated in other tests } @@ -386,7 +384,6 @@ void TextBufferTests::TestNewlineCursor() { TextBuffer& textBuffer = GetTbi(); - const short sBufferHeight = textBuffer.GetSize().Height(); const short sBufferWidth = textBuffer.GetSize().Width(); @@ -559,7 +556,7 @@ void TextBufferTests::TestMixedRgbAndLegacyForeground() const TextBuffer& tbi = si.GetTextBuffer(); StateMachine& stateMachine = si.GetStateMachine(); const Cursor& cursor = tbi.GetCursor(); - + // Case 1 - // Write '\E[m\E[38;2;64;128;255mX\E[49mX\E[m' // Make sure that the second X has RGB attributes (FG and BG) @@ -578,8 +575,8 @@ void TextBufferTests::TestMixedRgbAndLegacyForeground() const auto attrB = attrs[x - 1]; Log::Comment(NoThrowString().Format( L"cursor={X:%d,Y:%d}", - x, y - )); + x, + y)); LOG_ATTR(attrA); LOG_ATTR(attrB); @@ -595,7 +592,6 @@ void TextBufferTests::TestMixedRgbAndLegacyForeground() wchar_t* reset = L"\x1b[0m"; stateMachine.ProcessString(reset, std::wcslen(reset)); - } void TextBufferTests::TestMixedRgbAndLegacyBackground() @@ -623,8 +619,8 @@ void TextBufferTests::TestMixedRgbAndLegacyBackground() const auto attrB = attrs[x - 1]; Log::Comment(NoThrowString().Format( L"cursor={X:%d,Y:%d}", - x, y - )); + x, + y)); LOG_ATTR(attrA); LOG_ATTR(attrB); @@ -665,8 +661,8 @@ void TextBufferTests::TestMixedRgbAndLegacyUnderline() const auto attrB = attrs[x - 1]; Log::Comment(NoThrowString().Format( L"cursor={X:%d,Y:%d}", - x, y - )); + x, + y)); LOG_ATTR(attrA); LOG_ATTR(attrB); @@ -680,12 +676,11 @@ void TextBufferTests::TestMixedRgbAndLegacyUnderline() VERIFY_ARE_EQUAL(gci.LookupBackgroundColor(attrB), RGB(64, 128, 255)); VERIFY_ARE_EQUAL(gci.LookupForegroundColor(attrB), gci.LookupForegroundColor(si.GetAttributes())); - VERIFY_ARE_EQUAL(attrA.GetLegacyAttributes()&COMMON_LVB_UNDERSCORE, 0); - VERIFY_ARE_EQUAL(attrB.GetLegacyAttributes()&COMMON_LVB_UNDERSCORE, COMMON_LVB_UNDERSCORE); + VERIFY_ARE_EQUAL(attrA.GetLegacyAttributes() & COMMON_LVB_UNDERSCORE, 0); + VERIFY_ARE_EQUAL(attrB.GetLegacyAttributes() & COMMON_LVB_UNDERSCORE, COMMON_LVB_UNDERSCORE); wchar_t* reset = L"\x1b[0m"; stateMachine.ProcessString(reset, std::wcslen(reset)); - } void TextBufferTests::TestMixedRgbAndLegacyBrightness() @@ -714,8 +709,8 @@ void TextBufferTests::TestMixedRgbAndLegacyBrightness() const auto attrB = attrs[x - 1]; Log::Comment(NoThrowString().Format( L"cursor={X:%d,Y:%d}", - x, y - )); + x, + y)); LOG_ATTR(attrA); LOG_ATTR(attrB); @@ -761,8 +756,8 @@ void TextBufferTests::TestRgbEraseLine() Log::Comment(NoThrowString().Format( L"cursor={X:%d,Y:%d}", - x, y - )); + x, + y)); VERIFY_ARE_EQUAL(x, 2); VERIFY_ARE_EQUAL(y, 0); @@ -812,8 +807,8 @@ void TextBufferTests::TestUnBold() Log::Comment(NoThrowString().Format( L"cursor={X:%d,Y:%d}", - x, y - )); + x, + y)); VERIFY_ARE_EQUAL(x, 2); VERIFY_ARE_EQUAL(y, 0); @@ -826,8 +821,8 @@ void TextBufferTests::TestUnBold() Log::Comment(NoThrowString().Format( L"cursor={X:%d,Y:%d}", - x, y - )); + x, + y)); LOG_ATTR(attrA); LOG_ATTR(attrB); @@ -864,8 +859,8 @@ void TextBufferTests::TestUnBoldRgb() Log::Comment(NoThrowString().Format( L"cursor={X:%d,Y:%d}", - x, y - )); + x, + y)); VERIFY_ARE_EQUAL(x, 2); VERIFY_ARE_EQUAL(y, 0); @@ -878,8 +873,8 @@ void TextBufferTests::TestUnBoldRgb() Log::Comment(NoThrowString().Format( L"cursor={X:%d,Y:%d}", - x, y - )); + x, + y)); LOG_ATTR(attrA); LOG_ATTR(attrB); @@ -924,8 +919,8 @@ void TextBufferTests::TestComplexUnBold() Log::Comment(NoThrowString().Format( L"cursor={X:%d,Y:%d}", - x, y - )); + x, + y)); VERIFY_ARE_EQUAL(x, 6); VERIFY_ARE_EQUAL(y, 0); @@ -942,11 +937,10 @@ void TextBufferTests::TestComplexUnBold() Log::Comment(NoThrowString().Format( L"cursor={X:%d,Y:%d}", - x, y - )); + x, + y)); Log::Comment(NoThrowString().Format( - L"attrA=%s", VerifyOutputTraits::ToString(attrA).GetBuffer() - )); + L"attrA=%s", VerifyOutputTraits::ToString(attrA).GetBuffer())); LOG_ATTR(attrA); LOG_ATTR(attrB); LOG_ATTR(attrC); @@ -989,7 +983,6 @@ void TextBufferTests::TestComplexUnBold() stateMachine.ProcessString(&reset[0], reset.length()); } - void TextBufferTests::CopyAttrs() { CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); @@ -1015,8 +1008,8 @@ void TextBufferTests::CopyAttrs() Log::Comment(NoThrowString().Format( L"cursor={X:%d,Y:%d}", - x, y - )); + x, + y)); VERIFY_ARE_EQUAL(x, 0); VERIFY_ARE_EQUAL(y, 0); @@ -1029,15 +1022,14 @@ void TextBufferTests::CopyAttrs() Log::Comment(NoThrowString().Format( L"cursor={X:%d,Y:%d}", - x, y - )); + x, + y)); LOG_ATTR(attrA); LOG_ATTR(attrB); VERIFY_ARE_EQUAL(gci.LookupForegroundColor(attrA), dark_blue); VERIFY_ARE_EQUAL(gci.LookupForegroundColor(attrB), dark_magenta); - } void TextBufferTests::EmptySgrTest() @@ -1070,8 +1062,8 @@ void TextBufferTests::EmptySgrTest() const COLORREF darkRed = gci.GetColorTableEntry(4); Log::Comment(NoThrowString().Format( L"cursor={X:%d,Y:%d}", - x, y - )); + x, + y)); VERIFY_IS_TRUE(x >= 3); const auto& row = tbi.GetRowByOffset(y); @@ -1084,8 +1076,8 @@ void TextBufferTests::EmptySgrTest() Log::Comment(NoThrowString().Format( L"cursor={X:%d,Y:%d}", - x, y - )); + x, + y)); LOG_ATTR(attrA); LOG_ATTR(attrB); @@ -1136,8 +1128,8 @@ void TextBufferTests::TestReverseReset() Log::Comment(NoThrowString().Format( L"cursor={X:%d,Y:%d}", - x, y - )); + x, + y)); VERIFY_IS_TRUE(x >= 3); const auto& row = tbi.GetRowByOffset(y); @@ -1150,8 +1142,8 @@ void TextBufferTests::TestReverseReset() Log::Comment(NoThrowString().Format( L"cursor={X:%d,Y:%d}", - x, y - )); + x, + y)); LOG_ATTR(attrA); LOG_ATTR(attrB); @@ -1242,8 +1234,8 @@ void TextBufferTests::CopyLastAttr() Log::Comment(NoThrowString().Format( L"cursor={X:%d,Y:%d}", - x, y - )); + x, + y)); const ROW& row1 = tbi.GetRowByOffset(y + 1); const ROW& row2 = tbi.GetRowByOffset(y + 2); @@ -1265,8 +1257,8 @@ void TextBufferTests::CopyLastAttr() Log::Comment(NoThrowString().Format( L"cursor={X:%d,Y:%d}", - x, y - )); + x, + y)); LOG_ATTR(attr1A); LOG_ATTR(attr2A); @@ -1284,7 +1276,6 @@ void TextBufferTests::CopyLastAttr() VERIFY_ARE_EQUAL(gci.LookupForegroundColor(attr2B), solCyan); VERIFY_ARE_EQUAL(gci.LookupBackgroundColor(attr2B), solBg); - VERIFY_ARE_EQUAL(gci.LookupForegroundColor(attr3A), solFg); VERIFY_ARE_EQUAL(gci.LookupBackgroundColor(attr3A), solBg); @@ -1306,8 +1297,7 @@ void TextBufferTests::TestRgbThenBold() const Cursor& cursor = tbi.GetCursor(); // See MSFT:16398982 Log::Comment(NoThrowString().Format( - L"Test that a bold following a RGB color doesn't remove the RGB color" - )); + L"Test that a bold following a RGB color doesn't remove the RGB color")); Log::Comment(L"\"\\x1b[38;2;40;40;40m\\x1b[48;2;168;153;132mX\\x1b[1mX\\x1b[m\""); const auto foreground = RGB(40, 40, 40); const auto background = RGB(168, 153, 132); @@ -1323,11 +1313,10 @@ void TextBufferTests::TestRgbThenBold() const auto attrB = attrs[x - 1]; Log::Comment(NoThrowString().Format( L"cursor={X:%d,Y:%d}", - x, y - )); + x, + y)); Log::Comment(NoThrowString().Format( - L"attrA should be RGB, and attrB should be the same as attrA, NOT bolded" - )); + L"attrA should be RGB, and attrB should be the same as attrA, NOT bolded")); LOG_ATTR(attrA); LOG_ATTR(attrB); @@ -1352,10 +1341,9 @@ void TextBufferTests::TestResetClearsBoldness() StateMachine& stateMachine = si.GetStateMachine(); const Cursor& cursor = tbi.GetCursor(); Log::Comment(NoThrowString().Format( - L"Test that resetting bold attributes clears the boldness." - )); + L"Test that resetting bold attributes clears the boldness.")); const auto x0 = cursor.GetPosition().X; - + // Test assumes that the background/foreground were default attribute when it starts up, // so set that here. TextAttribute defaultAttribute; @@ -1381,11 +1369,10 @@ void TextBufferTests::TestResetClearsBoldness() const auto attrD = attrs[x0 + 3]; Log::Comment(NoThrowString().Format( L"cursor={X:%d,Y:%d}", - x, y - )); + x, + y)); Log::Comment(NoThrowString().Format( - L"attrA should be RGB, and attrB should be the same as attrA, NOT bolded" - )); + L"attrA should be RGB, and attrB should be the same as attrA, NOT bolded")); LOG_ATTR(attrA); LOG_ATTR(attrB); @@ -1450,8 +1437,8 @@ void TextBufferTests::TestBackspaceStrings() Log::Comment(NoThrowString().Format( L"cursor={X:%d,Y:%d}", - x0, y0 - )); + x0, + y0)); std::wstring seq = L"a\b \b"; stateMachine.ProcessString(seq.c_str(), seq.length()); @@ -1495,8 +1482,8 @@ void TextBufferTests::TestBackspaceStringsAPI() Log::Comment(NoThrowString().Format( L"cursor={X:%d,Y:%d}", - x0, y0 - )); + x0, + y0)); // We're going to write an "a" to the buffer in various ways, then try // backspacing it with "\b \b". @@ -1509,8 +1496,7 @@ void TextBufferTests::TestBackspaceStringsAPI() size_t seqCb = 6; Log::Comment(NoThrowString().Format( - L"Using WriteCharsLegacy, write \\b \\b as a single string." - )); + L"Using WriteCharsLegacy, write \\b \\b as a single string.")); { wchar_t* str = L"\b \b"; VERIFY_SUCCESS_NTSTATUS(WriteCharsLegacy(si, str, str, str, &seqCb, nullptr, cursor.GetPosition().X, 0, nullptr)); @@ -1519,8 +1505,7 @@ void TextBufferTests::TestBackspaceStringsAPI() VERIFY_ARE_EQUAL(cursor.GetPosition().Y, y0); Log::Comment(NoThrowString().Format( - L"Using DoWriteConsole, write \\b \\b as a single string." - )); + L"Using DoWriteConsole, write \\b \\b as a single string.")); VERIFY_SUCCEEDED(DoWriteConsole(L"a", &aCb, si, waiter)); VERIFY_SUCCEEDED(DoWriteConsole(str, &seqCb, si, waiter)); @@ -1531,8 +1516,7 @@ void TextBufferTests::TestBackspaceStringsAPI() seqCb = 2; Log::Comment(NoThrowString().Format( - L"Using DoWriteConsole, write \\b \\b as seperate strings." - )); + L"Using DoWriteConsole, write \\b \\b as seperate strings.")); VERIFY_SUCCEEDED(DoWriteConsole(L"a", &seqCb, si, waiter)); VERIFY_SUCCEEDED(DoWriteConsole(L"\b", &seqCb, si, waiter)); @@ -1542,10 +1526,8 @@ void TextBufferTests::TestBackspaceStringsAPI() VERIFY_ARE_EQUAL(cursor.GetPosition().X, x0); VERIFY_ARE_EQUAL(cursor.GetPosition().Y, y0); - Log::Comment(NoThrowString().Format( - L"Using WriteCharsLegacy, write \\b \\b as seperate strings." - )); + L"Using WriteCharsLegacy, write \\b \\b as seperate strings.")); { wchar_t* str = L"a"; VERIFY_SUCCESS_NTSTATUS(WriteCharsLegacy(si, str, str, str, &seqCb, nullptr, cursor.GetPosition().X, 0, nullptr)); @@ -1565,7 +1547,6 @@ void TextBufferTests::TestBackspaceStringsAPI() VERIFY_ARE_EQUAL(cursor.GetPosition().X, x0); VERIFY_ARE_EQUAL(cursor.GetPosition().Y, y0); - } void TextBufferTests::TestRepeatCharacter() @@ -1582,8 +1563,7 @@ void TextBufferTests::TestRepeatCharacter() cursor.SetYPosition(0); Log::Comment( - L"Test 0: Simply repeat a single character." - ); + L"Test 0: Simply repeat a single character."); std::wstring sequence = L"X"; stateMachine.ProcessString(sequence); @@ -1603,8 +1583,7 @@ void TextBufferTests::TestRepeatCharacter() } Log::Comment( - L"Test 1: Try repeating characters after another VT action. It should do nothing." - ); + L"Test 1: Try repeating characters after another VT action. It should do nothing."); stateMachine.ProcessString(L"\n"); stateMachine.ProcessString(L"A"); @@ -1629,8 +1608,7 @@ void TextBufferTests::TestRepeatCharacter() } Log::Comment( - L"Test 2: Repeat a character lots of times" - ); + L"Test 2: Repeat a character lots of times"); stateMachine.ProcessString(L"\x1b[3;H"); stateMachine.ProcessString(L"C"); @@ -1652,8 +1630,7 @@ void TextBufferTests::TestRepeatCharacter() } Log::Comment( - L"Test 3: try repeating a non-graphical character. It should do nothing." - ); + L"Test 3: try repeating a non-graphical character. It should do nothing."); stateMachine.ProcessString(L"\r\n"); VERIFY_ARE_EQUAL(cursor.GetPosition().X, 0); @@ -1664,10 +1641,8 @@ void TextBufferTests::TestRepeatCharacter() VERIFY_ARE_EQUAL(cursor.GetPosition().X, 0); VERIFY_ARE_EQUAL(cursor.GetPosition().Y, 4); - Log::Comment( - L"Test 4: try repeating multiple times. It should do nothing." - ); + L"Test 4: try repeating multiple times. It should do nothing."); stateMachine.ProcessString(L"\r\n"); VERIFY_ARE_EQUAL(cursor.GetPosition().X, 0); @@ -1791,7 +1766,6 @@ void TextBufferTests::ResizeTraditional() viewIt++; } } - } // This tests that when buffer storage rows are rotated around during a resize traditional operation, @@ -1939,7 +1913,7 @@ void TextBufferTests::ResizeTraditionalHighUnicodeColumnRemoval() VERIFY_ARE_EQUAL(1u, _buffer->GetUnicodeStorage()._map.size(), L"There should be one item in the map."); // Perform resize to trim off the column of the buffer that included the emoji - COORD trimmedBufferSize{ bufferSize.X - 1, bufferSize.Y}; + COORD trimmedBufferSize{ bufferSize.X - 1, bufferSize.Y }; VERIFY_NT_SUCCESS(_buffer->ResizeTraditional(trimmedBufferSize)); diff --git a/src/host/ut_host/TitleTests.cpp b/src/host/ut_host/TitleTests.cpp index ec5166505..2584e64d1 100644 --- a/src/host/ut_host/TitleTests.cpp +++ b/src/host/ut_host/TitleTests.cpp @@ -29,7 +29,6 @@ class TitleTests return false; } - TEST_METHOD(TestTranslateConsoleTitle) { BEGIN_TEST_METHOD_PROPERTIES() diff --git a/src/host/ut_host/Utf16ParserTests.cpp b/src/host/ut_host/Utf16ParserTests.cpp index 2c050ee38..ff4c33161 100644 --- a/src/host/ut_host/Utf16ParserTests.cpp +++ b/src/host/ut_host/Utf16ParserTests.cpp @@ -11,7 +11,6 @@ using namespace WEX::Common; using namespace WEX::Logging; using namespace WEX::TestExecution; - static const std::vector CyrillicChar = { 0x0431 }; // lowercase be static const std::vector LatinChar = { 0x0061 }; // uppercase A static const std::vector FullWidthChar = { 0xFF2D }; // fullwidth latin small letter m diff --git a/src/host/ut_host/Utf8ToWideCharParserTests.cpp b/src/host/ut_host/Utf8ToWideCharParserTests.cpp index 72e488d6a..fbd28788b 100644 --- a/src/host/ut_host/Utf8ToWideCharParserTests.cpp +++ b/src/host/ut_host/Utf8ToWideCharParserTests.cpp @@ -19,20 +19,19 @@ class Utf8ToWideCharParserTests static const unsigned int utf8CodePage = 65001; static const unsigned int USACodePage = 1252; - TEST_CLASS(Utf8ToWideCharParserTests); TEST_METHOD(ConvertsAsciiTest) { Log::Comment(L"Testing that ASCII chars are correctly converted to wide chars"); - auto parser = Utf8ToWideCharParser { utf8CodePage }; + auto parser = Utf8ToWideCharParser{ utf8CodePage }; // ascii "hello" const unsigned char hello[5] = { 0x48, 0x65, 0x6c, 0x6c, 0x6f }; const unsigned char wideHello[10] = { 0x48, 0x00, 0x65, 0x00, 0x6c, 0x00, 0x6c, 0x00, 0x6f, 0x00 }; unsigned int count = 5; unsigned int consumed = 0; unsigned int generated = 0; - unique_ptr output { nullptr }; + unique_ptr output{ nullptr }; VERIFY_SUCCEEDED(parser.Parse(hello, count, consumed, output, generated)); VERIFY_ARE_EQUAL(consumed, (unsigned int)5); @@ -49,14 +48,14 @@ class Utf8ToWideCharParserTests TEST_METHOD(ConvertSimpleUtf8Test) { Log::Comment(L"Testing that a simple UTF8 sequence can be converted"); - auto parser = Utf8ToWideCharParser { utf8CodePage }; + auto parser = Utf8ToWideCharParser{ utf8CodePage }; // U+3059, U+3057 (hiragana sushi) - const unsigned char sushi[6] = { 0xe3, 0x81, 0x99, 0xe3, 0x81, 0x97}; + const unsigned char sushi[6] = { 0xe3, 0x81, 0x99, 0xe3, 0x81, 0x97 }; const unsigned char wideSushi[4] = { 0x59, 0x30, 0x57, 0x30 }; unsigned int count = 6; unsigned int consumed = 0; unsigned int generated = 0; - unique_ptr output { nullptr }; + unique_ptr output{ nullptr }; VERIFY_SUCCEEDED(parser.Parse(sushi, count, consumed, output, generated)); VERIFY_ARE_EQUAL(consumed, (unsigned int)6); @@ -76,11 +75,11 @@ class Utf8ToWideCharParserTests // U+3057 (hiragana shi) unsigned char shi[3] = { 0xe3, 0x81, 0x97 }; unsigned char wideShi[2] = { 0x57, 0x30 }; - auto parser = Utf8ToWideCharParser { utf8CodePage }; + auto parser = Utf8ToWideCharParser{ utf8CodePage }; unsigned int count = 1; unsigned int consumed = 0; unsigned int generated = 0; - unique_ptr output { nullptr }; + unique_ptr output{ nullptr }; for (int i = 0; i < 2; ++i) { @@ -112,8 +111,8 @@ class Utf8ToWideCharParserTests unsigned int count = 4; unsigned int consumed = 0; unsigned int generated = 0; - unique_ptr output { nullptr }; - auto parser = Utf8ToWideCharParser { utf8CodePage }; + unique_ptr output{ nullptr }; + auto parser = Utf8ToWideCharParser{ utf8CodePage }; VERIFY_SUCCEEDED(parser.Parse(sushi, count, consumed, output, generated)); // check that we got the first wide char back @@ -157,6 +156,8 @@ class Utf8ToWideCharParserTests TEST_METHOD(MergesMultiplePartialSequencesTest) { Log::Comment(L"Testing that partial sequences sent individually will be merged together"); + + // clang-format off // (hiragana doomo arigatoo) const unsigned char doomoArigatoo[24] = { 0xe3, 0x81, 0xa9, // U+3069 @@ -178,12 +179,14 @@ class Utf8ToWideCharParserTests 0x68, 0x30, 0x46, 0x30 }; + // clang-format on + // send first 4 bytes unsigned int count = 4; unsigned int consumed = 0; unsigned int generated = 0; - unique_ptr output { nullptr }; - auto parser = Utf8ToWideCharParser { utf8CodePage }; + unique_ptr output{ nullptr }; + auto parser = Utf8ToWideCharParser{ utf8CodePage }; VERIFY_SUCCEEDED(parser.Parse(doomoArigatoo, count, consumed, output, generated)); VERIFY_ARE_EQUAL(consumed, (unsigned int)4); @@ -191,7 +194,7 @@ class Utf8ToWideCharParserTests VERIFY_ARE_NOT_EQUAL(output.get(), nullptr); unsigned char* pReturnedBytes = reinterpret_cast(output.get()); - for(int i = 0; i < 2; ++i) + for (int i = 0; i < 2; ++i) { VERIFY_ARE_EQUAL(wideDoomoArigatoo[i], pReturnedBytes[i]); } @@ -207,7 +210,7 @@ class Utf8ToWideCharParserTests VERIFY_ARE_NOT_EQUAL(output.get(), nullptr); pReturnedBytes = reinterpret_cast(output.get()); - for(int i = 0; i < 10; ++i) + for (int i = 0; i < 10; ++i) { VERIFY_ARE_EQUAL(wideDoomoArigatoo[i + 2], pReturnedBytes[i]); } @@ -223,7 +226,7 @@ class Utf8ToWideCharParserTests VERIFY_ARE_NOT_EQUAL(output.get(), nullptr); pReturnedBytes = reinterpret_cast(output.get()); - for(int i = 0; i < 4; ++i) + for (int i = 0; i < 4; ++i) { VERIFY_ARE_EQUAL(wideDoomoArigatoo[i + 12], pReturnedBytes[i]); } @@ -232,18 +235,22 @@ class Utf8ToWideCharParserTests TEST_METHOD(RemovesInvalidSequencesTest) { Log::Comment(L"Testing that invalid sequences are removed and don't stop the parsing of the rest"); + + // clang-format off // hiragana sushi with junk between japanese characters const unsigned char sushi[9] = { 0xe3, 0x81, 0x99, // U+3059 0x80, 0x81, 0x82, // junk continuation bytes 0xe3, 0x81, 0x97 // U+3057 }; + // clang-format on + const unsigned char wideSushi[4] = { 0x59, 0x30, 0x57, 0x30 }; unsigned int count = 9; unsigned int consumed = 0; unsigned int generated = 0; - unique_ptr output { nullptr }; - auto parser = Utf8ToWideCharParser { utf8CodePage }; + unique_ptr output{ nullptr }; + auto parser = Utf8ToWideCharParser{ utf8CodePage }; VERIFY_SUCCEEDED(parser.Parse(sushi, count, consumed, output, generated)); VERIFY_ARE_EQUAL(consumed, (unsigned int)9); @@ -251,7 +258,7 @@ class Utf8ToWideCharParserTests VERIFY_ARE_NOT_EQUAL(output.get(), nullptr); unsigned char* pReturnedBytes = reinterpret_cast(output.get()); - for(int i = 0; i < ARRAYSIZE(wideSushi); ++i) + for (int i = 0; i < ARRAYSIZE(wideSushi); ++i) { VERIFY_ARE_EQUAL(wideSushi[i], pReturnedBytes[i]); } @@ -260,14 +267,14 @@ class Utf8ToWideCharParserTests TEST_METHOD(PartialBytesAreDroppedOnCodePageChangeTest) { Log::Comment(L"Testing that a saved partial sequence is cleared when the codepage changes"); - auto parser = Utf8ToWideCharParser { utf8CodePage }; + auto parser = Utf8ToWideCharParser{ utf8CodePage }; // 2 bytes of a 4 byte sequence const unsigned int inputSize = 2; const unsigned char partialSequence[inputSize] = { 0xF0, 0x80 }; unsigned int count = inputSize; unsigned int consumed = 0; unsigned int generated = 0; - unique_ptr output { nullptr }; + unique_ptr output{ nullptr }; VERIFY_SUCCEEDED(parser.Parse(partialSequence, count, consumed, output, generated)); VERIFY_ARE_EQUAL(parser._currentState, Utf8ToWideCharParser::_State::BeginPartialParse); VERIFY_ARE_EQUAL(parser._bytesStored, inputSize); @@ -285,7 +292,7 @@ class Utf8ToWideCharParserTests TEST_METHOD(_IsLeadByteTest) { Log::Comment(L"Testing that _IsLeadByte properly differentiates correct from incorrect sequences"); - auto parser = Utf8ToWideCharParser { utf8CodePage }; + auto parser = Utf8ToWideCharParser{ utf8CodePage }; VERIFY_IS_TRUE(parser._IsLeadByte(0xC0)); // 2 byte sequence VERIFY_IS_TRUE(parser._IsLeadByte(0xE0)); // 3 byte sequence VERIFY_IS_TRUE(parser._IsLeadByte(0xF0)); // 4 byte sequence @@ -300,11 +307,10 @@ class Utf8ToWideCharParserTests VERIFY_IS_FALSE(parser._IsLeadByte(0xFF)); // all 1's } - TEST_METHOD(_IsContinuationByteTest) { Log::Comment(L"Testing that _IsContinuationByte properly differentiates correct from incorrect sequences"); - auto parser = Utf8ToWideCharParser { utf8CodePage }; + auto parser = Utf8ToWideCharParser{ utf8CodePage }; for (BYTE i = 0x00; i < 0xFF; ++i) { if (IsBitSet(i, 0x80) && !IsBitSet(i, 0x40)) @@ -322,7 +328,7 @@ class Utf8ToWideCharParserTests TEST_METHOD(_IsAsciiByteTest) { Log::Comment(L"Testing that _IsAsciiByte properly differentiates correct from incorrect sequences"); - auto parser = Utf8ToWideCharParser { utf8CodePage }; + auto parser = Utf8ToWideCharParser{ utf8CodePage }; for (BYTE i = 0x00; i < 0x80; ++i) { VERIFY_IS_TRUE(parser._IsAsciiByte(i), NoThrowString().Format(L"Byte is 0x%02x", i)); @@ -336,7 +342,7 @@ class Utf8ToWideCharParserTests TEST_METHOD(_Utf8SequenceSizeTest) { Log::Comment(L"Testing that _Utf8SequenceSize correctly counts the number of MSB 1's"); - auto parser = Utf8ToWideCharParser { utf8CodePage }; + auto parser = Utf8ToWideCharParser{ utf8CodePage }; VERIFY_ARE_EQUAL(parser._Utf8SequenceSize(0x00), (unsigned int)0); VERIFY_ARE_EQUAL(parser._Utf8SequenceSize(0x80), (unsigned int)1); VERIFY_ARE_EQUAL(parser._Utf8SequenceSize(0xC2), (unsigned int)2); @@ -349,5 +355,4 @@ class Utf8ToWideCharParserTests VERIFY_ARE_EQUAL(parser._Utf8SequenceSize(0xFE), (unsigned int)7); VERIFY_ARE_EQUAL(parser._Utf8SequenceSize(0xFF), (unsigned int)8); } - }; diff --git a/src/host/ut_host/UtilsTests.cpp b/src/host/ut_host/UtilsTests.cpp index 4e74d93c2..0e6c87581 100644 --- a/src/host/ut_host/UtilsTests.cpp +++ b/src/host/ut_host/UtilsTests.cpp @@ -72,7 +72,7 @@ class UtilsTests Log::Comment(String().Format(L"Coordinates - A: (%d, %d) B: (%d, %d)", coordA.X, coordA.Y, coordB.X, coordB.Y)); } - void SubtractRandom(short &psValue) + void SubtractRandom(short& psValue) { SHORT const sRand = RandomShort(); psValue -= gsl::narrow(std::max(sRand % psValue, 1)); diff --git a/src/host/ut_host/ViewportTests.cpp b/src/host/ut_host/ViewportTests.cpp index af6c482ad..d82028d9a 100644 --- a/src/host/ut_host/ViewportTests.cpp +++ b/src/host/ut_host/ViewportTests.cpp @@ -202,7 +202,9 @@ class ViewportTests VERIFY_ARE_EQUAL(1, v.Height()); VERIFY_ARE_EQUAL(1, v.Width()); VERIFY_ARE_EQUAL(origin, v.Origin()); + // clang-format off VERIFY_ARE_EQUAL(COORD({ 1, 1, }), v.Dimensions()); + // clang-format on } TEST_METHOD(ToRect) @@ -379,7 +381,6 @@ class ViewportTests view.Clamp(pos); VERIFY_ARE_EQUAL(before, pos, L"Verify clamp did nothing for position in top right corner."); - COORD expected; expected.X = rect.Right; expected.Y = rect.Top; @@ -431,7 +432,8 @@ class ViewportTests Viewport invalidView = Viewport::Empty(); VERIFY_THROWS_SPECIFIC(invalidView.Clamp(pos), - wil::ResultException, [](wil::ResultException& e) { return e.GetErrorCode() == E_NOT_VALID_STATE; }); + wil::ResultException, + [](wil::ResultException& e) { return e.GetErrorCode() == E_NOT_VALID_STATE; }); } TEST_METHOD(ClampViewport) @@ -795,7 +797,8 @@ class ViewportTests adjust = { SHORT_MAX, SHORT_MAX }; VERIFY_THROWS_SPECIFIC(const auto vp = Viewport::Offset(original, adjust), - wil::ResultException, [](wil::ResultException& e) { return e.GetErrorCode() == HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); }); + wil::ResultException, + [](wil::ResultException& e) { return e.GetErrorCode() == HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); }); } TEST_METHOD(Union) diff --git a/src/host/ut_host/VtIoTests.cpp b/src/host/ut_host/VtIoTests.cpp index 77610004c..860fb9209 100644 --- a/src/host/ut_host/VtIoTests.cpp +++ b/src/host/ut_host/VtIoTests.cpp @@ -19,7 +19,6 @@ using namespace WEX::Logging; using namespace WEX::TestExecution; using namespace std; - class Microsoft::Console::VirtualTerminal::VtIoTests { TEST_CLASS(VtIoTests); @@ -105,21 +104,18 @@ void VtIoTests::DtorTestJustEngine() L"This test is going to instantiate a bunch of VtIos in different \n" L"scenarios to see if something causes a weird cleanup.\n" L"It's here because of the strange nature of VtEngine having members\n" - L"that are only defined in UNIT_TESTING" - )); + L"that are only defined in UNIT_TESTING")); const WORD colorTableSize = 16; COLORREF colorTable[colorTableSize]; VtIoTestColorProvider p; Log::Comment(NoThrowString().Format( - L"New some engines and delete them" - )); + L"New some engines and delete them")); for (int i = 0; i < 25; ++i) { Log::Comment(NoThrowString().Format( - L"New/Delete loop #%d", i - )); + L"New/Delete loop #%d", i)); wil::unique_hfile hOutputFile; hOutputFile.reset(INVALID_HANDLE_VALUE); @@ -149,7 +145,6 @@ void VtIoTests::DtorTestJustEngine() delete pRenderEngineWinTelnet; Log::Comment(NoThrowString().Format(L"Deleted.")); } - } void VtIoTests::DtorTestDeleteVtio() @@ -158,21 +153,18 @@ void VtIoTests::DtorTestDeleteVtio() L"This test is going to instantiate a bunch of VtIos in different \n" L"scenarios to see if something causes a weird cleanup.\n" L"It's here because of the strange nature of VtEngine having members\n" - L"that are only defined in UNIT_TESTING" - )); + L"that are only defined in UNIT_TESTING")); const WORD colorTableSize = 16; COLORREF colorTable[colorTableSize]; VtIoTestColorProvider p; Log::Comment(NoThrowString().Format( - L"New some engines and delete them" - )); + L"New some engines and delete them")); for (int i = 0; i < 25; ++i) { Log::Comment(NoThrowString().Format( - L"New/Delete loop #%d", i - )); + L"New/Delete loop #%d", i)); wil::unique_hfile hOutputFile = wil::unique_hfile(INVALID_HANDLE_VALUE); @@ -227,7 +219,6 @@ void VtIoTests::DtorTestDeleteVtio() delete vtio; Log::Comment(NoThrowString().Format(L"Deleted.")); } - } void VtIoTests::DtorTestStackAlloc() @@ -236,21 +227,18 @@ void VtIoTests::DtorTestStackAlloc() L"This test is going to instantiate a bunch of VtIos in different \n" L"scenarios to see if something causes a weird cleanup.\n" L"It's here because of the strange nature of VtEngine having members\n" - L"that are only defined in UNIT_TESTING" - )); + L"that are only defined in UNIT_TESTING")); const WORD colorTableSize = 16; COLORREF colorTable[colorTableSize]; VtIoTestColorProvider p; Log::Comment(NoThrowString().Format( - L"make some engines and let them fall out of scope" - )); + L"make some engines and let them fall out of scope")); for (int i = 0; i < 25; ++i) { Log::Comment(NoThrowString().Format( - L"Scope Exit Auto cleanup #%d", i - )); + L"Scope Exit Auto cleanup #%d", i)); wil::unique_hfile hOutputFile; @@ -296,7 +284,6 @@ void VtIoTests::DtorTestStackAlloc() colorTableSize); } } - } void VtIoTests::DtorTestStackAllocMany() @@ -305,21 +292,18 @@ void VtIoTests::DtorTestStackAllocMany() L"This test is going to instantiate a bunch of VtIos in different \n" L"scenarios to see if something causes a weird cleanup.\n" L"It's here because of the strange nature of VtEngine having members\n" - L"that are only defined in UNIT_TESTING" - )); + L"that are only defined in UNIT_TESTING")); const WORD colorTableSize = 16; COLORREF colorTable[colorTableSize]; VtIoTestColorProvider p; Log::Comment(NoThrowString().Format( - L"Try an make a whole bunch all at once, and have them all fall out of scope at once." - )); + L"Try an make a whole bunch all at once, and have them all fall out of scope at once.")); for (int i = 0; i < 25; ++i) { Log::Comment(NoThrowString().Format( - L"Multiple engines, one scope loop #%d", i - )); + L"Multiple engines, one scope loop #%d", i)); wil::unique_hfile hOutputFile; { @@ -358,14 +342,12 @@ void VtIoTests::DtorTestStackAllocMany() colorTableSize); } } - } void VtIoTests::RendererDtorAndThread() { Log::Comment(NoThrowString().Format( - L"Test deleting a Renderer a bunch of times" - )); + L"Test deleting a Renderer a bunch of times")); for (int i = 0; i < 16; ++i) { @@ -389,8 +371,7 @@ void VtIoTests::RendererDtorAndThread() void VtIoTests::RendererDtorAndThreadAndDx() { Log::Comment(NoThrowString().Format( - L"Test deleting a Renderer a bunch of times" - )); + L"Test deleting a Renderer a bunch of times")); for (int i = 0; i < 16; ++i) { diff --git a/src/host/ut_host/VtRendererTests.cpp b/src/host/ut_host/VtRendererTests.cpp index 99cd16f0f..0b528270a 100644 --- a/src/host/ut_host/VtRendererTests.cpp +++ b/src/host/ut_host/VtRendererTests.cpp @@ -38,7 +38,6 @@ static const std::string CURSOR_HOME = "\x1b[H"; // We don't use null because that will confuse the VERIFY macros re: string length. const char* const EMPTY_CALLBACK_SENTINEL = "\xff"; - class VtRenderTestColorProvider : public Microsoft::Console::IDefaultColorProvider { public: @@ -62,6 +61,7 @@ class Microsoft::Console::Render::VtRendererTest TEST_CLASS_SETUP(ClassSetup) { + // clang-format off g_ColorTable[0] = RGB( 12, 12, 12); // Black g_ColorTable[1] = RGB( 0, 55, 218); // Dark Blue g_ColorTable[2] = RGB( 19, 161, 14); // Dark Green @@ -78,6 +78,7 @@ class Microsoft::Console::Render::VtRendererTest g_ColorTable[13] = RGB(180, 0, 158); // Bright Magenta g_ColorTable[14] = RGB(249, 241, 165); // Bright Yellow g_ColorTable[15] = RGB(242, 242, 242); // White + // clang-format on return true; } @@ -131,7 +132,8 @@ Viewport VtRendererTest::SetUpViewport() bool VtRendererTest::WriteCallback(const char* const pch, size_t const cch) { std::string actualString = std::string(pch, cch); - VERIFY_IS_GREATER_THAN(qExpectedInput.size(), static_cast(0), + VERIFY_IS_GREATER_THAN(qExpectedInput.size(), + static_cast(0), NoThrowString().Format(L"writing=\"%hs\", expecting %u strings", actualString.c_str(), qExpectedInput.size())); std::string first = qExpectedInput.front(); @@ -170,7 +172,6 @@ void VtRendererTest::TestPaint(VtEngine& engine, std::function pfn) // - void VtRendererTest::TestPaintXterm(XtermEngine& engine, std::function pfn) { - HRESULT hr = engine.StartPaint(); pfn(); // If we didn't have anything to do on this frame, still execute our @@ -188,7 +189,8 @@ void VtRendererTest::TestPaintXterm(XtermEngine& engine, std::function p VERIFY_SUCCEEDED(engine.EndPaint()); - VERIFY_ARE_EQUAL(qExpectedInput.size(), static_cast(0), + VERIFY_ARE_EQUAL(qExpectedInput.size(), + static_cast(0), L"Done painting, there shouldn't be any output we're still expecting"); } @@ -231,10 +233,10 @@ void VtRendererTest::VtSequenceHelperTests() VERIFY_SUCCEEDED(engine->_EraseCharacter(2)); qExpectedInput.push_back("\x1b[2;3H"); - VERIFY_SUCCEEDED(engine->_CursorPosition({2, 1})); + VERIFY_SUCCEEDED(engine->_CursorPosition({ 2, 1 })); qExpectedInput.push_back("\x1b[1;1H"); - VERIFY_SUCCEEDED(engine->_CursorPosition({0, 0})); + VERIFY_SUCCEEDED(engine->_CursorPosition({ 0, 0 })); qExpectedInput.push_back("\x1b[H"); VERIFY_SUCCEEDED(engine->_CursorHome()); @@ -266,35 +268,28 @@ void VtRendererTest::Xterm256TestInvalidate() Viewport view = SetUpViewport(); Log::Comment(NoThrowString().Format( - L"Make sure that invalidating all invalidates the whole viewport." - )); + L"Make sure that invalidating all invalidates the whole viewport.")); VERIFY_SUCCEEDED(engine->InvalidateAll()); qExpectedInput.push_back("\x1b[2J"); - TestPaint(*engine, [&]() - { + TestPaint(*engine, [&]() { VERIFY_ARE_EQUAL(view, engine->_invalidRect); }); Log::Comment(NoThrowString().Format( - L"Make sure that invalidating anything only invalidates that portion" - )); - SMALL_RECT invalid = {1, 1, 1, 1}; + L"Make sure that invalidating anything only invalidates that portion")); + SMALL_RECT invalid = { 1, 1, 1, 1 }; VERIFY_SUCCEEDED(engine->Invalidate(&invalid)); - TestPaint(*engine, [&]() - { + TestPaint(*engine, [&]() { VERIFY_ARE_EQUAL(invalid, engine->_invalidRect.ToExclusive()); }); Log::Comment(NoThrowString().Format( - L"Make sure that scrolling only invalidates part of the viewport, and sends the right sequences" - )); - COORD scrollDelta = {0, 1}; + L"Make sure that scrolling only invalidates part of the viewport, and sends the right sequences")); + COORD scrollDelta = { 0, 1 }; VERIFY_SUCCEEDED(engine->InvalidateScroll(&scrollDelta)); - TestPaintXterm(*engine, [&]() - { + TestPaintXterm(*engine, [&]() { Log::Comment(NoThrowString().Format( - L"---- Scrolled one down, only top line is invalid. ----" - )); + L"---- Scrolled one down, only top line is invalid. ----")); invalid = view.ToExclusive(); invalid.Bottom = 1; @@ -305,14 +300,12 @@ void VtRendererTest::Xterm256TestInvalidate() VERIFY_SUCCEEDED(engine->ScrollFrame()); }); - scrollDelta = {0, 3}; + scrollDelta = { 0, 3 }; VERIFY_SUCCEEDED(engine->InvalidateScroll(&scrollDelta)); - TestPaintXterm(*engine, [&]() - { + TestPaintXterm(*engine, [&]() { Log::Comment(NoThrowString().Format( - L"---- Scrolled three down, only top 3 lines are invalid. ----" - )); + L"---- Scrolled three down, only top 3 lines are invalid. ----")); invalid = view.ToExclusive(); invalid.Bottom = 3; @@ -322,13 +315,11 @@ void VtRendererTest::Xterm256TestInvalidate() VERIFY_SUCCEEDED(engine->ScrollFrame()); }); - scrollDelta = {0, -1}; + scrollDelta = { 0, -1 }; VERIFY_SUCCEEDED(engine->InvalidateScroll(&scrollDelta)); - TestPaintXterm(*engine, [&]() - { + TestPaintXterm(*engine, [&]() { Log::Comment(NoThrowString().Format( - L"---- Scrolled one up, only bottom line is invalid. ----" - )); + L"---- Scrolled one up, only bottom line is invalid. ----")); invalid = view.ToExclusive(); invalid.Top = invalid.Bottom - 1; @@ -339,13 +330,11 @@ void VtRendererTest::Xterm256TestInvalidate() VERIFY_SUCCEEDED(engine->ScrollFrame()); }); - scrollDelta = {0, -3}; + scrollDelta = { 0, -3 }; VERIFY_SUCCEEDED(engine->InvalidateScroll(&scrollDelta)); - TestPaintXterm(*engine, [&]() - { + TestPaintXterm(*engine, [&]() { Log::Comment(NoThrowString().Format( - L"---- Scrolled three up, only bottom 3 lines are invalid. ----" - )); + L"---- Scrolled three up, only bottom 3 lines are invalid. ----")); invalid = view.ToExclusive(); invalid.Top = invalid.Bottom - 3; @@ -357,18 +346,15 @@ void VtRendererTest::Xterm256TestInvalidate() }); Log::Comment(NoThrowString().Format( - L"Multiple scrolls are coalesced" - )); + L"Multiple scrolls are coalesced")); - scrollDelta = {0, 1}; + scrollDelta = { 0, 1 }; VERIFY_SUCCEEDED(engine->InvalidateScroll(&scrollDelta)); - scrollDelta = {0, 2}; + scrollDelta = { 0, 2 }; VERIFY_SUCCEEDED(engine->InvalidateScroll(&scrollDelta)); - TestPaintXterm(*engine, [&]() - { + TestPaintXterm(*engine, [&]() { Log::Comment(NoThrowString().Format( - L"---- Scrolled three down, only top 3 lines are invalid. ----" - )); + L"---- Scrolled three down, only top 3 lines are invalid. ----")); invalid = view.ToExclusive(); invalid.Bottom = 3; @@ -378,25 +364,21 @@ void VtRendererTest::Xterm256TestInvalidate() VERIFY_SUCCEEDED(engine->ScrollFrame()); }); - scrollDelta = {0, 1}; + scrollDelta = { 0, 1 }; VERIFY_SUCCEEDED(engine->InvalidateScroll(&scrollDelta)); Log::Comment(NoThrowString().Format( - VerifyOutputTraits::ToString(engine->_invalidRect.ToExclusive()) - )); + VerifyOutputTraits::ToString(engine->_invalidRect.ToExclusive()))); - scrollDelta = {0, -1}; + scrollDelta = { 0, -1 }; VERIFY_SUCCEEDED(engine->InvalidateScroll(&scrollDelta)); Log::Comment(NoThrowString().Format( - VerifyOutputTraits::ToString(engine->_invalidRect.ToExclusive()) - )); + VerifyOutputTraits::ToString(engine->_invalidRect.ToExclusive()))); qExpectedInput.push_back("\x1b[2J"); - TestPaint(*engine, [&]() - { + TestPaint(*engine, [&]() { Log::Comment(NoThrowString().Format( L"---- Scrolled one down and one up, nothing should change ----" - L" But it still does for now MSFT:14169294" - )); + L" But it still does for now MSFT:14169294")); invalid = view.ToExclusive(); VERIFY_ARE_EQUAL(invalid, engine->_invalidRect.ToExclusive()); @@ -421,42 +403,33 @@ void VtRendererTest::Xterm256TestColors() Viewport view = SetUpViewport(); Log::Comment(NoThrowString().Format( - L"Test changing the text attributes" - )); + L"Test changing the text attributes")); Log::Comment(NoThrowString().Format( L"Begin by setting some test values - FG,BG = (1,2,3), (4,5,6) to start" - L"These values were picked for ease of formatting raw COLORREF values." - )); + L"These values were picked for ease of formatting raw COLORREF values.")); qExpectedInput.push_back("\x1b[38;2;1;2;3m"); qExpectedInput.push_back("\x1b[48;2;5;6;7m"); VERIFY_SUCCEEDED(engine->UpdateDrawingBrushes(0x00030201, 0x00070605, 0, false, false)); - TestPaint(*engine, [&]() - { + TestPaint(*engine, [&]() { Log::Comment(NoThrowString().Format( - L"----Change only the BG----" - )); + L"----Change only the BG----")); qExpectedInput.push_back("\x1b[48;2;7;8;9m"); VERIFY_SUCCEEDED(engine->UpdateDrawingBrushes(0x00030201, 0x00090807, 0, false, false)); Log::Comment(NoThrowString().Format( - L"----Change only the FG----" - )); + L"----Change only the FG----")); qExpectedInput.push_back("\x1b[38;2;10;11;12m"); VERIFY_SUCCEEDED(engine->UpdateDrawingBrushes(0x000c0b0a, 0x00090807, 0, false, false)); - }); - TestPaint(*engine, [&]() - { + TestPaint(*engine, [&]() { Log::Comment(NoThrowString().Format( - L"Make sure that color setting persists across EndPaint/StartPaint" - )); + L"Make sure that color setting persists across EndPaint/StartPaint")); qExpectedInput.push_back(EMPTY_CALLBACK_SENTINEL); VERIFY_SUCCEEDED(engine->UpdateDrawingBrushes(0x000c0b0a, 0x00090807, 0, false, false)); WriteCallback(EMPTY_CALLBACK_SENTINEL, 1); // This will make sure nothing was written to the callback - }); // Now also do the body of the 16color test as well. @@ -464,56 +437,45 @@ void VtRendererTest::Xterm256TestColors() // test actually uses an RGB value instead of the closest match. Log::Comment(NoThrowString().Format( - L"Begin by setting the default colors - FG,BG = BRIGHT_WHITE,DARK_BLACK" - )); + L"Begin by setting the default colors - FG,BG = BRIGHT_WHITE,DARK_BLACK")); qExpectedInput.push_back("\x1b[m"); VERIFY_SUCCEEDED(engine->UpdateDrawingBrushes(g_ColorTable[15], g_ColorTable[0], 0, false, false)); - TestPaint(*engine, [&]() - { + TestPaint(*engine, [&]() { Log::Comment(NoThrowString().Format( - L"----Change only the BG----" - )); + L"----Change only the BG----")); qExpectedInput.push_back("\x1b[41m"); // Background DARK_RED VERIFY_SUCCEEDED(engine->UpdateDrawingBrushes(g_ColorTable[15], g_ColorTable[4], 0, false, false)); Log::Comment(NoThrowString().Format( - L"----Change only the FG----" - )); + L"----Change only the FG----")); qExpectedInput.push_back("\x1b[37m"); // Foreground DARK_WHITE VERIFY_SUCCEEDED(engine->UpdateDrawingBrushes(g_ColorTable[7], g_ColorTable[4], 0, false, false)); Log::Comment(NoThrowString().Format( - L"----Change only the BG to something not in the table----" - )); + L"----Change only the BG to something not in the table----")); qExpectedInput.push_back("\x1b[48;2;1;1;1m"); // Background DARK_BLACK VERIFY_SUCCEEDED(engine->UpdateDrawingBrushes(g_ColorTable[7], 0x010101, 0, false, false)); Log::Comment(NoThrowString().Format( - L"----Change only the BG to the 'Default' background----" - )); + L"----Change only the BG to the 'Default' background----")); qExpectedInput.push_back("\x1b[49m"); // Background DARK_BLACK VERIFY_SUCCEEDED(engine->UpdateDrawingBrushes(g_ColorTable[7], g_ColorTable[0], 0, false, false)); - Log::Comment(NoThrowString().Format( - L"----Back to defaults----" - )); + L"----Back to defaults----")); qExpectedInput.push_back("\x1b[m"); VERIFY_SUCCEEDED(engine->UpdateDrawingBrushes(g_ColorTable[15], g_ColorTable[0], 0, false, false)); }); - TestPaint(*engine, [&]() - { + TestPaint(*engine, [&]() { Log::Comment(NoThrowString().Format( - L"Make sure that color setting persists across EndPaint/StartPaint" - )); + L"Make sure that color setting persists across EndPaint/StartPaint")); qExpectedInput.push_back(EMPTY_CALLBACK_SENTINEL); VERIFY_SUCCEEDED(engine->UpdateDrawingBrushes(g_ColorTable[15], g_ColorTable[0], 0, false, false)); WriteCallback(EMPTY_CALLBACK_SENTINEL, 1); // This will make sure nothing was written to the callback - }); } @@ -534,89 +496,75 @@ void VtRendererTest::Xterm256TestCursor() Viewport view = SetUpViewport(); Log::Comment(NoThrowString().Format( - L"Test moving the cursor around. Every sequence should have both params to CUP explicitly." - )); - TestPaint(*engine, [&]() - { + L"Test moving the cursor around. Every sequence should have both params to CUP explicitly.")); + TestPaint(*engine, [&]() { qExpectedInput.push_back("\x1b[2;2H"); - VERIFY_SUCCEEDED(engine->_MoveCursor({1, 1})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 1, 1 })); Log::Comment(NoThrowString().Format( - L"----Only move Y coord----" - )); + L"----Only move Y coord----")); qExpectedInput.push_back("\x1b[31;2H"); - VERIFY_SUCCEEDED(engine->_MoveCursor({1, 30})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 1, 30 })); Log::Comment(NoThrowString().Format( - L"----Only move X coord----" - )); + L"----Only move X coord----")); qExpectedInput.push_back("\x1b[29C"); - VERIFY_SUCCEEDED(engine->_MoveCursor({30, 30})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 30, 30 })); Log::Comment(NoThrowString().Format( - L"----Sending the same move sends nothing----" - )); + L"----Sending the same move sends nothing----")); qExpectedInput.push_back(EMPTY_CALLBACK_SENTINEL); - VERIFY_SUCCEEDED(engine->_MoveCursor({30, 30})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 30, 30 })); WriteCallback(EMPTY_CALLBACK_SENTINEL, 1); Log::Comment(NoThrowString().Format( - L"----moving home sends a simple sequence----" - )); + L"----moving home sends a simple sequence----")); qExpectedInput.push_back("\x1b[H"); - VERIFY_SUCCEEDED(engine->_MoveCursor({0, 0})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 0, 0 })); Log::Comment(NoThrowString().Format( - L"----move into the line to test some other sequences----" - )); + L"----move into the line to test some other sequences----")); qExpectedInput.push_back("\x1b[7C"); - VERIFY_SUCCEEDED(engine->_MoveCursor({7, 0})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 7, 0 })); Log::Comment(NoThrowString().Format( - L"----move down one line (x stays the same)----" - )); + L"----move down one line (x stays the same)----")); qExpectedInput.push_back("\n"); - VERIFY_SUCCEEDED(engine->_MoveCursor({7, 1})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 7, 1 })); Log::Comment(NoThrowString().Format( - L"----move to the start of the next line----" - )); + L"----move to the start of the next line----")); qExpectedInput.push_back("\r\n"); - VERIFY_SUCCEEDED(engine->_MoveCursor({0, 2})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 0, 2 })); Log::Comment(NoThrowString().Format( - L"----move into the line to test some other sequnces----" - )); + L"----move into the line to test some other sequnces----")); qExpectedInput.push_back("\x1b[2;8H"); - VERIFY_SUCCEEDED(engine->_MoveCursor({7, 1})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 7, 1 })); Log::Comment(NoThrowString().Format( - L"----move to the start of this line (y stays the same)----" - )); + L"----move to the start of this line (y stays the same)----")); qExpectedInput.push_back("\r"); - VERIFY_SUCCEEDED(engine->_MoveCursor({0, 1})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 0, 1 })); qExpectedInput.push_back("\x1b[?25h"); }); - TestPaint(*engine, [&]() - { + TestPaint(*engine, [&]() { Log::Comment(NoThrowString().Format( L"Sending the same move across paint calls sends nothing." - L"The cursor's last \"real\" position was 0,0" - )); + L"The cursor's last \"real\" position was 0,0")); qExpectedInput.push_back(EMPTY_CALLBACK_SENTINEL); - VERIFY_SUCCEEDED(engine->_MoveCursor({0, 1})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 0, 1 })); WriteCallback(EMPTY_CALLBACK_SENTINEL, 1); Log::Comment(NoThrowString().Format( - L"Paint some text at 0,0, then try moving the cursor to where it currently is." - )); + L"Paint some text at 0,0, then try moving the cursor to where it currently is.")); qExpectedInput.push_back("\x1b[1C"); qExpectedInput.push_back("asdfghjkl"); const wchar_t* const line = L"asdfghjkl"; - const unsigned char rgWidths[] = {1, 1, 1, 1, 1, 1, 1, 1, 1}; + const unsigned char rgWidths[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1 }; std::vector clusters; for (size_t i = 0; i < wcslen(line); i++) @@ -627,20 +575,17 @@ void VtRendererTest::Xterm256TestCursor() VERIFY_SUCCEEDED(engine->PaintBufferLine({ clusters.data(), clusters.size() }, { 1, 1 }, false)); qExpectedInput.push_back(EMPTY_CALLBACK_SENTINEL); - VERIFY_SUCCEEDED(engine->_MoveCursor({10, 1})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 10, 1 })); WriteCallback(EMPTY_CALLBACK_SENTINEL, 1); - }); // Note that only PaintBufferLine updates the "Real" cursor position, which // the cursor is moved back to at the end of each paint - TestPaint(*engine, [&]() - { + TestPaint(*engine, [&]() { Log::Comment(NoThrowString().Format( - L"Sending the same move across paint calls sends nothing." - )); + L"Sending the same move across paint calls sends nothing.")); qExpectedInput.push_back(EMPTY_CALLBACK_SENTINEL); - VERIFY_SUCCEEDED(engine->_MoveCursor({10, 1})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 10, 1 })); WriteCallback(EMPTY_CALLBACK_SENTINEL, 1); }); } @@ -662,35 +607,28 @@ void VtRendererTest::XtermTestInvalidate() Viewport view = SetUpViewport(); Log::Comment(NoThrowString().Format( - L"Make sure that invalidating all invalidates the whole viewport." - )); + L"Make sure that invalidating all invalidates the whole viewport.")); VERIFY_SUCCEEDED(engine->InvalidateAll()); qExpectedInput.push_back("\x1b[2J"); - TestPaint(*engine, [&]() - { + TestPaint(*engine, [&]() { VERIFY_ARE_EQUAL(view, engine->_invalidRect); }); Log::Comment(NoThrowString().Format( - L"Make sure that invalidating anything only invalidates that portion" - )); - SMALL_RECT invalid = {1, 1, 1, 1}; + L"Make sure that invalidating anything only invalidates that portion")); + SMALL_RECT invalid = { 1, 1, 1, 1 }; VERIFY_SUCCEEDED(engine->Invalidate(&invalid)); - TestPaintXterm(*engine, [&]() - { + TestPaintXterm(*engine, [&]() { VERIFY_ARE_EQUAL(invalid, engine->_invalidRect.ToExclusive()); }); Log::Comment(NoThrowString().Format( - L"Make sure that scrolling only invalidates part of the viewport, and sends the right sequences" - )); - COORD scrollDelta = {0, 1}; + L"Make sure that scrolling only invalidates part of the viewport, and sends the right sequences")); + COORD scrollDelta = { 0, 1 }; VERIFY_SUCCEEDED(engine->InvalidateScroll(&scrollDelta)); - TestPaintXterm(*engine, [&]() - { + TestPaintXterm(*engine, [&]() { Log::Comment(NoThrowString().Format( - L"---- Scrolled one down, only top line is invalid. ----" - )); + L"---- Scrolled one down, only top line is invalid. ----")); invalid = view.ToExclusive(); invalid.Bottom = 1; @@ -701,13 +639,11 @@ void VtRendererTest::XtermTestInvalidate() VERIFY_SUCCEEDED(engine->ScrollFrame()); }); - scrollDelta = {0, 3}; + scrollDelta = { 0, 3 }; VERIFY_SUCCEEDED(engine->InvalidateScroll(&scrollDelta)); - TestPaintXterm(*engine, [&]() - { + TestPaintXterm(*engine, [&]() { Log::Comment(NoThrowString().Format( - L"---- Scrolled three down, only top 3 lines are invalid. ----" - )); + L"---- Scrolled three down, only top 3 lines are invalid. ----")); invalid = view.ToExclusive(); invalid.Bottom = 3; @@ -717,13 +653,11 @@ void VtRendererTest::XtermTestInvalidate() VERIFY_SUCCEEDED(engine->ScrollFrame()); }); - scrollDelta = {0, -1}; + scrollDelta = { 0, -1 }; VERIFY_SUCCEEDED(engine->InvalidateScroll(&scrollDelta)); - TestPaintXterm(*engine, [&]() - { + TestPaintXterm(*engine, [&]() { Log::Comment(NoThrowString().Format( - L"---- Scrolled one up, only bottom line is invalid. ----" - )); + L"---- Scrolled one up, only bottom line is invalid. ----")); invalid = view.ToExclusive(); invalid.Top = invalid.Bottom - 1; @@ -734,13 +668,11 @@ void VtRendererTest::XtermTestInvalidate() VERIFY_SUCCEEDED(engine->ScrollFrame()); }); - scrollDelta = {0, -3}; + scrollDelta = { 0, -3 }; VERIFY_SUCCEEDED(engine->InvalidateScroll(&scrollDelta)); - TestPaintXterm(*engine, [&]() - { + TestPaintXterm(*engine, [&]() { Log::Comment(NoThrowString().Format( - L"---- Scrolled three up, only bottom 3 lines are invalid. ----" - )); + L"---- Scrolled three up, only bottom 3 lines are invalid. ----")); invalid = view.ToExclusive(); invalid.Top = invalid.Bottom - 3; @@ -752,18 +684,15 @@ void VtRendererTest::XtermTestInvalidate() }); Log::Comment(NoThrowString().Format( - L"Multiple scrolls are coalesced" - )); + L"Multiple scrolls are coalesced")); - scrollDelta = {0, 1}; + scrollDelta = { 0, 1 }; VERIFY_SUCCEEDED(engine->InvalidateScroll(&scrollDelta)); - scrollDelta = {0, 2}; + scrollDelta = { 0, 2 }; VERIFY_SUCCEEDED(engine->InvalidateScroll(&scrollDelta)); - TestPaintXterm(*engine, [&]() - { + TestPaintXterm(*engine, [&]() { Log::Comment(NoThrowString().Format( - L"---- Scrolled three down, only top 3 lines are invalid. ----" - )); + L"---- Scrolled three down, only top 3 lines are invalid. ----")); invalid = view.ToExclusive(); invalid.Bottom = 3; @@ -773,25 +702,21 @@ void VtRendererTest::XtermTestInvalidate() VERIFY_SUCCEEDED(engine->ScrollFrame()); }); - scrollDelta = {0, 1}; + scrollDelta = { 0, 1 }; VERIFY_SUCCEEDED(engine->InvalidateScroll(&scrollDelta)); Log::Comment(NoThrowString().Format( - VerifyOutputTraits::ToString(engine->_invalidRect.ToExclusive()) - )); + VerifyOutputTraits::ToString(engine->_invalidRect.ToExclusive()))); - scrollDelta = {0, -1}; + scrollDelta = { 0, -1 }; VERIFY_SUCCEEDED(engine->InvalidateScroll(&scrollDelta)); Log::Comment(NoThrowString().Format( - VerifyOutputTraits::ToString(engine->_invalidRect.ToExclusive()) - )); + VerifyOutputTraits::ToString(engine->_invalidRect.ToExclusive()))); qExpectedInput.push_back("\x1b[2J"); - TestPaint(*engine, [&]() - { + TestPaint(*engine, [&]() { Log::Comment(NoThrowString().Format( L"---- Scrolled one down and one up, nothing should change ----" - L" But it still does for now MSFT:14169294" - )); + L" But it still does for now MSFT:14169294")); invalid = view.ToExclusive(); VERIFY_ARE_EQUAL(view, engine->_invalidRect); @@ -816,61 +741,49 @@ void VtRendererTest::XtermTestColors() Viewport view = SetUpViewport(); Log::Comment(NoThrowString().Format( - L"Test changing the text attributes" - )); + L"Test changing the text attributes")); Log::Comment(NoThrowString().Format( - L"Begin by setting the default colors - FG,BG = BRIGHT_WHITE,DARK_BLACK" - )); + L"Begin by setting the default colors - FG,BG = BRIGHT_WHITE,DARK_BLACK")); qExpectedInput.push_back("\x1b[m"); VERIFY_SUCCEEDED(engine->UpdateDrawingBrushes(g_ColorTable[15], g_ColorTable[0], 0, false, false)); - TestPaint(*engine, [&]() - { + TestPaint(*engine, [&]() { Log::Comment(NoThrowString().Format( - L"----Change only the BG----" - )); + L"----Change only the BG----")); qExpectedInput.push_back("\x1b[41m"); // Background DARK_RED VERIFY_SUCCEEDED(engine->UpdateDrawingBrushes(g_ColorTable[15], g_ColorTable[4], 0, false, false)); Log::Comment(NoThrowString().Format( - L"----Change only the FG----" - )); + L"----Change only the FG----")); qExpectedInput.push_back("\x1b[37m"); // Foreground DARK_WHITE VERIFY_SUCCEEDED(engine->UpdateDrawingBrushes(g_ColorTable[7], g_ColorTable[4], 0, false, false)); Log::Comment(NoThrowString().Format( - L"----Change only the BG to something not in the table----" - )); + L"----Change only the BG to something not in the table----")); qExpectedInput.push_back("\x1b[40m"); // Background DARK_BLACK VERIFY_SUCCEEDED(engine->UpdateDrawingBrushes(g_ColorTable[7], 0x010101, 0, false, false)); Log::Comment(NoThrowString().Format( - L"----Change only the BG to the 'Default' background----" - )); + L"----Change only the BG to the 'Default' background----")); qExpectedInput.push_back("\x1b[40m"); // Background DARK_BLACK VERIFY_SUCCEEDED(engine->UpdateDrawingBrushes(g_ColorTable[7], g_ColorTable[0], 0, false, false)); - Log::Comment(NoThrowString().Format( - L"----Back to defaults----" - )); + L"----Back to defaults----")); qExpectedInput.push_back("\x1b[m"); VERIFY_SUCCEEDED(engine->UpdateDrawingBrushes(g_ColorTable[15], g_ColorTable[0], 0, false, false)); }); - TestPaint(*engine, [&]() - { + TestPaint(*engine, [&]() { Log::Comment(NoThrowString().Format( - L"Make sure that color setting persists across EndPaint/StartPaint" - )); + L"Make sure that color setting persists across EndPaint/StartPaint")); qExpectedInput.push_back(EMPTY_CALLBACK_SENTINEL); VERIFY_SUCCEEDED(engine->UpdateDrawingBrushes(g_ColorTable[15], g_ColorTable[0], 0, false, false)); WriteCallback(EMPTY_CALLBACK_SENTINEL, 1); // This will make sure nothing was written to the callback }); - } void VtRendererTest::XtermTestCursor() @@ -890,89 +803,75 @@ void VtRendererTest::XtermTestCursor() Viewport view = SetUpViewport(); Log::Comment(NoThrowString().Format( - L"Test moving the cursor around. Every sequence should have both params to CUP explicitly." - )); - TestPaint(*engine, [&]() - { + L"Test moving the cursor around. Every sequence should have both params to CUP explicitly.")); + TestPaint(*engine, [&]() { qExpectedInput.push_back("\x1b[2;2H"); - VERIFY_SUCCEEDED(engine->_MoveCursor({1, 1})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 1, 1 })); Log::Comment(NoThrowString().Format( - L"----Only move Y coord----" - )); + L"----Only move Y coord----")); qExpectedInput.push_back("\x1b[31;2H"); - VERIFY_SUCCEEDED(engine->_MoveCursor({1, 30})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 1, 30 })); Log::Comment(NoThrowString().Format( - L"----Only move X coord----" - )); + L"----Only move X coord----")); qExpectedInput.push_back("\x1b[29C"); - VERIFY_SUCCEEDED(engine->_MoveCursor({30, 30})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 30, 30 })); Log::Comment(NoThrowString().Format( - L"----Sending the same move sends nothing----" - )); + L"----Sending the same move sends nothing----")); qExpectedInput.push_back(EMPTY_CALLBACK_SENTINEL); - VERIFY_SUCCEEDED(engine->_MoveCursor({30, 30})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 30, 30 })); WriteCallback(EMPTY_CALLBACK_SENTINEL, 1); Log::Comment(NoThrowString().Format( - L"----moving home sends a simple sequence----" - )); + L"----moving home sends a simple sequence----")); qExpectedInput.push_back("\x1b[H"); - VERIFY_SUCCEEDED(engine->_MoveCursor({0, 0})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 0, 0 })); Log::Comment(NoThrowString().Format( - L"----move into the line to test some other sequences----" - )); + L"----move into the line to test some other sequences----")); qExpectedInput.push_back("\x1b[7C"); - VERIFY_SUCCEEDED(engine->_MoveCursor({7, 0})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 7, 0 })); Log::Comment(NoThrowString().Format( - L"----move down one line (x stays the same)----" - )); + L"----move down one line (x stays the same)----")); qExpectedInput.push_back("\n"); - VERIFY_SUCCEEDED(engine->_MoveCursor({7, 1})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 7, 1 })); Log::Comment(NoThrowString().Format( - L"----move to the start of the next line----" - )); + L"----move to the start of the next line----")); qExpectedInput.push_back("\r\n"); - VERIFY_SUCCEEDED(engine->_MoveCursor({0, 2})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 0, 2 })); Log::Comment(NoThrowString().Format( - L"----move into the line to test some other sequnces----" - )); + L"----move into the line to test some other sequnces----")); qExpectedInput.push_back("\x1b[2;8H"); - VERIFY_SUCCEEDED(engine->_MoveCursor({7, 1})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 7, 1 })); Log::Comment(NoThrowString().Format( - L"----move to the start of this line (y stays the same)----" - )); + L"----move to the start of this line (y stays the same)----")); qExpectedInput.push_back("\r"); - VERIFY_SUCCEEDED(engine->_MoveCursor({0, 1})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 0, 1 })); qExpectedInput.push_back("\x1b[?25h"); }); - TestPaint(*engine, [&]() - { + TestPaint(*engine, [&]() { Log::Comment(NoThrowString().Format( L"Sending the same move across paint calls sends nothing." - L"The cursor's last \"real\" position was 0,0" - )); + L"The cursor's last \"real\" position was 0,0")); qExpectedInput.push_back(EMPTY_CALLBACK_SENTINEL); - VERIFY_SUCCEEDED(engine->_MoveCursor({0,1})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 0, 1 })); WriteCallback(EMPTY_CALLBACK_SENTINEL, 1); Log::Comment(NoThrowString().Format( - L"Paint some text at 0,0, then try moving the cursor to where it currently is." - )); + L"Paint some text at 0,0, then try moving the cursor to where it currently is.")); qExpectedInput.push_back("\x1b[1C"); qExpectedInput.push_back("asdfghjkl"); const wchar_t* const line = L"asdfghjkl"; - const unsigned char rgWidths[] = {1, 1, 1, 1, 1, 1, 1, 1, 1}; + const unsigned char rgWidths[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1 }; std::vector clusters; for (size_t i = 0; i < wcslen(line); i++) @@ -983,23 +882,19 @@ void VtRendererTest::XtermTestCursor() VERIFY_SUCCEEDED(engine->PaintBufferLine({ clusters.data(), clusters.size() }, { 1, 1 }, false)); qExpectedInput.push_back(EMPTY_CALLBACK_SENTINEL); - VERIFY_SUCCEEDED(engine->_MoveCursor({10, 1})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 10, 1 })); WriteCallback(EMPTY_CALLBACK_SENTINEL, 1); - }); // Note that only PaintBufferLine updates the "Real" cursor position, which // the cursor is moved back to at the end of each paint - TestPaint(*engine, [&]() - { + TestPaint(*engine, [&]() { Log::Comment(NoThrowString().Format( - L"Sending the same move across paint calls sends nothing." - )); + L"Sending the same move across paint calls sends nothing.")); qExpectedInput.push_back(EMPTY_CALLBACK_SENTINEL); - VERIFY_SUCCEEDED(engine->_MoveCursor({10, 1})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 10, 1 })); WriteCallback(EMPTY_CALLBACK_SENTINEL, 1); }); - } void VtRendererTest::WinTelnetTestInvalidate() @@ -1012,77 +907,66 @@ void VtRendererTest::WinTelnetTestInvalidate() Viewport view = SetUpViewport(); Log::Comment(NoThrowString().Format( - L"Make sure that invalidating all invalidates the whole viewport." - )); + L"Make sure that invalidating all invalidates the whole viewport.")); VERIFY_SUCCEEDED(engine->InvalidateAll()); - TestPaint(*engine, [&]() - { + TestPaint(*engine, [&]() { VERIFY_ARE_EQUAL(view, engine->_invalidRect); }); Log::Comment(NoThrowString().Format( - L"Make sure that invalidating anything only invalidates that portion" - )); - SMALL_RECT invalid = {1, 1, 1, 1}; + L"Make sure that invalidating anything only invalidates that portion")); + SMALL_RECT invalid = { 1, 1, 1, 1 }; VERIFY_SUCCEEDED(engine->Invalidate(&invalid)); - TestPaint(*engine, [&]() - { + TestPaint(*engine, [&]() { VERIFY_ARE_EQUAL(invalid, engine->_invalidRect.ToExclusive()); }); Log::Comment(NoThrowString().Format( - L"Make sure that scrolling invalidates the whole viewport, and sends no VT sequences" - )); - COORD scrollDelta = {0, 1}; + L"Make sure that scrolling invalidates the whole viewport, and sends no VT sequences")); + COORD scrollDelta = { 0, 1 }; VERIFY_SUCCEEDED(engine->InvalidateScroll(&scrollDelta)); - TestPaint(*engine, [&]() - { + TestPaint(*engine, [&]() { VERIFY_ARE_EQUAL(view, engine->_invalidRect); qExpectedInput.push_back(EMPTY_CALLBACK_SENTINEL); // sentinel VERIFY_SUCCEEDED(engine->ScrollFrame()); WriteCallback(EMPTY_CALLBACK_SENTINEL, 1); // This will make sure nothing was written to the callback }); - scrollDelta = {0, -1}; + scrollDelta = { 0, -1 }; VERIFY_SUCCEEDED(engine->InvalidateScroll(&scrollDelta)); - TestPaint(*engine, [&]() - { + TestPaint(*engine, [&]() { VERIFY_ARE_EQUAL(view, engine->_invalidRect); qExpectedInput.push_back(EMPTY_CALLBACK_SENTINEL); VERIFY_SUCCEEDED(engine->ScrollFrame()); WriteCallback(EMPTY_CALLBACK_SENTINEL, 1); // This will make sure nothing was written to the callback }); - scrollDelta = {1, 0}; + scrollDelta = { 1, 0 }; VERIFY_SUCCEEDED(engine->InvalidateScroll(&scrollDelta)); - TestPaint(*engine, [&]() - { + TestPaint(*engine, [&]() { VERIFY_ARE_EQUAL(view, engine->_invalidRect); qExpectedInput.push_back(EMPTY_CALLBACK_SENTINEL); VERIFY_SUCCEEDED(engine->ScrollFrame()); WriteCallback(EMPTY_CALLBACK_SENTINEL, 1); // This will make sure nothing was written to the callback }); - scrollDelta = {-1, 0}; + scrollDelta = { -1, 0 }; VERIFY_SUCCEEDED(engine->InvalidateScroll(&scrollDelta)); - TestPaint(*engine, [&]() - { + TestPaint(*engine, [&]() { VERIFY_ARE_EQUAL(view, engine->_invalidRect); qExpectedInput.push_back(EMPTY_CALLBACK_SENTINEL); VERIFY_SUCCEEDED(engine->ScrollFrame()); WriteCallback(EMPTY_CALLBACK_SENTINEL, 1); // This will make sure nothing was written to the callback }); - scrollDelta = {1, -1}; + scrollDelta = { 1, -1 }; VERIFY_SUCCEEDED(engine->InvalidateScroll(&scrollDelta)); - TestPaint(*engine, [&]() - { + TestPaint(*engine, [&]() { VERIFY_ARE_EQUAL(view, engine->_invalidRect); qExpectedInput.push_back(EMPTY_CALLBACK_SENTINEL); VERIFY_SUCCEEDED(engine->ScrollFrame()); WriteCallback(EMPTY_CALLBACK_SENTINEL, 1); // This will make sure nothing was written to the callback }); - } void VtRendererTest::WinTelnetTestColors() @@ -1095,59 +979,47 @@ void VtRendererTest::WinTelnetTestColors() Viewport view = SetUpViewport(); Log::Comment(NoThrowString().Format( - L"Test changing the text attributes" - )); + L"Test changing the text attributes")); Log::Comment(NoThrowString().Format( - L"Begin by setting the default colors - FG,BG = BRIGHT_WHITE,DARK_BLACK" - )); + L"Begin by setting the default colors - FG,BG = BRIGHT_WHITE,DARK_BLACK")); qExpectedInput.push_back("\x1b[m"); VERIFY_SUCCEEDED(engine->UpdateDrawingBrushes(g_ColorTable[15], g_ColorTable[0], 0, false, false)); - TestPaint(*engine, [&]() - { + TestPaint(*engine, [&]() { Log::Comment(NoThrowString().Format( - L"----Change only the BG----" - )); + L"----Change only the BG----")); qExpectedInput.push_back("\x1b[41m"); // Background DARK_RED VERIFY_SUCCEEDED(engine->UpdateDrawingBrushes(g_ColorTable[15], g_ColorTable[4], 0, false, false)); Log::Comment(NoThrowString().Format( - L"----Change only the FG----" - )); + L"----Change only the FG----")); qExpectedInput.push_back("\x1b[37m"); // Foreground DARK_WHITE VERIFY_SUCCEEDED(engine->UpdateDrawingBrushes(g_ColorTable[7], g_ColorTable[4], 0, false, false)); Log::Comment(NoThrowString().Format( - L"----Change only the BG to something not in the table----" - )); + L"----Change only the BG to something not in the table----")); qExpectedInput.push_back("\x1b[40m"); // Background DARK_BLACK VERIFY_SUCCEEDED(engine->UpdateDrawingBrushes(g_ColorTable[7], 0x010101, 0, false, false)); Log::Comment(NoThrowString().Format( - L"----Change only the BG to the 'Default' background----" - )); + L"----Change only the BG to the 'Default' background----")); qExpectedInput.push_back("\x1b[40m"); // Background DARK_BLACK VERIFY_SUCCEEDED(engine->UpdateDrawingBrushes(g_ColorTable[7], g_ColorTable[0], 0, false, false)); - Log::Comment(NoThrowString().Format( - L"----Back to defaults----" - )); + L"----Back to defaults----")); qExpectedInput.push_back("\x1b[m"); VERIFY_SUCCEEDED(engine->UpdateDrawingBrushes(g_ColorTable[15], g_ColorTable[0], 0, false, false)); }); - TestPaint(*engine, [&]() - { + TestPaint(*engine, [&]() { Log::Comment(NoThrowString().Format( - L"Make sure that color setting persists across EndPaint/StartPaint" - )); + L"Make sure that color setting persists across EndPaint/StartPaint")); qExpectedInput.push_back(EMPTY_CALLBACK_SENTINEL); VERIFY_SUCCEEDED(engine->UpdateDrawingBrushes(g_ColorTable[15], g_ColorTable[0], 0, false, false)); WriteCallback(EMPTY_CALLBACK_SENTINEL, 1); // This will make sure nothing was written to the callback - }); } @@ -1161,60 +1033,51 @@ void VtRendererTest::WinTelnetTestCursor() Viewport view = SetUpViewport(); Log::Comment(NoThrowString().Format( - L"Test moving the cursor around. Every sequence should have both params to CUP explicitly." - )); - TestPaint(*engine, [&]() - { + L"Test moving the cursor around. Every sequence should have both params to CUP explicitly.")); + TestPaint(*engine, [&]() { qExpectedInput.push_back("\x1b[2;2H"); - VERIFY_SUCCEEDED(engine->_MoveCursor({1, 1})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 1, 1 })); Log::Comment(NoThrowString().Format( - L"----Only move X coord----" - )); + L"----Only move X coord----")); qExpectedInput.push_back("\x1b[31;2H"); - VERIFY_SUCCEEDED(engine->_MoveCursor({1, 30})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 1, 30 })); Log::Comment(NoThrowString().Format( - L"----Only move Y coord----" - )); + L"----Only move Y coord----")); qExpectedInput.push_back("\x1b[31;31H"); - VERIFY_SUCCEEDED(engine->_MoveCursor({30, 30})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 30, 30 })); Log::Comment(NoThrowString().Format( - L"----Sending the same move sends nothing----" - )); + L"----Sending the same move sends nothing----")); qExpectedInput.push_back(EMPTY_CALLBACK_SENTINEL); - VERIFY_SUCCEEDED(engine->_MoveCursor({30, 30})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 30, 30 })); WriteCallback(EMPTY_CALLBACK_SENTINEL, 1); // The "real" location is the last place the cursor was moved to not // during the course of VT operations - eg the last place text was written, // or the cursor was manually painted at (MSFT 13310327) Log::Comment(NoThrowString().Format( - L"Make sure the cursor gets moved back to the last real location it was at" - )); + L"Make sure the cursor gets moved back to the last real location it was at")); qExpectedInput.push_back("\x1b[1;1H"); // EndPaint will send this sequence for us. }); - TestPaint(*engine, [&]() - { + TestPaint(*engine, [&]() { Log::Comment(NoThrowString().Format( L"Sending the same move across paint calls sends nothing." - L"The cursor's last \"real\" position was 0,0" - )); + L"The cursor's last \"real\" position was 0,0")); qExpectedInput.push_back(EMPTY_CALLBACK_SENTINEL); - VERIFY_SUCCEEDED(engine->_MoveCursor({0, 0})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 0, 0 })); WriteCallback(EMPTY_CALLBACK_SENTINEL, 1); Log::Comment(NoThrowString().Format( - L"Paint some text at 0,0, then try moving the cursor to where it currently is." - )); + L"Paint some text at 0,0, then try moving the cursor to where it currently is.")); qExpectedInput.push_back("\x1b[2;2H"); qExpectedInput.push_back("asdfghjkl"); const wchar_t* const line = L"asdfghjkl"; - const unsigned char rgWidths[] = {1, 1, 1, 1, 1, 1, 1, 1, 1}; + const unsigned char rgWidths[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1 }; std::vector clusters; for (size_t i = 0; i < wcslen(line); i++) @@ -1225,20 +1088,17 @@ void VtRendererTest::WinTelnetTestCursor() VERIFY_SUCCEEDED(engine->PaintBufferLine({ clusters.data(), clusters.size() }, { 1, 1 }, false)); qExpectedInput.push_back(EMPTY_CALLBACK_SENTINEL); - VERIFY_SUCCEEDED(engine->_MoveCursor({10, 1})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 10, 1 })); WriteCallback(EMPTY_CALLBACK_SENTINEL, 1); - }); // Note that only PaintBufferLine updates the "Real" cursor position, which // the cursor is moved back to at the end of each paint - TestPaint(*engine, [&]() - { + TestPaint(*engine, [&]() { Log::Comment(NoThrowString().Format( - L"Sending the same move across paint calls sends nothing." - )); + L"Sending the same move across paint calls sends nothing.")); qExpectedInput.push_back(EMPTY_CALLBACK_SENTINEL); - VERIFY_SUCCEEDED(engine->_MoveCursor({10, 1})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 10, 1 })); WriteCallback(EMPTY_CALLBACK_SENTINEL, 1); }); } @@ -1259,21 +1119,17 @@ void VtRendererTest::TestWrapping() Viewport view = SetUpViewport(); - TestPaintXterm(*engine, [&]() - { + TestPaintXterm(*engine, [&]() { Log::Comment(NoThrowString().Format( - L"Make sure the cursor is at 0,0" - )); + L"Make sure the cursor is at 0,0")); qExpectedInput.push_back("\x1b[H"); - VERIFY_SUCCEEDED(engine->_MoveCursor({0, 0})); + VERIFY_SUCCEEDED(engine->_MoveCursor({ 0, 0 })); }); - TestPaintXterm(*engine, [&]() - { + TestPaintXterm(*engine, [&]() { Log::Comment(NoThrowString().Format( L"Painting a line that wrapped, then painting another line, and " - L"making sure we don't manually move the cursor between those paints." - )); + L"making sure we don't manually move the cursor between those paints.")); qExpectedInput.push_back("asdfghjkl"); // TODO: Undoing this behavior due to 18123777. Will come back in MSFT:16485846 qExpectedInput.push_back("\r\n"); @@ -1281,7 +1137,7 @@ void VtRendererTest::TestWrapping() const wchar_t* const line1 = L"asdfghjkl"; const wchar_t* const line2 = L"zxcvbnm,."; - const unsigned char rgWidths[] = {1, 1, 1, 1, 1, 1, 1, 1, 1}; + const unsigned char rgWidths[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1 }; std::vector clusters1; for (size_t i = 0; i < wcslen(line1); i++) @@ -1296,7 +1152,6 @@ void VtRendererTest::TestWrapping() VERIFY_SUCCEEDED(engine->PaintBufferLine({ clusters1.data(), clusters1.size() }, { 0, 0 }, false)); VERIFY_SUCCEEDED(engine->PaintBufferLine({ clusters2.data(), clusters2.size() }, { 0, 1 }, false)); - }); } @@ -1325,7 +1180,7 @@ void VtRendererTest::TestResize() // Resize the viewport to 120x30 // Everything should be invalidated, and a resize message sent. - const auto newView = Viewport::FromDimensions({0, 0}, {120, 30}); + const auto newView = Viewport::FromDimensions({ 0, 0 }, { 120, 30 }); qExpectedInput.push_back("\x1b[8;30;120t"); VERIFY_SUCCEEDED(engine->UpdateViewport(newView.ToInclusive())); @@ -1335,6 +1190,4 @@ void VtRendererTest::TestResize() VERIFY_IS_FALSE(engine->_firstPaint); VERIFY_IS_FALSE(engine->_suppressResizeRepaint); }); - - } diff --git a/src/host/utf8ToWideCharParser.cpp b/src/host/utf8ToWideCharParser.cpp index 4c2199886..0e6143153 100644 --- a/src/host/utf8ToWideCharParser.cpp +++ b/src/host/utf8ToWideCharParser.cpp @@ -26,10 +26,10 @@ const byte MostSignificantBitMask = 0x80; // Return Value: // - A new instance of the parser. Utf8ToWideCharParser::Utf8ToWideCharParser(const unsigned int codePage) : - _currentCodePage { codePage }, - _bytesStored { 0 }, - _currentState { _State::Ready }, - _convertedWideChars { nullptr } + _currentCodePage{ codePage }, + _bytesStored{ 0 }, + _currentState{ _State::Ready }, + _convertedWideChars{ nullptr } { std::fill_n(_utf8CodePointPieces, _UTF8_BYTE_SEQUENCE_MAX, 0ui8); } @@ -65,12 +65,11 @@ void Utf8ToWideCharParser::SetCodePage(const unsigned int codePage) // in. On error this will contain nullptr instead of an array. // Return Value: // - -[[nodiscard]] -HRESULT Utf8ToWideCharParser::Parse(_In_reads_(cchBuffer) const byte* const pBytes, - _In_ unsigned int const cchBuffer, - _Out_ unsigned int& cchConsumed, - _Inout_ std::unique_ptr& converted, - _Out_ unsigned int& cchConverted) +[[nodiscard]] HRESULT Utf8ToWideCharParser::Parse(_In_reads_(cchBuffer) const byte* const pBytes, + _In_ unsigned int const cchBuffer, + _Out_ unsigned int& cchConsumed, + _Inout_ std::unique_ptr& converted, + _Out_ unsigned int& cchConverted) { cchConsumed = 0; cchConverted = 0; @@ -93,33 +92,33 @@ HRESULT Utf8ToWideCharParser::Parse(_In_reads_(cchBuffer) const byte* const pByt _convertedWideChars.reset(nullptr); while (loop) { - switch(_currentState) + switch (_currentState) { - case _State::Ready: - wideCharCount = _ParseFullRange(pBytes, cchBuffer); - break; - case _State::BeginPartialParse: - wideCharCount = _InvolvedParse(pBytes, cchBuffer); - break; - case _State::Error: - hr = E_FAIL; - _Reset(); - wideCharCount = 0; - loop = false; - break; - case _State::Finished: - _currentState = _State::Ready; - cchConsumed = cchBuffer; - loop = false; - break; - case _State::AwaitingMoreBytes: - _currentState = _State::BeginPartialParse; - cchConsumed = cchBuffer; - loop = false; - break; - default: - _currentState = _State::Error; - break; + case _State::Ready: + wideCharCount = _ParseFullRange(pBytes, cchBuffer); + break; + case _State::BeginPartialParse: + wideCharCount = _InvolvedParse(pBytes, cchBuffer); + break; + case _State::Error: + hr = E_FAIL; + _Reset(); + wideCharCount = 0; + loop = false; + break; + case _State::Finished: + _currentState = _State::Ready; + cchConsumed = cchBuffer; + loop = false; + break; + case _State::AwaitingMoreBytes: + _currentState = _State::BeginPartialParse; + cchConsumed = cchBuffer; + loop = false; + break; + default: + _currentState = _State::Error; + break; } } converted.swap(_convertedWideChars); @@ -326,7 +325,7 @@ unsigned int Utf8ToWideCharParser::_ParseFullRange(_In_reads_(cb) const byte* co LOG_LAST_ERROR(); _currentState = _State::Error; } - else + else { _currentState = _State::Finished; } @@ -393,11 +392,11 @@ unsigned int Utf8ToWideCharParser::_InvolvedParse(_In_reads_(cb) const byte* con { _convertedWideChars = std::make_unique(bufferSize); bufferSize = MultiByteToWideChar(_currentCodePage, - 0, - reinterpret_cast(validSequence.first.get()), - validSequence.second, - _convertedWideChars.get(), - bufferSize); + 0, + reinterpret_cast(validSequence.first.get()), + validSequence.second, + _convertedWideChars.get(), + bufferSize); if (bufferSize == 0) { LOG_LAST_ERROR(); diff --git a/src/host/utf8ToWideCharParser.hpp b/src/host/utf8ToWideCharParser.hpp index 87669b052..e4678a081 100644 --- a/src/host/utf8ToWideCharParser.hpp +++ b/src/host/utf8ToWideCharParser.hpp @@ -21,21 +21,20 @@ class Utf8ToWideCharParser final public: Utf8ToWideCharParser(const unsigned int codePage); void SetCodePage(const unsigned int codePage); - [[nodiscard]] - HRESULT Parse(_In_reads_(cchBuffer) const byte* const pBytes, - _In_ unsigned int const cchBuffer, - _Out_ unsigned int& cchConsumed, - _Inout_ std::unique_ptr& converted, - _Out_ unsigned int& cchConverted); + [[nodiscard]] HRESULT Parse(_In_reads_(cchBuffer) const byte* const pBytes, + _In_ unsigned int const cchBuffer, + _Out_ unsigned int& cchConsumed, + _Inout_ std::unique_ptr& converted, + _Out_ unsigned int& cchConverted); private: enum class _State { - Ready, // ready for input, no partially parsed code points - Error, // error in parsing given bytes + Ready, // ready for input, no partially parsed code points + Error, // error in parsing given bytes BeginPartialParse, // not a clean byte sequence, needs involved parsing AwaitingMoreBytes, // have a partial sequence saved, waiting for the rest of it - Finished // ready to return a wide char sequence + Finished // ready to return a wide char sequence }; bool _IsLeadByte(_In_ byte ch); diff --git a/src/host/utils.cpp b/src/host/utils.cpp index f8cd2d01f..450834e24 100644 --- a/src/host/utils.cpp +++ b/src/host/utils.cpp @@ -25,10 +25,10 @@ short CalcCursorYOffsetInPixels(const short sFontSizeY, const ULONG ulSize) noex { // TODO: MSFT 10229700 - Note, we want to likely enforce that this isn't negative. // Pretty sure there's not a valid case for negative offsets here. - return (short)((sFontSizeY)-(ulSize)); + return (short)((sFontSizeY) - (ulSize)); } -WORD ConvertStringToDec(_In_ PCWSTR pwchToConvert, _Out_opt_ PCWSTR * const ppwchEnd) noexcept +WORD ConvertStringToDec(_In_ PCWSTR pwchToConvert, _Out_opt_ PCWSTR* const ppwchEnd) noexcept { WORD val = 0; @@ -55,7 +55,6 @@ WORD ConvertStringToDec(_In_ PCWSTR pwchToConvert, _Out_opt_ PCWSTR * const ppwc return val; } - // Routine Description: // - Retrieves string resources from our resource files. // Arguments: @@ -115,20 +114,21 @@ UINT s_LoadStringEx(_In_ HINSTANCE hModule, _In_ UINT wID, _Out_writes_(cchBuffe wID &= 0x0F; for (;;) { - cch = *((WCHAR *)lpsz++); // PASCAL like string count - // first WCHAR is count of WCHARs + // PASCAL like string count + // first WCHAR is count of WCHARs + cch = *((WCHAR*)lpsz++); if (wID-- == 0) { break; } - lpsz += cch; // Step to start if next string + lpsz += cch; // Step to start if next string } // chhBufferMax == 0 means return a pointer to the read-only resource buffer. if (cchBufferMax == 0) { - *(LPTSTR *)lpBuffer = lpsz; + *(LPTSTR*)lpBuffer = lpsz; } else { diff --git a/src/host/utils.hpp b/src/host/utils.hpp index 79dc82b44..5b7dea913 100644 --- a/src/host/utils.hpp +++ b/src/host/utils.hpp @@ -25,14 +25,14 @@ Author(s): short CalcWindowSizeX(const SMALL_RECT& rect) noexcept; short CalcWindowSizeY(const SMALL_RECT& rect) noexcept; short CalcCursorYOffsetInPixels(const short sFontSizeY, const ULONG ulSize) noexcept; -WORD ConvertStringToDec(_In_ PCWSTR pwchToConvert, _Out_opt_ PCWSTR * const ppwchEnd) noexcept; +WORD ConvertStringToDec(_In_ PCWSTR pwchToConvert, _Out_opt_ PCWSTR* const ppwchEnd) noexcept; std::wstring _LoadString(const UINT id); static UINT s_LoadStringEx(_In_ HINSTANCE hModule, - _In_ UINT wID, - _Out_writes_(cchBufferMax) LPWSTR lpBuffer, - _In_ UINT cchBufferMax, - _In_ WORD wLangId); + _In_ UINT wID, + _Out_writes_(cchBufferMax) LPWSTR lpBuffer, + _In_ UINT cchBufferMax, + _In_ WORD wLangId); class Utils { diff --git a/src/inc/CppCoreCheck/warnings.h b/src/inc/CppCoreCheck/warnings.h index 5ce8f6ff3..1a990fc43 100644 --- a/src/inc/CppCoreCheck/warnings.h +++ b/src/inc/CppCoreCheck/warnings.h @@ -4,6 +4,8 @@ // This file contains symbolic constants for warning numbers. // +// clang-format off + #pragma once enum ECppCoreCheckWarningCodes @@ -107,7 +109,4 @@ enum ECppCoreCheckWarningCodes #define CPPCORECHECK_UNIQUE_POINTER_WARNINGS 26410 26411 26414 26415 - - - - +// clang-format on diff --git a/src/inc/DefaultSettings.h b/src/inc/DefaultSettings.h index 145bba02b..e9cdfb411 100644 --- a/src/inc/DefaultSettings.h +++ b/src/inc/DefaultSettings.h @@ -26,7 +26,7 @@ constexpr COLORREF DEFAULT_BACKGROUND_WITH_ALPHA = OPACITY_OPAQUE | DEFAULT_BACK constexpr COLORREF POWERSHELL_BLUE = RGB(1, 36, 86); constexpr short DEFAULT_HISTORY_SIZE = 9001; -const std::wstring DEFAULT_FONT_FACE { L"Consolas" }; +const std::wstring DEFAULT_FONT_FACE{ L"Consolas" }; constexpr int DEFAULT_FONT_SIZE = 10; constexpr int DEFAULT_ROWS = 30; diff --git a/src/inc/HostAndPropsheetIncludes.h b/src/inc/HostAndPropsheetIncludes.h index 4ffc2eedc..87bad9ec7 100644 --- a/src/inc/HostAndPropsheetIncludes.h +++ b/src/inc/HostAndPropsheetIncludes.h @@ -2,6 +2,8 @@ // Licensed under the MIT license. #pragma once +// clang-format off + // Define and then undefine WIN32_NO_STATUS because windows.h has no guard to prevent it from double defing certain statuses // when included with ntstatus.h #define WIN32_NO_STATUS @@ -46,3 +48,5 @@ typedef NTSTATUS *PNTSTATUS; #include "conddkrefs.h" #include "conwinuserrefs.h" + +// clang-format on diff --git a/src/inc/IDefaultColorProvider.hpp b/src/inc/IDefaultColorProvider.hpp index 36bb92b69..607caab5e 100644 --- a/src/inc/IDefaultColorProvider.hpp +++ b/src/inc/IDefaultColorProvider.hpp @@ -24,5 +24,5 @@ namespace Microsoft::Console virtual COLORREF GetDefaultBackground() const = 0; }; - inline Microsoft::Console::IDefaultColorProvider::~IDefaultColorProvider() { } + inline Microsoft::Console::IDefaultColorProvider::~IDefaultColorProvider() {} } diff --git a/src/inc/ITerminalOutputConnection.hpp b/src/inc/ITerminalOutputConnection.hpp index f323c84c5..3b1875d14 100644 --- a/src/inc/ITerminalOutputConnection.hpp +++ b/src/inc/ITerminalOutputConnection.hpp @@ -21,11 +21,9 @@ namespace Microsoft::Console public: virtual ~ITerminalOutputConnection() = 0; - [[nodiscard]] - virtual HRESULT WriteTerminalUtf8(const std::string& str) = 0; - [[nodiscard]] - virtual HRESULT WriteTerminalW(const std::wstring& wstr) = 0; + [[nodiscard]] virtual HRESULT WriteTerminalUtf8(const std::string& str) = 0; + [[nodiscard]] virtual HRESULT WriteTerminalW(const std::wstring& wstr) = 0; }; - inline Microsoft::Console::ITerminalOutputConnection::~ITerminalOutputConnection() { } + inline Microsoft::Console::ITerminalOutputConnection::~ITerminalOutputConnection() {} } diff --git a/src/inc/ITerminalOwner.hpp b/src/inc/ITerminalOwner.hpp index 31c6e535c..b2ba1e574 100644 --- a/src/inc/ITerminalOwner.hpp +++ b/src/inc/ITerminalOwner.hpp @@ -29,5 +29,5 @@ namespace Microsoft::Console }; // See docs/virtual-dtors.md for an explanation of why this is weird. - inline Microsoft::Console::ITerminalOwner::~ITerminalOwner() { } + inline Microsoft::Console::ITerminalOwner::~ITerminalOwner() {} } diff --git a/src/inc/LibraryIncludes.h b/src/inc/LibraryIncludes.h index b44c35167..7e4d40a4b 100644 --- a/src/inc/LibraryIncludes.h +++ b/src/inc/LibraryIncludes.h @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. +// clang-format off + #pragma once @@ -67,3 +69,5 @@ #include #pragma warning(pop) + +// clang-format on diff --git a/src/inc/VtIoModes.hpp b/src/inc/VtIoModes.hpp index 9e9458597..29fe56921 100644 --- a/src/inc/VtIoModes.hpp +++ b/src/inc/VtIoModes.hpp @@ -12,8 +12,8 @@ enum class VtIoMode XTERM_ASCII }; -const wchar_t* const XTERM_STRING = L"xterm"; -const wchar_t* const XTERM_256_STRING = L"xterm-256color"; -const wchar_t* const WIN_TELNET_STRING = L"win-telnet"; -const wchar_t* const XTERM_ASCII_STRING = L"xterm-ascii"; -const wchar_t* const DEFAULT_STRING = L""; +const wchar_t* const XTERM_STRING = L"xterm"; +const wchar_t* const XTERM_256_STRING = L"xterm-256color"; +const wchar_t* const WIN_TELNET_STRING = L"win-telnet"; +const wchar_t* const XTERM_ASCII_STRING = L"xterm-ascii"; +const wchar_t* const DEFAULT_STRING = L""; diff --git a/src/inc/argb.h b/src/inc/argb.h index 2c5170410..d8972b7f1 100644 --- a/src/inc/argb.h +++ b/src/inc/argb.h @@ -17,7 +17,7 @@ Author(s): constexpr COLORREF ARGB(const BYTE a, const BYTE r, const BYTE g, const BYTE b) noexcept { - return (a<<24) | (b<<16) | (g<<8) | (r); + return (a << 24) | (b << 16) | (g << 8) | (r); } #ifdef RGB diff --git a/src/inc/conattrs.hpp b/src/inc/conattrs.hpp index 529ae07d1..5e5325190 100644 --- a/src/inc/conattrs.hpp +++ b/src/inc/conattrs.hpp @@ -6,7 +6,7 @@ Licensed under the MIT license. #define FG_ATTRS (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY) #define BG_ATTRS (BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_INTENSITY) -#define META_ATTRS (COMMON_LVB_LEADING_BYTE | COMMON_LVB_TRAILING_BYTE | COMMON_LVB_GRID_HORIZONTAL | COMMON_LVB_GRID_LVERTICAL | COMMON_LVB_GRID_RVERTICAL | COMMON_LVB_REVERSE_VIDEO | COMMON_LVB_UNDERSCORE ) +#define META_ATTRS (COMMON_LVB_LEADING_BYTE | COMMON_LVB_TRAILING_BYTE | COMMON_LVB_GRID_HORIZONTAL | COMMON_LVB_GRID_LVERTICAL | COMMON_LVB_GRID_RVERTICAL | COMMON_LVB_REVERSE_VIDEO | COMMON_LVB_UNDERSCORE) WORD FindNearestTableIndex(const COLORREF Color, _In_reads_(cColorTable) const COLORREF* const ColorTable, @@ -29,15 +29,15 @@ COLORREF BackgroundColor(const WORD wLegacyAttrs, _In_reads_(cColorTable) const COLORREF* const ColorTable, const size_t cColorTable); -const WORD WINDOWS_RED_ATTR = FOREGROUND_RED; -const WORD WINDOWS_GREEN_ATTR = FOREGROUND_GREEN; -const WORD WINDOWS_BLUE_ATTR = FOREGROUND_BLUE; -const WORD WINDOWS_BRIGHT_ATTR = FOREGROUND_INTENSITY; +const WORD WINDOWS_RED_ATTR = FOREGROUND_RED; +const WORD WINDOWS_GREEN_ATTR = FOREGROUND_GREEN; +const WORD WINDOWS_BLUE_ATTR = FOREGROUND_BLUE; +const WORD WINDOWS_BRIGHT_ATTR = FOREGROUND_INTENSITY; -const WORD XTERM_RED_ATTR = 0x01; -const WORD XTERM_GREEN_ATTR = 0x02; -const WORD XTERM_BLUE_ATTR = 0x04; -const WORD XTERM_BRIGHT_ATTR = 0x08; +const WORD XTERM_RED_ATTR = 0x01; +const WORD XTERM_GREEN_ATTR = 0x02; +const WORD XTERM_BLUE_ATTR = 0x04; +const WORD XTERM_BRIGHT_ATTR = 0x08; enum class CursorType : unsigned int { diff --git a/src/inc/conime.h b/src/inc/conime.h index f2637cf94..65412fbe0 100644 --- a/src/inc/conime.h +++ b/src/inc/conime.h @@ -25,39 +25,34 @@ Revision History: #define CONIME_ATTRCOLOR_SIZE 8 #define CONIME_CURSOR_RIGHT 0x10 -#define CONIME_CURSOR_LEFT 0x20 +#define CONIME_CURSOR_LEFT 0x20 -[[nodiscard]] -HRESULT ImeStartComposition(); +[[nodiscard]] HRESULT ImeStartComposition(); -[[nodiscard]] -HRESULT ImeEndComposition(); +[[nodiscard]] HRESULT ImeEndComposition(); -[[nodiscard]] -HRESULT ImeComposeData(std::wstring_view text, - std::basic_string_view attributes, - std::basic_string_view colorArray); +[[nodiscard]] HRESULT ImeComposeData(std::wstring_view text, + std::basic_string_view attributes, + std::basic_string_view colorArray); -[[nodiscard]] -HRESULT ImeClearComposeData(); +[[nodiscard]] HRESULT ImeClearComposeData(); -[[nodiscard]] -HRESULT ImeComposeResult(std::wstring_view text); +[[nodiscard]] HRESULT ImeComposeResult(std::wstring_view text); // Default composition color attributes -#define DEFAULT_COMP_ENTERED \ - (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | \ +#define DEFAULT_COMP_ENTERED \ + (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | \ COMMON_LVB_UNDERSCORE) -#define DEFAULT_COMP_ALREADY_CONVERTED \ - (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | \ - BACKGROUND_BLUE ) -#define DEFAULT_COMP_CONVERSION \ - (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | \ +#define DEFAULT_COMP_ALREADY_CONVERTED \ + (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | \ + BACKGROUND_BLUE) +#define DEFAULT_COMP_CONVERSION \ + (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | \ COMMON_LVB_UNDERSCORE) -#define DEFAULT_COMP_YET_CONVERTED \ - (FOREGROUND_BLUE | \ - BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED | \ +#define DEFAULT_COMP_YET_CONVERTED \ + (FOREGROUND_BLUE | \ + BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED | \ COMMON_LVB_UNDERSCORE) -#define DEFAULT_COMP_INPUT_ERROR \ - ( FOREGROUND_RED | \ +#define DEFAULT_COMP_INPUT_ERROR \ + (FOREGROUND_RED | \ COMMON_LVB_UNDERSCORE) diff --git a/src/inc/conint.h b/src/inc/conint.h index 1f307a58b..fcb77fd3d 100644 --- a/src/inc/conint.h +++ b/src/inc/conint.h @@ -25,16 +25,13 @@ Revision History: namespace Microsoft::Console::Internal { - namespace ProcessPolicy { - [[nodiscard]] - HRESULT CheckAppModelPolicy(const HANDLE hToken, - bool& fIsWrongWayBlocked) noexcept; + [[nodiscard]] HRESULT CheckAppModelPolicy(const HANDLE hToken, + bool& fIsWrongWayBlocked) noexcept; - [[nodiscard]] - HRESULT CheckIntegrityLevelPolicy(const HANDLE hOtherToken, - bool& fIsWrongWayBlocked) noexcept; + [[nodiscard]] HRESULT CheckIntegrityLevelPolicy(const HANDLE hOtherToken, + bool& fIsWrongWayBlocked) noexcept; } namespace EdpPolicy diff --git a/src/inc/conpty-universal.h b/src/inc/conpty-universal.h index be879a04f..a6384d3d3 100644 --- a/src/inc/conpty-universal.h +++ b/src/inc/conpty-universal.h @@ -41,8 +41,7 @@ const unsigned int PTY_SIGNAL_RESIZE_WINDOW = 8u; // struct WStringCaseInsensitiveCompare { - [[nodiscard]] - bool operator()(const std::wstring& lhs, const std::wstring& rhs) const noexcept + [[nodiscard]] bool operator()(const std::wstring& lhs, const std::wstring& rhs) const noexcept { return (::_wcsicmp(lhs.c_str(), rhs.c_str()) < 0); } @@ -50,25 +49,23 @@ struct WStringCaseInsensitiveCompare using EnvironmentVariableMapW = std::map; -[[nodiscard]] -HRESULT CreateConPty(const std::wstring& cmdline, - const unsigned short w, - const unsigned short h, - HANDLE* const hInput, - HANDLE* const hOutput, - HANDLE* const hSignal, - PROCESS_INFORMATION* const piPty, - const EnvironmentVariableMapW& extraEnvVars = {}) noexcept; +[[nodiscard]] HRESULT CreateConPty(const std::wstring& cmdline, + const unsigned short w, + const unsigned short h, + HANDLE* const hInput, + HANDLE* const hOutput, + HANDLE* const hSignal, + PROCESS_INFORMATION* const piPty, + const EnvironmentVariableMapW& extraEnvVars = {}) noexcept; bool SignalResizeWindow(const HANDLE hSignal, const unsigned short w, const unsigned short h); -[[nodiscard]] -HRESULT UpdateEnvironmentMapW(EnvironmentVariableMapW& map) noexcept; +[[nodiscard]] HRESULT UpdateEnvironmentMapW(EnvironmentVariableMapW& map) noexcept; -[[nodiscard]] -HRESULT EnvironmentMapToEnvironmentStringsW(EnvironmentVariableMapW& map, std::vector& newEnvVars) noexcept; +[[nodiscard]] HRESULT EnvironmentMapToEnvironmentStringsW(EnvironmentVariableMapW& map, + std::vector& newEnvVars) noexcept; // Function Description: // - Updates an EnvironmentVariableMapW with the current process's unicode @@ -77,9 +74,7 @@ HRESULT EnvironmentMapToEnvironmentStringsW(EnvironmentVariableMapW& map, std::v // - map: The map to populate with the current processes's environment variables. // Return Value: // - S_OK if we succeeded, or an appropriate HRESULT for failing -[[nodiscard]] -__declspec(noinline) inline -HRESULT UpdateEnvironmentMapW(EnvironmentVariableMapW& map) noexcept +[[nodiscard]] __declspec(noinline) inline HRESULT UpdateEnvironmentMapW(EnvironmentVariableMapW& map) noexcept { LPWCH currentEnvVars{}; auto freeCurrentEnv = wil::scope_exit([&] { @@ -123,9 +118,7 @@ HRESULT UpdateEnvironmentMapW(EnvironmentVariableMapW& map) noexcept // - newEnvVars: The vector that will be used to create the new environment block. // Return Value: // - S_OK if we succeeded, or an appropriate HRESULT for failing -[[nodiscard]] -__declspec(noinline) inline -HRESULT EnvironmentMapToEnvironmentStringsW(EnvironmentVariableMapW& map, std::vector& newEnvVars) noexcept +[[nodiscard]] __declspec(noinline) inline HRESULT EnvironmentMapToEnvironmentStringsW(EnvironmentVariableMapW& map, std::vector& newEnvVars) noexcept { // Clear environment block before use. constexpr size_t cbChar{ sizeof(decltype(newEnvVars.begin())::value_type) }; @@ -137,7 +130,7 @@ HRESULT EnvironmentMapToEnvironmentStringsW(EnvironmentVariableMapW& map, std::v // Resize environment block to fit map. size_t cchEnv{ 2 }; // For the block's double NULL-terminator. - for (const auto&[name, value] : map) + for (const auto& [name, value] : map) { // Final form of "name=value\0". cchEnv += name.size() + 1 + value.size() + 1; @@ -152,7 +145,7 @@ HRESULT EnvironmentMapToEnvironmentStringsW(EnvironmentVariableMapW& map, std::v // Transform each map entry and copy it into the new environment block. LPWCH pEnvVars{ newEnvVars.data() }; size_t cbRemaining{ cchEnv * cbChar }; - for (const auto&[name, value] : map) + for (const auto& [name, value] : map) { // Final form of "name=value\0" for every entry. { @@ -218,17 +211,15 @@ HRESULT EnvironmentMapToEnvironmentStringsW(EnvironmentVariableMapW& map, std::v // Return Value: // - S_OK if we succeeded, or an appropriate HRESULT for failing format the // commandline or failing to launch the conhost -[[nodiscard]] -__declspec(noinline) inline -HRESULT CreateConPty(const std::wstring& cmdline, - std::optional startingDirectory, - const unsigned short w, - const unsigned short h, - HANDLE* const hInput, - HANDLE* const hOutput, - HANDLE* const hSignal, - PROCESS_INFORMATION* const piPty, - const EnvironmentVariableMapW& extraEnvVars = {}) noexcept +[[nodiscard]] __declspec(noinline) inline HRESULT CreateConPty(const std::wstring& cmdline, + std::optional startingDirectory, + const unsigned short w, + const unsigned short h, + HANDLE* const hInput, + HANDLE* const hOutput, + HANDLE* const hSignal, + PROCESS_INFORMATION* const piPty, + const EnvironmentVariableMapW& extraEnvVars = {}) noexcept { // Create some anon pipes so we can pass handles down and into the console. // IMPORTANT NOTE: @@ -248,7 +239,7 @@ HRESULT CreateConPty(const std::wstring& cmdline, HANDLE signalPipeConhostSide; SECURITY_ATTRIBUTES sa; - sa = {0}; + sa = { 0 }; sa.nLength = sizeof(sa); sa.bInheritHandle = FALSE; sa.lpSecurityDescriptor = nullptr; @@ -275,7 +266,7 @@ HRESULT CreateConPty(const std::wstring& cmdline, conhostCmdline += L" -- "; conhostCmdline += cmdline; - STARTUPINFO si = {0}; + STARTUPINFO si = { 0 }; si.cb = sizeof(STARTUPINFOW); si.hStdInput = inPipeConhostSide; si.hStdOutput = outPipeConhostSide; @@ -287,7 +278,7 @@ HRESULT CreateConPty(const std::wstring& cmdline, { return E_OUTOFMEMORY; } - HRESULT hr = StringCchCopy(mutableCommandline.get(), conhostCmdline.length()+1, conhostCmdline.c_str()); + HRESULT hr = StringCchCopy(mutableCommandline.get(), conhostCmdline.length() + 1, conhostCmdline.c_str()); if (!SUCCEEDED(hr)) { return hr; @@ -307,7 +298,7 @@ HRESULT CreateConPty(const std::wstring& cmdline, EnvironmentVariableMapW tempEnvMap{ extraEnvVars }; auto zeroEnvMap = wil::scope_exit([&] { // Can't zero the keys, but at least we can zero the values. - for (auto&[name, value] : tempEnvMap) + for (auto& [name, value] : tempEnvMap) { ::SecureZeroMemory(value.data(), value.size() * sizeof(decltype(value.begin())::value_type)); } @@ -326,14 +317,14 @@ HRESULT CreateConPty(const std::wstring& cmdline, bool fSuccess = !!CreateProcessW( nullptr, mutableCommandline.get(), - nullptr, // lpProcessAttributes - nullptr, // lpThreadAttributes - true, // bInheritHandles - dwCreationFlags, // dwCreationFlags - lpEnvironment, // lpEnvironment - lpCurrentDirectory, // lpCurrentDirectory - &si, // lpStartupInfo - piPty // lpProcessInformation + nullptr, // lpProcessAttributes + nullptr, // lpThreadAttributes + true, // bInheritHandles + dwCreationFlags, // dwCreationFlags + lpEnvironment, // lpEnvironment + lpCurrentDirectory, // lpCurrentDirectory + &si, // lpStartupInfo + piPty // lpProcessInformation ); CloseHandle(inPipeConhostSide); @@ -351,8 +342,7 @@ HRESULT CreateConPty(const std::wstring& cmdline, // - h: The new height of the pty, in characters // Return Value: // - true if the resize succeeded, else false. -__declspec(noinline) inline -bool SignalResizeWindow(HANDLE hSignal, const unsigned short w, const unsigned short h) +__declspec(noinline) inline bool SignalResizeWindow(HANDLE hSignal, const unsigned short w, const unsigned short h) { unsigned short signalPacket[3]; signalPacket[0] = PTY_SIGNAL_RESIZE_WINDOW; @@ -361,4 +351,3 @@ bool SignalResizeWindow(HANDLE hSignal, const unsigned short w, const unsigned s return !!WriteFile(hSignal, signalPacket, sizeof(signalPacket), nullptr, nullptr); } - diff --git a/src/inc/conpty.h b/src/inc/conpty.h index 236732295..ff980d7c2 100644 --- a/src/inc/conpty.h +++ b/src/inc/conpty.h @@ -9,19 +9,18 @@ const unsigned int PTY_SIGNAL_RESIZE_WINDOW = 8u; -HRESULT CreateConPty(const std::wstring& cmdline, // _In_ - const unsigned short w, // _In_ - const unsigned short h, // _In_ - HANDLE* const hInput, // _Out_ - HANDLE* const hOutput, // _Out_ - HANDLE* const hSignal, // _Out_ +HRESULT CreateConPty(const std::wstring& cmdline, // _In_ + const unsigned short w, // _In_ + const unsigned short h, // _In_ + HANDLE* const hInput, // _Out_ + HANDLE* const hOutput, // _Out_ + HANDLE* const hSignal, // _Out_ PROCESS_INFORMATION* const piPty); // _Out_ bool SignalResizeWindow(const HANDLE hSignal, const unsigned short w, const unsigned short h); - // Function Description: // - Creates a headless conhost in "pty mode" and launches the given commandline // attached to the conhost. Gives back handles to three different pipes: @@ -45,14 +44,13 @@ bool SignalResizeWindow(const HANDLE hSignal, // Return Value: // - S_OK if we succeeded, or an appropriate HRESULT for failing format the // commandline or failing to launch the conhost -__declspec(noinline) inline -HRESULT CreateConPty(const std::wstring& cmdline, - const unsigned short w, - const unsigned short h, - HANDLE* const hInput, - HANDLE* const hOutput, - HANDLE* const hSignal, - PROCESS_INFORMATION* const piPty) +__declspec(noinline) inline HRESULT CreateConPty(const std::wstring& cmdline, + const unsigned short w, + const unsigned short h, + HANDLE* const hInput, + HANDLE* const hOutput, + HANDLE* const hSignal, + PROCESS_INFORMATION* const piPty) { // Create some anon pipes so we can pass handles down and into the console. // IMPORTANT NOTE: @@ -72,7 +70,7 @@ HRESULT CreateConPty(const std::wstring& cmdline, HANDLE signalPipeConhostSide; SECURITY_ATTRIBUTES sa; - sa = {0}; + sa = { 0 }; sa.nLength = sizeof(sa); sa.bInheritHandle = FALSE; sa.lpSecurityDescriptor = nullptr; @@ -101,7 +99,7 @@ HRESULT CreateConPty(const std::wstring& cmdline, conhostCmdline += L" -- "; conhostCmdline += cmdline; - STARTUPINFO si = {0}; + STARTUPINFO si = { 0 }; si.cb = sizeof(STARTUPINFOW); si.hStdInput = inPipeConhostSide; si.hStdOutput = outPipeConhostSide; @@ -113,7 +111,7 @@ HRESULT CreateConPty(const std::wstring& cmdline, { return E_OUTOFMEMORY; } - HRESULT hr = StringCchCopy(mutableCommandline.get(), conhostCmdline.length()+1, conhostCmdline.c_str()); + HRESULT hr = StringCchCopy(mutableCommandline.get(), conhostCmdline.length() + 1, conhostCmdline.c_str()); if (!SUCCEEDED(hr)) { return hr; @@ -122,14 +120,14 @@ HRESULT CreateConPty(const std::wstring& cmdline, bool fSuccess = !!CreateProcessW( nullptr, mutableCommandline.get(), - nullptr, // lpProcessAttributes - nullptr, // lpThreadAttributes - true, // bInheritHandles - 0, // dwCreationFlags - nullptr, // lpEnvironment - nullptr, // lpCurrentDirectory - &si, // lpStartupInfo - piPty // lpProcessInformation + nullptr, // lpProcessAttributes + nullptr, // lpThreadAttributes + true, // bInheritHandles + 0, // dwCreationFlags + nullptr, // lpEnvironment + nullptr, // lpCurrentDirectory + &si, // lpStartupInfo + piPty // lpProcessInformation ); CloseHandle(inPipeConhostSide); @@ -147,8 +145,7 @@ HRESULT CreateConPty(const std::wstring& cmdline, // - h: The new height of the pty, in characters // Return Value: // - true if the resize succeeded, else false. -__declspec(noinline) inline -bool SignalResizeWindow(HANDLE hSignal, const unsigned short w, const unsigned short h) +__declspec(noinline) inline bool SignalResizeWindow(HANDLE hSignal, const unsigned short w, const unsigned short h) { unsigned short signalPacket[3]; signalPacket[0] = PTY_SIGNAL_RESIZE_WINDOW; diff --git a/src/inc/consoletaeftemplates.hpp b/src/inc/consoletaeftemplates.hpp index ad717c843..aa169ad4e 100644 --- a/src/inc/consoletaeftemplates.hpp +++ b/src/inc/consoletaeftemplates.hpp @@ -20,7 +20,7 @@ Revision History: namespace WEX::TestExecution { template<> - class VerifyOutputTraits < SMALL_RECT > + class VerifyOutputTraits { public: static WEX::Common::NoThrowString ToString(const SMALL_RECT& sr) @@ -30,15 +30,15 @@ namespace WEX::TestExecution }; template<> - class VerifyCompareTraits < SMALL_RECT, SMALL_RECT > + class VerifyCompareTraits { public: static bool AreEqual(const SMALL_RECT& expected, const SMALL_RECT& actual) { return expected.Left == actual.Left && - expected.Right == actual.Right && - expected.Top == actual.Top && - expected.Bottom == actual.Bottom; + expected.Right == actual.Right && + expected.Top == actual.Top && + expected.Bottom == actual.Bottom; } static bool AreSame(const SMALL_RECT& expected, const SMALL_RECT& actual) @@ -57,7 +57,7 @@ namespace WEX::TestExecution }; template<> - class VerifyOutputTraits < COORD > + class VerifyOutputTraits { public: static WEX::Common::NoThrowString ToString(const COORD& coord) @@ -67,13 +67,13 @@ namespace WEX::TestExecution }; template<> - class VerifyCompareTraits < COORD, COORD> + class VerifyCompareTraits { public: static bool AreEqual(const COORD& expected, const COORD& actual) { return expected.X == actual.X && - expected.Y == actual.Y; + expected.Y == actual.Y; } static bool AreSame(const COORD& expected, const COORD& actual) @@ -85,16 +85,16 @@ namespace WEX::TestExecution { // less is on a line above greater (Y values less than) return (expectedLess.Y < expectedGreater.Y) || - // or on the same lines and less is left of greater (X values less than) - ((expectedLess.Y == expectedGreater.Y) && (expectedLess.X < expectedGreater.X)); + // or on the same lines and less is left of greater (X values less than) + ((expectedLess.Y == expectedGreater.Y) && (expectedLess.X < expectedGreater.X)); } static bool IsGreaterThan(const COORD& expectedGreater, const COORD& expectedLess) { // greater is on a line below less (Y value greater than) return (expectedGreater.Y > expectedLess.Y) || - // or on the same lines and greater is right of less (X values greater than) - ((expectedGreater.Y == expectedLess.Y) && (expectedGreater.X > expectedLess.X)); + // or on the same lines and greater is right of less (X values greater than) + ((expectedGreater.Y == expectedLess.Y) && (expectedGreater.X > expectedLess.X)); } static bool IsNull(const COORD& object) @@ -104,7 +104,7 @@ namespace WEX::TestExecution }; template<> - class VerifyOutputTraits < CONSOLE_CURSOR_INFO > + class VerifyOutputTraits { public: static WEX::Common::NoThrowString ToString(const CONSOLE_CURSOR_INFO& cci) @@ -114,13 +114,13 @@ namespace WEX::TestExecution }; template<> - class VerifyCompareTraits < CONSOLE_CURSOR_INFO, CONSOLE_CURSOR_INFO > + class VerifyCompareTraits { public: static bool AreEqual(const CONSOLE_CURSOR_INFO& expected, const CONSOLE_CURSOR_INFO& actual) { return expected.bVisible == actual.bVisible && - expected.dwSize == actual.dwSize; + expected.dwSize == actual.dwSize; } static bool AreSame(const CONSOLE_CURSOR_INFO& expected, const CONSOLE_CURSOR_INFO& actual) @@ -139,68 +139,67 @@ namespace WEX::TestExecution }; template<> - class VerifyOutputTraits < CONSOLE_SCREEN_BUFFER_INFOEX > + class VerifyOutputTraits { public: static WEX::Common::NoThrowString ToString(const CONSOLE_SCREEN_BUFFER_INFOEX& sbiex) { return WEX::Common::NoThrowString().Format(L"(Full:%s Attrs:0x%x PopupAttrs:0x%x CursorPos:%s Size:%s MaxSize:%s Viewport:%s)\r\nColors:\r\n(0:0x%x)\r\n(1:0x%x)\r\n(2:0x%x)\r\n(3:0x%x)\r\n(4:0x%x)\r\n(5:0x%x)\r\n(6:0x%x)\r\n(7:0x%x)\r\n(8:0x%x)\r\n(9:0x%x)\r\n(A:0x%x)\r\n(B:0x%x)\r\n(C:0x%x)\r\n(D:0x%x)\r\n(E:0x%x)\r\n(F:0x%x)\r\n", - sbiex.bFullscreenSupported ? L"True" : L"False", - sbiex.wAttributes, - sbiex.wPopupAttributes, - VerifyOutputTraits::ToString(sbiex.dwCursorPosition).ToCStrWithFallbackTo(L"Fail"), - VerifyOutputTraits::ToString(sbiex.dwSize).ToCStrWithFallbackTo(L"Fail"), - VerifyOutputTraits::ToString(sbiex.dwMaximumWindowSize).ToCStrWithFallbackTo(L"Fail"), - VerifyOutputTraits::ToString(sbiex.srWindow).ToCStrWithFallbackTo(L"Fail"), - sbiex.ColorTable[0], - sbiex.ColorTable[1], - sbiex.ColorTable[2], - sbiex.ColorTable[3], - sbiex.ColorTable[4], - sbiex.ColorTable[5], - sbiex.ColorTable[6], - sbiex.ColorTable[7], - sbiex.ColorTable[8], - sbiex.ColorTable[9], - sbiex.ColorTable[10], - sbiex.ColorTable[11], - sbiex.ColorTable[12], - sbiex.ColorTable[13], - sbiex.ColorTable[14], - sbiex.ColorTable[15]); - + sbiex.bFullscreenSupported ? L"True" : L"False", + sbiex.wAttributes, + sbiex.wPopupAttributes, + VerifyOutputTraits::ToString(sbiex.dwCursorPosition).ToCStrWithFallbackTo(L"Fail"), + VerifyOutputTraits::ToString(sbiex.dwSize).ToCStrWithFallbackTo(L"Fail"), + VerifyOutputTraits::ToString(sbiex.dwMaximumWindowSize).ToCStrWithFallbackTo(L"Fail"), + VerifyOutputTraits::ToString(sbiex.srWindow).ToCStrWithFallbackTo(L"Fail"), + sbiex.ColorTable[0], + sbiex.ColorTable[1], + sbiex.ColorTable[2], + sbiex.ColorTable[3], + sbiex.ColorTable[4], + sbiex.ColorTable[5], + sbiex.ColorTable[6], + sbiex.ColorTable[7], + sbiex.ColorTable[8], + sbiex.ColorTable[9], + sbiex.ColorTable[10], + sbiex.ColorTable[11], + sbiex.ColorTable[12], + sbiex.ColorTable[13], + sbiex.ColorTable[14], + sbiex.ColorTable[15]); } }; template<> - class VerifyCompareTraits < CONSOLE_SCREEN_BUFFER_INFOEX, CONSOLE_SCREEN_BUFFER_INFOEX > + class VerifyCompareTraits { public: static bool AreEqual(const CONSOLE_SCREEN_BUFFER_INFOEX& expected, const CONSOLE_SCREEN_BUFFER_INFOEX& actual) { return expected.bFullscreenSupported == actual.bFullscreenSupported && - expected.wAttributes == actual.wAttributes && - expected.wPopupAttributes == actual.wPopupAttributes && - VerifyCompareTraits::AreEqual(expected.dwCursorPosition, actual.dwCursorPosition) && - VerifyCompareTraits::AreEqual(expected.dwSize, actual.dwSize) && - VerifyCompareTraits::AreEqual(expected.dwMaximumWindowSize, actual.dwMaximumWindowSize) && - VerifyCompareTraits::AreEqual(expected.srWindow, actual.srWindow) && - expected.ColorTable[0] == actual.ColorTable[0] && - expected.ColorTable[1] == actual.ColorTable[1] && - expected.ColorTable[2] == actual.ColorTable[2] && - expected.ColorTable[3] == actual.ColorTable[3] && - expected.ColorTable[4] == actual.ColorTable[4] && - expected.ColorTable[5] == actual.ColorTable[5] && - expected.ColorTable[6] == actual.ColorTable[6] && - expected.ColorTable[7] == actual.ColorTable[7] && - expected.ColorTable[8] == actual.ColorTable[8] && - expected.ColorTable[9] == actual.ColorTable[9] && - expected.ColorTable[10] == actual.ColorTable[10] && - expected.ColorTable[11] == actual.ColorTable[11] && - expected.ColorTable[12] == actual.ColorTable[12] && - expected.ColorTable[13] == actual.ColorTable[13] && - expected.ColorTable[14] == actual.ColorTable[14] && - expected.ColorTable[15] == actual.ColorTable[15]; + expected.wAttributes == actual.wAttributes && + expected.wPopupAttributes == actual.wPopupAttributes && + VerifyCompareTraits::AreEqual(expected.dwCursorPosition, actual.dwCursorPosition) && + VerifyCompareTraits::AreEqual(expected.dwSize, actual.dwSize) && + VerifyCompareTraits::AreEqual(expected.dwMaximumWindowSize, actual.dwMaximumWindowSize) && + VerifyCompareTraits::AreEqual(expected.srWindow, actual.srWindow) && + expected.ColorTable[0] == actual.ColorTable[0] && + expected.ColorTable[1] == actual.ColorTable[1] && + expected.ColorTable[2] == actual.ColorTable[2] && + expected.ColorTable[3] == actual.ColorTable[3] && + expected.ColorTable[4] == actual.ColorTable[4] && + expected.ColorTable[5] == actual.ColorTable[5] && + expected.ColorTable[6] == actual.ColorTable[6] && + expected.ColorTable[7] == actual.ColorTable[7] && + expected.ColorTable[8] == actual.ColorTable[8] && + expected.ColorTable[9] == actual.ColorTable[9] && + expected.ColorTable[10] == actual.ColorTable[10] && + expected.ColorTable[11] == actual.ColorTable[11] && + expected.ColorTable[12] == actual.ColorTable[12] && + expected.ColorTable[13] == actual.ColorTable[13] && + expected.ColorTable[14] == actual.ColorTable[14] && + expected.ColorTable[15] == actual.ColorTable[15]; } static bool AreSame(const CONSOLE_SCREEN_BUFFER_INFOEX& expected, const CONSOLE_SCREEN_BUFFER_INFOEX& actual) @@ -215,33 +214,33 @@ namespace WEX::TestExecution static bool IsNull(const CONSOLE_SCREEN_BUFFER_INFOEX& object) { return object.bFullscreenSupported == 0 && - object.wAttributes == 0 && - object.wPopupAttributes == 0 && - VerifyCompareTraits::IsNull(object.dwCursorPosition) && - VerifyCompareTraits::IsNull(object.dwSize) && - VerifyCompareTraits::IsNull(object.dwMaximumWindowSize) && - VerifyCompareTraits::IsNull(object.srWindow) && - object.ColorTable[0] == 0x0 && - object.ColorTable[1] == 0x0 && - object.ColorTable[2] == 0x0 && - object.ColorTable[3] == 0x0 && - object.ColorTable[4] == 0x0 && - object.ColorTable[5] == 0x0 && - object.ColorTable[6] == 0x0 && - object.ColorTable[7] == 0x0 && - object.ColorTable[8] == 0x0 && - object.ColorTable[9] == 0x0 && - object.ColorTable[10] == 0x0 && - object.ColorTable[11] == 0x0 && - object.ColorTable[12] == 0x0 && - object.ColorTable[13] == 0x0 && - object.ColorTable[14] == 0x0 && - object.ColorTable[15] == 0x0; + object.wAttributes == 0 && + object.wPopupAttributes == 0 && + VerifyCompareTraits::IsNull(object.dwCursorPosition) && + VerifyCompareTraits::IsNull(object.dwSize) && + VerifyCompareTraits::IsNull(object.dwMaximumWindowSize) && + VerifyCompareTraits::IsNull(object.srWindow) && + object.ColorTable[0] == 0x0 && + object.ColorTable[1] == 0x0 && + object.ColorTable[2] == 0x0 && + object.ColorTable[3] == 0x0 && + object.ColorTable[4] == 0x0 && + object.ColorTable[5] == 0x0 && + object.ColorTable[6] == 0x0 && + object.ColorTable[7] == 0x0 && + object.ColorTable[8] == 0x0 && + object.ColorTable[9] == 0x0 && + object.ColorTable[10] == 0x0 && + object.ColorTable[11] == 0x0 && + object.ColorTable[12] == 0x0 && + object.ColorTable[13] == 0x0 && + object.ColorTable[14] == 0x0 && + object.ColorTable[15] == 0x0; } }; template<> - class VerifyOutputTraits + class VerifyOutputTraits { public: static WEX::Common::NoThrowString ToString(const INPUT_RECORD& ir) @@ -249,76 +248,76 @@ namespace WEX::TestExecution SetVerifyOutput verifySettings(VerifyOutputSettings::LogOnlyFailures); WCHAR szBuf[1024]; VERIFY_SUCCEEDED(StringCchCopy(szBuf, ARRAYSIZE(szBuf), L"(ev: ")); - switch(ir.EventType) + switch (ir.EventType) { - case FOCUS_EVENT: - { - WCHAR szFocus[512]; - VERIFY_SUCCEEDED(StringCchPrintf(szFocus, - ARRAYSIZE(szFocus), - L"FOCUS set: %s)", - ir.Event.FocusEvent.bSetFocus ? L"T" : L"F")); - VERIFY_SUCCEEDED(StringCchCat(szBuf, ARRAYSIZE(szBuf), szFocus)); - break; - } + case FOCUS_EVENT: + { + WCHAR szFocus[512]; + VERIFY_SUCCEEDED(StringCchPrintf(szFocus, + ARRAYSIZE(szFocus), + L"FOCUS set: %s)", + ir.Event.FocusEvent.bSetFocus ? L"T" : L"F")); + VERIFY_SUCCEEDED(StringCchCat(szBuf, ARRAYSIZE(szBuf), szFocus)); + break; + } - case KEY_EVENT: - { - WCHAR szKey[512]; - VERIFY_SUCCEEDED(StringCchPrintf(szKey, - ARRAYSIZE(szKey), - L"KEY down: %s reps: %d kc: 0x%x sc: 0x%x uc: %d ctl: 0x%x)", - ir.Event.KeyEvent.bKeyDown ? L"T" : L"F", - ir.Event.KeyEvent.wRepeatCount, - ir.Event.KeyEvent.wVirtualKeyCode, - ir.Event.KeyEvent.wVirtualScanCode, - ir.Event.KeyEvent.uChar.UnicodeChar, - ir.Event.KeyEvent.dwControlKeyState)); - VERIFY_SUCCEEDED(StringCchCat(szBuf, ARRAYSIZE(szBuf), szKey)); - break; - } + case KEY_EVENT: + { + WCHAR szKey[512]; + VERIFY_SUCCEEDED(StringCchPrintf(szKey, + ARRAYSIZE(szKey), + L"KEY down: %s reps: %d kc: 0x%x sc: 0x%x uc: %d ctl: 0x%x)", + ir.Event.KeyEvent.bKeyDown ? L"T" : L"F", + ir.Event.KeyEvent.wRepeatCount, + ir.Event.KeyEvent.wVirtualKeyCode, + ir.Event.KeyEvent.wVirtualScanCode, + ir.Event.KeyEvent.uChar.UnicodeChar, + ir.Event.KeyEvent.dwControlKeyState)); + VERIFY_SUCCEEDED(StringCchCat(szBuf, ARRAYSIZE(szBuf), szKey)); + break; + } - case MENU_EVENT: - { - WCHAR szMenu[512]; - VERIFY_SUCCEEDED(StringCchPrintf(szMenu, - ARRAYSIZE(szMenu), - L"MENU cmd: %d (0x%x))", - ir.Event.MenuEvent.dwCommandId, - ir.Event.MenuEvent.dwCommandId)); - VERIFY_SUCCEEDED(StringCchCat(szBuf, ARRAYSIZE(szBuf), szMenu)); - break; - } + case MENU_EVENT: + { + WCHAR szMenu[512]; + VERIFY_SUCCEEDED(StringCchPrintf(szMenu, + ARRAYSIZE(szMenu), + L"MENU cmd: %d (0x%x))", + ir.Event.MenuEvent.dwCommandId, + ir.Event.MenuEvent.dwCommandId)); + VERIFY_SUCCEEDED(StringCchCat(szBuf, ARRAYSIZE(szBuf), szMenu)); + break; + } - case MOUSE_EVENT: - { - WCHAR szMouse[512]; - VERIFY_SUCCEEDED(StringCchPrintf(szMouse, - ARRAYSIZE(szMouse), - L"MOUSE pos: (%d, %d) buttons: 0x%x ctl: 0x%x evflags: 0x%x)", - ir.Event.MouseEvent.dwMousePosition.X, - ir.Event.MouseEvent.dwMousePosition.Y, - ir.Event.MouseEvent.dwButtonState, - ir.Event.MouseEvent.dwControlKeyState, - ir.Event.MouseEvent.dwEventFlags)); - VERIFY_SUCCEEDED(StringCchCat(szBuf, ARRAYSIZE(szBuf), szMouse)); - break; - } + case MOUSE_EVENT: + { + WCHAR szMouse[512]; + VERIFY_SUCCEEDED(StringCchPrintf(szMouse, + ARRAYSIZE(szMouse), + L"MOUSE pos: (%d, %d) buttons: 0x%x ctl: 0x%x evflags: 0x%x)", + ir.Event.MouseEvent.dwMousePosition.X, + ir.Event.MouseEvent.dwMousePosition.Y, + ir.Event.MouseEvent.dwButtonState, + ir.Event.MouseEvent.dwControlKeyState, + ir.Event.MouseEvent.dwEventFlags)); + VERIFY_SUCCEEDED(StringCchCat(szBuf, ARRAYSIZE(szBuf), szMouse)); + break; + } - case WINDOW_BUFFER_SIZE_EVENT: - { - WCHAR szBufferSize[512]; - VERIFY_SUCCEEDED(StringCchPrintf(szBufferSize, - ARRAYSIZE(szBufferSize), - L"WINDOW_BUFFER_SIZE (%d, %d)", - ir.Event.WindowBufferSizeEvent.dwSize.X, - ir.Event.WindowBufferSizeEvent.dwSize.Y)); - VERIFY_SUCCEEDED(StringCchCat(szBuf, ARRAYSIZE(szBuf), szBufferSize)); - break; - } + case WINDOW_BUFFER_SIZE_EVENT: + { + WCHAR szBufferSize[512]; + VERIFY_SUCCEEDED(StringCchPrintf(szBufferSize, + ARRAYSIZE(szBufferSize), + L"WINDOW_BUFFER_SIZE (%d, %d)", + ir.Event.WindowBufferSizeEvent.dwSize.X, + ir.Event.WindowBufferSizeEvent.dwSize.Y)); + VERIFY_SUCCEEDED(StringCchCat(szBuf, ARRAYSIZE(szBuf), szBufferSize)); + break; + } - default: - VERIFY_FAIL(L"ERROR: unknown input event type encountered"); + default: + VERIFY_FAIL(L"ERROR: unknown input event type encountered"); } return WEX::Common::NoThrowString(szBuf); @@ -326,7 +325,7 @@ namespace WEX::TestExecution }; template<> - class VerifyCompareTraits < INPUT_RECORD, INPUT_RECORD > + class VerifyCompareTraits { public: static bool AreEqual(const INPUT_RECORD& expected, const INPUT_RECORD& actual) @@ -345,11 +344,11 @@ namespace WEX::TestExecution case KEY_EVENT: { fEqual = (expected.Event.KeyEvent.bKeyDown == actual.Event.KeyEvent.bKeyDown && - expected.Event.KeyEvent.wRepeatCount == actual.Event.KeyEvent.wRepeatCount && - expected.Event.KeyEvent.wVirtualKeyCode == actual.Event.KeyEvent.wVirtualKeyCode && - expected.Event.KeyEvent.wVirtualScanCode == actual.Event.KeyEvent.wVirtualScanCode && - expected.Event.KeyEvent.uChar.UnicodeChar == actual.Event.KeyEvent.uChar.UnicodeChar && - expected.Event.KeyEvent.dwControlKeyState == actual.Event.KeyEvent.dwControlKeyState); + expected.Event.KeyEvent.wRepeatCount == actual.Event.KeyEvent.wRepeatCount && + expected.Event.KeyEvent.wVirtualKeyCode == actual.Event.KeyEvent.wVirtualKeyCode && + expected.Event.KeyEvent.wVirtualScanCode == actual.Event.KeyEvent.wVirtualScanCode && + expected.Event.KeyEvent.uChar.UnicodeChar == actual.Event.KeyEvent.uChar.UnicodeChar && + expected.Event.KeyEvent.dwControlKeyState == actual.Event.KeyEvent.dwControlKeyState); break; } @@ -362,17 +361,17 @@ namespace WEX::TestExecution case MOUSE_EVENT: { fEqual = (expected.Event.MouseEvent.dwMousePosition.X == actual.Event.MouseEvent.dwMousePosition.X && - expected.Event.MouseEvent.dwMousePosition.Y == actual.Event.MouseEvent.dwMousePosition.Y && - expected.Event.MouseEvent.dwButtonState == actual.Event.MouseEvent.dwButtonState && - expected.Event.MouseEvent.dwControlKeyState == actual.Event.MouseEvent.dwControlKeyState && - expected.Event.MouseEvent.dwEventFlags == actual.Event.MouseEvent.dwEventFlags); + expected.Event.MouseEvent.dwMousePosition.Y == actual.Event.MouseEvent.dwMousePosition.Y && + expected.Event.MouseEvent.dwButtonState == actual.Event.MouseEvent.dwButtonState && + expected.Event.MouseEvent.dwControlKeyState == actual.Event.MouseEvent.dwControlKeyState && + expected.Event.MouseEvent.dwEventFlags == actual.Event.MouseEvent.dwEventFlags); break; } case WINDOW_BUFFER_SIZE_EVENT: { fEqual = (expected.Event.WindowBufferSizeEvent.dwSize.X == actual.Event.WindowBufferSizeEvent.dwSize.X && - expected.Event.WindowBufferSizeEvent.dwSize.Y == actual.Event.WindowBufferSizeEvent.dwSize.Y); + expected.Event.WindowBufferSizeEvent.dwSize.Y == actual.Event.WindowBufferSizeEvent.dwSize.Y); break; } @@ -400,7 +399,7 @@ namespace WEX::TestExecution }; template<> - class VerifyOutputTraits + class VerifyOutputTraits { public: static WEX::Common::NoThrowString ToString(const CONSOLE_FONT_INFO& cfi) @@ -410,14 +409,14 @@ namespace WEX::TestExecution }; template<> - class VerifyCompareTraits + class VerifyCompareTraits { public: static bool AreEqual(const CONSOLE_FONT_INFO& expected, const CONSOLE_FONT_INFO& actual) { return expected.nFont == actual.nFont && - expected.dwFontSize.X == actual.dwFontSize.X && - expected.dwFontSize.Y == actual.dwFontSize.Y; + expected.dwFontSize.X == actual.dwFontSize.X && + expected.dwFontSize.Y == actual.dwFontSize.Y; } static bool AreSame(const CONSOLE_FONT_INFO& expected, const CONSOLE_FONT_INFO& actual) @@ -428,13 +427,13 @@ namespace WEX::TestExecution static bool IsLessThan(const CONSOLE_FONT_INFO& expectedLess, const CONSOLE_FONT_INFO& expectedGreater) { return expectedLess.dwFontSize.X < expectedGreater.dwFontSize.X && - expectedLess.dwFontSize.Y < expectedGreater.dwFontSize.Y; + expectedLess.dwFontSize.Y < expectedGreater.dwFontSize.Y; } static bool IsGreaterThan(const CONSOLE_FONT_INFO& expectedGreater, const CONSOLE_FONT_INFO& expectedLess) { return expectedLess.dwFontSize.X < expectedGreater.dwFontSize.X && - expectedLess.dwFontSize.Y < expectedGreater.dwFontSize.Y; + expectedLess.dwFontSize.Y < expectedGreater.dwFontSize.Y; } static bool IsNull(const CONSOLE_FONT_INFO& object) @@ -444,33 +443,35 @@ namespace WEX::TestExecution }; template<> - class VerifyOutputTraits + class VerifyOutputTraits { public: static WEX::Common::NoThrowString ToString(const CONSOLE_FONT_INFOEX& cfiex) { return WEX::Common::NoThrowString().Format(L"Index: %d Size: (X:%d, Y:%d) Family: 0x%x (%d) Weight: 0x%x (%d) Name: %ls", - cfiex.nFont, - cfiex.dwFontSize.X, - cfiex.dwFontSize.Y, - cfiex.FontFamily, cfiex.FontFamily, - cfiex.FontWeight, cfiex.FontWeight, - cfiex.FaceName); + cfiex.nFont, + cfiex.dwFontSize.X, + cfiex.dwFontSize.Y, + cfiex.FontFamily, + cfiex.FontFamily, + cfiex.FontWeight, + cfiex.FontWeight, + cfiex.FaceName); } }; template<> - class VerifyCompareTraits + class VerifyCompareTraits { public: static bool AreEqual(const CONSOLE_FONT_INFOEX& expected, const CONSOLE_FONT_INFOEX& actual) { return expected.nFont == actual.nFont && - expected.dwFontSize.X == actual.dwFontSize.X && - expected.dwFontSize.Y == actual.dwFontSize.Y && - expected.FontFamily == actual.FontFamily && - expected.FontWeight == actual.FontWeight && - 0 == wcscmp(expected.FaceName, actual.FaceName); + expected.dwFontSize.X == actual.dwFontSize.X && + expected.dwFontSize.Y == actual.dwFontSize.Y && + expected.FontFamily == actual.FontFamily && + expected.FontWeight == actual.FontWeight && + 0 == wcscmp(expected.FaceName, actual.FaceName); } static bool AreSame(const CONSOLE_FONT_INFOEX& expected, const CONSOLE_FONT_INFOEX& actual) @@ -481,24 +482,24 @@ namespace WEX::TestExecution static bool IsLessThan(const CONSOLE_FONT_INFOEX& expectedLess, const CONSOLE_FONT_INFOEX& expectedGreater) { return expectedLess.dwFontSize.X < expectedGreater.dwFontSize.X && - expectedLess.dwFontSize.Y < expectedGreater.dwFontSize.Y; + expectedLess.dwFontSize.Y < expectedGreater.dwFontSize.Y; } static bool IsGreaterThan(const CONSOLE_FONT_INFOEX& expectedGreater, const CONSOLE_FONT_INFOEX& expectedLess) { return expectedLess.dwFontSize.X < expectedGreater.dwFontSize.X && - expectedLess.dwFontSize.Y < expectedGreater.dwFontSize.Y; + expectedLess.dwFontSize.Y < expectedGreater.dwFontSize.Y; } static bool IsNull(const CONSOLE_FONT_INFOEX& object) { return object.nFont == 0 && object.dwFontSize.X == 0 && object.dwFontSize.Y == 0 && - object.FontFamily == 0 && object.FontWeight == 0 && object.FaceName[0] == L'\0'; + object.FontFamily == 0 && object.FontWeight == 0 && object.FaceName[0] == L'\0'; } }; template<> - class VerifyOutputTraits < CHAR_INFO > + class VerifyOutputTraits { public: static WEX::Common::NoThrowString ToString(const CHAR_INFO& ci) @@ -510,22 +511,22 @@ namespace WEX::TestExecution char const ch = ci.Char.AsciiChar != '\0' ? ci.Char.AsciiChar : 0x20; return WEX::Common::NoThrowString().Format(L"Unicode Char: %lc (0x%x), Attributes: 0x%x, [Ascii Char: %c (0x%hhx)]", - wch, - ci.Char.UnicodeChar, - ci.Attributes, - ch, - ci.Char.AsciiChar); + wch, + ci.Char.UnicodeChar, + ci.Attributes, + ch, + ci.Char.AsciiChar); } }; template<> - class VerifyCompareTraits < CHAR_INFO, CHAR_INFO > + class VerifyCompareTraits { public: static bool AreEqual(const CHAR_INFO& expected, const CHAR_INFO& actual) { return expected.Attributes == actual.Attributes && - expected.Char.UnicodeChar == actual.Char.UnicodeChar; + expected.Char.UnicodeChar == actual.Char.UnicodeChar; } static bool AreSame(const CHAR_INFO& expected, const CHAR_INFO& actual) @@ -543,9 +544,8 @@ namespace WEX::TestExecution } }; - template<> - class VerifyOutputTraits < std::wstring_view > + class VerifyOutputTraits { public: static WEX::Common::NoThrowString ToString(const std::wstring_view& view) @@ -555,7 +555,7 @@ namespace WEX::TestExecution }; template<> - class VerifyCompareTraits < std::wstring_view, std::wstring_view > + class VerifyCompareTraits { public: static bool AreEqual(const std::wstring_view& expected, const std::wstring_view& actual) diff --git a/src/inc/contsf.h b/src/inc/contsf.h index 67ac9a554..d7fbacdb4 100644 --- a/src/inc/contsf.h +++ b/src/inc/contsf.h @@ -28,13 +28,12 @@ Revision History: extern "C" { #endif - typedef RECT(*GetSuggestionWindowPos)(); +typedef RECT (*GetSuggestionWindowPos)(); - BOOL ActivateTextServices(HWND hwndConsole, GetSuggestionWindowPos pfnPosition); - void DeactivateTextServices(); - BOOL NotifyTextServices(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT* lplResult); +BOOL ActivateTextServices(HWND hwndConsole, GetSuggestionWindowPos pfnPosition); +void DeactivateTextServices(); +BOOL NotifyTextServices(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT* lplResult); #ifdef __cplusplus } #endif - diff --git a/src/inc/cpl_core.h b/src/inc/cpl_core.h index 6652bb555..fabad8873 100644 --- a/src/inc/cpl_core.h +++ b/src/inc/cpl_core.h @@ -1,5 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. + /* * General rules for being installed in the Control Panel: * @@ -19,8 +20,9 @@ * */ #ifndef _INC_CPL -#define _INC_CPL +#define _INC_CPL +// clang-format off #include /* Assume byte packing throughout */ @@ -181,5 +183,6 @@ typedef LPNEWCPLINFOA LPNEWCPLINFO; #include -#endif /* _INC_CPL */ +// clang-format on +#endif /* _INC_CPL */ diff --git a/src/inc/test/CommonState.hpp b/src/inc/test/CommonState.hpp index b3288e103..cd10f24f5 100644 --- a/src/inc/test/CommonState.hpp +++ b/src/inc/test/CommonState.hpp @@ -31,7 +31,6 @@ unit testing projects in the codebase without a bunch of overhead. class CommonState { public: - static const SHORT s_csWindowWidth = 80; static const SHORT s_csWindowHeight = 80; static const SHORT s_csBufferWidth = 80; @@ -157,7 +156,7 @@ public: try { std::unique_ptr textBuffer = std::make_unique(coordScreenBufferSize, - TextAttribute{FOREGROUND_BLUE | FOREGROUND_GREEN | BACKGROUND_RED | BACKGROUND_INTENSITY}, + TextAttribute{ FOREGROUND_BLUE | FOREGROUND_GREEN | BACKGROUND_RED | BACKGROUND_INTENSITY }, uiCursorSize, gci.pCurrentScreenBuffer->GetRenderTarget()); if (textBuffer.get() == nullptr) @@ -222,8 +221,7 @@ public: textBuffer.GetCursor().SetYPosition(cRowsToFill); } - [[nodiscard]] - NTSTATUS GetTextBufferInfoInitResult() + [[nodiscard]] NTSTATUS GetTextBufferInfoInitResult() { return m_ntstatusTextBufferInfo; } @@ -241,7 +239,11 @@ private: // 9 characters, 6 spaces. 15 total // か = \x304b // き = \x304d - const PCWSTR pwszText = L"AB" L"\x304b\x304b" L"C" L"\x304d\x304d" L"DE "; + const PCWSTR pwszText = L"AB" + L"\x304b\x304b" + L"C" + L"\x304d\x304d" + L"DE "; const size_t length = wcslen(pwszText); std::vector attrs(length, DbcsAttribute()); @@ -288,7 +290,7 @@ private: } } - void FillBisect(ROW *pRow) + void FillBisect(ROW* pRow) { const CONSOLE_INFORMATION& gci = Microsoft::Console::Interactivity::ServiceLocator::LocateGlobals().getConsoleInformation(); // length 80 string of text with bisecting characters at the beginning and end. diff --git a/src/inc/unicode.hpp b/src/inc/unicode.hpp index b7ea15e03..9438d81fe 100644 --- a/src/inc/unicode.hpp +++ b/src/inc/unicode.hpp @@ -15,15 +15,15 @@ Author(s): #pragma once -#define CP_UTF8 65001 -#define CP_USA 437 -#define CP_KOREAN 949 -#define CP_JAPANESE 932 -#define CP_CHINESE_SIMPLIFIED 936 +#define CP_UTF8 65001 +#define CP_USA 437 +#define CP_KOREAN 949 +#define CP_JAPANESE 932 +#define CP_CHINESE_SIMPLIFIED 936 #define CP_CHINESE_TRADITIONAL 950 -#define IsBilingualCP(cp) ((cp)==CP_JAPANESE || (cp)==CP_KOREAN) -#define IsEastAsianCP(cp) ((cp)==CP_JAPANESE || (cp)==CP_KOREAN || (cp)==CP_CHINESE_TRADITIONAL || (cp)==CP_CHINESE_SIMPLIFIED) +#define IsBilingualCP(cp) ((cp) == CP_JAPANESE || (cp) == CP_KOREAN) +#define IsEastAsianCP(cp) ((cp) == CP_JAPANESE || (cp) == CP_KOREAN || (cp) == CP_CHINESE_TRADITIONAL || (cp) == CP_CHINESE_SIMPLIFIED) // UNICODE_NULL is a Windows macro definition const wchar_t UNICODE_BACKSPACE = 0x8; diff --git a/src/interactivity/base/ApiDetector.cpp b/src/interactivity/base/ApiDetector.cpp index ff6c2eddc..50e482e3e 100644 --- a/src/interactivity/base/ApiDetector.cpp +++ b/src/interactivity/base/ApiDetector.cpp @@ -12,11 +12,11 @@ using namespace Microsoft::Console::Interactivity; // API Sets -#define EXT_API_SET_NTUSER_WINDOW L"ext-ms-win-ntuser-window-l1-1-0" +#define EXT_API_SET_NTUSER_WINDOW L"ext-ms-win-ntuser-window-l1-1-0" // This may not be defined depending on the SDK version being targetted. #ifndef LOAD_LIBRARY_SEARCH_SYSTEM32_NO_FORWARDER -#define LOAD_LIBRARY_SEARCH_SYSTEM32_NO_FORWARDER 0x00004000 +#define LOAD_LIBRARY_SEARCH_SYSTEM32_NO_FORWARDER 0x00004000 #endif #pragma region Public Methods @@ -27,8 +27,7 @@ using namespace Microsoft::Console::Interactivity; // Arguments: // - level - pointer to an APILevel enum stating the level of support the // system offers for the given functionality. -[[nodiscard]] -NTSTATUS ApiDetector::DetectNtUserWindow(_Out_ ApiLevel* level) +[[nodiscard]] NTSTATUS ApiDetector::DetectNtUserWindow(_Out_ ApiLevel* level) { // N.B.: Testing for the API set implies the function is present. return DetectApiSupport(EXT_API_SET_NTUSER_WINDOW, nullptr, level); @@ -38,8 +37,7 @@ NTSTATUS ApiDetector::DetectNtUserWindow(_Out_ ApiLevel* level) #pragma region Private Methods -[[nodiscard]] -NTSTATUS ApiDetector::DetectApiSupport(_In_ LPCWSTR lpApiHost, _In_ LPCSTR lpProcedure, _Out_ ApiLevel* level) +[[nodiscard]] NTSTATUS ApiDetector::DetectApiSupport(_In_ LPCWSTR lpApiHost, _In_ LPCSTR lpProcedure, _Out_ ApiLevel* level) { if (!level) { @@ -47,7 +45,7 @@ NTSTATUS ApiDetector::DetectApiSupport(_In_ LPCWSTR lpApiHost, _In_ LPCSTR lpPro } NTSTATUS status = STATUS_SUCCESS; - HMODULE hModule = nullptr; + HMODULE hModule = nullptr; status = TryLoadWellKnownLibrary(lpApiHost, &hModule); if (NT_SUCCESS(status) && lpProcedure) @@ -60,8 +58,8 @@ NTSTATUS ApiDetector::DetectApiSupport(_In_ LPCWSTR lpApiHost, _In_ LPCSTR lpPro return STATUS_SUCCESS; } -[[nodiscard]] -NTSTATUS ApiDetector::TryLoadWellKnownLibrary(_In_ LPCWSTR lpLibrary, _Outptr_result_nullonfailure_ HMODULE *phModule) +[[nodiscard]] NTSTATUS ApiDetector::TryLoadWellKnownLibrary(_In_ LPCWSTR lpLibrary, + _Outptr_result_nullonfailure_ HMODULE* phModule) { NTSTATUS status = STATUS_SUCCESS; @@ -106,10 +104,11 @@ NTSTATUS ApiDetector::TryLoadWellKnownLibrary(_In_ LPCWSTR lpLibrary, _Outptr_re return status; } -[[nodiscard]] -NTSTATUS ApiDetector::TryLoadWellKnownLibrary(_In_ LPCWSTR lpLibrary, _In_ DWORD dwLoaderFlags, _Outptr_result_nullonfailure_ HMODULE *phModule) +[[nodiscard]] NTSTATUS ApiDetector::TryLoadWellKnownLibrary(_In_ LPCWSTR lpLibrary, + _In_ DWORD dwLoaderFlags, + _Outptr_result_nullonfailure_ HMODULE* phModule) { - HMODULE hModule = nullptr; + HMODULE hModule = nullptr; hModule = LoadLibraryExW(lpLibrary, nullptr, @@ -126,8 +125,7 @@ NTSTATUS ApiDetector::TryLoadWellKnownLibrary(_In_ LPCWSTR lpLibrary, _In_ DWORD } } -[[nodiscard]] -NTSTATUS ApiDetector::TryLocateProcedure(_In_ HMODULE hModule, _In_ LPCSTR lpProcedure) +[[nodiscard]] NTSTATUS ApiDetector::TryLocateProcedure(_In_ HMODULE hModule, _In_ LPCSTR lpProcedure) { FARPROC proc = GetProcAddress(hModule, lpProcedure); diff --git a/src/interactivity/base/ApiDetector.hpp b/src/interactivity/base/ApiDetector.hpp index b7fdb3a56..e03f364f5 100644 --- a/src/interactivity/base/ApiDetector.hpp +++ b/src/interactivity/base/ApiDetector.hpp @@ -16,20 +16,15 @@ namespace Microsoft::Console::Interactivity class ApiDetector final { public: - [[nodiscard]] - static NTSTATUS DetectNtUserWindow(_Out_ ApiLevel* level); + [[nodiscard]] static NTSTATUS DetectNtUserWindow(_Out_ ApiLevel* level); private: - [[nodiscard]] - static NTSTATUS DetectApiSupport(_In_ LPCWSTR lpLibrary, _In_ LPCSTR lpApi, _Out_ ApiLevel* level); - [[nodiscard]] - static NTSTATUS TryLoadWellKnownLibrary(_In_ LPCWSTR library, _Outptr_result_nullonfailure_ HMODULE* module); - [[nodiscard]] - static NTSTATUS TryLocateProcedure(_In_ HMODULE hModule, _In_ LPCSTR lpProcedure); + [[nodiscard]] static NTSTATUS DetectApiSupport(_In_ LPCWSTR lpLibrary, _In_ LPCSTR lpApi, _Out_ ApiLevel* level); + [[nodiscard]] static NTSTATUS TryLoadWellKnownLibrary(_In_ LPCWSTR library, _Outptr_result_nullonfailure_ HMODULE* module); + [[nodiscard]] static NTSTATUS TryLocateProcedure(_In_ HMODULE hModule, _In_ LPCSTR lpProcedure); static void SetLevelAndFreeIfNecessary(_In_ NTSTATUS status, _In_ HMODULE hModule, _Out_ ApiLevel* level); - [[nodiscard]] - static NTSTATUS TryLoadWellKnownLibrary(_In_ LPCWSTR lpLibrary, - _In_ DWORD dwLoaderFlags, - _Outptr_result_nullonfailure_ HMODULE *phModule); + [[nodiscard]] static NTSTATUS TryLoadWellKnownLibrary(_In_ LPCWSTR lpLibrary, + _In_ DWORD dwLoaderFlags, + _Outptr_result_nullonfailure_ HMODULE* phModule); }; } diff --git a/src/interactivity/base/InteractivityFactory.cpp b/src/interactivity/base/InteractivityFactory.cpp index 8262e8075..99deec453 100644 --- a/src/interactivity/base/InteractivityFactory.cpp +++ b/src/interactivity/base/InteractivityFactory.cpp @@ -30,8 +30,7 @@ using namespace Microsoft::Console::Interactivity; #pragma region Public Methods -[[nodiscard]] -NTSTATUS InteractivityFactory::CreateConsoleControl(_Inout_ std::unique_ptr& control) +[[nodiscard]] NTSTATUS InteractivityFactory::CreateConsoleControl(_Inout_ std::unique_ptr& control) { NTSTATUS status = STATUS_SUCCESS; @@ -73,8 +72,7 @@ NTSTATUS InteractivityFactory::CreateConsoleControl(_Inout_ std::unique_ptr& thread) +[[nodiscard]] NTSTATUS InteractivityFactory::CreateConsoleInputThread(_Inout_ std::unique_ptr& thread) { NTSTATUS status = STATUS_SUCCESS; @@ -116,8 +114,7 @@ NTSTATUS InteractivityFactory::CreateConsoleInputThread(_Inout_ std::unique_ptr< return status; } -[[nodiscard]] -NTSTATUS InteractivityFactory::CreateHighDpiApi(_Inout_ std::unique_ptr& api) +[[nodiscard]] NTSTATUS InteractivityFactory::CreateHighDpiApi(_Inout_ std::unique_ptr& api) { NTSTATUS status = STATUS_SUCCESS; @@ -159,8 +156,7 @@ NTSTATUS InteractivityFactory::CreateHighDpiApi(_Inout_ std::unique_ptr& metrics) +[[nodiscard]] NTSTATUS InteractivityFactory::CreateWindowMetrics(_Inout_ std::unique_ptr& metrics) { NTSTATUS status = STATUS_SUCCESS; @@ -202,8 +198,7 @@ NTSTATUS InteractivityFactory::CreateWindowMetrics(_Inout_ std::unique_ptr& notifier) +[[nodiscard]] NTSTATUS InteractivityFactory::CreateAccessibilityNotifier(_Inout_ std::unique_ptr& notifier) { NTSTATUS status = STATUS_SUCCESS; @@ -221,11 +216,11 @@ NTSTATUS InteractivityFactory::CreateAccessibilityNotifier(_Inout_ std::unique_p newNotifier = std::make_unique(); break; - #ifdef BUILD_ONECORE_INTERACTIVITY +#ifdef BUILD_ONECORE_INTERACTIVITY case ApiLevel::OneCore: newNotifier = std::make_unique(); break; - #endif +#endif default: status = STATUS_INVALID_LEVEL; break; @@ -245,8 +240,7 @@ NTSTATUS InteractivityFactory::CreateAccessibilityNotifier(_Inout_ std::unique_p return status; } -[[nodiscard]] -NTSTATUS InteractivityFactory::CreateSystemConfigurationProvider(_Inout_ std::unique_ptr& provider) +[[nodiscard]] NTSTATUS InteractivityFactory::CreateSystemConfigurationProvider(_Inout_ std::unique_ptr& provider) { NTSTATUS status = STATUS_SUCCESS; @@ -264,11 +258,11 @@ NTSTATUS InteractivityFactory::CreateSystemConfigurationProvider(_Inout_ std::un NewProvider = std::make_unique(); break; - #ifdef BUILD_ONECORE_INTERACTIVITY +#ifdef BUILD_ONECORE_INTERACTIVITY case ApiLevel::OneCore: NewProvider = std::make_unique(); break; - #endif +#endif default: status = STATUS_INVALID_LEVEL; break; @@ -288,8 +282,7 @@ NTSTATUS InteractivityFactory::CreateSystemConfigurationProvider(_Inout_ std::un return status; } -[[nodiscard]] -NTSTATUS InteractivityFactory::CreateInputServices(_Inout_ std::unique_ptr& services) +[[nodiscard]] NTSTATUS InteractivityFactory::CreateInputServices(_Inout_ std::unique_ptr& services) { NTSTATUS status = STATUS_SUCCESS; @@ -307,11 +300,11 @@ NTSTATUS InteractivityFactory::CreateInputServices(_Inout_ std::unique_ptr(); break; - #ifdef BUILD_ONECORE_INTERACTIVITY +#ifdef BUILD_ONECORE_INTERACTIVITY case ApiLevel::OneCore: newServices = std::make_unique(); break; - #endif +#endif default: status = STATUS_INVALID_LEVEL; break; @@ -341,18 +334,18 @@ NTSTATUS InteractivityFactory::CreateInputServices(_Inout_ std::unique_ptr& control); - [[nodiscard]] - NTSTATUS CreateConsoleInputThread(_Inout_ std::unique_ptr& thread); + [[nodiscard]] NTSTATUS CreateConsoleControl(_Inout_ std::unique_ptr& control); + [[nodiscard]] NTSTATUS CreateConsoleInputThread(_Inout_ std::unique_ptr& thread); - [[nodiscard]] - NTSTATUS CreateHighDpiApi(_Inout_ std::unique_ptr& api); - [[nodiscard]] - NTSTATUS CreateWindowMetrics(_Inout_ std::unique_ptr& metrics); - [[nodiscard]] - NTSTATUS CreateAccessibilityNotifier(_Inout_ std::unique_ptr& notifier); - [[nodiscard]] - NTSTATUS CreateSystemConfigurationProvider(_Inout_ std::unique_ptr& provider); - [[nodiscard]] - NTSTATUS CreateInputServices(_Inout_ std::unique_ptr& services); + [[nodiscard]] NTSTATUS CreateHighDpiApi(_Inout_ std::unique_ptr& api); + [[nodiscard]] NTSTATUS CreateWindowMetrics(_Inout_ std::unique_ptr& metrics); + [[nodiscard]] NTSTATUS CreateAccessibilityNotifier(_Inout_ std::unique_ptr& notifier); + [[nodiscard]] NTSTATUS CreateSystemConfigurationProvider(_Inout_ std::unique_ptr& provider); + [[nodiscard]] NTSTATUS CreateInputServices(_Inout_ std::unique_ptr& services); - [[nodiscard]] - NTSTATUS CreatePseudoWindow(HWND& hwnd); + [[nodiscard]] NTSTATUS CreatePseudoWindow(HWND& hwnd); }; } diff --git a/src/interactivity/base/ServiceLocator.cpp b/src/interactivity/base/ServiceLocator.cpp index 560dd19c2..858c25a02 100644 --- a/src/interactivity/base/ServiceLocator.cpp +++ b/src/interactivity/base/ServiceLocator.cpp @@ -24,7 +24,7 @@ std::unique_ptr ServiceLocator::s_inputServices; IConsoleWindow* ServiceLocator::s_consoleWindow = nullptr; -Globals ServiceLocator::s_globals; +Globals ServiceLocator::s_globals; bool ServiceLocator::s_pseudoWindowInitialized = false; wil::unique_hwnd ServiceLocator::s_pseudoWindow = 0; @@ -71,8 +71,7 @@ void ServiceLocator::RundownAndExit(const HRESULT hr) #pragma region Creation Methods -[[nodiscard]] -NTSTATUS ServiceLocator::CreateConsoleInputThread(_Outptr_result_nullonfailure_ IConsoleInputThread** thread) +[[nodiscard]] NTSTATUS ServiceLocator::CreateConsoleInputThread(_Outptr_result_nullonfailure_ IConsoleInputThread** thread) { NTSTATUS status = STATUS_SUCCESS; @@ -104,8 +103,7 @@ NTSTATUS ServiceLocator::CreateConsoleInputThread(_Outptr_result_nullonfailure_ #pragma region Set Methods -[[nodiscard]] -NTSTATUS ServiceLocator::SetConsoleWindowInstance(_In_ IConsoleWindow* window) +[[nodiscard]] NTSTATUS ServiceLocator::SetConsoleWindowInstance(_In_ IConsoleWindow* window) { NTSTATUS status = STATUS_SUCCESS; @@ -129,12 +127,12 @@ NTSTATUS ServiceLocator::SetConsoleWindowInstance(_In_ IConsoleWindow* window) #pragma region Location Methods -IConsoleWindow *ServiceLocator::LocateConsoleWindow() +IConsoleWindow* ServiceLocator::LocateConsoleWindow() { return s_consoleWindow; } -IConsoleControl *ServiceLocator::LocateConsoleControl() +IConsoleControl* ServiceLocator::LocateConsoleControl() { NTSTATUS status = STATUS_SUCCESS; @@ -310,8 +308,7 @@ HWND ServiceLocator::LocatePseudoWindow() #pragma region Private Methods -[[nodiscard]] -NTSTATUS ServiceLocator::LoadInteractivityFactory() +[[nodiscard]] NTSTATUS ServiceLocator::LoadInteractivityFactory() { NTSTATUS status = STATUS_SUCCESS; diff --git a/src/interactivity/base/precomp.h b/src/interactivity/base/precomp.h index a8b9af497..7e62e825d 100644 --- a/src/interactivity/base/precomp.h +++ b/src/interactivity/base/precomp.h @@ -9,12 +9,12 @@ typedef char CCHAR; typedef short CSHORT; typedef ULONG CLONG; -typedef CCHAR *PCCHAR; -typedef CSHORT *PCSHORT; -typedef CLONG *PCLONG; +typedef CCHAR* PCCHAR; +typedef CSHORT* PCSHORT; +typedef CLONG* PCLONG; typedef ULONG LOGICAL; -typedef ULONG *PLOGICAL; +typedef ULONG* PLOGICAL; // End ntdef.h and winnt.h #include diff --git a/src/interactivity/inc/IAccessibilityNotifier.hpp b/src/interactivity/inc/IAccessibilityNotifier.hpp index 23d4b7f85..1a72ba57e 100644 --- a/src/interactivity/inc/IAccessibilityNotifier.hpp +++ b/src/interactivity/inc/IAccessibilityNotifier.hpp @@ -39,7 +39,7 @@ namespace Microsoft::Console::Interactivity virtual void NotifyConsoleEndApplicationEvent(_In_ DWORD processId) = 0; protected: - IAccessibilityNotifier() { } + IAccessibilityNotifier() {} IAccessibilityNotifier(IAccessibilityNotifier const&) = delete; IAccessibilityNotifier& operator=(IAccessibilityNotifier const&) = delete; diff --git a/src/interactivity/inc/IConsoleControl.hpp b/src/interactivity/inc/IConsoleControl.hpp index 97503f899..ce257ebaf 100644 --- a/src/interactivity/inc/IConsoleControl.hpp +++ b/src/interactivity/inc/IConsoleControl.hpp @@ -21,18 +21,15 @@ namespace Microsoft::Console::Interactivity { public: virtual ~IConsoleControl() = 0; - [[nodiscard]] - virtual NTSTATUS NotifyConsoleApplication(DWORD dwProcessId) = 0; - [[nodiscard]] - virtual NTSTATUS SetForeground(HANDLE hProcess, BOOL fForeground) = 0; - [[nodiscard]] - virtual NTSTATUS EndTask(HANDLE hProcessId, DWORD dwEventType, ULONG ulCtrlFlags) = 0; + [[nodiscard]] virtual NTSTATUS NotifyConsoleApplication(DWORD dwProcessId) = 0; + [[nodiscard]] virtual NTSTATUS SetForeground(HANDLE hProcess, BOOL fForeground) = 0; + [[nodiscard]] virtual NTSTATUS EndTask(HANDLE hProcessId, DWORD dwEventType, ULONG ulCtrlFlags) = 0; protected: - IConsoleControl() { } + IConsoleControl() {} IConsoleControl(IConsoleControl const&) = delete; - IConsoleControl& operator=(IConsoleControl const &) = delete; + IConsoleControl& operator=(IConsoleControl const&) = delete; }; inline IConsoleControl::~IConsoleControl() {} diff --git a/src/interactivity/inc/IConsoleInputThread.hpp b/src/interactivity/inc/IConsoleInputThread.hpp index ff6fd5f8b..c23d09515 100644 --- a/src/interactivity/inc/IConsoleInputThread.hpp +++ b/src/interactivity/inc/IConsoleInputThread.hpp @@ -23,8 +23,8 @@ namespace Microsoft::Console::Interactivity virtual ~IConsoleInputThread() = 0; virtual HANDLE Start() = 0; - HANDLE GetHandle() { return _hThread; } - DWORD GetThreadId() { return _dwThreadId; } + HANDLE GetHandle() { return _hThread; } + DWORD GetThreadId() { return _dwThreadId; } protected: // Prevent accidental copies. @@ -34,11 +34,11 @@ namespace Microsoft::Console::Interactivity // .ctor IConsoleInputThread() : _hThread(nullptr), - _dwThreadId((DWORD)(-1)) { } + _dwThreadId((DWORD)(-1)) {} // Protected Variables HANDLE _hThread; - DWORD _dwThreadId; + DWORD _dwThreadId; }; inline IConsoleInputThread::~IConsoleInputThread() {} diff --git a/src/interactivity/inc/IConsoleWindow.hpp b/src/interactivity/inc/IConsoleWindow.hpp index 13e2f0007..d6585e020 100644 --- a/src/interactivity/inc/IConsoleWindow.hpp +++ b/src/interactivity/inc/IConsoleWindow.hpp @@ -61,13 +61,11 @@ namespace Microsoft::Console::Interactivity virtual void UpdateWindowText() = 0; virtual void HorizontalScroll(const WORD wScrollCommand, - const WORD wAbsoluteChange) = 0; + const WORD wAbsoluteChange) = 0; virtual void VerticalScroll(const WORD wScrollCommand, const WORD wAbsoluteChange) = 0; - [[nodiscard]] - virtual HRESULT SignalUia(_In_ EVENTID id) = 0; - [[nodiscard]] - virtual HRESULT UiaSetTextAreaFocus() = 0; + [[nodiscard]] virtual HRESULT SignalUia(_In_ EVENTID id) = 0; + [[nodiscard]] virtual HRESULT UiaSetTextAreaFocus() = 0; virtual RECT GetWindowRect() const = 0; }; diff --git a/src/interactivity/inc/IHighDpiApi.hpp b/src/interactivity/inc/IHighDpiApi.hpp index 53abb1bf0..b748c33c0 100644 --- a/src/interactivity/inc/IHighDpiApi.hpp +++ b/src/interactivity/inc/IHighDpiApi.hpp @@ -20,14 +20,13 @@ namespace Microsoft::Console::Interactivity { public: virtual BOOL SetProcessDpiAwarenessContext() = 0; - [[nodiscard]] - virtual HRESULT SetProcessPerMonitorDpiAwareness() = 0; + [[nodiscard]] virtual HRESULT SetProcessPerMonitorDpiAwareness() = 0; virtual BOOL EnablePerMonitorDialogScaling() = 0; virtual ~IHighDpiApi() = 0; protected: - IHighDpiApi() { } + IHighDpiApi() {} IHighDpiApi(IHighDpiApi const&) = delete; IHighDpiApi& operator=(IHighDpiApi const&) = delete; diff --git a/src/interactivity/inc/IInputServices.hpp b/src/interactivity/inc/IInputServices.hpp index 79bd44aa1..301661082 100644 --- a/src/interactivity/inc/IInputServices.hpp +++ b/src/interactivity/inc/IInputServices.hpp @@ -22,11 +22,11 @@ namespace Microsoft::Console::Interactivity virtual UINT MapVirtualKeyW(_In_ UINT uCode, _In_ UINT uMapType) = 0; virtual SHORT VkKeyScanW(_In_ WCHAR ch) = 0; virtual SHORT GetKeyState(_In_ int nVirtKey) = 0; - virtual BOOL TranslateCharsetInfo(_Inout_ DWORD FAR *lpSrc, _Out_ LPCHARSETINFO lpCs, _In_ DWORD dwFlags) = 0; + virtual BOOL TranslateCharsetInfo(_Inout_ DWORD FAR* lpSrc, _Out_ LPCHARSETINFO lpCs, _In_ DWORD dwFlags) = 0; virtual ~IInputServices() = 0; protected: - IInputServices() { } + IInputServices() {} IInputServices(IInputServices const&) = delete; IInputServices& operator=(IInputServices const&) = delete; diff --git a/src/interactivity/inc/IInteractivityFactory.hpp b/src/interactivity/inc/IInteractivityFactory.hpp index 5e95e7ec6..4996f30d6 100644 --- a/src/interactivity/inc/IInteractivityFactory.hpp +++ b/src/interactivity/inc/IInteractivityFactory.hpp @@ -33,24 +33,16 @@ namespace Microsoft::Console::Interactivity { public: virtual ~IInteractivityFactory() = 0; - [[nodiscard]] - virtual NTSTATUS CreateConsoleControl(_Inout_ std::unique_ptr& control) = 0; - [[nodiscard]] - virtual NTSTATUS CreateConsoleInputThread(_Inout_ std::unique_ptr& thread) = 0; + [[nodiscard]] virtual NTSTATUS CreateConsoleControl(_Inout_ std::unique_ptr& control) = 0; + [[nodiscard]] virtual NTSTATUS CreateConsoleInputThread(_Inout_ std::unique_ptr& thread) = 0; - [[nodiscard]] - virtual NTSTATUS CreateHighDpiApi(_Inout_ std::unique_ptr& api) = 0; - [[nodiscard]] - virtual NTSTATUS CreateWindowMetrics(_Inout_ std::unique_ptr& metrics) = 0; - [[nodiscard]] - virtual NTSTATUS CreateAccessibilityNotifier(_Inout_ std::unique_ptr& notifier) = 0; - [[nodiscard]] - virtual NTSTATUS CreateSystemConfigurationProvider(_Inout_ std::unique_ptr& provider) = 0; - [[nodiscard]] - virtual NTSTATUS CreateInputServices(_Inout_ std::unique_ptr& services) = 0; + [[nodiscard]] virtual NTSTATUS CreateHighDpiApi(_Inout_ std::unique_ptr& api) = 0; + [[nodiscard]] virtual NTSTATUS CreateWindowMetrics(_Inout_ std::unique_ptr& metrics) = 0; + [[nodiscard]] virtual NTSTATUS CreateAccessibilityNotifier(_Inout_ std::unique_ptr& notifier) = 0; + [[nodiscard]] virtual NTSTATUS CreateSystemConfigurationProvider(_Inout_ std::unique_ptr& provider) = 0; + [[nodiscard]] virtual NTSTATUS CreateInputServices(_Inout_ std::unique_ptr& services) = 0; - [[nodiscard]] - virtual NTSTATUS CreatePseudoWindow(HWND& hwnd) = 0; + [[nodiscard]] virtual NTSTATUS CreatePseudoWindow(HWND& hwnd) = 0; }; inline IInteractivityFactory::~IInteractivityFactory() {} diff --git a/src/interactivity/inc/ISystemConfigurationProvider.hpp b/src/interactivity/inc/ISystemConfigurationProvider.hpp index 50fef9201..d2a5a879e 100644 --- a/src/interactivity/inc/ISystemConfigurationProvider.hpp +++ b/src/interactivity/inc/ISystemConfigurationProvider.hpp @@ -33,13 +33,13 @@ namespace Microsoft::Console::Interactivity virtual ULONG GetNumberOfWheelScrollCharacters() = 0; virtual void GetSettingsFromLink(_Inout_ Settings* pLinkSettings, - _Inout_updates_bytes_(*pdwTitleLength) LPWSTR pwszTitle, - _Inout_ PDWORD pdwTitleLength, - _In_ PCWSTR pwszCurrDir, - _In_ PCWSTR pwszAppName) = 0; + _Inout_updates_bytes_(*pdwTitleLength) LPWSTR pwszTitle, + _Inout_ PDWORD pdwTitleLength, + _In_ PCWSTR pwszCurrDir, + _In_ PCWSTR pwszAppName) = 0; protected: - ISystemConfigurationProvider() { }; + ISystemConfigurationProvider(){}; ISystemConfigurationProvider(ISystemConfigurationProvider const&) = delete; ISystemConfigurationProvider& operator=(ISystemConfigurationProvider const&) = delete; diff --git a/src/interactivity/inc/IWindowMetrics.hpp b/src/interactivity/inc/IWindowMetrics.hpp index c13493e41..889d07574 100644 --- a/src/interactivity/inc/IWindowMetrics.hpp +++ b/src/interactivity/inc/IWindowMetrics.hpp @@ -25,7 +25,7 @@ namespace Microsoft::Console::Interactivity virtual RECT GetMaxClientRectInPixels() = 0; protected: - IWindowMetrics() { } + IWindowMetrics() {} IWindowMetrics(IWindowMetrics const&) = delete; IWindowMetrics& operator=(IWindowMetrics const&) = delete; diff --git a/src/interactivity/inc/ServiceLocator.hpp b/src/interactivity/inc/ServiceLocator.hpp index 3e419b759..fcd1f0936 100644 --- a/src/interactivity/inc/ServiceLocator.hpp +++ b/src/interactivity/inc/ServiceLocator.hpp @@ -28,7 +28,6 @@ namespace Microsoft::Console::Interactivity class ServiceLocator final { public: - static void RundownAndExit(const HRESULT hr); // N.B.: Location methods without corresponding creation methods @@ -36,63 +35,64 @@ namespace Microsoft::Console::Interactivity // In case the on-demand creation fails, the return value // is nullptr and a message is logged. + static IAccessibilityNotifier* LocateAccessibilityNotifier(); - static IAccessibilityNotifier *LocateAccessibilityNotifier(); - - static IConsoleControl *LocateConsoleControl(); - template static T *LocateConsoleControl() + static IConsoleControl* LocateConsoleControl(); + template + static T* LocateConsoleControl() { return static_cast(LocateConsoleControl()); } - [[nodiscard]] - static NTSTATUS CreateConsoleInputThread(_Outptr_result_nullonfailure_ IConsoleInputThread** thread); - static IConsoleInputThread *LocateConsoleInputThread(); - template static T *LocateConsoleInputThread() + [[nodiscard]] static NTSTATUS CreateConsoleInputThread(_Outptr_result_nullonfailure_ IConsoleInputThread** thread); + static IConsoleInputThread* LocateConsoleInputThread(); + template + static T* LocateConsoleInputThread() { return static_cast(LocateConsoleInputThread()); } - [[nodiscard]] - static NTSTATUS SetConsoleWindowInstance(_In_ IConsoleWindow *window); - static IConsoleWindow *LocateConsoleWindow(); - template static T *LocateConsoleWindow() + [[nodiscard]] static NTSTATUS SetConsoleWindowInstance(_In_ IConsoleWindow* window); + static IConsoleWindow* LocateConsoleWindow(); + template + static T* LocateConsoleWindow() { return static_cast(s_consoleWindow); } - static IWindowMetrics *LocateWindowMetrics(); - template static T *LocateWindowMetrics() + static IWindowMetrics* LocateWindowMetrics(); + template + static T* LocateWindowMetrics() { return static_cast(LocateWindowMetrics()); } - static IHighDpiApi *LocateHighDpiApi(); - template static T *LocateHighDpiApi() + static IHighDpiApi* LocateHighDpiApi(); + template + static T* LocateHighDpiApi() { return static_cast(LocateHighDpiApi()); } - static IInputServices *LocateInputServices(); - template static T *LocateInputServices() + static IInputServices* LocateInputServices(); + template + static T* LocateInputServices() { return static_cast(LocateInputServices()); } - static ISystemConfigurationProvider *LocateSystemConfigurationProvider(); + static ISystemConfigurationProvider* LocateSystemConfigurationProvider(); static Globals& LocateGlobals(); static HWND LocatePseudoWindow(); - protected: ServiceLocator(ServiceLocator const&) = delete; ServiceLocator& operator=(ServiceLocator const&) = delete; private: - [[nodiscard]] - static NTSTATUS LoadInteractivityFactory(); + [[nodiscard]] static NTSTATUS LoadInteractivityFactory(); static std::unique_ptr s_interactivityFactory; diff --git a/src/interactivity/inc/VtApiRedirection.hpp b/src/interactivity/inc/VtApiRedirection.hpp index 66fb24f30..14dcc1cc8 100644 --- a/src/interactivity/inc/VtApiRedirection.hpp +++ b/src/interactivity/inc/VtApiRedirection.hpp @@ -20,9 +20,9 @@ Author: #pragma once -#define MapVirtualKeyW(x,y) VTRedirMapVirtualKeyW(x,y) -#define VkKeyScanW(x) VTRedirVkKeyScanW(x) -#define GetKeyState(x) VTRedirGetKeyState(x) +#define MapVirtualKeyW(x, y) VTRedirMapVirtualKeyW(x, y) +#define VkKeyScanW(x) VTRedirVkKeyScanW(x) +#define GetKeyState(x) VTRedirGetKeyState(x) UINT VTRedirMapVirtualKeyW(_In_ UINT uCode, _In_ UINT uMapType); SHORT VTRedirVkKeyScanW(_In_ WCHAR ch); diff --git a/src/interactivity/onecore/BgfxEngine.cpp b/src/interactivity/onecore/BgfxEngine.cpp index 9cae44325..02eb42c57 100644 --- a/src/interactivity/onecore/BgfxEngine.cpp +++ b/src/interactivity/onecore/BgfxEngine.cpp @@ -20,12 +20,12 @@ using namespace Microsoft::Console::Render; using namespace Microsoft::Console::Interactivity; using namespace Microsoft::Console::Interactivity::OneCore; -BgfxEngine::BgfxEngine(PVOID SharedViewBase, LONG DisplayHeight, LONG DisplayWidth, LONG FontWidth, LONG FontHeight) - : RenderEngineBase(), - _sharedViewBase((ULONG_PTR)SharedViewBase), - _displayHeight(DisplayHeight), - _displayWidth(DisplayWidth), - _currentLegacyColorAttribute(DEFAULT_COLOR_ATTRIBUTE) +BgfxEngine::BgfxEngine(PVOID SharedViewBase, LONG DisplayHeight, LONG DisplayWidth, LONG FontWidth, LONG FontHeight) : + RenderEngineBase(), + _sharedViewBase((ULONG_PTR)SharedViewBase), + _displayHeight(DisplayHeight), + _displayWidth(DisplayWidth), + _currentLegacyColorAttribute(DEFAULT_COLOR_ATTRIBUTE) { _runLength = sizeof(CD_IO_CHARACTER) * DisplayWidth; @@ -33,64 +33,54 @@ BgfxEngine::BgfxEngine(PVOID SharedViewBase, LONG DisplayHeight, LONG DisplayWid _fontSize.Y = FontHeight > SHORT_MAX ? SHORT_MAX : (SHORT)FontHeight; } -[[nodiscard]] -HRESULT BgfxEngine::Invalidate(const SMALL_RECT* const /*psrRegion*/) noexcept +[[nodiscard]] HRESULT BgfxEngine::Invalidate(const SMALL_RECT* const /*psrRegion*/) noexcept { return S_OK; } -[[nodiscard]] -HRESULT BgfxEngine::InvalidateCursor(const COORD* const /*pcoordCursor*/) noexcept +[[nodiscard]] HRESULT BgfxEngine::InvalidateCursor(const COORD* const /*pcoordCursor*/) noexcept { return S_OK; } -[[nodiscard]] -HRESULT BgfxEngine::InvalidateSystem(const RECT* const /*prcDirtyClient*/) noexcept +[[nodiscard]] HRESULT BgfxEngine::InvalidateSystem(const RECT* const /*prcDirtyClient*/) noexcept { return S_OK; } -[[nodiscard]] -HRESULT BgfxEngine::InvalidateSelection(const std::vector& /*rectangles*/) noexcept +[[nodiscard]] HRESULT BgfxEngine::InvalidateSelection(const std::vector& /*rectangles*/) noexcept { return S_OK; } -[[nodiscard]] -HRESULT BgfxEngine::InvalidateScroll(const COORD* const /*pcoordDelta*/) noexcept +[[nodiscard]] HRESULT BgfxEngine::InvalidateScroll(const COORD* const /*pcoordDelta*/) noexcept { return S_OK; } -[[nodiscard]] -HRESULT BgfxEngine::InvalidateAll() noexcept +[[nodiscard]] HRESULT BgfxEngine::InvalidateAll() noexcept { return S_OK; } -[[nodiscard]] -HRESULT BgfxEngine::InvalidateCircling(_Out_ bool* const pForcePaint) noexcept +[[nodiscard]] HRESULT BgfxEngine::InvalidateCircling(_Out_ bool* const pForcePaint) noexcept { *pForcePaint = false; return S_FALSE; } -[[nodiscard]] -HRESULT BgfxEngine::PrepareForTeardown(_Out_ bool* const pForcePaint) noexcept +[[nodiscard]] HRESULT BgfxEngine::PrepareForTeardown(_Out_ bool* const pForcePaint) noexcept { *pForcePaint = false; return S_FALSE; } -[[nodiscard]] -HRESULT BgfxEngine::StartPaint() noexcept +[[nodiscard]] HRESULT BgfxEngine::StartPaint() noexcept { return S_OK; } -[[nodiscard]] -HRESULT BgfxEngine::EndPaint() noexcept +[[nodiscard]] HRESULT BgfxEngine::EndPaint() noexcept { NTSTATUS Status; @@ -101,7 +91,7 @@ HRESULT BgfxEngine::EndPaint() noexcept if (NT_SUCCESS(Status)) { - for (SHORT i = 0 ; i < _displayHeight ; i++) + for (SHORT i = 0; i < _displayHeight; i++) { OldRunBase = (PVOID)(_sharedViewBase + (i * 2 * _runLength)); NewRunBase = (PVOID)(_sharedViewBase + (i * 2 * _runLength) + _runLength); @@ -119,20 +109,17 @@ HRESULT BgfxEngine::EndPaint() noexcept // - // Return Value: // - S_FALSE since we do nothing. -[[nodiscard]] -HRESULT BgfxEngine::Present() noexcept +[[nodiscard]] HRESULT BgfxEngine::Present() noexcept { return S_FALSE; } -[[nodiscard]] -HRESULT BgfxEngine::ScrollFrame() noexcept +[[nodiscard]] HRESULT BgfxEngine::ScrollFrame() noexcept { return S_OK; } -[[nodiscard]] -HRESULT BgfxEngine::PaintBackground() noexcept +[[nodiscard]] HRESULT BgfxEngine::PaintBackground() noexcept { PVOID OldRunBase; PVOID NewRunBase; @@ -140,7 +127,7 @@ HRESULT BgfxEngine::PaintBackground() noexcept PCD_IO_CHARACTER OldRun; PCD_IO_CHARACTER NewRun; - for (SHORT i = 0 ; i < _displayHeight ; i++) + for (SHORT i = 0; i < _displayHeight; i++) { OldRunBase = (PVOID)(_sharedViewBase + (i * 2 * _runLength)); NewRunBase = (PVOID)(_sharedViewBase + (i * 2 * _runLength) + _runLength); @@ -148,7 +135,7 @@ HRESULT BgfxEngine::PaintBackground() noexcept OldRun = (PCD_IO_CHARACTER)OldRunBase; NewRun = (PCD_IO_CHARACTER)NewRunBase; - for (SHORT j = 0 ; j < _displayWidth ; j++) + for (SHORT j = 0; j < _displayWidth; j++) { NewRun[j].Character = L' '; NewRun[j].Atribute = 0; @@ -158,17 +145,16 @@ HRESULT BgfxEngine::PaintBackground() noexcept return S_OK; } -[[nodiscard]] -HRESULT BgfxEngine::PaintBufferLine(const std::basic_string_view clusters, - const COORD coord, - const bool /*trimLeft*/) noexcept +[[nodiscard]] HRESULT BgfxEngine::PaintBufferLine(const std::basic_string_view clusters, + const COORD coord, + const bool /*trimLeft*/) noexcept { try { PVOID NewRunBase = (PVOID)(_sharedViewBase + (coord.Y * 2 * _runLength) + _runLength); PCD_IO_CHARACTER NewRun = (PCD_IO_CHARACTER)NewRunBase; - for (size_t i = 0 ; i < clusters.size() && i < (size_t)_displayWidth ; i++) + for (size_t i = 0; i < clusters.size() && i < (size_t)_displayWidth; i++) { NewRun[coord.X + i].Character = clusters.at(i).GetTextAsSingle(); NewRun[coord.X + i].Atribute = _currentLegacyColorAttribute; @@ -179,23 +165,20 @@ HRESULT BgfxEngine::PaintBufferLine(const std::basic_string_view cluste CATCH_RETURN(); } -[[nodiscard]] -HRESULT BgfxEngine::PaintBufferGridLines(GridLines const /*lines*/, - COLORREF const /*color*/, - size_t const /*cchLine*/, - COORD const /*coordTarget*/) noexcept +[[nodiscard]] HRESULT BgfxEngine::PaintBufferGridLines(GridLines const /*lines*/, + COLORREF const /*color*/, + size_t const /*cchLine*/, + COORD const /*coordTarget*/) noexcept { return S_OK; } -[[nodiscard]] -HRESULT BgfxEngine::PaintSelection(const SMALL_RECT /*rect*/) noexcept +[[nodiscard]] HRESULT BgfxEngine::PaintSelection(const SMALL_RECT /*rect*/) noexcept { return S_OK; } -[[nodiscard]] -HRESULT BgfxEngine::PaintCursor(const IRenderEngine::CursorOptions& options) noexcept +[[nodiscard]] HRESULT BgfxEngine::PaintCursor(const IRenderEngine::CursorOptions& options) noexcept { // TODO: MSFT: 11448021 - Modify BGFX to support rendering full-width // characters and a full-width cursor. @@ -208,29 +191,25 @@ HRESULT BgfxEngine::PaintCursor(const IRenderEngine::CursorOptions& options) noe NTSTATUS Status = ServiceLocator::LocateInputServices()->RequestSetCursor(&CursorInfo); return HRESULT_FROM_NT(Status); - } -[[nodiscard]] -HRESULT BgfxEngine::UpdateDrawingBrushes(COLORREF const /*colorForeground*/, - COLORREF const /*colorBackground*/, - const WORD legacyColorAttribute, - const bool /*isBold*/, - bool const /*isSettingDefaultBrushes*/) noexcept +[[nodiscard]] HRESULT BgfxEngine::UpdateDrawingBrushes(COLORREF const /*colorForeground*/, + COLORREF const /*colorBackground*/, + const WORD legacyColorAttribute, + const bool /*isBold*/, + bool const /*isSettingDefaultBrushes*/) noexcept { _currentLegacyColorAttribute = legacyColorAttribute; return S_OK; } -[[nodiscard]] -HRESULT BgfxEngine::UpdateFont(const FontInfoDesired& /*pfiFontInfoDesired*/, FontInfo& /*pfiFontInfo*/) noexcept +[[nodiscard]] HRESULT BgfxEngine::UpdateFont(const FontInfoDesired& /*pfiFontInfoDesired*/, FontInfo& /*pfiFontInfo*/) noexcept { return S_OK; } -[[nodiscard]] -HRESULT BgfxEngine::UpdateDpi(int const /*iDpi*/) noexcept +[[nodiscard]] HRESULT BgfxEngine::UpdateDpi(int const /*iDpi*/) noexcept { return S_OK; } @@ -242,14 +221,12 @@ HRESULT BgfxEngine::UpdateDpi(int const /*iDpi*/) noexcept // - srNewViewport - The bounds of the new viewport. // Return Value: // - HRESULT S_OK -[[nodiscard]] -HRESULT BgfxEngine::UpdateViewport(const SMALL_RECT /*srNewViewport*/) noexcept +[[nodiscard]] HRESULT BgfxEngine::UpdateViewport(const SMALL_RECT /*srNewViewport*/) noexcept { return S_OK; } -[[nodiscard]] -HRESULT BgfxEngine::GetProposedFont(const FontInfoDesired& /*pfiFontInfoDesired*/, FontInfo& /*pfiFontInfo*/, int const /*iDpi*/) noexcept +[[nodiscard]] HRESULT BgfxEngine::GetProposedFont(const FontInfoDesired& /*pfiFontInfoDesired*/, FontInfo& /*pfiFontInfo*/, int const /*iDpi*/) noexcept { return S_OK; } @@ -265,15 +242,13 @@ SMALL_RECT BgfxEngine::GetDirtyRectInChars() return r; } -[[nodiscard]] -HRESULT BgfxEngine::GetFontSize(_Out_ COORD* const pFontSize) noexcept +[[nodiscard]] HRESULT BgfxEngine::GetFontSize(_Out_ COORD* const pFontSize) noexcept { - *pFontSize =_fontSize; + *pFontSize = _fontSize; return S_OK; } -[[nodiscard]] -HRESULT BgfxEngine::IsGlyphWideByFont(const std::wstring_view /*glyph*/, _Out_ bool* const pResult) noexcept +[[nodiscard]] HRESULT BgfxEngine::IsGlyphWideByFont(const std::wstring_view /*glyph*/, _Out_ bool* const pResult) noexcept { *pResult = false; return S_OK; @@ -286,8 +261,7 @@ HRESULT BgfxEngine::IsGlyphWideByFont(const std::wstring_view /*glyph*/, _Out_ b // - newTitle: the new string to use for the title of the window // Return Value: // - S_OK -[[nodiscard]] -HRESULT BgfxEngine::_DoUpdateTitle(_In_ const std::wstring& /*newTitle*/) noexcept +[[nodiscard]] HRESULT BgfxEngine::_DoUpdateTitle(_In_ const std::wstring& /*newTitle*/) noexcept { return S_OK; } diff --git a/src/interactivity/onecore/BgfxEngine.hpp b/src/interactivity/onecore/BgfxEngine.hpp index 80fc5d88e..19a255503 100644 --- a/src/interactivity/onecore/BgfxEngine.hpp +++ b/src/interactivity/onecore/BgfxEngine.hpp @@ -33,72 +33,47 @@ namespace Microsoft::Console::Render ~BgfxEngine() override = default; // IRenderEngine Members - [[nodiscard]] - HRESULT Invalidate(const SMALL_RECT* const psrRegion) noexcept override; - [[nodiscard]] - HRESULT InvalidateCursor(const COORD* const pcoordCursor) noexcept override; - [[nodiscard]] - HRESULT InvalidateSystem(const RECT* const prcDirtyClient) noexcept override; - [[nodiscard]] - HRESULT InvalidateSelection(const std::vector& rectangles) noexcept override; - [[nodiscard]] - HRESULT InvalidateScroll(const COORD* const pcoordDelta) noexcept override; - [[nodiscard]] - HRESULT InvalidateAll() noexcept override; - [[nodiscard]] - HRESULT InvalidateCircling(_Out_ bool* const pForcePaint) noexcept override; - [[nodiscard]] - HRESULT PrepareForTeardown(_Out_ bool* const pForcePaint) noexcept override; + [[nodiscard]] HRESULT Invalidate(const SMALL_RECT* const psrRegion) noexcept override; + [[nodiscard]] HRESULT InvalidateCursor(const COORD* const pcoordCursor) noexcept override; + [[nodiscard]] HRESULT InvalidateSystem(const RECT* const prcDirtyClient) noexcept override; + [[nodiscard]] HRESULT InvalidateSelection(const std::vector& rectangles) noexcept override; + [[nodiscard]] HRESULT InvalidateScroll(const COORD* const pcoordDelta) noexcept override; + [[nodiscard]] HRESULT InvalidateAll() noexcept override; + [[nodiscard]] HRESULT InvalidateCircling(_Out_ bool* const pForcePaint) noexcept override; + [[nodiscard]] HRESULT PrepareForTeardown(_Out_ bool* const pForcePaint) noexcept override; - [[nodiscard]] - HRESULT StartPaint() noexcept override; - [[nodiscard]] - HRESULT EndPaint() noexcept override; - [[nodiscard]] - HRESULT Present() noexcept override; + [[nodiscard]] HRESULT StartPaint() noexcept override; + [[nodiscard]] HRESULT EndPaint() noexcept override; + [[nodiscard]] HRESULT Present() noexcept override; - [[nodiscard]] - HRESULT ScrollFrame() noexcept override; + [[nodiscard]] HRESULT ScrollFrame() noexcept override; - [[nodiscard]] - HRESULT PaintBackground() noexcept override; - [[nodiscard]] - HRESULT PaintBufferLine(const std::basic_string_view clusters, - const COORD coord, - const bool trimLeft) noexcept override; - [[nodiscard]] - HRESULT PaintBufferGridLines(GridLines const lines, COLORREF const color, size_t const cchLine, COORD const coordTarget) noexcept override; - [[nodiscard]] - HRESULT PaintSelection(const SMALL_RECT rect) noexcept override; + [[nodiscard]] HRESULT PaintBackground() noexcept override; + [[nodiscard]] HRESULT PaintBufferLine(const std::basic_string_view clusters, + const COORD coord, + const bool trimLeft) noexcept override; + [[nodiscard]] HRESULT PaintBufferGridLines(GridLines const lines, COLORREF const color, size_t const cchLine, COORD const coordTarget) noexcept override; + [[nodiscard]] HRESULT PaintSelection(const SMALL_RECT rect) noexcept override; - [[nodiscard]] - HRESULT PaintCursor(const CursorOptions& options) noexcept override; - - [[nodiscard]] - HRESULT UpdateDrawingBrushes(COLORREF const colorForeground, - COLORREF const colorBackground, - const WORD legacyColorAttribute, - const bool isBold, - bool const isSettingDefaultBrushes) noexcept override; - [[nodiscard]] - HRESULT UpdateFont(const FontInfoDesired& fiFontInfoDesired, FontInfo& fiFontInfo) noexcept override; - [[nodiscard]] - HRESULT UpdateDpi(int const iDpi) noexcept override; - [[nodiscard]] - HRESULT UpdateViewport(const SMALL_RECT srNewViewport) noexcept override; + [[nodiscard]] HRESULT PaintCursor(const CursorOptions& options) noexcept override; - [[nodiscard]] - HRESULT GetProposedFont(const FontInfoDesired& fiFontInfoDesired, FontInfo& fiFontInfo, int const iDpi) noexcept override; + [[nodiscard]] HRESULT UpdateDrawingBrushes(COLORREF const colorForeground, + COLORREF const colorBackground, + const WORD legacyColorAttribute, + const bool isBold, + bool const isSettingDefaultBrushes) noexcept override; + [[nodiscard]] HRESULT UpdateFont(const FontInfoDesired& fiFontInfoDesired, FontInfo& fiFontInfo) noexcept override; + [[nodiscard]] HRESULT UpdateDpi(int const iDpi) noexcept override; + [[nodiscard]] HRESULT UpdateViewport(const SMALL_RECT srNewViewport) noexcept override; + + [[nodiscard]] HRESULT GetProposedFont(const FontInfoDesired& fiFontInfoDesired, FontInfo& fiFontInfo, int const iDpi) noexcept override; SMALL_RECT GetDirtyRectInChars() override; - [[nodiscard]] - HRESULT GetFontSize(_Out_ COORD* const pFontSize) noexcept override; - [[nodiscard]] - HRESULT IsGlyphWideByFont(const std::wstring_view glyph, _Out_ bool* const pResult) noexcept override; + [[nodiscard]] HRESULT GetFontSize(_Out_ COORD* const pFontSize) noexcept override; + [[nodiscard]] HRESULT IsGlyphWideByFont(const std::wstring_view glyph, _Out_ bool* const pResult) noexcept override; protected: - [[nodiscard]] - HRESULT _DoUpdateTitle(_In_ const std::wstring& newTitle) noexcept override; + [[nodiscard]] HRESULT _DoUpdateTitle(_In_ const std::wstring& newTitle) noexcept override; private: ULONG_PTR _sharedViewBase; diff --git a/src/interactivity/onecore/ConIoSrvComm.cpp b/src/interactivity/onecore/ConIoSrvComm.cpp index 928e19e0a..abd9c47eb 100644 --- a/src/interactivity/onecore/ConIoSrvComm.cpp +++ b/src/interactivity/onecore/ConIoSrvComm.cpp @@ -35,7 +35,6 @@ ConIoSrvComm::ConIoSrvComm() : _fIsInputInitialized(false), pWddmConEngine(nullptr) { - } ConIoSrvComm::~ConIoSrvComm() @@ -47,7 +46,7 @@ ConIoSrvComm::~ConIoSrvComm() CloseHandle(_inputPipeThreadHandle); _inputPipeThreadHandle = nullptr; } - + // Free any handles we might have open. if (INVALID_HANDLE_VALUE != _pipeReadHandle) { @@ -70,8 +69,7 @@ ConIoSrvComm::~ConIoSrvComm() #pragma region Communication -[[nodiscard]] -NTSTATUS ConIoSrvComm::Connect() +[[nodiscard]] NTSTATUS ConIoSrvComm::Connect() { BOOL Ret = TRUE; NTSTATUS Status = STATUS_SUCCESS; @@ -115,8 +113,7 @@ NTSTATUS ConIoSrvComm::Connect() NULL); // Initialize the connection message attributes. - PALPC_MESSAGE_ATTRIBUTES ConnectionMessageAttributes - = (PALPC_MESSAGE_ATTRIBUTES)&ConnectionMessageAttributesBuffer; + PALPC_MESSAGE_ATTRIBUTES ConnectionMessageAttributes = (PALPC_MESSAGE_ATTRIBUTES)&ConnectionMessageAttributesBuffer; Status = AlpcInitializeMessageAttribute(CIS_MSG_ATTR_FLAGS, ConnectionMessageAttributes, @@ -133,7 +130,7 @@ NTSTATUS ConIoSrvComm::Connect() // Set up the port attributes. PortAttributes.Flags = ALPC_PORFLG_ACCEPT_DUP_HANDLES | - ALPC_PORFLG_ACCEPT_INDIRECT_HANDLES; + ALPC_PORFLG_ACCEPT_INDIRECT_HANDLES; PortAttributes.MaxMessageLength = sizeof(CIS_MSG); PortAttributes.MaxPoolUsage = 0x4000; PortAttributes.MaxSectionSize = 0; @@ -223,8 +220,7 @@ NTSTATUS ConIoSrvComm::Connect() return Status; } -[[nodiscard]] -NTSTATUS ConIoSrvComm::EnsureConnection() +[[nodiscard]] NTSTATUS ConIoSrvComm::EnsureConnection() { NTSTATUS Status; @@ -251,7 +247,7 @@ VOID ConIoSrvComm::ServiceInputPipe() 0, FALSE, DUPLICATE_SAME_ACCESS)); - + BOOL Ret; CIS_EVENT Event = { 0 }; @@ -296,8 +292,7 @@ VOID ConIoSrvComm::ServiceInputPipe() } } -[[nodiscard]] -NTSTATUS ConIoSrvComm::SendRequestReceiveReply(PCIS_MSG Message) const +[[nodiscard]] NTSTATUS ConIoSrvComm::SendRequestReceiveReply(PCIS_MSG Message) const { NTSTATUS Status; @@ -327,7 +322,7 @@ NTSTATUS ConIoSrvComm::SendRequestReceiveReply(PCIS_MSG Message) const VOID ConIoSrvComm::HandleFocusEvent(PCIS_EVENT Event) { BOOL Ret; - IRenderer *Renderer; + IRenderer* Renderer; CIS_EVENT ReplyEvent; Renderer = ServiceLocator::LocateGlobals().pRender; @@ -469,8 +464,7 @@ VOID ConIoSrvComm::CleanupForHeadless(const NTSTATUS status) #pragma region Request Methods -[[nodiscard]] -NTSTATUS ConIoSrvComm::RequestGetDisplaySize(_Inout_ PCD_IO_DISPLAY_SIZE pCdDisplaySize) const +[[nodiscard]] NTSTATUS ConIoSrvComm::RequestGetDisplaySize(_Inout_ PCD_IO_DISPLAY_SIZE pCdDisplaySize) const { NTSTATUS Status; @@ -487,8 +481,7 @@ NTSTATUS ConIoSrvComm::RequestGetDisplaySize(_Inout_ PCD_IO_DISPLAY_SIZE pCdDisp return Status; } -[[nodiscard]] -NTSTATUS ConIoSrvComm::RequestGetFontSize(_Inout_ PCD_IO_FONT_SIZE pCdFontSize) const +[[nodiscard]] NTSTATUS ConIoSrvComm::RequestGetFontSize(_Inout_ PCD_IO_FONT_SIZE pCdFontSize) const { NTSTATUS Status; @@ -505,8 +498,7 @@ NTSTATUS ConIoSrvComm::RequestGetFontSize(_Inout_ PCD_IO_FONT_SIZE pCdFontSize) return Status; } -[[nodiscard]] -NTSTATUS ConIoSrvComm::RequestSetCursor(_In_ CD_IO_CURSOR_INFORMATION* const pCdCursorInformation) const +[[nodiscard]] NTSTATUS ConIoSrvComm::RequestSetCursor(_In_ CD_IO_CURSOR_INFORMATION* const pCdCursorInformation) const { NTSTATUS Status; @@ -523,8 +515,7 @@ NTSTATUS ConIoSrvComm::RequestSetCursor(_In_ CD_IO_CURSOR_INFORMATION* const pCd return Status; } -[[nodiscard]] -NTSTATUS ConIoSrvComm::RequestUpdateDisplay(_In_ SHORT RowIndex) const +[[nodiscard]] NTSTATUS ConIoSrvComm::RequestUpdateDisplay(_In_ SHORT RowIndex) const { NTSTATUS Status; @@ -541,8 +532,7 @@ NTSTATUS ConIoSrvComm::RequestUpdateDisplay(_In_ SHORT RowIndex) const return Status; } -[[nodiscard]] -NTSTATUS ConIoSrvComm::RequestMapVirtualKey(_In_ UINT uCode, _In_ UINT uMapType, _Out_ UINT* puReturnValue) +[[nodiscard]] NTSTATUS ConIoSrvComm::RequestMapVirtualKey(_In_ UINT uCode, _In_ UINT uMapType, _Out_ UINT* puReturnValue) { NTSTATUS Status; @@ -564,8 +554,7 @@ NTSTATUS ConIoSrvComm::RequestMapVirtualKey(_In_ UINT uCode, _In_ UINT uMapType, return Status; } -[[nodiscard]] -NTSTATUS ConIoSrvComm::RequestVkKeyScan(_In_ WCHAR wCharacter, _Out_ SHORT* psReturnValue) +[[nodiscard]] NTSTATUS ConIoSrvComm::RequestVkKeyScan(_In_ WCHAR wCharacter, _Out_ SHORT* psReturnValue) { NTSTATUS Status; @@ -586,8 +575,7 @@ NTSTATUS ConIoSrvComm::RequestVkKeyScan(_In_ WCHAR wCharacter, _Out_ SHORT* psRe return Status; } -[[nodiscard]] -NTSTATUS ConIoSrvComm::RequestGetKeyState(_In_ int iVirtualKey, _Out_ SHORT *psReturnValue) +[[nodiscard]] NTSTATUS ConIoSrvComm::RequestGetKeyState(_In_ int iVirtualKey, _Out_ SHORT* psReturnValue) { NTSTATUS Status; @@ -608,8 +596,7 @@ NTSTATUS ConIoSrvComm::RequestGetKeyState(_In_ int iVirtualKey, _Out_ SHORT *psR return Status; } -[[nodiscard]] -USHORT ConIoSrvComm::GetDisplayMode() const +[[nodiscard]] USHORT ConIoSrvComm::GetDisplayMode() const { return _displayMode; } @@ -671,7 +658,7 @@ SHORT ConIoSrvComm::GetKeyState(int nVirtKey) return ReturnValue; } -BOOL ConIoSrvComm::TranslateCharsetInfo(DWORD * lpSrc, LPCHARSETINFO lpCs, DWORD dwFlags) +BOOL ConIoSrvComm::TranslateCharsetInfo(DWORD* lpSrc, LPCHARSETINFO lpCs, DWORD dwFlags) { SetLastError(ERROR_SUCCESS); @@ -703,15 +690,13 @@ BOOL ConIoSrvComm::TranslateCharsetInfo(DWORD * lpSrc, LPCHARSETINFO lpCs, DWORD #pragma endregion - -[[nodiscard]] -NTSTATUS ConIoSrvComm::InitializeBgfx() +[[nodiscard]] NTSTATUS ConIoSrvComm::InitializeBgfx() { NTSTATUS Status; Globals& globals = ServiceLocator::LocateGlobals(); FAIL_FAST_IF_NULL(globals.pRender); - IWindowMetrics * const Metrics = ServiceLocator::LocateWindowMetrics(); + IWindowMetrics* const Metrics = ServiceLocator::LocateWindowMetrics(); // Fetch the display size from the console driver. const RECT DisplaySize = Metrics->GetMaxClientRectInPixels(); @@ -746,8 +731,7 @@ NTSTATUS ConIoSrvComm::InitializeBgfx() return Status; } -[[nodiscard]] -NTSTATUS ConIoSrvComm::InitializeWddmCon() +[[nodiscard]] NTSTATUS ConIoSrvComm::InitializeWddmCon() { Globals& globals = ServiceLocator::LocateGlobals(); FAIL_FAST_IF_NULL(globals.pRender); diff --git a/src/interactivity/onecore/ConIoSrvComm.hpp b/src/interactivity/onecore/ConIoSrvComm.hpp index 0ca3f3c29..5e4cf3d82 100644 --- a/src/interactivity/onecore/ConIoSrvComm.hpp +++ b/src/interactivity/onecore/ConIoSrvComm.hpp @@ -32,28 +32,19 @@ namespace Microsoft::Console::Interactivity::OneCore ConIoSrvComm(); ~ConIoSrvComm() override; - [[nodiscard]] - NTSTATUS Connect(); + [[nodiscard]] NTSTATUS Connect(); VOID ServiceInputPipe(); - [[nodiscard]] - NTSTATUS RequestGetDisplaySize(_Inout_ PCD_IO_DISPLAY_SIZE pCdDisplaySize) const; - [[nodiscard]] - NTSTATUS RequestGetFontSize(_Inout_ PCD_IO_FONT_SIZE pCdFontSize) const; - [[nodiscard]] - NTSTATUS RequestSetCursor(_In_ CD_IO_CURSOR_INFORMATION* const pCdCursorInformation) const; - [[nodiscard]] - NTSTATUS RequestUpdateDisplay(_In_ SHORT RowIndex) const; + [[nodiscard]] NTSTATUS RequestGetDisplaySize(_Inout_ PCD_IO_DISPLAY_SIZE pCdDisplaySize) const; + [[nodiscard]] NTSTATUS RequestGetFontSize(_Inout_ PCD_IO_FONT_SIZE pCdFontSize) const; + [[nodiscard]] NTSTATUS RequestSetCursor(_In_ CD_IO_CURSOR_INFORMATION* const pCdCursorInformation) const; + [[nodiscard]] NTSTATUS RequestUpdateDisplay(_In_ SHORT RowIndex) const; - [[nodiscard]] - NTSTATUS RequestMapVirtualKey(_In_ UINT uCode, _In_ UINT uMapType, _Out_ UINT* puReturnValue); - [[nodiscard]] - NTSTATUS RequestVkKeyScan(_In_ WCHAR wCharacter, _Out_ SHORT* psReturnValue); - [[nodiscard]] - NTSTATUS RequestGetKeyState(_In_ int iVirtualKey, _Out_ SHORT *psReturnValue); + [[nodiscard]] NTSTATUS RequestMapVirtualKey(_In_ UINT uCode, _In_ UINT uMapType, _Out_ UINT* puReturnValue); + [[nodiscard]] NTSTATUS RequestVkKeyScan(_In_ WCHAR wCharacter, _Out_ SHORT* psReturnValue); + [[nodiscard]] NTSTATUS RequestGetKeyState(_In_ int iVirtualKey, _Out_ SHORT* psReturnValue); - [[nodiscard]] - USHORT GetDisplayMode() const; + [[nodiscard]] USHORT GetDisplayMode() const; PVOID GetSharedViewBase() const; @@ -63,24 +54,21 @@ namespace Microsoft::Console::Interactivity::OneCore UINT MapVirtualKeyW(UINT uCode, UINT uMapType); SHORT VkKeyScanW(WCHAR ch); SHORT GetKeyState(int nVirtKey); - BOOL TranslateCharsetInfo(DWORD * lpSrc, LPCHARSETINFO lpCs, DWORD dwFlags); + BOOL TranslateCharsetInfo(DWORD* lpSrc, LPCHARSETINFO lpCs, DWORD dwFlags); - [[nodiscard]] - NTSTATUS InitializeBgfx(); - [[nodiscard]] - NTSTATUS InitializeWddmCon(); + [[nodiscard]] NTSTATUS InitializeBgfx(); + [[nodiscard]] NTSTATUS InitializeWddmCon(); Microsoft::Console::Render::WddmConEngine* pWddmConEngine; + private: - [[nodiscard]] - NTSTATUS EnsureConnection(); - [[nodiscard]] - NTSTATUS SendRequestReceiveReply(PCIS_MSG Message) const; + [[nodiscard]] NTSTATUS EnsureConnection(); + [[nodiscard]] NTSTATUS SendRequestReceiveReply(PCIS_MSG Message) const; VOID HandleFocusEvent(PCIS_EVENT const FocusEvent); HANDLE _inputPipeThreadHandle; - + HANDLE _pipeReadHandle; HANDLE _pipeWriteHandle; @@ -91,6 +79,5 @@ namespace Microsoft::Console::Interactivity::OneCore USHORT _displayMode; bool _fIsInputInitialized; - }; } diff --git a/src/interactivity/onecore/ConsoleControl.cpp b/src/interactivity/onecore/ConsoleControl.cpp index 417574269..a0014c7a9 100644 --- a/src/interactivity/onecore/ConsoleControl.cpp +++ b/src/interactivity/onecore/ConsoleControl.cpp @@ -12,20 +12,17 @@ using namespace Microsoft::Console::Interactivity::OneCore; #pragma region IConsoleControl Members -[[nodiscard]] -NTSTATUS ConsoleControl::NotifyConsoleApplication(_In_ DWORD /*dwProcessId*/) +[[nodiscard]] NTSTATUS ConsoleControl::NotifyConsoleApplication(_In_ DWORD /*dwProcessId*/) { return STATUS_SUCCESS; } -[[nodiscard]] -NTSTATUS ConsoleControl::SetForeground(_In_ HANDLE /*hProcess*/, _In_ BOOL /*fForeground*/) +[[nodiscard]] NTSTATUS ConsoleControl::SetForeground(_In_ HANDLE /*hProcess*/, _In_ BOOL /*fForeground*/) { return STATUS_SUCCESS; } -[[nodiscard]] -NTSTATUS ConsoleControl::EndTask(_In_ HANDLE hProcessId, _In_ DWORD dwEventType, _In_ ULONG ulCtrlFlags) +[[nodiscard]] NTSTATUS ConsoleControl::EndTask(_In_ HANDLE hProcessId, _In_ DWORD dwEventType, _In_ ULONG ulCtrlFlags) { USER_API_MSG m; PENDTASKMSG a = &m.u.EndTask; diff --git a/src/interactivity/onecore/ConsoleControl.hpp b/src/interactivity/onecore/ConsoleControl.hpp index 48d27c389..98e14af8e 100644 --- a/src/interactivity/onecore/ConsoleControl.hpp +++ b/src/interactivity/onecore/ConsoleControl.hpp @@ -24,11 +24,8 @@ namespace Microsoft::Console::Interactivity::OneCore { public: // IConsoleControl Members - [[nodiscard]] - NTSTATUS NotifyConsoleApplication(_In_ DWORD dwProcessId); - [[nodiscard]] - NTSTATUS SetForeground(_In_ HANDLE hProcess, _In_ BOOL fForeground); - [[nodiscard]] - NTSTATUS EndTask(_In_ HANDLE hProcessId, _In_ DWORD dwEventType, _In_ ULONG ulCtrlFlags); + [[nodiscard]] NTSTATUS NotifyConsoleApplication(_In_ DWORD dwProcessId); + [[nodiscard]] NTSTATUS SetForeground(_In_ HANDLE hProcess, _In_ BOOL fForeground); + [[nodiscard]] NTSTATUS EndTask(_In_ HANDLE hProcessId, _In_ DWORD dwEventType, _In_ ULONG ulCtrlFlags); }; } diff --git a/src/interactivity/onecore/ConsoleInputThread.cpp b/src/interactivity/onecore/ConsoleInputThread.cpp index 472a50167..18738bb00 100644 --- a/src/interactivity/onecore/ConsoleInputThread.cpp +++ b/src/interactivity/onecore/ConsoleInputThread.cpp @@ -16,11 +16,10 @@ using namespace Microsoft::Console::Interactivity; using namespace Microsoft::Console::Interactivity::OneCore; - DWORD WINAPI ConsoleInputThreadProcOneCore(LPVOID /*lpParam*/) { Globals& globals = ServiceLocator::LocateGlobals(); - ConIoSrvComm * const Server = ServiceLocator::LocateInputServices(); + ConIoSrvComm* const Server = ServiceLocator::LocateInputServices(); NTSTATUS Status = Server->Connect(); @@ -31,7 +30,7 @@ DWORD WINAPI ConsoleInputThreadProcOneCore(LPVOID /*lpParam*/) if (DisplayMode != CIS_DISPLAY_MODE_NONE) { // Create and set the console window. - ConsoleWindow * const wnd = new(std::nothrow) ConsoleWindow(); + ConsoleWindow* const wnd = new (std::nothrow) ConsoleWindow(); Status = NT_TESTNULL(wnd); if (NT_SUCCESS(Status)) @@ -65,7 +64,7 @@ DWORD WINAPI ConsoleInputThreadProcOneCore(LPVOID /*lpParam*/) // This will never return. Server->ServiceInputPipe(); } - catch(...) + catch (...) { // If we couldn't set up the input thread, log and cleanup // and go to headless mode instead. @@ -124,7 +123,7 @@ HANDLE ConsoleInputThread::Start() return hThread; } -ConIoSrvComm *ConsoleInputThread::GetConIoSrvComm() +ConIoSrvComm* ConsoleInputThread::GetConIoSrvComm() { return _pConIoSrvComm; } diff --git a/src/interactivity/onecore/ConsoleInputThread.hpp b/src/interactivity/onecore/ConsoleInputThread.hpp index 112d23be8..f901a0bb8 100644 --- a/src/interactivity/onecore/ConsoleInputThread.hpp +++ b/src/interactivity/onecore/ConsoleInputThread.hpp @@ -26,9 +26,9 @@ namespace Microsoft::Console::Interactivity::OneCore public: HANDLE Start(); - ConIoSrvComm *GetConIoSrvComm(); + ConIoSrvComm* GetConIoSrvComm(); private: - ConIoSrvComm *_pConIoSrvComm; + ConIoSrvComm* _pConIoSrvComm; }; } diff --git a/src/interactivity/onecore/ConsoleWindow.cpp b/src/interactivity/onecore/ConsoleWindow.cpp index 569c66c3c..74255a400 100644 --- a/src/interactivity/onecore/ConsoleWindow.cpp +++ b/src/interactivity/onecore/ConsoleWindow.cpp @@ -125,20 +125,18 @@ void ConsoleWindow::VerticalScroll(const WORD /*wScrollCommand*/, const WORD /*w { } -[[nodiscard]] -HRESULT ConsoleWindow::SignalUia(_In_ EVENTID /*id*/) +[[nodiscard]] HRESULT ConsoleWindow::SignalUia(_In_ EVENTID /*id*/) { return E_NOTIMPL; } -[[nodiscard]] -HRESULT ConsoleWindow::UiaSetTextAreaFocus() +[[nodiscard]] HRESULT ConsoleWindow::UiaSetTextAreaFocus() { return E_NOTIMPL; } RECT ConsoleWindow::GetWindowRect() const { - RECT rc = {0}; + RECT rc = { 0 }; return rc; } diff --git a/src/interactivity/onecore/ConsoleWindow.hpp b/src/interactivity/onecore/ConsoleWindow.hpp index 35d840d7f..5a65dae4a 100644 --- a/src/interactivity/onecore/ConsoleWindow.hpp +++ b/src/interactivity/onecore/ConsoleWindow.hpp @@ -23,7 +23,6 @@ namespace Microsoft::Console::Interactivity::OneCore class ConsoleWindow sealed : public IConsoleWindow { public: - // Inherited via IConsoleWindow BOOL EnableBothScrollBars(); int UpdateScrollBar(bool isVertical, bool isAltBuffer, UINT pageSize, int maxSize, int viewportPosition); @@ -56,10 +55,8 @@ namespace Microsoft::Console::Interactivity::OneCore void HorizontalScroll(const WORD wScrollCommand, const WORD wAbsoluteChange); void VerticalScroll(const WORD wScrollCommand, const WORD wAbsoluteChange); - [[nodiscard]] - HRESULT SignalUia(_In_ EVENTID id); - [[nodiscard]] - HRESULT UiaSetTextAreaFocus(); + [[nodiscard]] HRESULT SignalUia(_In_ EVENTID id); + [[nodiscard]] HRESULT UiaSetTextAreaFocus(); RECT GetWindowRect() const; }; } diff --git a/src/interactivity/onecore/SystemConfigurationProvider.hpp b/src/interactivity/onecore/SystemConfigurationProvider.hpp index 654f1caf7..f7c468bc5 100644 --- a/src/interactivity/onecore/SystemConfigurationProvider.hpp +++ b/src/interactivity/onecore/SystemConfigurationProvider.hpp @@ -38,10 +38,11 @@ namespace Microsoft::Console::Interactivity::OneCore ULONG GetNumberOfWheelScrollCharacters(); void GetSettingsFromLink(_Inout_ Settings* pLinkSettings, - _Inout_updates_bytes_(*pdwTitleLength) LPWSTR pwszTitle, - _Inout_ PDWORD pdwTitleLength, - _In_ PCWSTR pwszCurrDir, - _In_ PCWSTR pwszAppName); + _Inout_updates_bytes_(*pdwTitleLength) LPWSTR pwszTitle, + _Inout_ PDWORD pdwTitleLength, + _In_ PCWSTR pwszCurrDir, + _In_ PCWSTR pwszAppName); + private: static const UINT s_DefaultCaretBlinkTime = 530; // milliseconds static const bool s_DefaultIsCaretBlinkingEnabled = true; diff --git a/src/interactivity/onecore/WindowMetrics.cpp b/src/interactivity/onecore/WindowMetrics.cpp index 0fd04ebc3..43d51c3b0 100644 --- a/src/interactivity/onecore/WindowMetrics.cpp +++ b/src/interactivity/onecore/WindowMetrics.cpp @@ -13,16 +13,16 @@ #pragma hdrstop // Default metrics for when in headless mode. -#define HEADLESS_FONT_SIZE_WIDTH (8) -#define HEADLESS_FONT_SIZE_HEIGHT (12) -#define HEADLESS_DISPLAY_SIZE_WIDTH (80) -#define HEADLESS_DISPLAY_SIZE_HEIGHT (25) +#define HEADLESS_FONT_SIZE_WIDTH (8) +#define HEADLESS_FONT_SIZE_HEIGHT (12) +#define HEADLESS_DISPLAY_SIZE_WIDTH (80) +#define HEADLESS_DISPLAY_SIZE_HEIGHT (25) using namespace Microsoft::Console::Interactivity::OneCore; RECT WindowMetrics::GetMinClientRectInPixels() { - ConIoSrvComm *Server; + ConIoSrvComm* Server; NTSTATUS Status; diff --git a/src/interactivity/onecore/precomp.h b/src/interactivity/onecore/precomp.h index dcf54628f..2ccc5b577 100644 --- a/src/interactivity/onecore/precomp.h +++ b/src/interactivity/onecore/precomp.h @@ -9,7 +9,7 @@ #include #include "wchar.h" -// Extension presence detection +// Extension presence detection #include #define _DDK_INCLUDED diff --git a/src/interactivity/win32/AccessibilityNotifier.cpp b/src/interactivity/win32/AccessibilityNotifier.cpp index c0ae78eda..a6d99b182 100644 --- a/src/interactivity/win32/AccessibilityNotifier.cpp +++ b/src/interactivity/win32/AccessibilityNotifier.cpp @@ -23,7 +23,6 @@ void AccessibilityNotifier::NotifyConsoleCaretEvent(_In_ RECT rectangle) &caretInfo, sizeof(caretInfo))); } - } void AccessibilityNotifier::NotifyConsoleCaretEvent(_In_ ConsoleCaretEventFlags flags, _In_ LONG position) @@ -60,12 +59,11 @@ void AccessibilityNotifier::NotifyConsoleCaretEvent(_In_ ConsoleCaretEventFlags } previousCursorLocation = currentCursorPosition; } - } void AccessibilityNotifier::NotifyConsoleUpdateScrollEvent(_In_ LONG x, _In_ LONG y) { - IConsoleWindow *pWindow = ServiceLocator::LocateConsoleWindow(); + IConsoleWindow* pWindow = ServiceLocator::LocateConsoleWindow(); if (pWindow) { NotifyWinEvent(EVENT_CONSOLE_UPDATE_SCROLL, @@ -77,7 +75,7 @@ void AccessibilityNotifier::NotifyConsoleUpdateScrollEvent(_In_ LONG x, _In_ LON void AccessibilityNotifier::NotifyConsoleUpdateSimpleEvent(_In_ LONG start, _In_ LONG charAndAttribute) { - IConsoleWindow *pWindow = ServiceLocator::LocateConsoleWindow(); + IConsoleWindow* pWindow = ServiceLocator::LocateConsoleWindow(); if (pWindow) { NotifyWinEvent(EVENT_CONSOLE_UPDATE_SIMPLE, @@ -89,7 +87,7 @@ void AccessibilityNotifier::NotifyConsoleUpdateSimpleEvent(_In_ LONG start, _In_ void AccessibilityNotifier::NotifyConsoleUpdateRegionEvent(_In_ LONG startXY, _In_ LONG endXY) { - IConsoleWindow *pWindow = ServiceLocator::LocateConsoleWindow(); + IConsoleWindow* pWindow = ServiceLocator::LocateConsoleWindow(); if (pWindow) { NotifyWinEvent(EVENT_CONSOLE_UPDATE_REGION, @@ -101,7 +99,7 @@ void AccessibilityNotifier::NotifyConsoleUpdateRegionEvent(_In_ LONG startXY, _I void AccessibilityNotifier::NotifyConsoleLayoutEvent() { - IConsoleWindow *pWindow = ServiceLocator::LocateConsoleWindow(); + IConsoleWindow* pWindow = ServiceLocator::LocateConsoleWindow(); if (pWindow) { NotifyWinEvent(EVENT_CONSOLE_LAYOUT, @@ -113,19 +111,19 @@ void AccessibilityNotifier::NotifyConsoleLayoutEvent() void AccessibilityNotifier::NotifyConsoleStartApplicationEvent(_In_ DWORD processId) { - IConsoleWindow *pWindow = ServiceLocator::LocateConsoleWindow(); + IConsoleWindow* pWindow = ServiceLocator::LocateConsoleWindow(); if (pWindow) { NotifyWinEvent(EVENT_CONSOLE_START_APPLICATION, - pWindow->GetWindowHandle(), - processId, - 0); + pWindow->GetWindowHandle(), + processId, + 0); } } void AccessibilityNotifier::NotifyConsoleEndApplicationEvent(_In_ DWORD processId) { - IConsoleWindow *pWindow = ServiceLocator::LocateConsoleWindow(); + IConsoleWindow* pWindow = ServiceLocator::LocateConsoleWindow(); if (pWindow) { NotifyWinEvent(EVENT_CONSOLE_END_APPLICATION, diff --git a/src/interactivity/win32/Clipboard.cpp b/src/interactivity/win32/Clipboard.cpp index d9d65e86b..874afd37d 100644 --- a/src/interactivity/win32/Clipboard.cpp +++ b/src/interactivity/win32/Clipboard.cpp @@ -38,7 +38,7 @@ void Clipboard::Copy(bool fAlsoCopyHtml) // store selection in clipboard StoreSelectionToClipboard(fAlsoCopyHtml); - Selection::Instance().ClearSelection(); // clear selection in console + Selection::Instance().ClearSelection(); // clear selection in console } CATCH_LOG(); } @@ -222,10 +222,10 @@ void Clipboard::StoreSelectionToClipboard(bool const fAlsoCopyHtml) // - lineSelection - true if entire line is being selected. False otherwise (box selection) // - selectionRects - the selection regions from which the data will be extracted from the buffer TextBuffer::TextAndColor Clipboard::RetrieveTextFromBuffer(const SCREEN_INFORMATION& screenInfo, - const bool lineSelection, - const std::vector& selectionRects) + const bool lineSelection, + const std::vector& selectionRects) { - const auto &buffer = screenInfo.GetTextBuffer(); + const auto& buffer = screenInfo.GetTextBuffer(); const bool trimTrailingWhitespace = !WI_IsFlagSet(GetKeyState(VK_SHIFT), KEY_PRESSED); const auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); @@ -247,7 +247,7 @@ TextBuffer::TextAndColor Clipboard::RetrieveTextFromBuffer(const SCREEN_INFORMAT // - string containing the generated HTML std::string Clipboard::GenHTML(const TextBuffer::TextAndColor& rows) { - std::string szClipboard; // we will build the data going back in this string buffer + std::string szClipboard; // we will build the data going back in this string buffer try { @@ -261,7 +261,7 @@ std::string Clipboard::GenHTML(const TextBuffer::TextAndColor& rows) "EndSelection:%010d\r\n"; // measure clip header - size_t const cbHeader = 157; // when formats are expanded, there will be 157 bytes in the header. + size_t const cbHeader = 157; // when formats are expanded, there will be 157 bytes in the header. std::string const szHtmlHeader = "Windows Console Host"; @@ -285,15 +285,15 @@ std::string Clipboard::GenHTML(const TextBuffer::TextAndColor& rows) size_t const cbSpanFontSize = 28 + (iFontHeightPoints / 10) + 1; std::string szSpanFontSize; - szSpanFontSize.resize(cbSpanFontSize + 1); // reserve space for null after string for sprintf + szSpanFontSize.resize(cbSpanFontSize + 1); // reserve space for null after string for sprintf sprintf_s(szSpanFontSize.data(), cbSpanFontSize + 1, szSpanFontSizePattern.data(), iFontHeightPoints); - szSpanFontSize.resize(cbSpanFontSize); //chop off null at end + szSpanFontSize.resize(cbSpanFontSize); //chop off null at end std::string const szSpanStartPattern = R"X()X"; - size_t const cbSpanStart = 53; // when format is expanded, there will be 53 bytes per color pattern. + size_t const cbSpanStart = 53; // when format is expanded, there will be 53 bytes per color pattern. std::string szSpanStart; - szSpanStart.resize(cbSpanStart + 1); // +1 for null terminator + szSpanStart.resize(cbSpanStart + 1); // +1 for null terminator std::string const szSpanStartFontPattern = R"X()X"; size_t const cbSpanStartFontPattern = 41; @@ -338,7 +338,7 @@ std::string Clipboard::GenHTML(const TextBuffer::TextAndColor& rows) // First we have to add the required header and then // some standard HTML boiler plate required for CF_HTML // as part of the HTML Clipboard format - szClipboard.append(cbHeader, 'H'); // reserve space for a header we fill in later + szClipboard.append(cbHeader, 'H'); // reserve space for a header we fill in later szClipboard.append(szHtmlHeader); szClipboard.append(szHtmlFragStart); @@ -406,13 +406,10 @@ std::string Clipboard::GenHTML(const TextBuffer::TextAndColor& rows) // start new span // format with color then copy formatted string - szSpanStart.resize(cbSpanStart + 1); // add room for null - sprintf_s(szSpanStart.data(), cbSpanStart + 1, szSpanStartPattern.data(), - GetRValue(fgColor), GetGValue(fgColor), GetBValue(fgColor), - GetRValue(bkColor), GetGValue(bkColor), GetBValue(bkColor)); - szSpanStart.resize(cbSpanStart); // chop null from sprintf + szSpanStart.resize(cbSpanStart + 1); // add room for null + sprintf_s(szSpanStart.data(), cbSpanStart + 1, szSpanStartPattern.data(), GetRValue(fgColor), GetGValue(fgColor), GetBValue(fgColor), GetRValue(bkColor), GetGValue(bkColor), GetBValue(bkColor)); + szSpanStart.resize(cbSpanStart); // chop null from sprintf szClipboard.append(szSpanStart); - } // accumulate 1 character @@ -459,30 +456,29 @@ std::string Clipboard::GenHTML(const TextBuffer::TextAndColor& rows) // we are done generating formating & building HTML for the selection // prepare the header text with the byte counts now that we know them - size_t const cbHtmlStart = cbHeader; // bytecount to start of HTML context - size_t const cbHtmlEnd = szClipboard.size() - 1; // don't count the null at the end - size_t const cbFragStart = cbHeader + cbHtmlHeader; // bytecount to start of selection fragment + size_t const cbHtmlStart = cbHeader; // bytecount to start of HTML context + size_t const cbHtmlEnd = szClipboard.size() - 1; // don't count the null at the end + size_t const cbFragStart = cbHeader + cbHtmlHeader; // bytecount to start of selection fragment size_t const cbFragEnd = cbHtmlEnd - cbHtmlFooter; // push the values into the required HTML 0.9 header format std::string szHtmlClipHeaderFinal; - szHtmlClipHeaderFinal.resize(cbHeader + 1); // add room for a null + szHtmlClipHeaderFinal.resize(cbHeader + 1); // add room for a null sprintf_s(szHtmlClipHeaderFinal.data(), cbHeader + 1, szHtmlClipFormat.data(), cbHtmlStart, cbHtmlEnd, cbFragStart, cbFragEnd, cbFragStart, cbFragEnd); - szHtmlClipHeaderFinal.resize(cbHeader); // chop off the null + szHtmlClipHeaderFinal.resize(cbHeader); // chop off the null // overwrite the reserved space with the actual header & offsets we calculated szClipboard.replace(0, cbHeader, szHtmlClipHeaderFinal.data()); } - catch(...) + catch (...) { LOG_HR(wil::ResultFromCaughtException()); - szClipboard.clear(); // dont return a partial html fragment... + szClipboard.clear(); // dont return a partial html fragment... } return szClipboard; } - // Routine Description: // - Copies the text given onto the global system clipboard. // Arguments: @@ -555,11 +551,10 @@ void Clipboard::CopyTextToSystemClipboard(const TextBuffer::TextAndColor& rows, globalHandle.release(); } - // Returns true if the character should be emitted to the paste stream // -- in some cases, we will change what character should be emitted, as in the case of "smart quotes" // Returns false if the character should not be emitted (e.g. ) -bool Clipboard::FilterCharacterOnPaste(_Inout_ WCHAR * const pwch) +bool Clipboard::FilterCharacterOnPaste(_Inout_ WCHAR* const pwch) { const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); bool fAllowChar = true; diff --git a/src/interactivity/win32/ConsoleControl.cpp b/src/interactivity/win32/ConsoleControl.cpp index 61720b984..a64d1b36a 100644 --- a/src/interactivity/win32/ConsoleControl.cpp +++ b/src/interactivity/win32/ConsoleControl.cpp @@ -15,8 +15,7 @@ using namespace Microsoft::Console::Interactivity::Win32; #pragma region IConsoleControl Members -[[nodiscard]] -NTSTATUS ConsoleControl::NotifyConsoleApplication(_In_ DWORD dwProcessId) +[[nodiscard]] NTSTATUS ConsoleControl::NotifyConsoleApplication(_In_ DWORD dwProcessId) { CONSOLE_PROCESS_INFO cpi; cpi.dwProcessID = dwProcessId; @@ -27,8 +26,7 @@ NTSTATUS ConsoleControl::NotifyConsoleApplication(_In_ DWORD dwProcessId) sizeof(CONSOLE_PROCESS_INFO)); } -[[nodiscard]] -NTSTATUS ConsoleControl::SetForeground(_In_ HANDLE hProcess, _In_ BOOL fForeground) +[[nodiscard]] NTSTATUS ConsoleControl::SetForeground(_In_ HANDLE hProcess, _In_ BOOL fForeground) { CONSOLESETFOREGROUND Flags; Flags.hProcess = hProcess; @@ -39,8 +37,7 @@ NTSTATUS ConsoleControl::SetForeground(_In_ HANDLE hProcess, _In_ BOOL fForegrou sizeof(Flags)); } -[[nodiscard]] -NTSTATUS ConsoleControl::EndTask(_In_ HANDLE hProcessId, _In_ DWORD dwEventType, _In_ ULONG ulCtrlFlags) +[[nodiscard]] NTSTATUS ConsoleControl::EndTask(_In_ HANDLE hProcessId, _In_ DWORD dwEventType, _In_ ULONG ulCtrlFlags) { auto pConsoleWindow = ServiceLocator::LocateConsoleWindow(); @@ -48,9 +45,7 @@ NTSTATUS ConsoleControl::EndTask(_In_ HANDLE hProcessId, _In_ DWORD dwEventType, ConsoleEndTaskParams.ProcessId = hProcessId; ConsoleEndTaskParams.ConsoleEventCode = dwEventType; ConsoleEndTaskParams.ConsoleFlags = ulCtrlFlags; - ConsoleEndTaskParams.hwnd = pConsoleWindow == nullptr - ? nullptr - : pConsoleWindow->GetWindowHandle(); + ConsoleEndTaskParams.hwnd = pConsoleWindow == nullptr ? nullptr : pConsoleWindow->GetWindowHandle(); return Control(ControlType::ConsoleEndTask, &ConsoleEndTaskParams, @@ -61,15 +56,14 @@ NTSTATUS ConsoleControl::EndTask(_In_ HANDLE hProcessId, _In_ DWORD dwEventType, #pragma region Public Methods -[[nodiscard]] -NTSTATUS ConsoleControl::Control(_In_ ControlType ConsoleCommand, - _In_reads_bytes_(ConsoleInformationLength) PVOID ConsoleInformation, - _In_ DWORD ConsoleInformationLength) +[[nodiscard]] NTSTATUS ConsoleControl::Control(_In_ ControlType ConsoleCommand, + _In_reads_bytes_(ConsoleInformationLength) PVOID ConsoleInformation, + _In_ DWORD ConsoleInformationLength) { #ifdef CON_USERPRIVAPI_INDIRECT if (_hUser32 != nullptr) { - typedef NTSTATUS(WINAPI *PfnConsoleControl)(ControlType Command, PVOID Information, DWORD Length); + typedef NTSTATUS(WINAPI * PfnConsoleControl)(ControlType Command, PVOID Information, DWORD Length); static PfnConsoleControl pfn = (PfnConsoleControl)GetProcAddress(_hUser32, "ConsoleControl"); @@ -90,7 +84,7 @@ BOOL ConsoleControl::EnterReaderModeHelper(_In_ HWND hwnd) #ifdef CON_USERPRIVAPI_INDIRECT if (_hUser32 != nullptr) { - typedef BOOL(WINAPI *PfnEnterReaderModeHelper)(HWND hwnd); + typedef BOOL(WINAPI * PfnEnterReaderModeHelper)(HWND hwnd); static PfnEnterReaderModeHelper pfn = (PfnEnterReaderModeHelper)GetProcAddress(_hUser32, "EnterReaderModeHelper"); @@ -106,13 +100,13 @@ BOOL ConsoleControl::EnterReaderModeHelper(_In_ HWND hwnd) #endif } -BOOL ConsoleControl::TranslateMessageEx(const MSG *pmsg, +BOOL ConsoleControl::TranslateMessageEx(const MSG* pmsg, _In_ UINT flags) { #ifdef CON_USERPRIVAPI_INDIRECT if (_hUser32 != nullptr) { - typedef BOOL(WINAPI *PfnTranslateMessageEx)(const MSG *pmsg, UINT flags); + typedef BOOL(WINAPI * PfnTranslateMessageEx)(const MSG* pmsg, UINT flags); static PfnTranslateMessageEx pfn = (PfnTranslateMessageEx)GetProcAddress(_hUser32, "TranslateMessageEx"); diff --git a/src/interactivity/win32/ConsoleControl.hpp b/src/interactivity/win32/ConsoleControl.hpp index b03bce56b..29b335a81 100644 --- a/src/interactivity/win32/ConsoleControl.hpp +++ b/src/interactivity/win32/ConsoleControl.hpp @@ -19,20 +19,21 @@ Author(s): //#define CON_USERPRIVAPI_INDIRECT // Used by TranslateMessageEx to purposefully return false to certain WM_KEYDOWN/WM_CHAR messages -#define TM_POSTCHARBREAKS 0x0002 +#define TM_POSTCHARBREAKS 0x0002 // Used by window structures to place our special frozen-console painting data #define GWL_CONSOLE_WNDALLOC (3 * sizeof(DWORD)) // Used for pre-resize querying of the new scaled size of a window when the DPI is about to change. -#define WM_GETDPISCALEDSIZE 0x02E4 +#define WM_GETDPISCALEDSIZE 0x02E4 namespace Microsoft::Console::Interactivity::Win32 { class ConsoleControl final : public IConsoleControl { public: - enum ControlType { + enum ControlType + { ConsoleSetVDMCursorBounds, ConsoleNotifyConsoleApplication, ConsoleFullscreenSwitch, @@ -44,23 +45,19 @@ namespace Microsoft::Console::Interactivity::Win32 }; // IConsoleControl Members - [[nodiscard]] - NTSTATUS NotifyConsoleApplication(_In_ DWORD dwProcessId); - [[nodiscard]] - NTSTATUS SetForeground(_In_ HANDLE hProcess, _In_ BOOL fForeground); - [[nodiscard]] - NTSTATUS EndTask(_In_ HANDLE hProcessId, _In_ DWORD dwEventType, _In_ ULONG ulCtrlFlags); + [[nodiscard]] NTSTATUS NotifyConsoleApplication(_In_ DWORD dwProcessId); + [[nodiscard]] NTSTATUS SetForeground(_In_ HANDLE hProcess, _In_ BOOL fForeground); + [[nodiscard]] NTSTATUS EndTask(_In_ HANDLE hProcessId, _In_ DWORD dwEventType, _In_ ULONG ulCtrlFlags); // Public Members - [[nodiscard]] - NTSTATUS Control(_In_ ConsoleControl::ControlType ConsoleCommand, - _In_reads_bytes_(ConsoleInformationLength) PVOID ConsoleInformation, - _In_ DWORD ConsoleInformationLength); + [[nodiscard]] NTSTATUS Control(_In_ ConsoleControl::ControlType ConsoleCommand, + _In_reads_bytes_(ConsoleInformationLength) PVOID ConsoleInformation, + _In_ DWORD ConsoleInformationLength); BOOL EnterReaderModeHelper(_In_ HWND hwnd); - BOOL TranslateMessageEx(const MSG *pmsg, - _In_ UINT flags); + BOOL TranslateMessageEx(const MSG* pmsg, + _In_ UINT flags); #ifdef CON_USERPRIVAPI_INDIRECT ConsoleControl(); diff --git a/src/interactivity/win32/ConsoleInputThread.cpp b/src/interactivity/win32/ConsoleInputThread.cpp index 8d09af52f..8331bcf22 100644 --- a/src/interactivity/win32/ConsoleInputThread.cpp +++ b/src/interactivity/win32/ConsoleInputThread.cpp @@ -14,7 +14,7 @@ using namespace Microsoft::Console::Interactivity::Win32; HANDLE ConsoleInputThread::Start() { HANDLE hThread = nullptr; - DWORD dwThreadId = (DWORD) -1; + DWORD dwThreadId = (DWORD)-1; hThread = CreateThread(nullptr, 0, diff --git a/src/interactivity/win32/CustomWindowMessages.h b/src/interactivity/win32/CustomWindowMessages.h index b582f96f6..c203df2ca 100644 --- a/src/interactivity/win32/CustomWindowMessages.h +++ b/src/interactivity/win32/CustomWindowMessages.h @@ -3,6 +3,8 @@ #pragma once +// clang-format off + // Custom window messages #define CM_SET_WINDOW_SIZE (WM_USER + 2) #define CM_BEEP (WM_USER + 3) @@ -26,3 +28,5 @@ #define CM_SET_KEY_STATE (WM_USER+18) #define CM_SET_KEYBOARD_LAYOUT (WM_USER+19) #endif + +// clang-format on diff --git a/src/interactivity/win32/InputServices.cpp b/src/interactivity/win32/InputServices.cpp index ece52e084..3d798e258 100644 --- a/src/interactivity/win32/InputServices.cpp +++ b/src/interactivity/win32/InputServices.cpp @@ -24,7 +24,7 @@ SHORT InputServices::GetKeyState(int nVirtKey) return ::GetKeyState(nVirtKey); } -BOOL InputServices::TranslateCharsetInfo(DWORD * lpSrc, LPCHARSETINFO lpCs, DWORD dwFlags) +BOOL InputServices::TranslateCharsetInfo(DWORD* lpSrc, LPCHARSETINFO lpCs, DWORD dwFlags) { return ::TranslateCharsetInfo(lpSrc, lpCs, dwFlags); } diff --git a/src/interactivity/win32/InputServices.hpp b/src/interactivity/win32/InputServices.hpp index 321070e26..6efe6d62c 100644 --- a/src/interactivity/win32/InputServices.hpp +++ b/src/interactivity/win32/InputServices.hpp @@ -24,6 +24,6 @@ namespace Microsoft::Console::Interactivity::Win32 UINT MapVirtualKeyW(UINT uCode, UINT uMapType); SHORT VkKeyScanW(WCHAR ch); SHORT GetKeyState(int nVirtKey); - BOOL TranslateCharsetInfo(DWORD * lpSrc, LPCHARSETINFO lpCs, DWORD dwFlags); + BOOL TranslateCharsetInfo(DWORD* lpSrc, LPCHARSETINFO lpCs, DWORD dwFlags); }; } diff --git a/src/interactivity/win32/SystemConfigurationProvider.cpp b/src/interactivity/win32/SystemConfigurationProvider.cpp index cea6fcf07..1c61bb052 100644 --- a/src/interactivity/win32/SystemConfigurationProvider.cpp +++ b/src/interactivity/win32/SystemConfigurationProvider.cpp @@ -77,7 +77,7 @@ void SystemConfigurationProvider::GetSettingsFromLink( gci.SetLinkTitle(std::wstring(pwszTitle, cch)); - wchar_t* const linkNameForCsi = new(std::nothrow) wchar_t[gci.GetLinkTitle().length()+1]{0}; + wchar_t* const linkNameForCsi = new (std::nothrow) wchar_t[gci.GetLinkTitle().length() + 1]{ 0 }; if (linkNameForCsi) { gci.GetLinkTitle().copy(linkNameForCsi, gci.GetLinkTitle().length()); @@ -93,14 +93,14 @@ void SystemConfigurationProvider::GetSettingsFromLink( int iShowWindow; WORD wHotKey; NTSTATUS Status = ShortcutSerialization::s_GetLinkValues(&csi, - &fReadConsoleProperties, - wszShortcutTitle, - ARRAYSIZE(wszShortcutTitle), - wszIconLocation, - ARRAYSIZE(wszIconLocation), - &iIconIndex, - &iShowWindow, - &wHotKey); + &fReadConsoleProperties, + wszShortcutTitle, + ARRAYSIZE(wszShortcutTitle), + wszIconLocation, + ARRAYSIZE(wszIconLocation), + &iIconIndex, + &iShowWindow, + &wHotKey); // Convert results back to appropriate types and set. if (SUCCEEDED(IntToWord(iShowWindow, &wShowWindow))) diff --git a/src/interactivity/win32/SystemConfigurationProvider.hpp b/src/interactivity/win32/SystemConfigurationProvider.hpp index b39cbad79..a99e6eb4f 100644 --- a/src/interactivity/win32/SystemConfigurationProvider.hpp +++ b/src/interactivity/win32/SystemConfigurationProvider.hpp @@ -34,10 +34,10 @@ namespace Microsoft::Console::Interactivity::Win32 ULONG GetNumberOfWheelScrollCharacters(); void GetSettingsFromLink(_Inout_ Settings* pLinkSettings, - _Inout_updates_bytes_(*pdwTitleLength) LPWSTR pwszTitle, - _Inout_ PDWORD pdwTitleLength, - _In_ PCWSTR pwszCurrDir, - _In_ PCWSTR pwszAppName); + _Inout_updates_bytes_(*pdwTitleLength) LPWSTR pwszTitle, + _Inout_ PDWORD pdwTitleLength, + _In_ PCWSTR pwszCurrDir, + _In_ PCWSTR pwszAppName); private: static const ULONG s_DefaultCursorWidth = 1; diff --git a/src/interactivity/win32/UiaTextRange.cpp b/src/interactivity/win32/UiaTextRange.cpp index e6c323ce0..eedb8305c 100644 --- a/src/interactivity/win32/UiaTextRange.cpp +++ b/src/interactivity/win32/UiaTextRange.cpp @@ -12,7 +12,6 @@ #include "../host/selection.hpp" #include "../host/search.h" - using namespace Microsoft::Console::Interactivity::Win32; using namespace Microsoft::Console::Interactivity::Win32::UiaTextRangeTracing; using namespace Microsoft::Console::Interactivity; @@ -82,13 +81,13 @@ void UiaTextRange::_outputRowConversions() for (unsigned int i = 0; i < totalRows; ++i) { std::wstringstream ss; - ss << i << "\t" << _screenInfoRowToTextBufferRow (i) << "\t" << _screenInfoRowToEndpoint(i) << "\n"; + ss << i << "\t" << _screenInfoRowToTextBufferRow(i) << "\t" << _screenInfoRowToEndpoint(i) << "\n"; std::wstring str = ss.str(); OutputDebugString(str.c_str()); } OutputDebugString(L"\n"); } - catch(...) + catch (...) { LOG_HR(wil::ResultFromCaughtException()); } @@ -145,10 +144,10 @@ std::deque UiaTextRange::GetSelectionRanges(_In_ IRawElementProvi return ranges; } - UiaTextRange* UiaTextRange::Create(_In_ IRawElementProviderSimple* const pProvider) { - UiaTextRange* range = nullptr;; + UiaTextRange* range = nullptr; + ; try { range = new UiaTextRange(pProvider); @@ -230,7 +229,6 @@ UiaTextRange* UiaTextRange::Create(_In_ IRawElementProviderSimple* const pProvid return range; } - // degenerate range constructor. UiaTextRange::UiaTextRange(_In_ IRawElementProviderSimple* const pProvider) : _cRefs{ 1 }, @@ -239,13 +237,13 @@ UiaTextRange::UiaTextRange(_In_ IRawElementProviderSimple* const pProvider) : _end{ 0 }, _degenerate{ true } { - _id = id; - ++id; + _id = id; + ++id; - // tracing - ApiMsgConstructor apiMsg; - apiMsg.Id = _id; - Tracing::s_TraceUia(nullptr, ApiCall::Constructor, &apiMsg); + // tracing + ApiMsgConstructor apiMsg; + apiMsg.Id = _id; + Tracing::s_TraceUia(nullptr, ApiCall::Constructor, &apiMsg); } UiaTextRange::UiaTextRange(_In_ IRawElementProviderSimple* const pProvider, @@ -330,8 +328,8 @@ UiaTextRange::UiaTextRange(const UiaTextRange& a) : _degenerate{ a._degenerate } { (static_cast(_pProvider))->AddRef(); - _id = id; - ++id; + _id = id; + ++id; #if defined(_DEBUG) && defined(UIATEXTRANGE_DEBUG_MSGS) OutputDebugString(L"Copy Constructor\n"); @@ -372,13 +370,15 @@ const bool UiaTextRange::IsDegenerate() const #pragma region IUnknown -IFACEMETHODIMP_(ULONG) UiaTextRange::AddRef() +IFACEMETHODIMP_(ULONG) +UiaTextRange::AddRef() { Tracing::s_TraceUia(this, ApiCall::AddRef, nullptr); return InterlockedIncrement(&_cRefs); } -IFACEMETHODIMP_(ULONG) UiaTextRange::Release() +IFACEMETHODIMP_(ULONG) +UiaTextRange::Release() { Tracing::s_TraceUia(this, ApiCall::Release, nullptr); @@ -422,7 +422,7 @@ IFACEMETHODIMP UiaTextRange::Clone(_Outptr_result_maybenull_ ITextRangeProvider* { *ppRetVal = new UiaTextRange(*this); } - catch(...) + catch (...) { *ppRetVal = nullptr; return wil::ResultFromCaughtException(); @@ -452,8 +452,7 @@ IFACEMETHODIMP UiaTextRange::Compare(_In_opt_ ITextRangeProvider* pRange, _Out_ { CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); gci.LockConsole(); - auto Unlock = wil::scope_exit([&] - { + auto Unlock = wil::scope_exit([&] { gci.UnlockConsole(); }); @@ -474,7 +473,6 @@ IFACEMETHODIMP UiaTextRange::Compare(_In_opt_ ITextRangeProvider* pRange, _Out_ return S_OK; } - IFACEMETHODIMP UiaTextRange::CompareEndpoints(_In_ TextPatternRangeEndpoint endpoint, _In_ ITextRangeProvider* pTargetRange, _In_ TextPatternRangeEndpoint targetEndpoint, @@ -526,8 +524,7 @@ IFACEMETHODIMP UiaTextRange::CompareEndpoints(_In_ TextPatternRangeEndpoint endp IFACEMETHODIMP UiaTextRange::ExpandToEnclosingUnit(_In_ TextUnit unit) { ServiceLocator::LocateGlobals().getConsoleInformation().LockConsole(); - auto Unlock = wil::scope_exit([&] - { + auto Unlock = wil::scope_exit([&] { ServiceLocator::LocateGlobals().getConsoleInformation().UnlockConsole(); }); @@ -647,14 +644,12 @@ IFACEMETHODIMP UiaTextRange::GetBoundingRectangles(_Outptr_result_maybenull_ SAF { CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); gci.LockConsole(); - auto Unlock = wil::scope_exit([&] - { + auto Unlock = wil::scope_exit([&] { gci.UnlockConsole(); }); *ppRetVal = nullptr; - try { // vector to put coords into. they go in as four doubles in the @@ -716,8 +711,7 @@ IFACEMETHODIMP UiaTextRange::GetText(_In_ int maxLength, _Out_ BSTR* pRetVal) { CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); gci.LockConsole(); - auto Unlock = wil::scope_exit([&] - { + auto Unlock = wil::scope_exit([&] { gci.UnlockConsole(); }); @@ -746,7 +740,7 @@ IFACEMETHODIMP UiaTextRange::GetText(_In_ int maxLength, _Out_ BSTR* pRetVal) #if defined(_DEBUG) && defined(UIATEXTRANGE_DEBUG_MSGS) std::wstringstream ss; ss << L"---Initial span start=" << _start << L" and end=" << _end << L"\n"; - ss << L"----Retrieving sr:" << startScreenInfoRow << L" sc:" << startColumn << L" er:" << endScreenInfoRow << L" ec:" << endColumn << L"\n"; + ss << L"----Retrieving sr:" << startScreenInfoRow << L" sc:" << startColumn << L" er:" << endScreenInfoRow << L" ec:" << endColumn << L"\n"; OutputDebugString(ss.str().c_str()); #endif @@ -816,8 +810,7 @@ IFACEMETHODIMP UiaTextRange::Move(_In_ TextUnit unit, _Out_ int* pRetVal) { ServiceLocator::LocateGlobals().getConsoleInformation().LockConsole(); - auto Unlock = wil::scope_exit([&] - { + auto Unlock = wil::scope_exit([&] { ServiceLocator::LocateGlobals().getConsoleInformation().UnlockConsole(); }); @@ -848,7 +841,6 @@ IFACEMETHODIMP UiaTextRange::Move(_In_ TextUnit unit, if (unit == TextUnit::TextUnit_Character) { moveFunc = &_moveByCharacter; - } else if (unit <= TextUnit::TextUnit_Line) { @@ -887,8 +879,7 @@ IFACEMETHODIMP UiaTextRange::MoveEndpointByUnit(_In_ TextPatternRangeEndpoint en _Out_ int* pRetVal) { ServiceLocator::LocateGlobals().getConsoleInformation().LockConsole(); - auto Unlock = wil::scope_exit([&] - { + auto Unlock = wil::scope_exit([&] { ServiceLocator::LocateGlobals().getConsoleInformation().UnlockConsole(); }); @@ -953,8 +944,7 @@ IFACEMETHODIMP UiaTextRange::MoveEndpointByRange(_In_ TextPatternRangeEndpoint e _In_ TextPatternRangeEndpoint targetEndpoint) { ServiceLocator::LocateGlobals().getConsoleInformation().LockConsole(); - auto Unlock = wil::scope_exit([&] - { + auto Unlock = wil::scope_exit([&] { ServiceLocator::LocateGlobals().getConsoleInformation().UnlockConsole(); }); @@ -1062,12 +1052,10 @@ IFACEMETHODIMP UiaTextRange::Select() { CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); gci.LockConsole(); - auto Unlock = wil::scope_exit([&] - { + auto Unlock = wil::scope_exit([&] { gci.UnlockConsole(); }); - if (_degenerate) { // calling Select on a degenerate range should clear any current selections @@ -1109,8 +1097,7 @@ IFACEMETHODIMP UiaTextRange::ScrollIntoView(_In_ BOOL alignToTop) { CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); gci.LockConsole(); - auto Unlock = wil::scope_exit([&] - { + auto Unlock = wil::scope_exit([&] { gci.UnlockConsole(); }); @@ -1173,7 +1160,6 @@ IFACEMETHODIMP UiaTextRange::ScrollIntoView(_In_ BOOL alignToTop) newViewport.Top = static_cast(topRow); newViewport.Bottom = static_cast(topRow + viewportHeight - 1); } - } FAIL_FAST_IF(!(newViewport.Top >= static_cast(topRow))); @@ -1187,7 +1173,6 @@ IFACEMETHODIMP UiaTextRange::ScrollIntoView(_In_ BOOL alignToTop) } CATCH_RETURN(); - // tracing ApiMsgScrollIntoView apiMsg; apiMsg.AlignToTop = !!alignToTop; @@ -1230,7 +1215,7 @@ const Microsoft::Console::Types::Viewport& UiaTextRange::_getViewport() // window. Microsoft::Console::Interactivity::IConsoleWindow* const UiaTextRange::_getIConsoleWindow() { - using namespace Microsoft::Console::Interactivity; + using namespace Microsoft::Console::Interactivity; IConsoleWindow* const pIConsoleWindow = ServiceLocator::LocateConsoleWindow(); THROW_HR_IF_NULL(E_POINTER, pIConsoleWindow); return pIConsoleWindow; @@ -1293,7 +1278,6 @@ const COORD UiaTextRange::_getScreenBufferCoords() return _getScreenInfo().GetBufferSize().Dimensions(); } - // Routine Description: // - Gets the width of the screen buffer rows // Arguments: @@ -1589,7 +1573,6 @@ const unsigned int UiaTextRange::_getLastScreenInfoRowIndex() return _getTotalRows() - 1; } - // Routine Description: // - returns the index of the first column of the screen info rows // Arguments: @@ -1702,7 +1685,7 @@ std::pair UiaTextRange::_moveByCharacterForward(const int mo // check if we're at the edge of the screen info buffer if (currentScreenInfoRow == moveState.LimitingRow && - currentColumn + 1>= right) + currentColumn + 1 >= right) { break; } diff --git a/src/interactivity/win32/UiaTextRange.hpp b/src/interactivity/win32/UiaTextRange.hpp index b64d98ab8..7a0e716db 100644 --- a/src/interactivity/win32/UiaTextRange.hpp +++ b/src/interactivity/win32/UiaTextRange.hpp @@ -71,8 +71,6 @@ constexpr IdType InvalidId = 0; namespace Microsoft::Console::Interactivity::Win32 { - - class UiaTextRange final : public ITextRangeProvider { private: @@ -136,7 +134,6 @@ namespace Microsoft::Console::Interactivity::Win32 }; public: - static std::deque GetSelectionRanges(_In_ IRawElementProviderSimple* pProvider); // degenerate range @@ -158,15 +155,16 @@ namespace Microsoft::Console::Interactivity::Win32 ~UiaTextRange(); - const IdType GetId() const; const Endpoint GetStart() const; const Endpoint GetEnd() const; const bool IsDegenerate() const; // IUnknown methods - IFACEMETHODIMP_(ULONG) AddRef(); - IFACEMETHODIMP_(ULONG) Release(); + IFACEMETHODIMP_(ULONG) + AddRef(); + IFACEMETHODIMP_(ULONG) + Release(); IFACEMETHODIMP QueryInterface(_In_ REFIID riid, _COM_Outptr_result_maybenull_ void** ppInterface); @@ -340,35 +338,35 @@ namespace Microsoft::Console::Interactivity::Win32 _Out_ int* const pAmountMoved); static std::tuple - _moveEndpointByUnitCharacter(const int moveCount, - const TextPatternRangeEndpoint endpoint, - const MoveState moveState, - _Out_ int* const pAmountMoved); + _moveEndpointByUnitCharacter(const int moveCount, + const TextPatternRangeEndpoint endpoint, + const MoveState moveState, + _Out_ int* const pAmountMoved); static std::tuple - _moveEndpointByUnitCharacterForward(const int moveCount, - const TextPatternRangeEndpoint endpoint, - const MoveState moveState, - _Out_ int* const pAmountMoved); + _moveEndpointByUnitCharacterForward(const int moveCount, + const TextPatternRangeEndpoint endpoint, + const MoveState moveState, + _Out_ int* const pAmountMoved); static std::tuple - _moveEndpointByUnitCharacterBackward(const int moveCount, - const TextPatternRangeEndpoint endpoint, - const MoveState moveState, - _Out_ int* const pAmountMoved); + _moveEndpointByUnitCharacterBackward(const int moveCount, + const TextPatternRangeEndpoint endpoint, + const MoveState moveState, + _Out_ int* const pAmountMoved); static std::tuple - _moveEndpointByUnitLine(const int moveCount, + _moveEndpointByUnitLine(const int moveCount, + const TextPatternRangeEndpoint endpoint, + const MoveState moveState, + _Out_ int* const pAmountMoved); + + static std::tuple + _moveEndpointByUnitDocument(const int moveCount, const TextPatternRangeEndpoint endpoint, const MoveState moveState, _Out_ int* const pAmountMoved); - static std::tuple - _moveEndpointByUnitDocument(const int moveCount, - const TextPatternRangeEndpoint endpoint, - const MoveState moveState, - _Out_ int* const pAmountMoved); - #ifdef UNIT_TESTING friend class ::UiaTextRangeTests; #endif @@ -376,7 +374,6 @@ namespace Microsoft::Console::Interactivity::Win32 namespace UiaTextRangeTracing { - enum class ApiCall { Constructor, diff --git a/src/interactivity/win32/WindowMetrics.cpp b/src/interactivity/win32/WindowMetrics.cpp index 325a6c105..b985faf83 100644 --- a/src/interactivity/win32/WindowMetrics.cpp +++ b/src/interactivity/win32/WindowMetrics.cpp @@ -12,7 +12,7 @@ // The following default masks are used in creating windows #define CONSOLE_WINDOW_FLAGS (WS_OVERLAPPEDWINDOW | WS_HSCROLL | WS_VSCROLL) -#define CONSOLE_WINDOW_EX_FLAGS (WS_EX_WINDOWEDGE | WS_EX_ACCEPTFILES | WS_EX_APPWINDOW ) +#define CONSOLE_WINDOW_EX_FLAGS (WS_EX_WINDOWEDGE | WS_EX_ACCEPTFILES | WS_EX_APPWINDOW) using namespace Microsoft::Console::Interactivity::Win32; @@ -82,7 +82,7 @@ RECT WindowMetrics::GetMaxWindowRectInPixels() // - the original value passed in will be left untouched. // Return Value: // - RECT containing the left, right, top, and bottom positions from the desktop origin in pixels. Measures the outer edges of the potential window. -RECT WindowMetrics::GetMaxWindowRectInPixels(const RECT * const prcSuggested, _Out_opt_ UINT * pDpiSuggested) +RECT WindowMetrics::GetMaxWindowRectInPixels(const RECT* const prcSuggested, _Out_opt_ UINT* pDpiSuggested) { // prepare rectangle RECT rc = *prcSuggested; @@ -96,7 +96,7 @@ RECT WindowMetrics::GetMaxWindowRectInPixels(const RECT * const prcSuggested, _O // NOTE: We must use the nearest monitor because sometimes the system moves the window around into strange spots while performing snap and Win+D operations. // Those operations won't work correctly if we use MONITOR_DEFAULTTOPRIMARY. - IConsoleWindow *pWindow = ServiceLocator::LocateConsoleWindow(); + IConsoleWindow* pWindow = ServiceLocator::LocateConsoleWindow(); if (pWindow == nullptr || (TRUE != EqualRect(&rc, &rcZero))) { // For invalid window handles or when we were passed a non-zero suggestion rectangle, get the monitor from the rect. @@ -258,7 +258,7 @@ void WindowMetrics::ConvertRect(_Inout_ RECT* const prc, const ConvertRectangle DWORD dwStyle = 0; DWORD dwExStyle = 0; - IConsoleWindow *pWindow = ServiceLocator::LocateConsoleWindow(); + IConsoleWindow* pWindow = ServiceLocator::LocateConsoleWindow(); if (pWindow != nullptr) { dwStyle = GetWindowStyle(pWindow->GetWindowHandle()); diff --git a/src/interactivity/win32/WindowMetrics.hpp b/src/interactivity/win32/WindowMetrics.hpp index 042d1b3f5..3d1aa9352 100644 --- a/src/interactivity/win32/WindowMetrics.hpp +++ b/src/interactivity/win32/WindowMetrics.hpp @@ -26,7 +26,7 @@ namespace Microsoft::Console::Interactivity::Win32 // Public Members RECT GetMaxWindowRectInPixels(); - RECT GetMaxWindowRectInPixels(const RECT * const prcSuggested, _Out_opt_ UINT * pDpiSuggested); + RECT GetMaxWindowRectInPixels(const RECT* const prcSuggested, _Out_opt_ UINT* pDpiSuggested); BOOL AdjustWindowRectEx(_Inout_ LPRECT prc, const DWORD dwStyle, @@ -38,8 +38,8 @@ namespace Microsoft::Console::Interactivity::Win32 const DWORD dwExStyle, const int iDpi); - void ConvertClientRectToWindowRect(_Inout_ RECT * const prc); - void ConvertWindowRectToClientRect(_Inout_ RECT * const prc); + void ConvertClientRectToWindowRect(_Inout_ RECT* const prc); + void ConvertWindowRectToClientRect(_Inout_ RECT* const prc); private: enum ConvertRectangle @@ -49,9 +49,9 @@ namespace Microsoft::Console::Interactivity::Win32 }; BOOL UnadjustWindowRectEx(_Inout_ LPRECT prc, - const DWORD dwStyle, - const BOOL fMenu, - const DWORD dwExStyle); + const DWORD dwStyle, + const BOOL fMenu, + const DWORD dwExStyle); void ConvertRect(_Inout_ RECT* const prc, const ConvertRectangle crDirection); }; diff --git a/src/interactivity/win32/clipboard.hpp b/src/interactivity/win32/clipboard.hpp index be4703bbd..00da8aaf2 100644 --- a/src/interactivity/win32/clipboard.hpp +++ b/src/interactivity/win32/clipboard.hpp @@ -41,14 +41,14 @@ namespace Microsoft::Console::Interactivity::Win32 void StoreSelectionToClipboard(_In_ bool const fAlsoCopyHtml); TextBuffer::TextAndColor RetrieveTextFromBuffer(const SCREEN_INFORMATION& screenInfo, - const bool lineSelection, - const std::vector& selectionRects); + const bool lineSelection, + const std::vector& selectionRects); void CopyHTMLToClipboard(const TextBuffer::TextAndColor& rows); - std::string GenHTML(const TextBuffer::TextAndColor & rows); + std::string GenHTML(const TextBuffer::TextAndColor& rows); void CopyTextToSystemClipboard(const TextBuffer::TextAndColor& rows, _In_ bool const fAlsoCopyHtml); - bool FilterCharacterOnPaste(_Inout_ WCHAR * const pwch); + bool FilterCharacterOnPaste(_Inout_ WCHAR* const pwch); #ifdef UNIT_TESTING friend class ClipboardTests; diff --git a/src/interactivity/win32/find.cpp b/src/interactivity/win32/find.cpp index a7b13a776..91124cec4 100644 --- a/src/interactivity/win32/find.cpp +++ b/src/interactivity/win32/find.cpp @@ -1,100 +1,100 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -#include "precomp.h" - -#include "find.h" -#include "resource.h" -#include "window.hpp" - -#include "..\..\host\dbcs.h" -#include "..\..\host\handle.h" -#include "..\..\host\search.h" - -#include "..\inc\ServiceLocator.hpp" - -#pragma hdrstop - -using namespace Microsoft::Console::Interactivity; - -INT_PTR CALLBACK FindDialogProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) -{ - CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); - // This bool is used to track which option - up or down - was used to perform the last search. That way, the next time the - // find dialog is opened, it will default to the last used option. - static bool fFindSearchUp = true; - WCHAR szBuf[SEARCH_STRING_LENGTH + 1]; - switch (Message) - { - case WM_INITDIALOG: - SetWindowLongPtrW(hWnd, DWLP_USER, lParam); - SendDlgItemMessageW(hWnd, ID_CONSOLE_FINDSTR, EM_LIMITTEXT, ARRAYSIZE(szBuf) - 1, 0); - CheckRadioButton(hWnd, ID_CONSOLE_FINDUP, ID_CONSOLE_FINDDOWN, (fFindSearchUp? ID_CONSOLE_FINDUP : ID_CONSOLE_FINDDOWN)); - return TRUE; - case WM_COMMAND: - { - switch (LOWORD(wParam)) - { - case IDOK: - { - USHORT const StringLength = (USHORT) GetDlgItemTextW(hWnd, ID_CONSOLE_FINDSTR, szBuf, ARRAYSIZE(szBuf)); - if (StringLength == 0) - { - break; - } - bool const IgnoreCase = IsDlgButtonChecked(hWnd, ID_CONSOLE_FINDCASE) == 0; - bool const Reverse = IsDlgButtonChecked(hWnd, ID_CONSOLE_FINDDOWN) == 0; - fFindSearchUp = !!Reverse; - SCREEN_INFORMATION& ScreenInfo = gci.GetActiveOutputBuffer(); - - std::wstring wstr(szBuf, StringLength); - - LockConsole(); - auto Unlock = wil::scope_exit([&] { UnlockConsole(); }); - - Search search(ScreenInfo, - wstr, - Reverse ? Search::Direction::Backward : Search::Direction::Forward, - IgnoreCase ? Search::Sensitivity::CaseInsensitive : Search::Sensitivity::CaseSensitive); - - if (search.FindNext()) - { - Telemetry::Instance().LogFindDialogNextClicked(StringLength, (Reverse != 0), (IgnoreCase == 0)); - search.Select(); - return TRUE; - } - else - { - // The string wasn't found. - ScreenInfo.SendNotifyBeep(); - } - break; - } - case IDCANCEL: - Telemetry::Instance().FindDialogClosed(); - EndDialog(hWnd, 0); - return TRUE; - } - break; - } - default: - break; - } - return FALSE; -} - -void DoFind() -{ - Globals& g = ServiceLocator::LocateGlobals(); - IConsoleWindow* const pWindow = ServiceLocator::LocateConsoleWindow(); - - UnlockConsole(); - if (pWindow != nullptr) - { - HWND const hwnd = pWindow->GetWindowHandle(); - - ++g.uiDialogBoxCount; - DialogBoxParamW(g.hInstance, MAKEINTRESOURCE(ID_CONSOLE_FINDDLG), hwnd, FindDialogProc, (LPARAM) nullptr); - --g.uiDialogBoxCount; - } -} +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +#include "precomp.h" + +#include "find.h" +#include "resource.h" +#include "window.hpp" + +#include "..\..\host\dbcs.h" +#include "..\..\host\handle.h" +#include "..\..\host\search.h" + +#include "..\inc\ServiceLocator.hpp" + +#pragma hdrstop + +using namespace Microsoft::Console::Interactivity; + +INT_PTR CALLBACK FindDialogProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) +{ + CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); + // This bool is used to track which option - up or down - was used to perform the last search. That way, the next time the + // find dialog is opened, it will default to the last used option. + static bool fFindSearchUp = true; + WCHAR szBuf[SEARCH_STRING_LENGTH + 1]; + switch (Message) + { + case WM_INITDIALOG: + SetWindowLongPtrW(hWnd, DWLP_USER, lParam); + SendDlgItemMessageW(hWnd, ID_CONSOLE_FINDSTR, EM_LIMITTEXT, ARRAYSIZE(szBuf) - 1, 0); + CheckRadioButton(hWnd, ID_CONSOLE_FINDUP, ID_CONSOLE_FINDDOWN, (fFindSearchUp ? ID_CONSOLE_FINDUP : ID_CONSOLE_FINDDOWN)); + return TRUE; + case WM_COMMAND: + { + switch (LOWORD(wParam)) + { + case IDOK: + { + USHORT const StringLength = (USHORT)GetDlgItemTextW(hWnd, ID_CONSOLE_FINDSTR, szBuf, ARRAYSIZE(szBuf)); + if (StringLength == 0) + { + break; + } + bool const IgnoreCase = IsDlgButtonChecked(hWnd, ID_CONSOLE_FINDCASE) == 0; + bool const Reverse = IsDlgButtonChecked(hWnd, ID_CONSOLE_FINDDOWN) == 0; + fFindSearchUp = !!Reverse; + SCREEN_INFORMATION& ScreenInfo = gci.GetActiveOutputBuffer(); + + std::wstring wstr(szBuf, StringLength); + + LockConsole(); + auto Unlock = wil::scope_exit([&] { UnlockConsole(); }); + + Search search(ScreenInfo, + wstr, + Reverse ? Search::Direction::Backward : Search::Direction::Forward, + IgnoreCase ? Search::Sensitivity::CaseInsensitive : Search::Sensitivity::CaseSensitive); + + if (search.FindNext()) + { + Telemetry::Instance().LogFindDialogNextClicked(StringLength, (Reverse != 0), (IgnoreCase == 0)); + search.Select(); + return TRUE; + } + else + { + // The string wasn't found. + ScreenInfo.SendNotifyBeep(); + } + break; + } + case IDCANCEL: + Telemetry::Instance().FindDialogClosed(); + EndDialog(hWnd, 0); + return TRUE; + } + break; + } + default: + break; + } + return FALSE; +} + +void DoFind() +{ + Globals& g = ServiceLocator::LocateGlobals(); + IConsoleWindow* const pWindow = ServiceLocator::LocateConsoleWindow(); + + UnlockConsole(); + if (pWindow != nullptr) + { + HWND const hwnd = pWindow->GetWindowHandle(); + + ++g.uiDialogBoxCount; + DialogBoxParamW(g.hInstance, MAKEINTRESOURCE(ID_CONSOLE_FINDDLG), hwnd, FindDialogProc, (LPARAM) nullptr); + --g.uiDialogBoxCount; + } +} diff --git a/src/interactivity/win32/icon.cpp b/src/interactivity/win32/icon.cpp index c65762d29..f156994b0 100644 --- a/src/interactivity/win32/icon.cpp +++ b/src/interactivity/win32/icon.cpp @@ -18,7 +18,6 @@ Icon::Icon() : _hIcon(nullptr), _hSmIcon(nullptr) { - } Icon::~Icon() @@ -50,8 +49,7 @@ Icon& Icon::Instance() // - phSmIcon - The small icon representation. // Return Value: // - S_OK or HRESULT failure code. -[[nodiscard]] -HRESULT Icon::GetIcons(_Out_opt_ HICON* const phIcon, _Out_opt_ HICON* const phSmIcon) +[[nodiscard]] HRESULT Icon::GetIcons(_Out_opt_ HICON* const phIcon, _Out_opt_ HICON* const phSmIcon) { HRESULT hr = S_OK; @@ -78,8 +76,7 @@ HRESULT Icon::GetIcons(_Out_opt_ HICON* const phIcon, _Out_opt_ HICON* const phS // - hSmIcon - The small icon handle or null to reset to default // Return Value: // - S_OK or HRESULT failure code. -[[nodiscard]] -HRESULT Icon::SetIcons(const HICON hIcon, const HICON hSmIcon) +[[nodiscard]] HRESULT Icon::SetIcons(const HICON hIcon, const HICON hSmIcon) { HRESULT hr = _SetIconFromReference(_hIcon, hIcon); @@ -120,8 +117,7 @@ HRESULT Icon::SetIcons(const HICON hIcon, const HICON hSmIcon) // - nIconIndex - Index offset of the icon within the file // Return Value: // - S_OK or HRESULT failure code. -[[nodiscard]] -HRESULT Icon::LoadIconsFromPath(_In_ PCWSTR pwszIconLocation, const int nIconIndex) +[[nodiscard]] HRESULT Icon::LoadIconsFromPath(_In_ PCWSTR pwszIconLocation, const int nIconIndex) { HRESULT hr = S_OK; @@ -148,8 +144,7 @@ HRESULT Icon::LoadIconsFromPath(_In_ PCWSTR pwszIconLocation, const int nIconIn // - hwnd - Handle to apply message workaround to. // Return Value: // - S_OK or HRESULT failure code. -[[nodiscard]] -HRESULT Icon::ApplyWindowMessageWorkaround(const HWND hwnd) +[[nodiscard]] HRESULT Icon::ApplyWindowMessageWorkaround(const HWND hwnd) { HICON hIcon; HICON hSmIcon; @@ -171,17 +166,16 @@ HRESULT Icon::ApplyWindowMessageWorkaround(const HWND hwnd) // - // Return Value: // - S_OK or HRESULT failure code. -[[nodiscard]] -HRESULT Icon::_Initialize() +[[nodiscard]] HRESULT Icon::_Initialize() { HRESULT hr = S_OK; if (!_fInitialized) { - #pragma warning(push) - #pragma warning(disable:4302) // typecast warning from MAKEINTRESOURCE +#pragma warning(push) +#pragma warning(disable : 4302) // typecast warning from MAKEINTRESOURCE _hDefaultIcon = LoadIconW(nullptr, MAKEINTRESOURCE(IDI_APPLICATION)); - #pragma warning(pop) +#pragma warning(pop) if (_hDefaultIcon == nullptr) { @@ -190,16 +184,15 @@ HRESULT Icon::_Initialize() if (SUCCEEDED(hr)) { - #pragma warning(push) - #pragma warning(disable:4302) // typecast warning from MAKEINTRESOURCE +#pragma warning(push) +#pragma warning(disable : 4302) // typecast warning from MAKEINTRESOURCE _hDefaultSmIcon = (HICON)LoadImageW(nullptr, - MAKEINTRESOURCE(IDI_APPLICATION), - IMAGE_ICON, - GetSystemMetrics(SM_CXSMICON), - GetSystemMetrics(SM_CYSMICON), - LR_SHARED - ); - #pragma warning(pop) + MAKEINTRESOURCE(IDI_APPLICATION), + IMAGE_ICON, + GetSystemMetrics(SM_CXSMICON), + GetSystemMetrics(SM_CYSMICON), + LR_SHARED); +#pragma warning(pop) if (_hDefaultSmIcon == nullptr) { @@ -237,8 +230,7 @@ void Icon::_DestroyNonDefaultIcons() // - phIcon - pointer to receive the chosen icon handle // Return Value: // - S_OK or HRESULT failure code. -[[nodiscard]] -HRESULT Icon::_GetAvailableIconFromReference(_In_ HICON& hIconRef, _In_ HICON& hDefaultIconRef, _Out_ HICON* const phIcon) +[[nodiscard]] HRESULT Icon::_GetAvailableIconFromReference(_In_ HICON& hIconRef, _In_ HICON& hDefaultIconRef, _Out_ HICON* const phIcon) { HRESULT hr = S_OK; @@ -267,8 +259,7 @@ HRESULT Icon::_GetAvailableIconFromReference(_In_ HICON& hIconRef, _In_ HICON& h // - phIcon - The pointer to fill with the icon if it is available. // Return Value: // - S_OK or HRESULT failure code. -[[nodiscard]] -HRESULT Icon::_GetDefaultIconFromReference(_In_ HICON& hIconRef, _Out_ HICON* const phIcon) +[[nodiscard]] HRESULT Icon::_GetDefaultIconFromReference(_In_ HICON& hIconRef, _Out_ HICON* const phIcon) { // expecting hIconRef to be pointing to either the regular or small default handles FAIL_FAST_IF(!(&hIconRef == &_hDefaultIcon || &hIconRef == &_hDefaultSmIcon)); @@ -291,8 +282,7 @@ HRESULT Icon::_GetDefaultIconFromReference(_In_ HICON& hIconRef, _Out_ HICON* co // - hNewIcon - The new icon handle to replace the reference with. // Return Value: // - S_OK or HRESULT failure code. -[[nodiscard]] -HRESULT Icon::_SetIconFromReference(_In_ HICON& hIconRef, const HICON hNewIcon) +[[nodiscard]] HRESULT Icon::_SetIconFromReference(_In_ HICON& hIconRef, const HICON hNewIcon) { // expecting hIconRef to be pointing to either the regular or small custom handles FAIL_FAST_IF(!(&hIconRef == &_hIcon || &hIconRef == &_hSmIcon)); diff --git a/src/interactivity/win32/icon.hpp b/src/interactivity/win32/icon.hpp index b32a94185..de15aa0e1 100644 --- a/src/interactivity/win32/icon.hpp +++ b/src/interactivity/win32/icon.hpp @@ -22,16 +22,12 @@ namespace Microsoft::Console::Interactivity::Win32 public: static Icon& Instance(); - [[nodiscard]] - HRESULT GetIcons(_Out_opt_ HICON* const phIcon, _Out_opt_ HICON* const phSmIcon); - [[nodiscard]] - HRESULT SetIcons(const HICON hIcon, const HICON hSmIcon); + [[nodiscard]] HRESULT GetIcons(_Out_opt_ HICON* const phIcon, _Out_opt_ HICON* const phSmIcon); + [[nodiscard]] HRESULT SetIcons(const HICON hIcon, const HICON hSmIcon); - [[nodiscard]] - HRESULT LoadIconsFromPath(_In_ PCWSTR pwszIconLocation, const int nIconIndex); + [[nodiscard]] HRESULT LoadIconsFromPath(_In_ PCWSTR pwszIconLocation, const int nIconIndex); - [[nodiscard]] - HRESULT ApplyWindowMessageWorkaround(const HWND hwnd); + [[nodiscard]] HRESULT ApplyWindowMessageWorkaround(const HWND hwnd); protected: Icon(); @@ -40,18 +36,14 @@ namespace Microsoft::Console::Interactivity::Win32 void operator=(Icon const&) = delete; private: - [[nodiscard]] - HRESULT _Initialize(); + [[nodiscard]] HRESULT _Initialize(); void _DestroyNonDefaultIcons(); // Helper methods - [[nodiscard]] - HRESULT _GetAvailableIconFromReference(_In_ HICON& hIconRef, _In_ HICON& hDefaultIconRef, _Out_ HICON* const phIcon); - [[nodiscard]] - HRESULT _GetDefaultIconFromReference(_In_ HICON& hIconRef, _Out_ HICON* const phIcon); - [[nodiscard]] - HRESULT _SetIconFromReference(_In_ HICON& hIconRef, const HICON hNewIcon); + [[nodiscard]] HRESULT _GetAvailableIconFromReference(_In_ HICON& hIconRef, _In_ HICON& hDefaultIconRef, _Out_ HICON* const phIcon); + [[nodiscard]] HRESULT _GetDefaultIconFromReference(_In_ HICON& hIconRef, _Out_ HICON* const phIcon); + [[nodiscard]] HRESULT _SetIconFromReference(_In_ HICON& hIconRef, const HICON hNewIcon); void _FreeIconFromReference(_In_ HICON& hIconRef); bool _fInitialized; diff --git a/src/interactivity/win32/menu.cpp b/src/interactivity/win32/menu.cpp index 0c24753ab..b1d11151d 100644 --- a/src/interactivity/win32/menu.cpp +++ b/src/interactivity/win32/menu.cpp @@ -34,7 +34,6 @@ Menu::Menu(HMENU hMenu, HMENU hHeirMenu) : _hMenu(hMenu), _hHeirMenu(hHeirMenu) { - } // Routine Description: @@ -43,11 +42,10 @@ Menu::Menu(HMENU hMenu, HMENU hHeirMenu) : // - hWnd - The handle to the console's window // Return Value: // - STATUS_SUCCESS or suitable NT error code -[[nodiscard]] -NTSTATUS Menu::CreateInstance(HWND hWnd) +[[nodiscard]] NTSTATUS Menu::CreateInstance(HWND hWnd) { NTSTATUS status = STATUS_SUCCESS; - HMENU hMenu = nullptr; + HMENU hMenu = nullptr; HMENU hHeirMenu = nullptr; int ItemLength; @@ -58,7 +56,7 @@ NTSTATUS Menu::CreateInstance(HWND hWnd) hHeirMenu = LoadMenuW(ServiceLocator::LocateGlobals().hInstance, MAKEINTRESOURCE(ID_CONSOLE_SYSTEMMENU)); - Menu *pNewMenu = new(std::nothrow) Menu(hMenu, hHeirMenu); + Menu* pNewMenu = new (std::nothrow) Menu(hMenu, hHeirMenu); status = NT_TESTNULL(pNewMenu); if (NT_SUCCESS(status)) @@ -138,7 +136,6 @@ Menu* Menu::Instance() Menu::~Menu() { - } // Routine Description: @@ -274,9 +271,9 @@ void Menu::s_ShowPropertiesDialog(HWND const hwnd, BOOL const Defaults) APPLET_PROC const pfnCplApplet = (APPLET_PROC)GetProcAddress((HMODULE)hLibrary, "CPlApplet"); if (pfnCplApplet != nullptr) { - (*pfnCplApplet) (hwnd, CPL_INIT, 0, 0); - (*pfnCplApplet) (hwnd, CPL_DBLCLK, (LPARAM)& StateInfo, 0); - (*pfnCplApplet) (hwnd, CPL_EXIT, 0, 0); + (*pfnCplApplet)(hwnd, CPL_INIT, 0, 0); + (*pfnCplApplet)(hwnd, CPL_DBLCLK, (LPARAM)&StateInfo, 0); + (*pfnCplApplet)(hwnd, CPL_EXIT, 0, 0); } LOG_IF_WIN32_BOOL_FALSE(FreeLibrary((HMODULE)hLibrary)); @@ -301,8 +298,7 @@ void Menu::s_ShowPropertiesDialog(HWND const hwnd, BOOL const Defaults) } } -[[nodiscard]] -HRESULT Menu::s_GetConsoleState(CONSOLE_STATE_INFO * const pStateInfo) +[[nodiscard]] HRESULT Menu::s_GetConsoleState(CONSOLE_STATE_INFO* const pStateInfo) { const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); const SCREEN_INFORMATION& ScreenInfo = gci.GetActiveOutputBuffer(); @@ -346,7 +342,7 @@ HRESULT Menu::s_GetConsoleState(CONSOLE_STATE_INFO * const pStateInfo) // Create mutable copies of the titles so the propsheet can do something with them. if (gci.GetOriginalTitle().length() > 0) { - pStateInfo->OriginalTitle = new(std::nothrow) wchar_t[gci.GetOriginalTitle().length()+1]{UNICODE_NULL}; + pStateInfo->OriginalTitle = new (std::nothrow) wchar_t[gci.GetOriginalTitle().length() + 1]{ UNICODE_NULL }; RETURN_IF_NULL_ALLOC(pStateInfo->OriginalTitle); gci.GetOriginalTitle().copy(pStateInfo->OriginalTitle, gci.GetOriginalTitle().length()); } @@ -357,7 +353,7 @@ HRESULT Menu::s_GetConsoleState(CONSOLE_STATE_INFO * const pStateInfo) if (gci.GetLinkTitle().length() > 0) { - pStateInfo->LinkTitle = new(std::nothrow) wchar_t[gci.GetLinkTitle().length()+1]{UNICODE_NULL}; + pStateInfo->LinkTitle = new (std::nothrow) wchar_t[gci.GetLinkTitle().length() + 1]{ UNICODE_NULL }; RETURN_IF_NULL_ALLOC(pStateInfo->LinkTitle); gci.GetLinkTitle().copy(pStateInfo->LinkTitle, gci.GetLinkTitle().length()); } @@ -604,7 +600,6 @@ void Menu::s_PropertiesUpdate(PCONSOLE_STATE_INFO pStateInfo) gci.ConsoleIme.RefreshAreaAttributes(); gci.SetInterceptCopyPaste(!!pStateInfo->InterceptCopyPaste); - } #pragma endregion diff --git a/src/interactivity/win32/menu.hpp b/src/interactivity/win32/menu.hpp index ca7e323a0..df4a62fc8 100644 --- a/src/interactivity/win32/menu.hpp +++ b/src/interactivity/win32/menu.hpp @@ -26,17 +26,15 @@ namespace Microsoft::Console::Interactivity::Win32 { public: Menu(_In_ HMENU hMenu, - _In_ HMENU hHeirMenu); - [[nodiscard]] - static NTSTATUS CreateInstance(_In_ HWND hWnd); + _In_ HMENU hHeirMenu); + [[nodiscard]] static NTSTATUS CreateInstance(_In_ HWND hWnd); static Menu* Instance(); ~Menu(); void Initialize(); static void s_ShowPropertiesDialog(const HWND hwnd, const BOOL Defaults); - [[nodiscard]] - static HRESULT s_GetConsoleState(_Out_ CONSOLE_STATE_INFO * const pStateInfo); + [[nodiscard]] static HRESULT s_GetConsoleState(_Out_ CONSOLE_STATE_INFO* const pStateInfo); static HMENU s_GetMenuHandle(); static HMENU s_GetHeirMenuHandle(); @@ -46,7 +44,7 @@ namespace Microsoft::Console::Interactivity::Win32 static Menu* s_Instance; - HMENU _hMenu; // handle to system menu - HMENU _hHeirMenu; // handle to menu we append to system menu + HMENU _hMenu; // handle to system menu + HMENU _hHeirMenu; // handle to menu we append to system menu }; } diff --git a/src/interactivity/win32/resource.h b/src/interactivity/win32/resource.h index 404591ea3..f45355721 100644 --- a/src/interactivity/win32/resource.h +++ b/src/interactivity/win32/resource.h @@ -15,6 +15,8 @@ Author(s): #pragma once +// clang-format off + // IDs of various STRINGTABLE entries #define ID_CONSOLE_MSGCMDLINEF2 0x1008 #define ID_CONSOLE_MSGCMDLINEF4 0x1009 @@ -45,3 +47,5 @@ Author(s): #define ID_CONSOLE_FINDCASE 602 #define ID_CONSOLE_FINDUP 603 #define ID_CONSOLE_FINDDOWN 604 + +// clang-format on diff --git a/src/interactivity/win32/screenInfoUiaProvider.cpp b/src/interactivity/win32/screenInfoUiaProvider.cpp index fc7d23d80..c8127e6c6 100644 --- a/src/interactivity/win32/screenInfoUiaProvider.cpp +++ b/src/interactivity/win32/screenInfoUiaProvider.cpp @@ -19,12 +19,12 @@ using namespace Microsoft::Console::Interactivity; // A helper function to create a SafeArray Version of an int array of a specified length SAFEARRAY* BuildIntSafeArray(_In_reads_(length) const int* const data, const int length) { - SAFEARRAY *psa = SafeArrayCreateVector(VT_I4, 0, length); + SAFEARRAY* psa = SafeArrayCreateVector(VT_I4, 0, length); if (psa != nullptr) { for (long i = 0; i < length; i++) { - if (FAILED(SafeArrayPutElement(psa, &i, (void *)&(data[i])))) + if (FAILED(SafeArrayPutElement(psa, &i, (void*)&(data[i])))) { SafeArrayDestroy(psa); psa = nullptr; @@ -48,8 +48,7 @@ ScreenInfoUiaProvider::~ScreenInfoUiaProvider() { } -[[nodiscard]] -HRESULT ScreenInfoUiaProvider::Signal(_In_ EVENTID id) +[[nodiscard]] HRESULT ScreenInfoUiaProvider::Signal(_In_ EVENTID id) { HRESULT hr = S_OK; // check to see if we're already firing this particular event @@ -78,13 +77,15 @@ HRESULT ScreenInfoUiaProvider::Signal(_In_ EVENTID id) #pragma region IUnknown -IFACEMETHODIMP_(ULONG) ScreenInfoUiaProvider::AddRef() +IFACEMETHODIMP_(ULONG) +ScreenInfoUiaProvider::AddRef() { Tracing::s_TraceUia(this, ApiCall::AddRef, nullptr); return InterlockedIncrement(&_cRefs); } -IFACEMETHODIMP_(ULONG) ScreenInfoUiaProvider::Release() +IFACEMETHODIMP_(ULONG) +ScreenInfoUiaProvider::Release() { Tracing::s_TraceUia(this, ApiCall::Release, nullptr); long val = InterlockedDecrement(&_cRefs); @@ -338,8 +339,7 @@ IFACEMETHODIMP ScreenInfoUiaProvider::GetSelection(_Outptr_result_maybenull_ SAF CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); ApiMsgGetSelection apiMsg; gci.LockConsole(); - auto Unlock = wil::scope_exit([&] - { + auto Unlock = wil::scope_exit([&] { gci.UnlockConsole(); }); @@ -454,8 +454,7 @@ IFACEMETHODIMP ScreenInfoUiaProvider::GetVisibleRanges(_Outptr_result_maybenull_ CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); gci.LockConsole(); - auto Unlock = wil::scope_exit([&] - { + auto Unlock = wil::scope_exit([&] { gci.UnlockConsole(); }); @@ -531,7 +530,7 @@ IFACEMETHODIMP ScreenInfoUiaProvider::RangeFromChild(_In_ IRawElementProviderSim IRawElementProviderSimple* pProvider; RETURN_IF_FAILED(this->QueryInterface(IID_PPV_ARGS(&pProvider))); - HRESULT hr = S_OK;; + HRESULT hr = S_OK; try { *ppRetVal = UiaTextRange::Create(pProvider); @@ -559,7 +558,7 @@ IFACEMETHODIMP ScreenInfoUiaProvider::RangeFromPoint(_In_ UiaPoint point, *ppRetVal = UiaTextRange::Create(pProvider, point); } - catch(...) + catch (...) { *ppRetVal = nullptr; hr = wil::ResultFromCaughtException(); diff --git a/src/interactivity/win32/screenInfoUiaProvider.hpp b/src/interactivity/win32/screenInfoUiaProvider.hpp index 08bb5060b..695105a1f 100644 --- a/src/interactivity/win32/screenInfoUiaProvider.hpp +++ b/src/interactivity/win32/screenInfoUiaProvider.hpp @@ -30,27 +30,29 @@ namespace Microsoft::Console::Interactivity::Win32 class WindowUiaProvider; - class ScreenInfoUiaProvider final : public IRawElementProviderSimple, - public IRawElementProviderFragment, - public ITextProvider + class ScreenInfoUiaProvider final : + public IRawElementProviderSimple, + public IRawElementProviderFragment, + public ITextProvider { public: ScreenInfoUiaProvider(_In_ WindowUiaProvider* const pUiaParent); virtual ~ScreenInfoUiaProvider(); - [[nodiscard]] - HRESULT Signal(_In_ EVENTID id); + [[nodiscard]] HRESULT Signal(_In_ EVENTID id); // IUnknown methods - IFACEMETHODIMP_(ULONG) AddRef(); - IFACEMETHODIMP_(ULONG) Release(); + IFACEMETHODIMP_(ULONG) + AddRef(); + IFACEMETHODIMP_(ULONG) + Release(); IFACEMETHODIMP QueryInterface(_In_ REFIID riid, - _COM_Outptr_result_maybenull_ void** ppInterface); + _COM_Outptr_result_maybenull_ void** ppInterface); // IRawElementProviderSimple methods IFACEMETHODIMP get_ProviderOptions(_Out_ ProviderOptions* pOptions); IFACEMETHODIMP GetPatternProvider(_In_ PATTERNID iid, - _COM_Outptr_result_maybenull_ IUnknown** ppInterface); + _COM_Outptr_result_maybenull_ IUnknown** ppInterface); IFACEMETHODIMP GetPropertyValue(_In_ PROPERTYID idProp, _Out_ VARIANT* pVariant); IFACEMETHODIMP get_HostRawElementProvider(_COM_Outptr_result_maybenull_ IRawElementProviderSimple** ppProvider); @@ -68,14 +70,13 @@ namespace Microsoft::Console::Interactivity::Win32 IFACEMETHODIMP GetSelection(_Outptr_result_maybenull_ SAFEARRAY** ppRetVal); IFACEMETHODIMP GetVisibleRanges(_Outptr_result_maybenull_ SAFEARRAY** ppRetVal); IFACEMETHODIMP RangeFromChild(_In_ IRawElementProviderSimple* childElement, - _COM_Outptr_result_maybenull_ ITextRangeProvider** ppRetVal); + _COM_Outptr_result_maybenull_ ITextRangeProvider** ppRetVal); IFACEMETHODIMP RangeFromPoint(_In_ UiaPoint point, - _COM_Outptr_result_maybenull_ ITextRangeProvider** ppRetVal); + _COM_Outptr_result_maybenull_ ITextRangeProvider** ppRetVal); IFACEMETHODIMP get_DocumentRange(_COM_Outptr_result_maybenull_ ITextRangeProvider** ppRetVal); IFACEMETHODIMP get_SupportedTextSelection(_Out_ SupportedTextSelection* pRetVal); private: - // Ref counter for COM object ULONG _cRefs; diff --git a/src/interactivity/win32/ut_interactivity_win32/UiaTextRangeTests.cpp b/src/interactivity/win32/ut_interactivity_win32/UiaTextRangeTests.cpp index 6fdd17e63..f9314b543 100644 --- a/src/interactivity/win32/ut_interactivity_win32/UiaTextRangeTests.cpp +++ b/src/interactivity/win32/ut_interactivity_win32/UiaTextRangeTests.cpp @@ -15,7 +15,6 @@ using namespace WEX::TestExecution; using namespace Microsoft::Console::Interactivity::Win32; - // UiaTextRange takes an object that implements // IRawElementProviderSimple as a constructor argument. Making a real // one would involve setting up the window which we don't want to do @@ -26,8 +25,17 @@ class DummyElementProvider final : public IRawElementProviderSimple { public: // IUnknown methods - IFACEMETHODIMP_(ULONG) AddRef() { return 1; } - IFACEMETHODIMP_(ULONG) Release() { return 1; } + IFACEMETHODIMP_(ULONG) + AddRef() + { + return 1; + } + + IFACEMETHODIMP_(ULONG) + Release() + { + return 1; + } IFACEMETHODIMP QueryInterface(_In_ REFIID /*riid*/, _COM_Outptr_result_maybenull_ void** /*ppInterface*/) { @@ -58,7 +66,6 @@ public: } }; - class UiaTextRangeTests { TEST_CLASS(UiaTextRangeTests); @@ -94,8 +101,7 @@ class UiaTextRangeTests } // set up default range - _range = new UiaTextRange - { + _range = new UiaTextRange{ &_dummyProvider, 0, 0, @@ -121,14 +127,13 @@ class UiaTextRangeTests const size_t _getRowWidth() const { const CharRow& charRow = _pTextBuffer->_GetFirstRow().GetCharRow(); - return charRow.MeasureRight()- charRow.MeasureLeft() ; + return charRow.MeasureRight() - charRow.MeasureLeft(); } TEST_METHOD(DegenerateRangesDetected) { // make a degenerate range and verify that it reports degenerate - UiaTextRange degenerate - { + UiaTextRange degenerate{ &_dummyProvider, 20, 19, @@ -139,8 +144,7 @@ class UiaTextRangeTests VERIFY_ARE_EQUAL(degenerate._start, degenerate._end); // make a non-degenerate range and verify that it reports as such - UiaTextRange notDegenerate1 - { + UiaTextRange notDegenerate1{ &_dummyProvider, 20, 20, @@ -178,8 +182,7 @@ class UiaTextRangeTests viewport.Top = 0; viewport.Bottom = 10; - std::vector> viewportSizes = - { + std::vector> viewportSizes = { { 0, 10 }, // viewport at top { 2, 10 }, // shifted viewport { totalRows - 5, totalRows + 3 } // viewport with 0th row @@ -220,7 +223,7 @@ class UiaTextRangeTests { VERIFY_ARE_EQUAL(i * rowWidth, _range->_textBufferRowToEndpoint(i)); // make sure that the translation is reversible - VERIFY_ARE_EQUAL(i , _range->_endpointToTextBufferRow(_range->_textBufferRowToEndpoint(i))); + VERIFY_ARE_EQUAL(i, _range->_endpointToTextBufferRow(_range->_textBufferRowToEndpoint(i))); } } @@ -229,7 +232,7 @@ class UiaTextRangeTests const auto rowWidth = _getRowWidth(); for (unsigned int i = 0; i < 5; ++i) { - VERIFY_ARE_EQUAL(i , _range->_textBufferRowToScreenInfoRow(_range->_screenInfoRowToTextBufferRow(i))); + VERIFY_ARE_EQUAL(i, _range->_textBufferRowToScreenInfoRow(_range->_screenInfoRowToTextBufferRow(i))); } } @@ -259,14 +262,13 @@ class UiaTextRangeTests TEST_METHOD(CanNormalizeRow) { const int totalRows = _pTextBuffer->TotalRowCount(); - std::vector> rowMappings = - { + std::vector> rowMappings = { { 0, 0 }, { totalRows / 2, totalRows / 2 }, { totalRows - 1, totalRows - 1 }, { totalRows, 0 }, { totalRows + 1, 1 }, - { -1, totalRows - 1} + { -1, totalRows - 1 } }; for (auto it = rowMappings.begin(); it != rowMappings.end(); ++it) @@ -306,8 +308,7 @@ class UiaTextRangeTests TEST_METHOD(CanCompareScreenCoords) { - const std::vector> testData = - { + const std::vector> testData = { { 0, 0, 0, 0, 0 }, { 5, 0, 5, 0, 0 }, { 2, 3, 2, 3, 0 }, @@ -321,10 +322,11 @@ class UiaTextRangeTests for (auto data : testData) { - VERIFY_ARE_EQUAL(std::get<4>(data), UiaTextRange::_compareScreenCoords(std::get<0>(data), - std::get<1>(data), - std::get<2>(data), - std::get<3>(data))); + VERIFY_ARE_EQUAL(std::get<4>(data), + UiaTextRange::_compareScreenCoords(std::get<0>(data), + std::get<1>(data), + std::get<2>(data), + std::get<3>(data))); } } @@ -335,6 +337,7 @@ class UiaTextRangeTests const ScreenInfoRow topRow = 0; const ScreenInfoRow bottomRow = _pTextBuffer->TotalRowCount() - 1; + // clang-format off const std::vector(data), amountMoved); VERIFY_ARE_EQUAL(std::get<4>(data), newEndpoints.first); VERIFY_ARE_EQUAL(std::get<5>(data), newEndpoints.second); - } } @@ -468,6 +471,7 @@ class UiaTextRangeTests const ScreenInfoRow topRow = 0; const ScreenInfoRow bottomRow = _pTextBuffer->TotalRowCount() - 1; + // clang-format off const std::vectorTotalRowCount() - 1; + // clang-format off const std::vectorTotalRowCount() - 1; + // clang-format off const std::vector(data), std::get<1>(result)); VERIFY_ARE_EQUAL(std::get<7>(data), std::get<2>(result)); } - - } TEST_METHOD(CanMoveEndpointByUnitDocument) @@ -1015,6 +1021,7 @@ class UiaTextRangeTests const ScreenInfoRow topRow = 0; const ScreenInfoRow bottomRow = _pTextBuffer->TotalRowCount() - 1; + // clang-format off const std::vector // Return Value: // - STATUS_SUCCESS or failure from loading icons/registering class with the system -[[nodiscard]] -NTSTATUS Window::s_RegisterWindowClass() +[[nodiscard]] NTSTATUS Window::s_RegisterWindowClass() { NTSTATUS status = STATUS_SUCCESS; @@ -192,9 +189,8 @@ void Window::_UpdateSystemMetrics() const // - pScreen - Attach to this screen for rendering the client area of the window // Return Value: // - STATUS_SUCCESS, invalid parameters, or various potential errors from calling CreateWindow -[[nodiscard]] -NTSTATUS Window::_MakeWindow(_In_ Settings* const pSettings, - _In_ SCREEN_INFORMATION* const pScreen) +[[nodiscard]] NTSTATUS Window::_MakeWindow(_In_ Settings* const pSettings, + _In_ SCREEN_INFORMATION* const pScreen) { Globals& g = ServiceLocator::LocateGlobals(); CONSOLE_INFORMATION& gci = g.getConsoleInformation(); @@ -303,7 +299,7 @@ NTSTATUS Window::_MakeWindow(_In_ Settings* const pSettings, nullptr, nullptr, this // handle to this window class, passed to WM_CREATE to help dispatching to this instance - ); + ); if (hWnd == nullptr) { @@ -392,8 +388,7 @@ void Window::_CloseWindow() const // - wShowWindow - See STARTUPINFO wShowWindow member: http://msdn.microsoft.com/en-us/library/windows/desktop/ms686331(v=vs.85).aspx // Return Value: // - STATUS_SUCCESS or system errors from activating the window and setting its show states -[[nodiscard]] -NTSTATUS Window::ActivateAndShow(const WORD wShowWindow) +[[nodiscard]] NTSTATUS Window::ActivateAndShow(const WORD wShowWindow) { CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); NTSTATUS status = STATUS_SUCCESS; @@ -443,7 +438,7 @@ void Window::ChangeViewport(const SMALL_RECT NewWindow) pSelection->HideSelection(); // Fire off an event to let accessibility apps know we've scrolled. - IAccessibilityNotifier *pNotifier = ServiceLocator::LocateAccessibilityNotifier(); + IAccessibilityNotifier* pNotifier = ServiceLocator::LocateAccessibilityNotifier(); if (pNotifier != nullptr) { pNotifier->NotifyConsoleUpdateScrollEvent(ScreenInfo.GetViewport().Left() - NewWindow.Left, @@ -492,12 +487,12 @@ void Window::UpdateWindowSize(const COORD coordSizeInChars) void Window::UpdateWindowPosition(_In_ POINT const ptNewPos) const { SetWindowPos(GetWindowHandle(), - nullptr, - ptNewPos.x, - ptNewPos.y, - 0, - 0, - SWP_NOSIZE | SWP_NOZORDER); + nullptr, + ptNewPos.x, + ptNewPos.y, + 0, + 0, + SWP_NOSIZE | SWP_NOZORDER); } // This routine adds or removes the name to or from the beginning of the window title. The possible names are "Scroll", "Mark", and "Select" @@ -506,15 +501,15 @@ void Window::UpdateWindowText() CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); const bool fInScrollMode = Scrolling::s_IsInScrollMode(); - Selection *pSelection = &Selection::Instance(); + Selection* pSelection = &Selection::Instance(); const bool fInKeyboardMarkMode = pSelection->IsInSelectingState() && pSelection->IsKeyboardMarkSelection(); const bool fInMouseSelectMode = pSelection->IsInSelectingState() && pSelection->IsMouseInitiatedSelection(); // should have at most one active mode FAIL_FAST_IF(!((fInKeyboardMarkMode && !fInMouseSelectMode && !fInScrollMode) || - (!fInKeyboardMarkMode && fInMouseSelectMode && !fInScrollMode) || - (!fInKeyboardMarkMode && !fInMouseSelectMode && fInScrollMode) || - (!fInKeyboardMarkMode && !fInMouseSelectMode && !fInScrollMode))); + (!fInKeyboardMarkMode && fInMouseSelectMode && !fInScrollMode) || + (!fInKeyboardMarkMode && !fInMouseSelectMode && fInScrollMode) || + (!fInKeyboardMarkMode && !fInMouseSelectMode && !fInScrollMode))); // determine which message, if any, we want to use DWORD dwMsgId = 0; @@ -574,12 +569,12 @@ void Window::_UpdateWindowSize(const SIZE sizeNew) ScreenInfo.InternalUpdateScrollBars(); SetWindowPos(GetWindowHandle(), - nullptr, - 0, - 0, - sizeNew.cx, - sizeNew.cy, - SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_DRAWFRAME); + nullptr, + 0, + 0, + sizeNew.cx, + sizeNew.cy, + SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_DRAWFRAME); } } @@ -591,8 +586,7 @@ void Window::_UpdateWindowSize(const SIZE sizeNew) // - - All state is read from the attached screen buffer // Return Value: // - STATUS_SUCCESS or suitable error code -[[nodiscard]] -NTSTATUS Window::_InternalSetWindowSize() +[[nodiscard]] NTSTATUS Window::_InternalSetWindowSize() { CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); SCREEN_INFORMATION& siAttached = GetScreenInfo(); @@ -1167,12 +1161,12 @@ void Window::_ApplyWindowSize() const RECT rcNewSize = _fIsInFullscreen ? _rcFullscreenWindowSize : _rcNonFullscreenWindowSize; SetWindowPos(GetWindowHandle(), - HWND_TOP, - rcNewSize.left, - rcNewSize.top, - RECT_WIDTH(&rcNewSize), - RECT_HEIGHT(&rcNewSize), - SWP_FRAMECHANGED); + HWND_TOP, + rcNewSize.left, + rcNewSize.top, + RECT_WIDTH(&rcNewSize), + RECT_HEIGHT(&rcNewSize), + SWP_FRAMECHANGED); SCREEN_INFORMATION& siAttached = GetScreenInfo(); siAttached.MakeCurrentCursorVisible(); @@ -1189,12 +1183,10 @@ void Window::s_ReinitializeFontsForDPIChange() gci.GetActiveOutputBuffer().RefreshFontWithRenderer(); } -[[nodiscard]] -LRESULT Window::s_RegPersistWindowPos(_In_ PCWSTR const pwszTitle, - const BOOL fAutoPos, - const Window* const pWindow) +[[nodiscard]] LRESULT Window::s_RegPersistWindowPos(_In_ PCWSTR const pwszTitle, + const BOOL fAutoPos, + const Window* const pWindow) { - const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); HKEY hCurrentUserKey, hConsoleKey, hTitleKey; // Open the current user registry key. @@ -1216,7 +1208,7 @@ LRESULT Window::s_RegPersistWindowPos(_In_ PCWSTR const pwszTitle, const COORD coordScreenBufferSize = gci.GetActiveOutputBuffer().GetBufferSize().Dimensions(); auto screenBufferWidth = coordScreenBufferSize.X; auto screenBufferHeight = coordScreenBufferSize.Y; - dwValue = MAKELONG(screenBufferWidth, screenBufferHeight); + dwValue = MAKELONG(screenBufferWidth, screenBufferHeight); Status = RegistrySerialization::s_UpdateValue(hConsoleKey, hTitleKey, CONSOLE_REGISTRY_BUFFERSIZE, @@ -1225,7 +1217,6 @@ LRESULT Window::s_RegPersistWindowPos(_In_ PCWSTR const pwszTitle, static_cast(sizeof(dwValue))); if (NT_SUCCESS(Status)) { - // Save window position if (fAutoPos) { @@ -1256,8 +1247,7 @@ LRESULT Window::s_RegPersistWindowPos(_In_ PCWSTR const pwszTitle, return Status; } -[[nodiscard]] -LRESULT Window::s_RegPersistWindowOpacity(_In_ PCWSTR const pwszTitle, const Window* const pWindow) +[[nodiscard]] LRESULT Window::s_RegPersistWindowOpacity(_In_ PCWSTR const pwszTitle, const Window* const pWindow) { HKEY hCurrentUserKey, hConsoleKey, hTitleKey; @@ -1309,8 +1299,7 @@ IRawElementProviderSimple* Window::_GetUiaProvider() return _pUiaProvider; } -[[nodiscard]] -HRESULT Window::SignalUia(_In_ EVENTID id) +[[nodiscard]] HRESULT Window::SignalUia(_In_ EVENTID id) { if (_pUiaProvider != nullptr) { @@ -1319,8 +1308,7 @@ HRESULT Window::SignalUia(_In_ EVENTID id) return S_FALSE; } -[[nodiscard]] -HRESULT Window::UiaSetTextAreaFocus() +[[nodiscard]] HRESULT Window::UiaSetTextAreaFocus() { if (_pUiaProvider != nullptr) { diff --git a/src/interactivity/win32/window.hpp b/src/interactivity/win32/window.hpp index 31503614d..dc884c008 100644 --- a/src/interactivity/win32/window.hpp +++ b/src/interactivity/win32/window.hpp @@ -16,7 +16,6 @@ Author(s): #include "..\inc\IConsoleWindow.hpp" - namespace Microsoft::Console::Interactivity::Win32 { class WindowUiaProvider; @@ -24,12 +23,10 @@ namespace Microsoft::Console::Interactivity::Win32 class Window final : public IConsoleWindow { public: - [[nodiscard]] - static NTSTATUS CreateInstance(_In_ Settings* const pSettings, - _In_ SCREEN_INFORMATION* const pScreen); + [[nodiscard]] static NTSTATUS CreateInstance(_In_ Settings* const pSettings, + _In_ SCREEN_INFORMATION* const pScreen); - [[nodiscard]] - NTSTATUS ActivateAndShow(const WORD wShowWindow); + [[nodiscard]] NTSTATUS ActivateAndShow(const WORD wShowWindow); ~Window(); @@ -79,18 +76,16 @@ namespace Microsoft::Console::Interactivity::Win32 BOOL PostUpdateWindowSize() const; BOOL PostUpdateExtendedEditKeys() const; - [[nodiscard]] - HRESULT SignalUia(_In_ EVENTID id); + [[nodiscard]] HRESULT SignalUia(_In_ EVENTID id); void SetOwner(); BOOL GetCursorPosition(_Out_ LPPOINT lpPoint); BOOL GetClientRectangle(_Out_ LPRECT lpRect); int MapPoints(_Inout_updates_(cPoints) LPPOINT lpPoints, - _In_ UINT cPoints); + _In_ UINT cPoints); BOOL ConvertScreenToClient(_Inout_ LPPOINT lpPoint); - [[nodiscard]] - HRESULT UiaSetTextAreaFocus(); + [[nodiscard]] HRESULT UiaSetTextAreaFocus(); protected: // prevent accidental generation of copies @@ -101,11 +96,9 @@ namespace Microsoft::Console::Interactivity::Win32 Window(); // Registration/init - [[nodiscard]] - static NTSTATUS s_RegisterWindowClass(); - [[nodiscard]] - NTSTATUS _MakeWindow(_In_ Settings* const pSettings, - _In_ SCREEN_INFORMATION* const pScreen); + [[nodiscard]] static NTSTATUS s_RegisterWindowClass(); + [[nodiscard]] NTSTATUS _MakeWindow(_In_ Settings* const pSettings, + _In_ SCREEN_INFORMATION* const pScreen); void _CloseWindow() const; static ATOM s_atomWindowClass; @@ -114,46 +107,39 @@ namespace Microsoft::Console::Interactivity::Win32 HWND _hWnd; static Window* s_Instance; - [[nodiscard]] - NTSTATUS _InternalSetWindowSize(); + [[nodiscard]] NTSTATUS _InternalSetWindowSize(); void _UpdateWindowSize(const SIZE sizeNew); void _UpdateSystemMetrics() const; // Wndproc - [[nodiscard]] - static LRESULT CALLBACK s_ConsoleWindowProc(_In_ HWND hwnd, - _In_ UINT uMsg, - _In_ WPARAM wParam, - _In_ LPARAM lParam); - [[nodiscard]] - LRESULT CALLBACK ConsoleWindowProc(_In_ HWND, - _In_ UINT uMsg, - _In_ WPARAM wParam, - _In_ LPARAM lParam); + [[nodiscard]] static LRESULT CALLBACK s_ConsoleWindowProc(_In_ HWND hwnd, + _In_ UINT uMsg, + _In_ WPARAM wParam, + _In_ LPARAM lParam); + [[nodiscard]] LRESULT CALLBACK ConsoleWindowProc(_In_ HWND, + _In_ UINT uMsg, + _In_ WPARAM wParam, + _In_ LPARAM lParam); // Wndproc helpers void _HandleDrop(const WPARAM wParam) const; - [[nodiscard]] - HRESULT _HandlePaint() const; + [[nodiscard]] HRESULT _HandlePaint() const; void _HandleWindowPosChanged(const LPARAM lParam); // Accessibility/UI Automation - [[nodiscard]] - LRESULT _HandleGetObject(const HWND hwnd, - const WPARAM wParam, - const LPARAM lParam); + [[nodiscard]] LRESULT _HandleGetObject(const HWND hwnd, + const WPARAM wParam, + const LPARAM lParam); IRawElementProviderSimple* _GetUiaProvider(); WindowUiaProvider* _pUiaProvider = nullptr; // Dynamic Settings helpers - [[nodiscard]] - static LRESULT s_RegPersistWindowPos(_In_ PCWSTR const pwszTitle, - const BOOL fAutoPos, - const Window* const pWindow); - [[nodiscard]] - static LRESULT s_RegPersistWindowOpacity(_In_ PCWSTR const pwszTitle, - const Window* const pWindow); + [[nodiscard]] static LRESULT s_RegPersistWindowPos(_In_ PCWSTR const pwszTitle, + const BOOL fAutoPos, + const Window* const pWindow); + [[nodiscard]] static LRESULT s_RegPersistWindowOpacity(_In_ PCWSTR const pwszTitle, + const Window* const pWindow); // The size/position of the window on the most recent update. // This is remembered so we can figure out which @@ -183,6 +169,6 @@ namespace Microsoft::Console::Interactivity::Win32 bool _fInDPIChange = false; static void s_ConvertWindowPosToWindowRect(const LPWINDOWPOS lpWindowPos, - _Out_ RECT* const prc); + _Out_ RECT* const prc); }; } diff --git a/src/interactivity/win32/windowUiaProvider.cpp b/src/interactivity/win32/windowUiaProvider.cpp index c831144b3..89806da35 100644 --- a/src/interactivity/win32/windowUiaProvider.cpp +++ b/src/interactivity/win32/windowUiaProvider.cpp @@ -18,7 +18,6 @@ WindowUiaProvider::WindowUiaProvider() : _pScreenInfoProvider{ nullptr }, _cRefs(1) { - } WindowUiaProvider::~WindowUiaProvider() @@ -61,8 +60,7 @@ WindowUiaProvider* WindowUiaProvider::Create() } } -[[nodiscard]] -HRESULT WindowUiaProvider::Signal(_In_ EVENTID id) +[[nodiscard]] HRESULT WindowUiaProvider::Signal(_In_ EVENTID id) { HRESULT hr = S_OK; @@ -106,8 +104,7 @@ HRESULT WindowUiaProvider::Signal(_In_ EVENTID id) return hr; } -[[nodiscard]] -HRESULT WindowUiaProvider::SetTextAreaFocus() +[[nodiscard]] HRESULT WindowUiaProvider::SetTextAreaFocus() { try { @@ -118,13 +115,15 @@ HRESULT WindowUiaProvider::SetTextAreaFocus() #pragma region IUnknown -IFACEMETHODIMP_(ULONG) WindowUiaProvider::AddRef() +IFACEMETHODIMP_(ULONG) +WindowUiaProvider::AddRef() { Tracing::s_TraceUia(this, ApiCall::AddRef, nullptr); return InterlockedIncrement(&_cRefs); } -IFACEMETHODIMP_(ULONG) WindowUiaProvider::Release() +IFACEMETHODIMP_(ULONG) +WindowUiaProvider::Release() { Tracing::s_TraceUia(this, ApiCall::Release, nullptr); long val = InterlockedDecrement(&_cRefs); @@ -259,7 +258,7 @@ IFACEMETHODIMP WindowUiaProvider::get_HostRawElementProvider(_COM_Outptr_result_ const HWND hwnd = _GetWindowHandle(); return UiaHostProviderFromHwnd(hwnd, ppProvider); } - catch(...) + catch (...) { return static_cast(UIA_E_ELEMENTNOTAVAILABLE); } @@ -379,8 +378,7 @@ HWND WindowUiaProvider::_GetWindowHandle() const return pIConsoleWindow->GetWindowHandle(); } -[[nodiscard]] -HRESULT WindowUiaProvider::_EnsureValidHwnd() const +[[nodiscard]] HRESULT WindowUiaProvider::_EnsureValidHwnd() const { try { diff --git a/src/interactivity/win32/windowUiaProvider.hpp b/src/interactivity/win32/windowUiaProvider.hpp index c4e4a436c..a14135e21 100644 --- a/src/interactivity/win32/windowUiaProvider.hpp +++ b/src/interactivity/win32/windowUiaProvider.hpp @@ -27,29 +27,30 @@ namespace Microsoft::Console::Interactivity::Win32 class Window; class ScreenInfoUiaProvider; - class WindowUiaProvider final : public IRawElementProviderSimple, - public IRawElementProviderFragment, - public IRawElementProviderFragmentRoot + class WindowUiaProvider final : + public IRawElementProviderSimple, + public IRawElementProviderFragment, + public IRawElementProviderFragmentRoot { public: static WindowUiaProvider* Create(); virtual ~WindowUiaProvider(); - [[nodiscard]] - HRESULT Signal(_In_ EVENTID id); - [[nodiscard]] - HRESULT SetTextAreaFocus(); + [[nodiscard]] HRESULT Signal(_In_ EVENTID id); + [[nodiscard]] HRESULT SetTextAreaFocus(); // IUnknown methods - IFACEMETHODIMP_(ULONG) AddRef(); - IFACEMETHODIMP_(ULONG) Release(); + IFACEMETHODIMP_(ULONG) + AddRef(); + IFACEMETHODIMP_(ULONG) + Release(); IFACEMETHODIMP QueryInterface(_In_ REFIID riid, - _COM_Outptr_result_maybenull_ void** ppInterface); + _COM_Outptr_result_maybenull_ void** ppInterface); // IRawElementProviderSimple methods IFACEMETHODIMP get_ProviderOptions(_Out_ ProviderOptions* pOptions); IFACEMETHODIMP GetPatternProvider(_In_ PATTERNID iid, - _COM_Outptr_result_maybenull_ IUnknown** ppInterface); + _COM_Outptr_result_maybenull_ IUnknown** ppInterface); IFACEMETHODIMP GetPropertyValue(_In_ PROPERTYID idProp, _Out_ VARIANT* pVariant); IFACEMETHODIMP get_HostRawElementProvider(_COM_Outptr_result_maybenull_ IRawElementProviderSimple** ppProvider); @@ -73,11 +74,9 @@ namespace Microsoft::Console::Interactivity::Win32 WindowUiaProvider(); HWND _GetWindowHandle() const; - [[nodiscard]] - HRESULT _EnsureValidHwnd() const; + [[nodiscard]] HRESULT _EnsureValidHwnd() const; static IConsoleWindow* const _getIConsoleWindow(); - // this is used to prevent the object from // signaling an event while it is already in the // process of signalling another event. diff --git a/src/interactivity/win32/windowdpiapi.cpp b/src/interactivity/win32/windowdpiapi.cpp index d771957f1..85ea5a53b 100644 --- a/src/interactivity/win32/windowdpiapi.cpp +++ b/src/interactivity/win32/windowdpiapi.cpp @@ -11,8 +11,7 @@ using namespace Microsoft::Console::Interactivity::Win32; #pragma region IHighDpiApi Members -[[nodiscard]] -HRESULT WindowDpiApi::SetProcessPerMonitorDpiAwareness() +[[nodiscard]] HRESULT WindowDpiApi::SetProcessPerMonitorDpiAwareness() { return SetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE); } @@ -32,7 +31,7 @@ BOOL WindowDpiApi::EnablePerMonitorDialogScaling() if (!fTried) { - pfnFunc = GetProcAddress(_hUser32, "EnablePerMonitorDialogScaling"); + pfnFunc = GetProcAddress(_hUser32, "EnablePerMonitorDialogScaling"); if (pfnFunc == nullptr) { @@ -62,7 +61,7 @@ BOOL WindowDpiApi::SetProcessDpiAwarenessContext(_In_ DPI_AWARENESS_CONTEXT dpiC #ifdef CON_DPIAPI_INDIRECT if (_hUser32 != nullptr) { - typedef int(WINAPI *PfnSetProcessDpiAwarenessContexts)(DPI_AWARENESS_CONTEXT dpiContext); + typedef int(WINAPI * PfnSetProcessDpiAwarenessContexts)(DPI_AWARENESS_CONTEXT dpiContext); static bool fTried = false; static PfnSetProcessDpiAwarenessContexts pfn = nullptr; @@ -78,7 +77,6 @@ BOOL WindowDpiApi::SetProcessDpiAwarenessContext(_In_ DPI_AWARENESS_CONTEXT dpiC { return pfn(dpiContext); } - } return FALSE; @@ -92,7 +90,7 @@ BOOL WindowDpiApi::EnableChildWindowDpiMessage(const HWND hwnd, const BOOL fEnab #ifdef CON_DPIAPI_INDIRECT if (_hUser32 != nullptr) { - typedef BOOL(WINAPI *PfnEnableChildWindowDpiMessage)(HWND hwnd, BOOL fEnable); + typedef BOOL(WINAPI * PfnEnableChildWindowDpiMessage)(HWND hwnd, BOOL fEnable); static bool fTried = false; static PfnEnableChildWindowDpiMessage pfn = nullptr; @@ -131,7 +129,7 @@ BOOL WindowDpiApi::AdjustWindowRectExForDpi(_Inout_ LPRECT const lpRect, #ifdef CON_DPIAPI_INDIRECT if (_hUser32 != nullptr) { - typedef BOOL(WINAPI *PfnAdjustWindowRectExForDpi)(LPRECT lpRect, DWORD dwStyle, BOOL bMenu, DWORD dwExStyle, int dpi); + typedef BOOL(WINAPI * PfnAdjustWindowRectExForDpi)(LPRECT lpRect, DWORD dwStyle, BOOL bMenu, DWORD dwExStyle, int dpi); static bool fTried = false; static PfnAdjustWindowRectExForDpi pfn = nullptr; @@ -167,7 +165,7 @@ int WindowDpiApi::GetWindowDPI(const HWND hwnd) #ifdef CON_DPIAPI_INDIRECT if (_hUser32 != nullptr) { - typedef int(WINAPI *PfnGetWindowDPI)(HWND hwnd); + typedef int(WINAPI * PfnGetWindowDPI)(HWND hwnd); static bool fTried = false; static PfnGetWindowDPI pfn = nullptr; @@ -203,7 +201,7 @@ int WindowDpiApi::GetSystemMetricsForDpi(const int nIndex, const UINT dpi) #ifdef CON_DPIAPI_INDIRECT if (_hUser32 != nullptr) { - typedef int(WINAPI *PfnGetDpiMetrics)(int nIndex, int dpi); + typedef int(WINAPI * PfnGetDpiMetrics)(int nIndex, int dpi); static bool fTried = false; static PfnGetDpiMetrics pfn = nullptr; @@ -226,7 +224,6 @@ int WindowDpiApi::GetSystemMetricsForDpi(const int nIndex, const UINT dpi) { return pfn(nIndex, dpi); } - } return GetSystemMetrics(nIndex); diff --git a/src/interactivity/win32/windowdpiapi.hpp b/src/interactivity/win32/windowdpiapi.hpp index 83321f139..4b5497ff2 100644 --- a/src/interactivity/win32/windowdpiapi.hpp +++ b/src/interactivity/win32/windowdpiapi.hpp @@ -23,16 +23,17 @@ Author(s): DECLARE_HANDLE(DPI_AWARENESS_CONTEXT); -typedef enum DPI_AWARENESS { +typedef enum DPI_AWARENESS +{ DPI_AWARENESS_INVALID = -1, DPI_AWARENESS_UNAWARE = 0, DPI_AWARENESS_SYSTEM_AWARE = 1, DPI_AWARENESS_PER_MONITOR_AWARE = 2 } DPI_AWARENESS; -#define DPI_AWARENESS_CONTEXT_UNAWARE ((DPI_AWARENESS_CONTEXT)-1) -#define DPI_AWARENESS_CONTEXT_SYSTEM_AWARE ((DPI_AWARENESS_CONTEXT)-2) -#define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE ((DPI_AWARENESS_CONTEXT)-3) +#define DPI_AWARENESS_CONTEXT_UNAWARE ((DPI_AWARENESS_CONTEXT)-1) +#define DPI_AWARENESS_CONTEXT_SYSTEM_AWARE ((DPI_AWARENESS_CONTEXT)-2) +#define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE ((DPI_AWARENESS_CONTEXT)-3) #endif @@ -49,23 +50,22 @@ namespace Microsoft::Console::Interactivity::Win32 public: // IHighDpi Interface BOOL SetProcessDpiAwarenessContext(); - [[nodiscard]] - HRESULT SetProcessPerMonitorDpiAwareness(); + [[nodiscard]] HRESULT SetProcessPerMonitorDpiAwareness(); BOOL EnablePerMonitorDialogScaling(); // Module-internal Functions BOOL SetProcessDpiAwarenessContext(_In_ DPI_AWARENESS_CONTEXT dpiContext); BOOL EnableChildWindowDpiMessage(const HWND hwnd, - const BOOL fEnable); + const BOOL fEnable); BOOL AdjustWindowRectExForDpi(_Inout_ LPRECT const lpRect, - const DWORD dwStyle, - const BOOL bMenu, - const DWORD dwExStyle, - const UINT dpi); + const DWORD dwStyle, + const BOOL bMenu, + const DWORD dwExStyle, + const UINT dpi); int GetWindowDPI(const HWND hwnd); int GetSystemMetricsForDpi(const int nIndex, - const UINT dpi); + const UINT dpi); #ifdef CON_DPIAPI_INDIRECT WindowDpiApi(); diff --git a/src/interactivity/win32/windowio.cpp b/src/interactivity/win32/windowio.cpp index d01fc1d95..921f3f011 100644 --- a/src/interactivity/win32/windowio.cpp +++ b/src/interactivity/win32/windowio.cpp @@ -94,9 +94,9 @@ VOID SetConsoleWindowOwner(const HWND hwnd, _Inout_opt_ ConsoleProcessHandle* pP // Comment out this line to enable UIA tree to be visible until UIAutomationCore.dll can support our scenario. LOG_IF_FAILED(ServiceLocator::LocateConsoleControl() - ->Control(ConsoleControl::ControlType::ConsoleSetWindowOwner, - &ConsoleOwner, - sizeof(ConsoleOwner))); + ->Control(ConsoleControl::ControlType::ConsoleSetWindowOwner, + &ConsoleOwner, + sizeof(ConsoleOwner))); } // ---------------------------- @@ -358,7 +358,6 @@ void HandleKeyEvent(const HWND hWnd, ServiceLocator::LocateConsoleWindow()->ChangeWindowOpacity(opacityDelta); return; } - } } } @@ -475,7 +474,7 @@ BOOL HandleSysKeyEvent(const HWND hWnd, const UINT Message, const WPARAM wParam, if (VirtualKeyCode == VK_ESCAPE && bCtrlDown && !(GetKeyState(VK_MENU) & KEY_PRESSED) && !(GetKeyState(VK_SHIFT) & KEY_PRESSED)) { - return TRUE; // call DefWindowProc + return TRUE; // call DefWindowProc } // check for alt-f4 @@ -485,12 +484,11 @@ BOOL HandleSysKeyEvent(const HWND hWnd, const UINT Message, const WPARAM wParam, } if (WI_IsFlagClear(lParam, WM_SYSKEYDOWN_ALT_PRESSED)) - { // we're iconic + { // we're iconic // Check for ENTER while iconic (restore accelerator). if (VirtualKeyCode == VK_RETURN) { - - return TRUE; // call DefWindowProc + return TRUE; // call DefWindowProc } else { @@ -521,16 +519,16 @@ BOOL HandleSysKeyEvent(const HWND hWnd, const UINT Message, const WPARAM wParam, return FALSE; } - return TRUE; // call DefWindowProc + return TRUE; // call DefWindowProc } if (VirtualKeyCode == VK_ESCAPE) { - return TRUE; // call DefWindowProc + return TRUE; // call DefWindowProc } if (VirtualKeyCode == VK_TAB) { - return TRUE; // call DefWindowProc + return TRUE; // call DefWindowProc } } @@ -539,8 +537,7 @@ BOOL HandleSysKeyEvent(const HWND hWnd, const UINT Message, const WPARAM wParam, return FALSE; } -[[nodiscard]] -static HRESULT _AdjustFontSize(const SHORT delta) noexcept +[[nodiscard]] static HRESULT _AdjustFontSize(const SHORT delta) noexcept { auto& globals = ServiceLocator::LocateGlobals(); auto& screenInfo = globals.getConsoleInformation().GetActiveOutputBuffer(); @@ -779,7 +776,6 @@ BOOL HandleMouseEvent(const SCREEN_INFORMATION& ScreenInfo, MousePosition = wordBounds.second; // update both ends of the selection since we may have adjusted the anchor in some circumstances. pSelection->AdjustSelection(wordBounds.first, wordBounds.second); - } catch (...) { @@ -917,7 +913,7 @@ BOOL HandleMouseEvent(const SCREEN_INFORMATION& ScreenInfo, EventFlags); EventsWritten = static_cast(gci.pInputBuffer->Write(std::move(mouseEvent))); } - catch(...) + catch (...) { LOG_HR(wil::ResultFromCaughtException()); EventsWritten = 0; @@ -947,7 +943,6 @@ LRESULT CALLBACK DialogHookProc(int nCode, WPARAM /*wParam*/, LPARAM lParam) { if (msg.message != WM_CHAR && msg.message != WM_DEADCHAR && msg.message != WM_SYSCHAR && msg.message != WM_SYSDEADCHAR) { - // don't store key info if dialog box input if (GetWindowLongPtrW(msg.hwnd, GWLP_HWNDPARENT) == 0) { @@ -962,7 +957,7 @@ LRESULT CALLBACK DialogHookProc(int nCode, WPARAM /*wParam*/, LPARAM lParam) // Routine Description: // - This routine gets called by the console input thread to set up the console window. -NTSTATUS InitWindowsSubsystem(_Out_ HHOOK * phhook) +NTSTATUS InitWindowsSubsystem(_Out_ HHOOK* phhook) { CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); ConsoleProcessHandle* ProcessData = gci.ProcessHandleList.FindProcessInList(ConsoleProcessList::ROOT_PROCESS_ID); diff --git a/src/interactivity/win32/windowproc.cpp b/src/interactivity/win32/windowproc.cpp index 21a73a6a3..5957eb65f 100644 --- a/src/interactivity/win32/windowproc.cpp +++ b/src/interactivity/win32/windowproc.cpp @@ -32,15 +32,13 @@ #include #include - using namespace Microsoft::Console::Interactivity::Win32; using namespace Microsoft::Console::Types; // The static and specific window procedures for this class are contained here #pragma region Window Procedure -[[nodiscard]] -LRESULT CALLBACK Window::s_ConsoleWindowProc(_In_ HWND hWnd, _In_ UINT Message, _In_ WPARAM wParam, _In_ LPARAM lParam) +[[nodiscard]] LRESULT CALLBACK Window::s_ConsoleWindowProc(_In_ HWND hWnd, _In_ UINT Message, _In_ WPARAM wParam, _In_ LPARAM lParam) { // Save the pointer here to the specific window instance when one is created if (Message == WM_CREATE) @@ -62,8 +60,7 @@ LRESULT CALLBACK Window::s_ConsoleWindowProc(_In_ HWND hWnd, _In_ UINT Message, return DefWindowProcW(hWnd, Message, wParam, lParam); } -[[nodiscard]] -LRESULT CALLBACK Window::ConsoleWindowProc(_In_ HWND hWnd, _In_ UINT Message, _In_ WPARAM wParam, _In_ LPARAM lParam) +[[nodiscard]] LRESULT CALLBACK Window::ConsoleWindowProc(_In_ HWND hWnd, _In_ UINT Message, _In_ WPARAM wParam, _In_ LPARAM lParam) { Globals& g = ServiceLocator::LocateGlobals(); CONSOLE_INFORMATION& gci = g.getConsoleInformation(); @@ -194,7 +191,7 @@ LRESULT CALLBACK Window::ConsoleWindowProc(_In_ HWND hWnd, _In_ UINT Message, _I // GetProposedFont can fail if there's no render engine yet. // This can happen if we're headless. // Just assume that the font is 1x1 in that case. - const COORD coordFontProposed = SUCCEEDED(hr) ? fiProposed.GetSize() : COORD({1, 1}); + const COORD coordFontProposed = SUCCEEDED(hr) ? fiProposed.GetSize() : COORD({ 1, 1 }); // Then from that font size, we need to calculate the client area. // Then from the client area we need to calculate the window area (using the proposed DPI scalar here as well.) @@ -347,7 +344,7 @@ LRESULT CALLBACK Window::ConsoleWindowProc(_In_ HWND hWnd, _In_ UINT Message, _I gci.GetCursorBlinker().SettingsChanged(); } - __fallthrough; + __fallthrough; case WM_DISPLAYCHANGE: { @@ -492,7 +489,10 @@ LRESULT CALLBACK Window::ConsoleWindowProc(_In_ HWND hWnd, _In_ UINT Message, _I TrackPopupMenuEx(hHeirMenu, TPM_RIGHTBUTTON | (GetSystemMetrics(SM_MENUDROPALIGNMENT) == 0 ? TPM_LEFTALIGN : TPM_RIGHTALIGN), - GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), hWnd, nullptr); + GET_X_LPARAM(lParam), + GET_Y_LPARAM(lParam), + hWnd, + nullptr); } else { @@ -649,13 +649,13 @@ LRESULT CALLBACK Window::ConsoleWindowProc(_In_ HWND hWnd, _In_ UINT Message, _I Status = 1; - bool isMouseWheel = Message == WM_MOUSEWHEEL; + bool isMouseWheel = Message == WM_MOUSEWHEEL; bool isMouseHWheel = Message == WM_MOUSEHWHEEL; if (isMouseWheel || isMouseHWheel) { short wheelDelta = (short)HIWORD(wParam); - bool hasShift = (wParam & MK_SHIFT) ? true : false; + bool hasShift = (wParam & MK_SHIFT) ? true : false; Scrolling::s_HandleMouseWheel(isMouseWheel, isMouseHWheel, @@ -821,8 +821,7 @@ void Window::_HandleWindowPosChanged(const LPARAM lParam) // - // Return Value: // - S_OK if we succeeded. ERROR_INVALID_HANDLE if there is no HWND. E_FAIL if GDI failed for some reason. -[[nodiscard]] -HRESULT Window::_HandlePaint() const +[[nodiscard]] HRESULT Window::_HandlePaint() const { HWND const hwnd = GetWindowHandle(); RETURN_HR_IF_NULL(HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE), hwnd); @@ -888,8 +887,7 @@ void Window::_HandleDrop(const WPARAM wParam) const } } -[[nodiscard]] -LRESULT Window::_HandleGetObject(const HWND hwnd, const WPARAM wParam, const LPARAM lParam) +[[nodiscard]] LRESULT Window::_HandleGetObject(const HWND hwnd, const WPARAM wParam, const LPARAM lParam) { LRESULT retVal = 0; diff --git a/src/interactivity/win32/windowtheme.cpp b/src/interactivity/win32/windowtheme.cpp index 5ca98a213..a1e58069f 100644 --- a/src/interactivity/win32/windowtheme.cpp +++ b/src/interactivity/win32/windowtheme.cpp @@ -24,15 +24,14 @@ WindowTheme::WindowTheme() } // Routine Description: -// - Attempts to set the dark mode on the given HWND. +// - Attempts to set the dark mode on the given HWND. // - Will check the system for user preferences and high contrast to see if it's a good idea // before setting it. // Arguments: // - hwnd - Window to apply dark mode to // Return Value: // - S_OK or suitable HRESULT from theming or DWM engines. -[[nodiscard]] -HRESULT WindowTheme::TrySetDarkMode(HWND hwnd) const noexcept +[[nodiscard]] HRESULT WindowTheme::TrySetDarkMode(HWND hwnd) const noexcept { // I have to be a big B BOOL or DwnSetWindowAttribute will be upset (E_INVALIDARG) when I am passed in. const BOOL isDarkMode = !!_IsDarkMode(); @@ -97,7 +96,7 @@ bool WindowTheme::_ShouldAppsUseDarkMode() const noexcept { if (_module.get() != nullptr) { - typedef bool(WINAPI *PfnShouldAppsUseDarkMode)(); + typedef bool(WINAPI * PfnShouldAppsUseDarkMode)(); static bool tried = false; static PfnShouldAppsUseDarkMode pfn = nullptr; diff --git a/src/interactivity/win32/windowtheme.hpp b/src/interactivity/win32/windowtheme.hpp index d4a25b97a..701b55cc2 100644 --- a/src/interactivity/win32/windowtheme.hpp +++ b/src/interactivity/win32/windowtheme.hpp @@ -20,8 +20,7 @@ namespace Microsoft::Console::Interactivity::Win32 public: WindowTheme(); - [[nodiscard]] - HRESULT TrySetDarkMode(HWND hwnd) const noexcept; + [[nodiscard]] HRESULT TrySetDarkMode(HWND hwnd) const noexcept; private: bool _IsDarkMode() const noexcept; diff --git a/src/internal/precomp.h b/src/internal/precomp.h index 7a6c2dda0..77ebd3b4e 100644 --- a/src/internal/precomp.h +++ b/src/internal/precomp.h @@ -16,7 +16,7 @@ Abstract: #include "LibraryIncludes.h" #ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers +#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers #endif // Windows Header Files: diff --git a/src/internal/stubs.cpp b/src/internal/stubs.cpp index 1636497fb..cf4569892 100644 --- a/src/internal/stubs.cpp +++ b/src/internal/stubs.cpp @@ -7,17 +7,15 @@ using namespace Microsoft::Console::Internal; -[[nodiscard]] -HRESULT ProcessPolicy::CheckAppModelPolicy(const HANDLE /*hToken*/, - bool& fIsWrongWayBlocked) noexcept +[[nodiscard]] HRESULT ProcessPolicy::CheckAppModelPolicy(const HANDLE /*hToken*/, + bool& fIsWrongWayBlocked) noexcept { fIsWrongWayBlocked = false; return S_OK; } -[[nodiscard]] -HRESULT ProcessPolicy::CheckIntegrityLevelPolicy(const HANDLE /*hOtherToken*/, - bool& fIsWrongWayBlocked) noexcept +[[nodiscard]] HRESULT ProcessPolicy::CheckIntegrityLevelPolicy(const HANDLE /*hOtherToken*/, + bool& fIsWrongWayBlocked) noexcept { fIsWrongWayBlocked = false; return S_OK; @@ -26,4 +24,3 @@ HRESULT ProcessPolicy::CheckIntegrityLevelPolicy(const HANDLE /*hOtherToken*/, void EdpPolicy::AuditClipboard(const std::wstring_view /*destinationName*/) noexcept { } - diff --git a/src/propsheet/ColorControl.cpp b/src/propsheet/ColorControl.cpp index ca9683693..d0fd6d131 100644 --- a/src/propsheet/ColorControl.cpp +++ b/src/propsheet/ColorControl.cpp @@ -33,7 +33,8 @@ void SimpleColorDoPaint(const HWND hColor, PAINTSTRUCT& ps, const int ColorId) GetClientRect(hColor, &rColor); rgbBrush = GetNearestColor(ps.hdc, GetColorForItem(ColorId)); - if ((hbr = CreateSolidBrush(rgbBrush)) != NULL) { + if ((hbr = CreateSolidBrush(rgbBrush)) != NULL) + { InflateRect(&rColor, -1, -1); FillRect(ps.hdc, &rColor, hbr); DeleteObject(hbr); @@ -42,8 +43,7 @@ void SimpleColorDoPaint(const HWND hColor, PAINTSTRUCT& ps, const int ColorId) // Routine Description: // - Window proc for the color buttons -[[nodiscard]] -LRESULT CALLBACK SimpleColorControlProc(const HWND hColor, const UINT wMsg, const WPARAM wParam, const LPARAM lParam) +[[nodiscard]] LRESULT CALLBACK SimpleColorControlProc(const HWND hColor, const UINT wMsg, const WPARAM wParam, const LPARAM lParam) { PAINTSTRUCT ps; int ColorId; @@ -52,18 +52,19 @@ LRESULT CALLBACK SimpleColorControlProc(const HWND hColor, const UINT wMsg, cons ColorId = GetWindowLong(hColor, GWL_ID); hDlg = GetParent(hColor); - switch (wMsg) { - case WM_GETDLGCODE: - return DLGC_WANTARROWS | DLGC_WANTTAB; - break; - case WM_PAINT: - BeginPaint(hColor, &ps); - SimpleColorDoPaint(hColor, ps, ColorId); - EndPaint(hColor, &ps); - break; - default: - return DefWindowProc(hColor, wMsg, wParam, lParam); - break; + switch (wMsg) + { + case WM_GETDLGCODE: + return DLGC_WANTARROWS | DLGC_WANTTAB; + break; + case WM_PAINT: + BeginPaint(hColor, &ps); + SimpleColorDoPaint(hColor, ps, ColorId); + EndPaint(hColor, &ps); + break; + default: + return DefWindowProc(hColor, wMsg, wParam, lParam); + break; } return TRUE; } diff --git a/src/propsheet/ColorControl.h b/src/propsheet/ColorControl.h index fc236f85f..b66a52453 100644 --- a/src/propsheet/ColorControl.h +++ b/src/propsheet/ColorControl.h @@ -14,6 +14,5 @@ Author(s): #pragma once -[[nodiscard]] -LRESULT CALLBACK SimpleColorControlProc(HWND hColor, UINT wMsg, WPARAM wParam, LPARAM lParam); +[[nodiscard]] LRESULT CALLBACK SimpleColorControlProc(HWND hColor, UINT wMsg, WPARAM wParam, LPARAM lParam); void SimpleColorDoPaint(HWND hColor, PAINTSTRUCT& ps, int ColorId); diff --git a/src/propsheet/ColorsPage.cpp b/src/propsheet/ColorsPage.cpp index 2d4c3d48d..f96e3ac6c 100644 --- a/src/propsheet/ColorsPage.cpp +++ b/src/propsheet/ColorsPage.cpp @@ -10,8 +10,7 @@ static int iColor; // Routine Description: // - Window proc for the color buttons -[[nodiscard]] -LRESULT CALLBACK ColorTableControlProc(HWND hColor, UINT wMsg, WPARAM wParam, LPARAM lParam) +[[nodiscard]] LRESULT CALLBACK ColorTableControlProc(HWND hColor, UINT wMsg, WPARAM wParam, LPARAM lParam) { PAINTSTRUCT ps; int ColorId; @@ -24,75 +23,78 @@ LRESULT CALLBACK ColorTableControlProc(HWND hColor, UINT wMsg, WPARAM wParam, LP ColorId = GetWindowLong(hColor, GWL_ID); hDlg = GetParent(hColor); - switch (wMsg) { - case WM_SETFOCUS: - if (ColorArray[iColor] != (BYTE)(ColorId - IDD_COLOR_1)) { - hWnd = GetDlgItem(hDlg, ColorArray[iColor]+IDD_COLOR_1); - SetFocus(hWnd); + switch (wMsg) + { + case WM_SETFOCUS: + if (ColorArray[iColor] != (BYTE)(ColorId - IDD_COLOR_1)) + { + hWnd = GetDlgItem(hDlg, ColorArray[iColor] + IDD_COLOR_1); + SetFocus(hWnd); + } + __fallthrough; + case WM_KILLFOCUS: + hdc = GetDC(hDlg); + hWnd = GetDlgItem(hDlg, IDD_COLOR_1); + GetWindowRect(hWnd, &rColor); + hWnd = GetDlgItem(hDlg, IDD_COLOR_16); + GetWindowRect(hWnd, &rTemp); + rColor.right = rTemp.right; + ScreenToClient(hDlg, (LPPOINT)&rColor.left); + ScreenToClient(hDlg, (LPPOINT)&rColor.right); + InflateRect(&rColor, 2, 2); + DrawFocusRect(hdc, &rColor); + ReleaseDC(hDlg, hdc); + break; + case WM_KEYDOWN: + switch (wParam) + { + case VK_UP: + case VK_LEFT: + if (ColorId > IDD_COLOR_1) + { + SendMessage(hDlg, CM_SETCOLOR, ColorId - 1 - IDD_COLOR_1, (LPARAM)hColor); } - __fallthrough; - case WM_KILLFOCUS: - hdc = GetDC(hDlg); + break; + case VK_DOWN: + case VK_RIGHT: + if (ColorId < IDD_COLOR_16) + { + SendMessage(hDlg, CM_SETCOLOR, ColorId + 1 - IDD_COLOR_1, (LPARAM)hColor); + } + break; + case VK_TAB: hWnd = GetDlgItem(hDlg, IDD_COLOR_1); - GetWindowRect(hWnd, &rColor); - hWnd = GetDlgItem(hDlg, IDD_COLOR_16); - GetWindowRect(hWnd, &rTemp); - rColor.right = rTemp.right; - ScreenToClient(hDlg, (LPPOINT)&rColor.left); - ScreenToClient(hDlg, (LPPOINT)&rColor.right); - InflateRect(&rColor, 2, 2); - DrawFocusRect(hdc, &rColor); - ReleaseDC(hDlg, hdc); - break; - case WM_KEYDOWN: - switch (wParam) { - case VK_UP: - case VK_LEFT: - if (ColorId > IDD_COLOR_1) { - SendMessage(hDlg, CM_SETCOLOR, - ColorId - 1 - IDD_COLOR_1, (LPARAM)hColor); - } - break; - case VK_DOWN: - case VK_RIGHT: - if (ColorId < IDD_COLOR_16) { - SendMessage(hDlg, CM_SETCOLOR, - ColorId + 1 - IDD_COLOR_1, (LPARAM)hColor); - } - break; - case VK_TAB: - hWnd = GetDlgItem(hDlg, IDD_COLOR_1); - hWnd = GetNextDlgTabItem(hDlg, hWnd, GetKeyState(VK_SHIFT) < 0); - SetFocus(hWnd); - break; - default: - return DefWindowProc(hColor, wMsg, wParam, lParam); - } - break; - case WM_RBUTTONDOWN: - case WM_LBUTTONDOWN: - SendMessage(hDlg, CM_SETCOLOR, - ColorId - IDD_COLOR_1, (LPARAM)hColor); - break; - case WM_PAINT: - - BeginPaint(hColor, &ps); - GetClientRect(hColor, &rColor); - - // are we the selected color for the current object? - if (ColorArray[iColor] == (BYTE)(ColorId - IDD_COLOR_1)) { - // highlight the selected color - FrameRect(ps.hdc, &rColor, (HBRUSH)GetStockObject(BLACK_BRUSH)); - InflateRect(&rColor, -1, -1); - FrameRect(ps.hdc, &rColor, (HBRUSH)GetStockObject(BLACK_BRUSH)); - } - - SimpleColorDoPaint(hColor, ps, ColorId); - EndPaint(hColor, &ps); + hWnd = GetNextDlgTabItem(hDlg, hWnd, GetKeyState(VK_SHIFT) < 0); + SetFocus(hWnd); break; default: - return SimpleColorControlProc(hColor, wMsg, wParam, lParam); - break; + return DefWindowProc(hColor, wMsg, wParam, lParam); + } + break; + case WM_RBUTTONDOWN: + case WM_LBUTTONDOWN: + SendMessage(hDlg, CM_SETCOLOR, ColorId - IDD_COLOR_1, (LPARAM)hColor); + break; + case WM_PAINT: + + BeginPaint(hColor, &ps); + GetClientRect(hColor, &rColor); + + // are we the selected color for the current object? + if (ColorArray[iColor] == (BYTE)(ColorId - IDD_COLOR_1)) + { + // highlight the selected color + FrameRect(ps.hdc, &rColor, (HBRUSH)GetStockObject(BLACK_BRUSH)); + InflateRect(&rColor, -1, -1); + FrameRect(ps.hdc, &rColor, (HBRUSH)GetStockObject(BLACK_BRUSH)); + } + + SimpleColorDoPaint(hColor, ps, ColorId); + EndPaint(hColor, &ps); + break; + default: + return SimpleColorControlProc(hColor, wMsg, wParam, lParam); + break; } return TRUE; } @@ -100,14 +102,14 @@ LRESULT CALLBACK ColorTableControlProc(HWND hColor, UINT wMsg, WPARAM wParam, LP bool InitColorsDialog(HWND hDlg) { ColorArray[IDD_COLOR_SCREEN_TEXT - IDD_COLOR_SCREEN_TEXT] = - LOBYTE(gpStateInfo->ScreenAttributes) & 0x0F; + LOBYTE(gpStateInfo->ScreenAttributes) & 0x0F; ColorArray[IDD_COLOR_SCREEN_BKGND - IDD_COLOR_SCREEN_TEXT] = - LOBYTE(gpStateInfo->ScreenAttributes >> 4); + LOBYTE(gpStateInfo->ScreenAttributes >> 4); ColorArray[IDD_COLOR_POPUP_TEXT - IDD_COLOR_SCREEN_TEXT] = - LOBYTE(gpStateInfo->PopupAttributes) & 0x0F; + LOBYTE(gpStateInfo->PopupAttributes) & 0x0F; ColorArray[IDD_COLOR_POPUP_BKGND - IDD_COLOR_SCREEN_TEXT] = - LOBYTE(gpStateInfo->PopupAttributes >> 4); - CheckRadioButton(hDlg,IDD_COLOR_SCREEN_TEXT,IDD_COLOR_POPUP_BKGND,IDD_COLOR_SCREEN_BKGND); + LOBYTE(gpStateInfo->PopupAttributes >> 4); + CheckRadioButton(hDlg, IDD_COLOR_SCREEN_TEXT, IDD_COLOR_POPUP_BKGND, IDD_COLOR_SCREEN_BKGND); iColor = IDD_COLOR_SCREEN_BKGND - IDD_COLOR_SCREEN_TEXT; // initialize size of edit controls @@ -118,18 +120,12 @@ bool InitColorsDialog(HWND hDlg) // initialize arrow controls - SendDlgItemMessage(hDlg, IDD_COLOR_REDSCROLL, UDM_SETRANGE, 0, - MAKELONG(255, 0)); - SendDlgItemMessage(hDlg, IDD_COLOR_REDSCROLL, UDM_SETPOS, 0, - MAKELONG(GetRValue(AttrToRGB(ColorArray[iColor])), 0)); - SendDlgItemMessage(hDlg, IDD_COLOR_GREENSCROLL, UDM_SETRANGE, 0, - MAKELONG(255, 0)); - SendDlgItemMessage(hDlg, IDD_COLOR_GREENSCROLL, UDM_SETPOS, 0, - MAKELONG(GetGValue(AttrToRGB(ColorArray[iColor])), 0)); - SendDlgItemMessage(hDlg, IDD_COLOR_BLUESCROLL, UDM_SETRANGE, 0, - MAKELONG(255, 0)); - SendDlgItemMessage(hDlg, IDD_COLOR_BLUESCROLL, UDM_SETPOS, 0, - MAKELONG(GetBValue(AttrToRGB(ColorArray[iColor])), 0)); + SendDlgItemMessage(hDlg, IDD_COLOR_REDSCROLL, UDM_SETRANGE, 0, MAKELONG(255, 0)); + SendDlgItemMessage(hDlg, IDD_COLOR_REDSCROLL, UDM_SETPOS, 0, MAKELONG(GetRValue(AttrToRGB(ColorArray[iColor])), 0)); + SendDlgItemMessage(hDlg, IDD_COLOR_GREENSCROLL, UDM_SETRANGE, 0, MAKELONG(255, 0)); + SendDlgItemMessage(hDlg, IDD_COLOR_GREENSCROLL, UDM_SETPOS, 0, MAKELONG(GetGValue(AttrToRGB(ColorArray[iColor])), 0)); + SendDlgItemMessage(hDlg, IDD_COLOR_BLUESCROLL, UDM_SETRANGE, 0, MAKELONG(255, 0)); + SendDlgItemMessage(hDlg, IDD_COLOR_BLUESCROLL, UDM_SETPOS, 0, MAKELONG(GetBValue(AttrToRGB(ColorArray[iColor])), 0)); CreateAndAssociateToolTipToControl(IDD_TRANSPARENCY, hDlg, IDS_TOOLTIP_OPACITY); @@ -154,221 +150,238 @@ INT_PTR WINAPI ColorDlgProc(HWND hDlg, UINT wMsg, WPARAM wParam, LPARAM lParam) BOOL bOK; static bool fHaveInitialized = false; - switch (wMsg) { - case WM_INITDIALOG: + switch (wMsg) + { + case WM_INITDIALOG: + { + fHaveInitialized = true; + return InitColorsDialog(hDlg); + } + + case WM_COMMAND: + { + if (!fHaveInitialized) { - fHaveInitialized = true; - return InitColorsDialog(hDlg); + return FALSE; } - case WM_COMMAND: + Item = LOWORD(wParam); + switch (Item) { - if (!fHaveInitialized) { - return FALSE; + case IDD_COLOR_SCREEN_TEXT: + case IDD_COLOR_SCREEN_BKGND: + case IDD_COLOR_POPUP_TEXT: + case IDD_COLOR_POPUP_BKGND: + hWndOld = GetDlgItem(hDlg, ColorArray[iColor] + IDD_COLOR_1); + + iColor = Item - IDD_COLOR_SCREEN_TEXT; + + // repaint new color + hWnd = GetDlgItem(hDlg, ColorArray[iColor] + IDD_COLOR_1); + InvalidateRect(hWnd, NULL, TRUE); + + // repaint old color + if (hWndOld != hWnd) + { + InvalidateRect(hWndOld, NULL, TRUE); } - Item = LOWORD(wParam); - switch (Item) { - case IDD_COLOR_SCREEN_TEXT: - case IDD_COLOR_SCREEN_BKGND: - case IDD_COLOR_POPUP_TEXT: - case IDD_COLOR_POPUP_BKGND: - hWndOld = GetDlgItem(hDlg, ColorArray[iColor]+IDD_COLOR_1); + return TRUE; - iColor = Item - IDD_COLOR_SCREEN_TEXT; - - // repaint new color - hWnd = GetDlgItem(hDlg, ColorArray[iColor]+IDD_COLOR_1); - InvalidateRect(hWnd, NULL, TRUE); - - // repaint old color - if (hWndOld != hWnd) { - InvalidateRect(hWndOld, NULL, TRUE); - } - - return TRUE; - - case IDD_COLOR_RED: - case IDD_COLOR_GREEN: - case IDD_COLOR_BLUE: + case IDD_COLOR_RED: + case IDD_COLOR_GREEN: + case IDD_COLOR_BLUE: + { + switch (HIWORD(wParam)) + { + case EN_UPDATE: + if (!CheckNum(hDlg, Item)) { - switch (HIWORD(wParam)) { - case EN_UPDATE: - if (!CheckNum (hDlg, Item)) { - Undo((HWND)lParam); - } - break; + Undo((HWND)lParam); + } + break; - case EN_CHANGE: - /* + case EN_CHANGE: + /* * Update the state info structure */ - Value = GetDlgItemInt(hDlg, Item, &bOK, TRUE); - if (bOK) { - if (Value > 255) { - UpdateItem(hDlg, Item, 255); - Value = 255; - } - if (Item == IDD_COLOR_RED) { - Red = Value; - } else { - Red = GetRValue(AttrToRGB(ColorArray[iColor])); - } - if (Item == IDD_COLOR_GREEN) { - Green = Value; - } else { - Green = GetGValue(AttrToRGB(ColorArray[iColor])); - } - if (Item == IDD_COLOR_BLUE) { - Blue = Value; - } else { - Blue = GetBValue(AttrToRGB(ColorArray[iColor])); - } - UpdateStateInfo(hDlg, ColorArray[iColor] + IDD_COLOR_1, - RGB(Red, Green, Blue)); - UpdateApplyButton(hDlg); - } - __fallthrough; + Value = GetDlgItemInt(hDlg, Item, &bOK, TRUE); + if (bOK) + { + if (Value > 255) + { + UpdateItem(hDlg, Item, 255); + Value = 255; + } + if (Item == IDD_COLOR_RED) + { + Red = Value; + } + else + { + Red = GetRValue(AttrToRGB(ColorArray[iColor])); + } + if (Item == IDD_COLOR_GREEN) + { + Green = Value; + } + else + { + Green = GetGValue(AttrToRGB(ColorArray[iColor])); + } + if (Item == IDD_COLOR_BLUE) + { + Blue = Value; + } + else + { + Blue = GetBValue(AttrToRGB(ColorArray[iColor])); + } + UpdateStateInfo(hDlg, ColorArray[iColor] + IDD_COLOR_1, RGB(Red, Green, Blue)); + UpdateApplyButton(hDlg); + } + __fallthrough; - case EN_KILLFOCUS: - /* + case EN_KILLFOCUS: + /* * Update the preview windows with the new value */ - hWnd = GetDlgItem(hDlg, IDD_COLOR_SCREEN_COLORS); - InvalidateRect(hWnd, NULL, FALSE); - hWnd = GetDlgItem(hDlg, IDD_COLOR_POPUP_COLORS); - InvalidateRect(hWnd, NULL, FALSE); - hWnd = GetDlgItem(hDlg, ColorArray[iColor]+IDD_COLOR_1); - InvalidateRect(hWnd, NULL, FALSE); - break; - } - return TRUE; - } + hWnd = GetDlgItem(hDlg, IDD_COLOR_SCREEN_COLORS); + InvalidateRect(hWnd, NULL, FALSE); + hWnd = GetDlgItem(hDlg, IDD_COLOR_POPUP_COLORS); + InvalidateRect(hWnd, NULL, FALSE); + hWnd = GetDlgItem(hDlg, ColorArray[iColor] + IDD_COLOR_1); + InvalidateRect(hWnd, NULL, FALSE); + break; } - break; + return TRUE; } + } + break; + } - case WM_NOTIFY: + case WM_NOTIFY: + { + const PSHNOTIFY* const pshn = (LPPSHNOTIFY)lParam; + switch (pshn->hdr.code) { - const PSHNOTIFY * const pshn = (LPPSHNOTIFY)lParam; - switch (pshn->hdr.code) { - case PSN_APPLY: - /* + case PSN_APPLY: + /* * Write out the state values and exit. */ - // Ignore opacity in v1 console - if (g_fForceV2) - { - gpStateInfo->bWindowTransparency = (BYTE)SendDlgItemMessage(hDlg, IDD_TRANSPARENCY, TBM_GETPOS, 0, 0); - } + // Ignore opacity in v1 console + if (g_fForceV2) + { + gpStateInfo->bWindowTransparency = (BYTE)SendDlgItemMessage(hDlg, IDD_TRANSPARENCY, TBM_GETPOS, 0, 0); + } - EndDlgPage(hDlg, !pshn->lParam); - return TRUE; + EndDlgPage(hDlg, !pshn->lParam); + return TRUE; - case PSN_RESET: - // Ignore opacity in v1 console - if (g_fForceV2 && g_bPreviewOpacity != gpStateInfo->bWindowTransparency) - { - SetLayeredWindowAttributes(gpStateInfo->hWnd, 0, gpStateInfo->bWindowTransparency, LWA_ALPHA); - } + case PSN_RESET: + // Ignore opacity in v1 console + if (g_fForceV2 && g_bPreviewOpacity != gpStateInfo->bWindowTransparency) + { + SetLayeredWindowAttributes(gpStateInfo->hWnd, 0, gpStateInfo->bWindowTransparency, LWA_ALPHA); + } - return 0; + return 0; - case PSN_SETACTIVE: - ToggleV2ColorControls(hDlg); - return 0; + case PSN_SETACTIVE: + ToggleV2ColorControls(hDlg); + return 0; - case PSN_KILLACTIVE: - /* + case PSN_KILLACTIVE: + /* * Fake the dialog proc into thinking the edit control just * lost focus so it'll update properly */ - Item = GetDlgCtrlID(GetFocus()); - if (Item) - { - SendMessage(hDlg, WM_COMMAND, MAKELONG(Item, EN_KILLFOCUS), 0); - } - return TRUE; + Item = GetDlgCtrlID(GetFocus()); + if (Item) + { + SendMessage(hDlg, WM_COMMAND, MAKELONG(Item, EN_KILLFOCUS), 0); } - break; + return TRUE; } + break; + } - case WM_VSCROLL: - /* + case WM_VSCROLL: + /* * Fake the dialog proc into thinking the edit control just * lost focus so it'll update properly */ - Item = GetDlgCtrlID((HWND)lParam) - 1; - SendMessage(hDlg, WM_COMMAND, MAKELONG(Item, EN_KILLFOCUS), 0); - return TRUE; + Item = GetDlgCtrlID((HWND)lParam) - 1; + SendMessage(hDlg, WM_COMMAND, MAKELONG(Item, EN_KILLFOCUS), 0); + return TRUE; - case WM_HSCROLL: - if (IDD_TRANSPARENCY == GetDlgCtrlID((HWND) lParam)) + case WM_HSCROLL: + if (IDD_TRANSPARENCY == GetDlgCtrlID((HWND)lParam)) + { + switch (LOWORD(wParam)) { - switch (LOWORD(wParam)) - { - //When moving slider with the mouse - case TB_THUMBPOSITION: - case TB_THUMBTRACK: - g_bPreviewOpacity = (BYTE) HIWORD(wParam); - break; + //When moving slider with the mouse + case TB_THUMBPOSITION: + case TB_THUMBTRACK: + g_bPreviewOpacity = (BYTE)HIWORD(wParam); + break; - //moving via keyboard - default: - g_bPreviewOpacity = (BYTE) SendMessage((HWND) lParam, TBM_GETPOS, 0, 0); - } - - PreviewOpacity(hDlg, g_bPreviewOpacity); - UpdateApplyButton(hDlg); - - return TRUE; + //moving via keyboard + default: + g_bPreviewOpacity = (BYTE)SendMessage((HWND)lParam, TBM_GETPOS, 0, 0); } - break; - case CM_SETCOLOR: - UpdateStateInfo(hDlg, iColor + IDD_COLOR_SCREEN_TEXT, (UINT)wParam); + PreviewOpacity(hDlg, g_bPreviewOpacity); UpdateApplyButton(hDlg); - hWndOld = GetDlgItem(hDlg, ColorArray[iColor]+IDD_COLOR_1); - - ColorArray[iColor] = (BYTE)wParam; - - /* Force the preview window to repaint */ - - if (iColor < (IDD_COLOR_POPUP_TEXT - IDD_COLOR_SCREEN_TEXT)) { - hWnd = GetDlgItem(hDlg, IDD_COLOR_SCREEN_COLORS); - } else { - hWnd = GetDlgItem(hDlg, IDD_COLOR_POPUP_COLORS); - } - InvalidateRect(hWnd, NULL, TRUE); - - // repaint new color - hWnd = GetDlgItem(hDlg, ColorArray[iColor]+IDD_COLOR_1); - InvalidateRect(hWnd, NULL, TRUE); - SetFocus(hWnd); - - UpdateItem(hDlg, IDD_COLOR_RED, - GetRValue(AttrToRGB(ColorArray[iColor]))); - UpdateItem(hDlg, IDD_COLOR_GREEN, - GetGValue(AttrToRGB(ColorArray[iColor]))); - UpdateItem(hDlg, IDD_COLOR_BLUE, - GetBValue(AttrToRGB(ColorArray[iColor]))); - - // repaint old color - if (hWndOld != hWnd) { - InvalidateRect(hWndOld, NULL, TRUE); - } return TRUE; + } + break; - default: - break; + case CM_SETCOLOR: + UpdateStateInfo(hDlg, iColor + IDD_COLOR_SCREEN_TEXT, (UINT)wParam); + UpdateApplyButton(hDlg); + + hWndOld = GetDlgItem(hDlg, ColorArray[iColor] + IDD_COLOR_1); + + ColorArray[iColor] = (BYTE)wParam; + + /* Force the preview window to repaint */ + + if (iColor < (IDD_COLOR_POPUP_TEXT - IDD_COLOR_SCREEN_TEXT)) + { + hWnd = GetDlgItem(hDlg, IDD_COLOR_SCREEN_COLORS); + } + else + { + hWnd = GetDlgItem(hDlg, IDD_COLOR_POPUP_COLORS); + } + InvalidateRect(hWnd, NULL, TRUE); + + // repaint new color + hWnd = GetDlgItem(hDlg, ColorArray[iColor] + IDD_COLOR_1); + InvalidateRect(hWnd, NULL, TRUE); + SetFocus(hWnd); + + UpdateItem(hDlg, IDD_COLOR_RED, GetRValue(AttrToRGB(ColorArray[iColor]))); + UpdateItem(hDlg, IDD_COLOR_GREEN, GetGValue(AttrToRGB(ColorArray[iColor]))); + UpdateItem(hDlg, IDD_COLOR_BLUE, GetBValue(AttrToRGB(ColorArray[iColor]))); + + // repaint old color + if (hWndOld != hWnd) + { + InvalidateRect(hWndOld, NULL, TRUE); + } + return TRUE; + + default: + break; } return FALSE; } - // enables or disables color page dialog controls depending on whether V2 is enabled or not void ToggleV2ColorControls(__in const HWND hDlg) { @@ -381,7 +394,6 @@ void ToggleV2ColorControls(__in const HWND hDlg) EnableWindow(GetDlgItem(hDlg, IDD_OPACITY_VALUE), g_fForceV2); } - void PreviewOpacity(HWND hDlg, BYTE bOpacity) { // Ignore opacity in v1 console @@ -390,7 +402,7 @@ void PreviewOpacity(HWND hDlg, BYTE bOpacity) WCHAR wszOpacityValue[4]; HWND hWndConsole = gpStateInfo->hWnd; - StringCchPrintf(wszOpacityValue, ARRAYSIZE(wszOpacityValue), L"%d", (int) ((float) bOpacity / BYTE_MAX * 100)); + StringCchPrintf(wszOpacityValue, ARRAYSIZE(wszOpacityValue), L"%d", (int)((float)bOpacity / BYTE_MAX * 100)); SetDlgItemText(hDlg, IDD_OPACITY_VALUE, wszOpacityValue); if (hWndConsole) @@ -406,14 +418,14 @@ void SetOpacitySlider(__in HWND hDlg) { if (g_fForceV2) { - if (0 == g_bPreviewOpacity) //if no preview opacity has been set yet... + if (0 == g_bPreviewOpacity) //if no preview opacity has been set yet... { g_bPreviewOpacity = (gpStateInfo->bWindowTransparency >= TRANSPARENCY_RANGE_MIN) ? gpStateInfo->bWindowTransparency : BYTE_MAX; } } else { - g_bPreviewOpacity = BYTE_MAX; //always fully opaque in V1 + g_bPreviewOpacity = BYTE_MAX; //always fully opaque in V1 } SendMessage(GetDlgItem(hDlg, IDD_TRANSPARENCY), TBM_SETPOS, TRUE, (LPARAM)(g_bPreviewOpacity)); diff --git a/src/propsheet/ColorsPage.h b/src/propsheet/ColorsPage.h index a1dbb166b..d58362356 100644 --- a/src/propsheet/ColorsPage.h +++ b/src/propsheet/ColorsPage.h @@ -18,5 +18,4 @@ void ToggleV2ColorControls(__in const HWND hDlg); INT_PTR WINAPI ColorDlgProc(HWND hDlg, UINT wMsg, WPARAM wParam, LPARAM lParam); void SetOpacitySlider(__in HWND hDlg); void PreviewOpacity(HWND hDlg, BYTE bOpacity); -[[nodiscard]] -LRESULT CALLBACK ColorTableControlProc(HWND hColor, UINT wMsg, WPARAM wParam, LPARAM lParam); +[[nodiscard]] LRESULT CALLBACK ColorTableControlProc(HWND hColor, UINT wMsg, WPARAM wParam, LPARAM lParam); diff --git a/src/propsheet/LayoutPage.cpp b/src/propsheet/LayoutPage.cpp index 367691a1c..69109c0d9 100644 --- a/src/propsheet/LayoutPage.cpp +++ b/src/propsheet/LayoutPage.cpp @@ -6,13 +6,13 @@ BOOL g_fScreenSizeDlgInitialized = FALSE; BOOL g_fInScreenSizeSETACTIVE = FALSE; - BOOL GetStateInfo(HWND /*hDlg*/, UINT Item, __out LPINT lpValue) { BOOL bRet = TRUE; int Value; - switch (Item) { + switch (Item) + { case IDD_SCRBUF_WIDTH: Value = gpStateInfo->ScreenBufferSize.X; break; @@ -57,7 +57,8 @@ INT_PTR WINAPI ScreenSizeDlgProc(HWND hDlg, UINT wMsg, WPARAM wParam, LPARAM lPa LONG cxFrame; LONG cyFrame; - switch (wMsg) { + switch (wMsg) + { case WM_INITDIALOG: // initialize size of edit controls @@ -70,39 +71,27 @@ INT_PTR WINAPI ScreenSizeDlgProc(HWND hDlg, UINT wMsg, WPARAM wParam, LPARAM lPa // Get some system parameters - xScreen = GetSystemMetrics(SM_XVIRTUALSCREEN); - yScreen = GetSystemMetrics(SM_YVIRTUALSCREEN); + xScreen = GetSystemMetrics(SM_XVIRTUALSCREEN); + yScreen = GetSystemMetrics(SM_YVIRTUALSCREEN); cxScreen = GetSystemMetrics(SM_CXVIRTUALSCREEN); cyScreen = GetSystemMetrics(SM_CYVIRTUALSCREEN); - cxFrame = GetSystemMetrics(SM_CXFRAME); - cyFrame = GetSystemMetrics(SM_CYFRAME); + cxFrame = GetSystemMetrics(SM_CXFRAME); + cyFrame = GetSystemMetrics(SM_CYFRAME); // initialize arrow controls - SendDlgItemMessage(hDlg, IDD_SCRBUF_WIDTHSCROLL, UDM_SETRANGE, 0, - MAKELONG(9999, 1)); - SendDlgItemMessage(hDlg, IDD_SCRBUF_WIDTHSCROLL, UDM_SETPOS, 0, - MAKELONG(gpStateInfo->ScreenBufferSize.X, 0)); - SendDlgItemMessage(hDlg, IDD_SCRBUF_HEIGHTSCROLL, UDM_SETRANGE, 0, - MAKELONG(9999, 1)); - SendDlgItemMessage(hDlg, IDD_SCRBUF_HEIGHTSCROLL, UDM_SETPOS, 0, - MAKELONG(gpStateInfo->ScreenBufferSize.Y, 0)); - SendDlgItemMessage(hDlg, IDD_WINDOW_WIDTHSCROLL, UDM_SETRANGE, 0, - MAKELONG(9999, 1)); - SendDlgItemMessage(hDlg, IDD_WINDOW_WIDTHSCROLL, UDM_SETPOS, 0, - MAKELONG(gpStateInfo->WindowSize.X, 0)); - SendDlgItemMessage(hDlg, IDD_WINDOW_HEIGHTSCROLL, UDM_SETRANGE, 0, - MAKELONG(9999, 1)); - SendDlgItemMessage(hDlg, IDD_WINDOW_HEIGHTSCROLL, UDM_SETPOS, 0, - MAKELONG(gpStateInfo->WindowSize.Y, 0)); - SendDlgItemMessage(hDlg, IDD_WINDOW_POSXSCROLL, UDM_SETRANGE, 0, - MAKELONG(xScreen + cxScreen - cxFrame, xScreen - cxFrame)); - SendDlgItemMessage(hDlg, IDD_WINDOW_POSXSCROLL, UDM_SETPOS, 0, - MAKELONG(gpStateInfo->WindowPosX, 0)); - SendDlgItemMessage(hDlg, IDD_WINDOW_POSYSCROLL, UDM_SETRANGE, 0, - MAKELONG(yScreen + cyScreen - cyFrame, yScreen - cyFrame)); - SendDlgItemMessage(hDlg, IDD_WINDOW_POSYSCROLL, UDM_SETPOS, 0, - MAKELONG(gpStateInfo->WindowPosY, 0)); + SendDlgItemMessage(hDlg, IDD_SCRBUF_WIDTHSCROLL, UDM_SETRANGE, 0, MAKELONG(9999, 1)); + SendDlgItemMessage(hDlg, IDD_SCRBUF_WIDTHSCROLL, UDM_SETPOS, 0, MAKELONG(gpStateInfo->ScreenBufferSize.X, 0)); + SendDlgItemMessage(hDlg, IDD_SCRBUF_HEIGHTSCROLL, UDM_SETRANGE, 0, MAKELONG(9999, 1)); + SendDlgItemMessage(hDlg, IDD_SCRBUF_HEIGHTSCROLL, UDM_SETPOS, 0, MAKELONG(gpStateInfo->ScreenBufferSize.Y, 0)); + SendDlgItemMessage(hDlg, IDD_WINDOW_WIDTHSCROLL, UDM_SETRANGE, 0, MAKELONG(9999, 1)); + SendDlgItemMessage(hDlg, IDD_WINDOW_WIDTHSCROLL, UDM_SETPOS, 0, MAKELONG(gpStateInfo->WindowSize.X, 0)); + SendDlgItemMessage(hDlg, IDD_WINDOW_HEIGHTSCROLL, UDM_SETRANGE, 0, MAKELONG(9999, 1)); + SendDlgItemMessage(hDlg, IDD_WINDOW_HEIGHTSCROLL, UDM_SETPOS, 0, MAKELONG(gpStateInfo->WindowSize.Y, 0)); + SendDlgItemMessage(hDlg, IDD_WINDOW_POSXSCROLL, UDM_SETRANGE, 0, MAKELONG(xScreen + cxScreen - cxFrame, xScreen - cxFrame)); + SendDlgItemMessage(hDlg, IDD_WINDOW_POSXSCROLL, UDM_SETPOS, 0, MAKELONG(gpStateInfo->WindowPosX, 0)); + SendDlgItemMessage(hDlg, IDD_WINDOW_POSYSCROLL, UDM_SETRANGE, 0, MAKELONG(yScreen + cyScreen - cyFrame, yScreen - cyFrame)); + SendDlgItemMessage(hDlg, IDD_WINDOW_POSYSCROLL, UDM_SETPOS, 0, MAKELONG(gpStateInfo->WindowPosY, 0)); // // put current values in dialog box @@ -129,18 +118,23 @@ INT_PTR WINAPI ScreenSizeDlgProc(HWND hDlg, UINT wMsg, WPARAM wParam, LPARAM lPa case WM_COMMAND: Item = LOWORD(wParam); - switch (Item) { + switch (Item) + { case IDD_SCRBUF_WIDTH: case IDD_SCRBUF_HEIGHT: case IDD_WINDOW_WIDTH: case IDD_WINDOW_HEIGHT: case IDD_WINDOW_POSX: case IDD_WINDOW_POSY: - switch (HIWORD(wParam)) { + switch (HIWORD(wParam)) + { case EN_UPDATE: - if (!CheckNum (hDlg, Item)) { + if (!CheckNum(hDlg, Item)) + { Undo((HWND)lParam); - } else if (!g_fInScreenSizeSETACTIVE && g_fScreenSizeDlgInitialized) { + } + else if (!g_fInScreenSizeSETACTIVE && g_fScreenSizeDlgInitialized) + { UpdateApplyButton(hDlg); } @@ -150,11 +144,15 @@ INT_PTR WINAPI ScreenSizeDlgProc(HWND hDlg, UINT wMsg, WPARAM wParam, LPARAM lPa * Update the state info structure */ Value = (UINT)SendDlgItemMessage(hDlg, Item + 1, UDM_GETPOS, 0, 0); - if (HIWORD(Value) == 0) { + if (HIWORD(Value) == 0) + { UpdateStateInfo(hDlg, Item, (SHORT)LOWORD(Value)); - } else { + } + else + { Value = GetStateInfo(hDlg, Item, &bOK); - if (bOK) { + if (bOK) + { UpdateItem(hDlg, Item, Value); } } @@ -180,11 +178,13 @@ INT_PTR WINAPI ScreenSizeDlgProc(HWND hDlg, UINT wMsg, WPARAM wParam, LPARAM lPa case IDD_AUTO_POSITION: Value = IsDlgButtonChecked(hDlg, IDD_AUTO_POSITION); UpdateStateInfo(hDlg, IDD_AUTO_POSITION, Value); - if (g_fScreenSizeDlgInitialized) { + if (g_fScreenSizeDlgInitialized) + { UpdateApplyButton(hDlg); } - for (Item = IDD_WINDOW_POSX; Item < IDD_AUTO_POSITION; Item++) { + for (Item = IDD_WINDOW_POSX; Item < IDD_AUTO_POSITION; Item++) + { hWnd = GetDlgItem(hDlg, Item); EnableWindow(hWnd, (Value == FALSE)); } @@ -197,8 +197,9 @@ INT_PTR WINAPI ScreenSizeDlgProc(HWND hDlg, UINT wMsg, WPARAM wParam, LPARAM lPa case WM_NOTIFY: { - const PSHNOTIFY * const pshn = (LPPSHNOTIFY)lParam; - switch (pshn->hdr.code) { + const PSHNOTIFY* const pshn = (LPPSHNOTIFY)lParam; + switch (pshn->hdr.code) + { case PSN_APPLY: /* * Write out the state values and exit. @@ -252,7 +253,6 @@ INT_PTR WINAPI ScreenSizeDlgProc(HWND hDlg, UINT wMsg, WPARAM wParam, LPARAM lPa return FALSE; } - // enables or disables layout page dialog controls depending on whether V2 is enabled or not void ToggleV2LayoutControls(__in const HWND hDlg) { diff --git a/src/propsheet/OptionsPage.cpp b/src/propsheet/OptionsPage.cpp index a5df7fda5..8ce4a638a 100644 --- a/src/propsheet/OptionsPage.cpp +++ b/src/propsheet/OptionsPage.cpp @@ -8,17 +8,21 @@ bool OptionsCommandCallback(HWND hDlg, const unsigned int Item, const unsigned i UINT Value; BOOL bOK; - switch (Item) { + switch (Item) + { case IDD_LANGUAGELIST: - switch (Notification) { - case CBN_SELCHANGE: { + switch (Notification) + { + case CBN_SELCHANGE: + { HWND hWndLanguageCombo; LONG lListIndex; hWndLanguageCombo = GetDlgItem(hDlg, IDD_LANGUAGELIST); lListIndex = (LONG)SendMessage(hWndLanguageCombo, CB_GETCURSEL, 0, 0); Value = (UINT)SendMessage(hWndLanguageCombo, CB_GETITEMDATA, lListIndex, 0); - if (Value != -1) { + if (Value != -1) + { fChangeCodePage = (Value != gpStateInfo->CodePage); UpdateStateInfo(hDlg, Item, Value); UpdateApplyButton(hDlg); @@ -27,7 +31,7 @@ bool OptionsCommandCallback(HWND hDlg, const unsigned int Item, const unsigned i } default: - DBGFONTS(("unhandled CBN_%x from POINTSLIST\n",Notification)); + DBGFONTS(("unhandled CBN_%x from POINTSLIST\n", Notification)); break; } return TRUE; @@ -35,7 +39,8 @@ bool OptionsCommandCallback(HWND hDlg, const unsigned int Item, const unsigned i case IDD_CURSOR_MEDIUM: case IDD_CURSOR_LARGE: UpdateStateInfo(hDlg, Item, 0); - if (Notification != EN_KILLFOCUS) { + if (Notification != EN_KILLFOCUS) + { // we don't want to light up the apply button just because a cursor selection lost focus -- this can // happen when switching between tabs even if there's no actual change in selection. UpdateApplyButton(hDlg); @@ -52,11 +57,15 @@ bool OptionsCommandCallback(HWND hDlg, const unsigned int Item, const unsigned i case IDD_HISTORY_SIZE: case IDD_HISTORY_NUM: - switch (Notification) { + switch (Notification) + { case EN_UPDATE: - if (!CheckNum(hDlg, Item)) { + if (!CheckNum(hDlg, Item)) + { Undo(hControlWindow); - } else if (g_fSettingsDlgInitialized) { + } + else if (g_fSettingsDlgInitialized) + { UpdateApplyButton(hDlg); } break; @@ -66,7 +75,8 @@ bool OptionsCommandCallback(HWND hDlg, const unsigned int Item, const unsigned i * Update the state info structure */ Value = GetDlgItemInt(hDlg, Item, &bOK, TRUE); - if (bOK) { + if (bOK) + { UpdateStateInfo(hDlg, Item, Value); UpdateApplyButton(hDlg); } @@ -122,7 +132,6 @@ bool OptionsCommandCallback(HWND hDlg, const unsigned int Item, const unsigned i UpdateApplyButton(hDlg); return TRUE; } - } return FALSE; } @@ -135,7 +144,8 @@ INT_PTR WINAPI SettingsDlgProc(HWND hDlg, UINT wMsg, WPARAM wParam, LPARAM lPara UINT Item; UINT Notification; - switch (wMsg) { + switch (wMsg) + { case WM_INITDIALOG: CheckDlgButton(hDlg, IDD_HISTORY_NODUP, gpStateInfo->HistoryNoDup); CheckDlgButton(hDlg, IDD_QUICKEDIT, gpStateInfo->QuickEdit); @@ -157,44 +167,56 @@ INT_PTR WINAPI SettingsDlgProc(HWND hDlg, UINT wMsg, WPARAM wParam, LPARAM lPara CreateAndAssociateToolTipToControl(IDD_INTERCEPT_COPY_PASTE, hDlg, IDS_TOOLTIP_INTERCEPT_COPY_PASTE); // initialize cursor radio buttons - if (gpStateInfo->CursorSize <= 25) { + if (gpStateInfo->CursorSize <= 25) + { Item = IDD_CURSOR_SMALL; - } else if (gpStateInfo->CursorSize <= 50) { + } + else if (gpStateInfo->CursorSize <= 50) + { Item = IDD_CURSOR_MEDIUM; - } else { + } + else + { Item = IDD_CURSOR_LARGE; } CheckRadioButton(hDlg, IDD_CURSOR_SMALL, IDD_CURSOR_LARGE, Item); - SetDlgItemInt(hDlg, IDD_HISTORY_SIZE, gpStateInfo->HistoryBufferSize, - FALSE); + SetDlgItemInt(hDlg, IDD_HISTORY_SIZE, gpStateInfo->HistoryBufferSize, FALSE); SendDlgItemMessage(hDlg, IDD_HISTORY_SIZE, EM_LIMITTEXT, 3, 0); - SendDlgItemMessage(hDlg, IDD_HISTORY_SIZESCROLL, UDM_SETRANGE, 0, - MAKELONG(999, 1)); + SendDlgItemMessage(hDlg, IDD_HISTORY_SIZESCROLL, UDM_SETRANGE, 0, MAKELONG(999, 1)); SetDlgItemInt(hDlg, IDD_HISTORY_NUM, gpStateInfo->NumberOfHistoryBuffers, FALSE); SendDlgItemMessage(hDlg, IDD_HISTORY_NUM, EM_LIMITTEXT, 3, 0); SendDlgItemMessage(hDlg, IDD_HISTORY_NUM, EM_SETSEL, 0, (DWORD)-1); - SendDlgItemMessage(hDlg, IDD_HISTORY_NUMSCROLL, UDM_SETRANGE, 0, - MAKELONG(999, 1)); + SendDlgItemMessage(hDlg, IDD_HISTORY_NUMSCROLL, UDM_SETRANGE, 0, MAKELONG(999, 1)); - if (g_fEastAsianSystem) { + if (g_fEastAsianSystem) + { // In CJK systems, we always show the codepage on both the defaults and non-defaults propsheets - if (gpStateInfo->Defaults) { + if (gpStateInfo->Defaults) + { LanguageListCreate(hDlg, gpStateInfo->CodePage); - } else { + } + else + { LanguageDisplay(hDlg, gpStateInfo->CodePage); } - } else { + } + else + { // On non-CJK systems, we show the codepage on a non-default propsheet, but don't allow the user to view or // change it on the defaults propsheet const HWND hwndLanguageGroupbox = GetDlgItem(hDlg, IDD_LANGUAGE_GROUPBOX); - if (hwndLanguageGroupbox) { - if (gpStateInfo->Defaults) { + if (hwndLanguageGroupbox) + { + if (gpStateInfo->Defaults) + { const HWND hwndLanguageList = GetDlgItem(hDlg, IDD_LANGUAGELIST); ShowWindow(hwndLanguageList, SW_HIDE); ShowWindow(hwndLanguageGroupbox, SW_HIDE); - } else { + } + else + { const HWND hwndLanguage = GetDlgItem(hDlg, IDD_LANGUAGE); LanguageDisplay(hDlg, gpStateInfo->CodePage); ShowWindow(hwndLanguage, SW_SHOW); @@ -216,54 +238,55 @@ INT_PTR WINAPI SettingsDlgProc(HWND hDlg, UINT wMsg, WPARAM wParam, LPARAM lPara if (lParam && (wParam == IDD_HELP_SYSLINK || wParam == IDD_HELP_LEGACY_LINK)) { // handle hyperlink click or keyboard activation - switch(((LPNMHDR)lParam)->code) + switch (((LPNMHDR)lParam)->code) { - case NM_CLICK: - case NM_RETURN: + case NM_CLICK: + case NM_RETURN: + { + PNMLINK pnmLink = (PNMLINK)lParam; + if (0 == pnmLink->item.iLink) { - PNMLINK pnmLink = (PNMLINK)lParam; - if (0 == pnmLink->item.iLink) - { - ShellExecute(NULL, - L"open", - pnmLink->item.szUrl, - NULL, - NULL, - SW_SHOW); - } - - break; + ShellExecute(NULL, + L"open", + pnmLink->item.szUrl, + NULL, + NULL, + SW_SHOW); } + + break; + } } } else { - const PSHNOTIFY * const pshn = (LPPSHNOTIFY)lParam; - if (lParam) + const PSHNOTIFY* const pshn = (LPPSHNOTIFY)lParam; + if (lParam) { - switch (pshn->hdr.code) { - case PSN_APPLY: - /* + switch (pshn->hdr.code) + { + case PSN_APPLY: + /* * Write out the state values and exit. */ - EndDlgPage(hDlg, !pshn->lParam); - return TRUE; + EndDlgPage(hDlg, !pshn->lParam); + return TRUE; - case PSN_SETACTIVE: - ToggleV2OptionsControls(hDlg); - return 0; + case PSN_SETACTIVE: + ToggleV2OptionsControls(hDlg); + return 0; - case PSN_KILLACTIVE: - /* + case PSN_KILLACTIVE: + /* * Fake the dialog proc into thinking the edit control just * lost focus so it'll update properly */ - Item = GetDlgCtrlID(GetFocus()); - if (Item) - { - SendMessage(hDlg, WM_COMMAND, MAKELONG(Item, EN_KILLFOCUS), 0); - } - return TRUE; + Item = GetDlgCtrlID(GetFocus()); + if (Item) + { + SendMessage(hDlg, WM_COMMAND, MAKELONG(Item, EN_KILLFOCUS), 0); + } + return TRUE; } } } diff --git a/src/propsheet/PropSheetHandler.cpp b/src/propsheet/PropSheetHandler.cpp index 871288593..d4b93c886 100644 --- a/src/propsheet/PropSheetHandler.cpp +++ b/src/propsheet/PropSheetHandler.cpp @@ -12,14 +12,20 @@ #include -#define PEMAGIC ((WORD)'P'+((WORD)'E'<<8)) +#define PEMAGIC ((WORD)'P' + ((WORD)'E' << 8)) static CONSOLE_STATE_INFO g_csi; using namespace Microsoft::WRL; // This class exposes console property sheets for use when launching the filesystem shortcut properties dialog. +// clang-format off [uuid(D2942F8E-478E-41D3-870A-35A16238F4EE)] -class ConsolePropertySheetHandler WrlFinal : public RuntimeClass, IShellExtInit, IShellPropSheetExt, IPersist, FtmBase> +class ConsolePropertySheetHandler WrlFinal : public RuntimeClass, + IShellExtInit, + IShellPropSheetExt, + IPersist, + FtmBase> +// clang-format on { public: HRESULT RuntimeClassInitialize() @@ -28,7 +34,7 @@ public: } // IPersist - STDMETHODIMP GetClassID(_Out_ CLSID *clsid) override + STDMETHODIMP GetClassID(_Out_ CLSID* clsid) override { *clsid = __uuidof(this); return S_OK; @@ -37,7 +43,7 @@ public: // IShellExtInit // Shell QI's for IShellExtInit and calls Initialize first. If we return a succeeding HRESULT, the shell will QI for // IShellPropSheetExt and call AddPages. A failing HRESULT causes the shell to skip us. - STDMETHODIMP Initialize(_In_ PCIDLIST_ABSOLUTE /*pidlFolder*/, _In_ IDataObject *pdtobj, _In_ HKEY /*hkeyProgID*/) + STDMETHODIMP Initialize(_In_ PCIDLIST_ABSOLUTE /*pidlFolder*/, _In_ IDataObject* pdtobj, _In_ HKEY /*hkeyProgID*/) { WCHAR szLinkFileName[MAX_PATH]; HRESULT hr = _ShouldAddPropertySheet(pdtobj, szLinkFileName, ARRAYSIZE(szLinkFileName)); @@ -127,11 +133,11 @@ private: /////////////////////////////////////////////////////////////////////////// // CODE FROM THE SHELL DEPOT'S `idllib.h` // get a link target item without resolving it. - HRESULT GetTargetIdList(_In_ IShellItem *psiLink, _COM_Outptr_ PIDLIST_ABSOLUTE *ppidl) + HRESULT GetTargetIdList(_In_ IShellItem* psiLink, _COM_Outptr_ PIDLIST_ABSOLUTE* ppidl) { *ppidl = nullptr; - IShellLink *psl; + IShellLink* psl; HRESULT hr = psiLink->BindToHandler(NULL, BHID_SFUIObject, IID_PPV_ARGS(&psl)); if (SUCCEEDED(hr)) { @@ -144,7 +150,7 @@ private: } return hr; } - HRESULT GetTargetItem(_In_ IShellItem *psiLink, _In_ REFIID riid, _COM_Outptr_ void **ppv) + HRESULT GetTargetItem(_In_ IShellItem* psiLink, _In_ REFIID riid, _COM_Outptr_ void** ppv) { *ppv = nullptr; @@ -159,7 +165,9 @@ private: } /////////////////////////////////////////////////////////////////////////// - HRESULT _GetShellItemLinkTargetExpanded(_In_ IShellItem *pShellItem, _Out_writes_(cchFilePathExtended) PWSTR pszFilePathExtended, const size_t cchFilePathExtended) + HRESULT _GetShellItemLinkTargetExpanded(_In_ IShellItem* pShellItem, + _Out_writes_(cchFilePathExtended) PWSTR pszFilePathExtended, + const size_t cchFilePathExtended) { ComPtr shellItemLinkTarget; HRESULT hr = GetTargetItem(pShellItem, IID_PPV_ARGS(&shellItemLinkTarget)); @@ -176,8 +184,9 @@ private: return hr; } - - HRESULT _ShouldAddPropertySheet(_In_ IDataObject *pdtobj, _Out_writes_(cchLinkFileName) PWSTR pszLinkFileName, const size_t cchLinkFileName) + HRESULT _ShouldAddPropertySheet(_In_ IDataObject* pdtobj, + _Out_writes_(cchLinkFileName) PWSTR pszLinkFileName, + const size_t cchLinkFileName) { ComPtr shellItemArray; HRESULT hr = SHCreateShellItemArrayFromDataObject(pdtobj, IID_PPV_ARGS(&shellItemArray)); @@ -202,7 +211,7 @@ private: { // Second expensive portion of this method -- cracks the PE header of the .lnk file target // if it's an executable - SHFILEINFO sfi = {0}; + SHFILEINFO sfi = { 0 }; DWORD_PTR dwFileType = SHGetFileInfo(szFileExpanded, 0 /*dwFileAttributes*/, &sfi, diff --git a/src/propsheet/TerminalPage.cpp b/src/propsheet/TerminalPage.cpp index f8eccb169..cbae87115 100644 --- a/src/propsheet/TerminalPage.cpp +++ b/src/propsheet/TerminalPage.cpp @@ -82,8 +82,7 @@ void _UpdateTextAndScroll(const HWND hDlg, const WORD scrollItem) noexcept { UpdateItem(hDlg, textItem, value); - SendDlgItemMessage(hDlg, scrollItem, UDM_SETPOS, 0, - MAKELONG(value, 0)); + SendDlgItemMessage(hDlg, scrollItem, UDM_SETPOS, 0, MAKELONG(value, 0)); } bool InitTerminalDialog(const HWND hDlg) noexcept @@ -91,7 +90,7 @@ bool InitTerminalDialog(const HWND hDlg) noexcept // Initialize the global handle to this dialog g_hTerminalDlg = hDlg; // Group radios - CheckRadioButton(hDlg,IDD_TERMINAL_INVERSE_CURSOR,IDD_TERMINAL_CURSOR_USECOLOR, IDD_TERMINAL_INVERSE_CURSOR); + CheckRadioButton(hDlg, IDD_TERMINAL_INVERSE_CURSOR, IDD_TERMINAL_CURSOR_USECOLOR, IDD_TERMINAL_INVERSE_CURSOR); // initialize size of edit controls SendDlgItemMessage(hDlg, IDD_TERMINAL_FG_RED, EM_LIMITTEXT, 3, 0); @@ -137,7 +136,9 @@ bool InitTerminalDialog(const HWND hDlg) noexcept } CheckDlgButton(hDlg, IDD_USE_TERMINAL_FG, initialTerminalFG); CheckDlgButton(hDlg, IDD_USE_TERMINAL_BG, initialTerminalBG); - CheckRadioButton(hDlg, IDD_TERMINAL_INVERSE_CURSOR, IDD_TERMINAL_CURSOR_USECOLOR, + CheckRadioButton(hDlg, + IDD_TERMINAL_INVERSE_CURSOR, + IDD_TERMINAL_CURSOR_USECOLOR, initialCursorLegacy ? IDD_TERMINAL_INVERSE_CURSOR : IDD_TERMINAL_CURSOR_USECOLOR); // Set the initial values in the edit boxes and scroll controls @@ -172,9 +173,9 @@ bool InitTerminalDialog(const HWND hDlg) noexcept InvalidateRect(GetDlgItem(hDlg, IDD_TERMINAL_CURSOR_COLOR), NULL, FALSE); CheckRadioButton(hDlg, - IDD_TERMINAL_LEGACY_CURSOR, IDD_TERMINAL_SOLIDBOX, - IDD_TERMINAL_LEGACY_CURSOR+gpStateInfo->CursorType); - + IDD_TERMINAL_LEGACY_CURSOR, + IDD_TERMINAL_SOLIDBOX, + IDD_TERMINAL_LEGACY_CURSOR + gpStateInfo->CursorType); CheckDlgButton(hDlg, IDD_DISABLE_SCROLLFORWARD, gpStateInfo->TerminalScrolling); @@ -215,7 +216,7 @@ void _ChangeColorControl(const HWND hDlg, b = newValue; } - setting = RGB(r,g,b); + setting = RGB(r, g, b); } InvalidateRect(GetDlgItem(hDlg, colorControl), NULL, FALSE); @@ -264,13 +265,14 @@ bool _CommandColorInput(const HWND hDlg, { bool handled = false; - switch (command) { - case EN_UPDATE: - case EN_CHANGE: - changeFunction(hDlg, item); - handled = true; - UpdateApplyButton(hDlg); - break; + switch (command) + { + case EN_UPDATE: + case EN_CHANGE: + changeFunction(hDlg, item); + handled = true; + UpdateApplyButton(hDlg); + break; } return handled; } @@ -278,56 +280,57 @@ bool _CommandColorInput(const HWND hDlg, bool TerminalDlgCommand(const HWND hDlg, const WORD item, const WORD command) noexcept { bool handled = false; - switch (item) { - case IDD_TERMINAL_CURSOR_USECOLOR: - case IDD_TERMINAL_INVERSE_CURSOR: - _UseCursorColor(hDlg, IsDlgButtonChecked(hDlg, IDD_TERMINAL_CURSOR_USECOLOR)); - handled = true; - UpdateApplyButton(hDlg); - break; - case IDD_USE_TERMINAL_FG: - _UseForeground(hDlg, IsDlgButtonChecked(hDlg, IDD_USE_TERMINAL_FG)); - handled = true; - UpdateApplyButton(hDlg); - break; - case IDD_USE_TERMINAL_BG: - _UseBackground(hDlg, IsDlgButtonChecked(hDlg, IDD_USE_TERMINAL_BG)); - handled = true; - UpdateApplyButton(hDlg); - break; + switch (item) + { + case IDD_TERMINAL_CURSOR_USECOLOR: + case IDD_TERMINAL_INVERSE_CURSOR: + _UseCursorColor(hDlg, IsDlgButtonChecked(hDlg, IDD_TERMINAL_CURSOR_USECOLOR)); + handled = true; + UpdateApplyButton(hDlg); + break; + case IDD_USE_TERMINAL_FG: + _UseForeground(hDlg, IsDlgButtonChecked(hDlg, IDD_USE_TERMINAL_FG)); + handled = true; + UpdateApplyButton(hDlg); + break; + case IDD_USE_TERMINAL_BG: + _UseBackground(hDlg, IsDlgButtonChecked(hDlg, IDD_USE_TERMINAL_BG)); + handled = true; + UpdateApplyButton(hDlg); + break; - case IDD_TERMINAL_FG_RED: - case IDD_TERMINAL_FG_GREEN: - case IDD_TERMINAL_FG_BLUE: - handled = _CommandColorInput(hDlg, item, command, _ChangeForegroundRGB); - break; + case IDD_TERMINAL_FG_RED: + case IDD_TERMINAL_FG_GREEN: + case IDD_TERMINAL_FG_BLUE: + handled = _CommandColorInput(hDlg, item, command, _ChangeForegroundRGB); + break; - case IDD_TERMINAL_BG_RED: - case IDD_TERMINAL_BG_GREEN: - case IDD_TERMINAL_BG_BLUE: - handled = _CommandColorInput(hDlg, item, command, _ChangeBackgroundRGB); - break; + case IDD_TERMINAL_BG_RED: + case IDD_TERMINAL_BG_GREEN: + case IDD_TERMINAL_BG_BLUE: + handled = _CommandColorInput(hDlg, item, command, _ChangeBackgroundRGB); + break; - case IDD_TERMINAL_CURSOR_RED: - case IDD_TERMINAL_CURSOR_GREEN: - case IDD_TERMINAL_CURSOR_BLUE: - handled = _CommandColorInput(hDlg, item, command, _ChangeCursorRGB); - break; + case IDD_TERMINAL_CURSOR_RED: + case IDD_TERMINAL_CURSOR_GREEN: + case IDD_TERMINAL_CURSOR_BLUE: + handled = _CommandColorInput(hDlg, item, command, _ChangeCursorRGB); + break; - case IDD_TERMINAL_LEGACY_CURSOR: - case IDD_TERMINAL_VERTBAR: - case IDD_TERMINAL_UNDERSCORE: - case IDD_TERMINAL_EMPTYBOX: - case IDD_TERMINAL_SOLIDBOX: - gpStateInfo->CursorType = item - IDD_TERMINAL_LEGACY_CURSOR; - UpdateApplyButton(hDlg); - handled = true; - break; - case IDD_DISABLE_SCROLLFORWARD: - gpStateInfo->TerminalScrolling = IsDlgButtonChecked(hDlg, IDD_DISABLE_SCROLLFORWARD); - UpdateApplyButton(hDlg); - handled = true; - break; + case IDD_TERMINAL_LEGACY_CURSOR: + case IDD_TERMINAL_VERTBAR: + case IDD_TERMINAL_UNDERSCORE: + case IDD_TERMINAL_EMPTYBOX: + case IDD_TERMINAL_SOLIDBOX: + gpStateInfo->CursorType = item - IDD_TERMINAL_LEGACY_CURSOR; + UpdateApplyButton(hDlg); + handled = true; + break; + case IDD_DISABLE_SCROLLFORWARD: + gpStateInfo->TerminalScrolling = IsDlgButtonChecked(hDlg, IDD_DISABLE_SCROLLFORWARD); + UpdateApplyButton(hDlg); + handled = true; + break; } return handled; @@ -337,90 +340,91 @@ INT_PTR WINAPI TerminalDlgProc(const HWND hDlg, const UINT wMsg, const WPARAM wP { static bool fHaveInitialized = false; - switch (wMsg) { - case WM_INITDIALOG: - fHaveInitialized = true; - return InitTerminalDialog(hDlg); - case WM_COMMAND: - if (!fHaveInitialized) - { - return false; - } - return TerminalDlgCommand(hDlg, LOWORD(wParam), HIWORD(wParam)); - case WM_NOTIFY: + switch (wMsg) + { + case WM_INITDIALOG: + fHaveInitialized = true; + return InitTerminalDialog(hDlg); + case WM_COMMAND: + if (!fHaveInitialized) { - if (lParam && (wParam == IDD_HELP_TERMINAL)) + return false; + } + return TerminalDlgCommand(hDlg, LOWORD(wParam), HIWORD(wParam)); + case WM_NOTIFY: + { + if (lParam && (wParam == IDD_HELP_TERMINAL)) + { + // handle hyperlink click or keyboard activation + switch (((LPNMHDR)lParam)->code) { - // handle hyperlink click or keyboard activation - switch(((LPNMHDR)lParam)->code) + case NM_CLICK: + case NM_RETURN: + { + PNMLINK pnmLink = (PNMLINK)lParam; + if (0 == pnmLink->item.iLink) { - case NM_CLICK: - case NM_RETURN: - { - PNMLINK pnmLink = (PNMLINK)lParam; - if (0 == pnmLink->item.iLink) - { - ShellExecute(NULL, - L"open", - pnmLink->item.szUrl, - NULL, - NULL, - SW_SHOW); - } - - break; - } + ShellExecute(NULL, + L"open", + pnmLink->item.szUrl, + NULL, + NULL, + SW_SHOW); } + + break; } - else - { - const PSHNOTIFY * const pshn = (LPPSHNOTIFY)lParam; - if (lParam) - { - switch (pshn->hdr.code) { - case PSN_APPLY: - EndDlgPage(hDlg, !pshn->lParam); - return TRUE; - case PSN_KILLACTIVE: - { - // Fake the dialog proc into thinking the edit control just - // lost focus so it'll update properly - int item = GetDlgCtrlID(GetFocus()); - if (item) - { - SendMessage(hDlg, WM_COMMAND, MAKELONG(item, EN_KILLFOCUS), 0); - } - return TRUE; - } - } - } - } } - case WM_VSCROLL: - // Fake the dialog proc into thinking the edit control just - // lost focus so it'll update properly - SendMessage(hDlg, WM_COMMAND, MAKELONG((GetDlgCtrlID((HWND)lParam) - 1), EN_KILLFOCUS), 0); - return TRUE; + else + { + const PSHNOTIFY* const pshn = (LPPSHNOTIFY)lParam; + if (lParam) + { + switch (pshn->hdr.code) + { + case PSN_APPLY: + EndDlgPage(hDlg, !pshn->lParam); + return TRUE; + case PSN_KILLACTIVE: + { + // Fake the dialog proc into thinking the edit control just + // lost focus so it'll update properly + int item = GetDlgCtrlID(GetFocus()); + if (item) + { + SendMessage(hDlg, WM_COMMAND, MAKELONG(item, EN_KILLFOCUS), 0); + } + return TRUE; + } + } + } + } + } + case WM_VSCROLL: + // Fake the dialog proc into thinking the edit control just + // lost focus so it'll update properly + SendMessage(hDlg, WM_COMMAND, MAKELONG((GetDlgCtrlID((HWND)lParam) - 1), EN_KILLFOCUS), 0); + return TRUE; - case WM_DESTROY: - // MSFT:20740368 - // When the propsheet is opened straight from explorer, NOT from - // conhost itself, then explorer will load console.dll once, - // and re-use it for subsequent launches. This means that on - // the first launch of the propsheet, our fHaveInitialized will - // be false until we actually do the init work, but on - // subsequent launches, fHaveInitialized will be re-used, and - // found to be true, and we'll zero out the values of the - // colors. This is because the message loop decides to update - // the values of the textboxes before we get a chance to put - // the current values into them. When the textboxes update, - // they'll overwrite the current color components with whatever - // they currently have, which is 0. - // To avoid this madness, make sure to reset our initialization - // state when the dialog is closed. - fHaveInitialized = false; - break; + case WM_DESTROY: + // MSFT:20740368 + // When the propsheet is opened straight from explorer, NOT from + // conhost itself, then explorer will load console.dll once, + // and re-use it for subsequent launches. This means that on + // the first launch of the propsheet, our fHaveInitialized will + // be false until we actually do the init work, but on + // subsequent launches, fHaveInitialized will be re-used, and + // found to be true, and we'll zero out the values of the + // colors. This is because the message loop decides to update + // the values of the textboxes before we get a chance to put + // the current values into them. When the textboxes update, + // they'll overwrite the current color components with whatever + // they currently have, which is 0. + // To avoid this madness, make sure to reset our initialization + // state when the dialog is closed. + fHaveInitialized = false; + break; } return false; diff --git a/src/propsheet/console.cpp b/src/propsheet/console.cpp index 50c238459..cf3683dc8 100644 --- a/src/propsheet/console.cpp +++ b/src/propsheet/console.cpp @@ -24,7 +24,7 @@ Revision History: UINT gnCurrentPage; #define SYSTEM_ROOT (L"%SystemRoot%") -#define SYSTEM_ROOT_LENGTH (sizeof(SYSTEM_ROOT) - sizeof(WCHAR)) +#define SYSTEM_ROOT_LENGTH (sizeof(SYSTEM_ROOT) - sizeof(WCHAR)) void RecreateFontHandles(const HWND hWnd); @@ -38,7 +38,8 @@ void UpdateItem(HWND hDlg, UINT item, UINT nNum) // Sends an EM_UNDO message. Typically used after some user data is determined to be invalid. void Undo(HWND hControlWindow) { - if (!InEM_UNDO) { + if (!InEM_UNDO) + { InEM_UNDO = TRUE; SendMessage(hControlWindow, EM_UNDO, 0, 0); InEM_UNDO = FALSE; @@ -54,15 +55,20 @@ BOOL CheckNum(HWND hDlg, UINT Item) BOOL fSigned; // The window position corrdinates can be signed, nothing else. - if (Item == IDD_WINDOW_POSX || Item == IDD_WINDOW_POSY) { + if (Item == IDD_WINDOW_POSX || Item == IDD_WINDOW_POSY) + { fSigned = TRUE; - } else { + } + else + { fSigned = FALSE; } GetDlgItemText(hDlg, Item, szNum, ARRAYSIZE(szNum)); - for (i = 0; szNum[i]; i++) { - if (!iswdigit(szNum[i]) && (!fSigned || i > 0 || szNum[i] != TEXT('-'))) { + for (i = 0; szNum[i]; i++) + { + if (!iswdigit(szNum[i]) && (!fSigned || i > 0 || szNum[i] != TEXT('-'))) + { return FALSE; } } @@ -81,7 +87,6 @@ void SaveConsoleSettingsIfNeeded(const HWND hwnd) (gpStateInfo->FontWeight == FW_NORMAL) && (wcscmp(gpStateInfo->FaceName, DefaultFaceName) == 0)) { - gpStateInfo->FontFamily = 0; gpStateInfo->FontSize.X = 0; gpStateInfo->FontSize.Y = 0; @@ -95,7 +100,7 @@ void SaveConsoleSettingsIfNeeded(const HWND hwnd) if (!NT_SUCCESS(ShortcutSerialization::s_SetLinkValues(gpStateInfo, g_fEastAsianSystem, g_fForceV2))) { WCHAR szMessage[MAX_PATH + 100]; - WCHAR awchBuffer[MAX_PATH] = {0}; + WCHAR awchBuffer[MAX_PATH] = { 0 }; STARTUPINFOW si; // An error occured try to save the link file, display a message box to that effect... @@ -136,7 +141,8 @@ void EndDlgPage(const HWND hDlg, const BOOL fSaveNow) /* * If we've already made a decision, we're done */ - if (gpStateInfo->UpdateValues) { + if (gpStateInfo->UpdateValues) + { SetDlgMsgResult(hDlg, PSN_APPLY, PSNRET_NOERROR); return; } @@ -152,7 +158,8 @@ void EndDlgPage(const HWND hDlg, const BOOL fSaveNow) SetDlgMsgResult(hDlg, PSN_APPLY, PSNRET_NOERROR); - if (fSaveNow) { + if (fSaveNow) + { // needed for "Apply" scenario SaveConsoleSettingsIfNeeded(hDlg); } @@ -178,10 +185,10 @@ void CreateAndAssociateToolTipToControl(const UINT dlgItem, const HWND hDlg, con if (hwndTooltip) { - WCHAR szTooltip[TOOLTIP_MAXLENGTH] = {0}; + WCHAR szTooltip[TOOLTIP_MAXLENGTH] = { 0 }; if (LoadString(ghInstance, idsToolTip, szTooltip, ARRAYSIZE(szTooltip)) > 0) { - TOOLINFO toolInfo = {0}; + TOOLINFO toolInfo = { 0 }; toolInfo.cbSize = sizeof(toolInfo); toolInfo.hwnd = hDlg; toolInfo.uFlags = TTF_IDISHWND | TTF_SUBCLASS; @@ -194,19 +201,22 @@ void CreateAndAssociateToolTipToControl(const UINT dlgItem, const HWND hDlg, con BOOL UpdateStateInfo(HWND hDlg, UINT Item, int Value) { - switch (Item) { + switch (Item) + { case IDD_SCRBUF_WIDTH: gpStateInfo->ScreenBufferSize.X = (SHORT)Value; // If we're in V2 mode with wrap text on OR if the window is larger than the buffer, adjust the window to match. - if ((g_fForceV2 && gpStateInfo->fWrapText) || gpStateInfo->WindowSize.X > Value) { + if ((g_fForceV2 && gpStateInfo->fWrapText) || gpStateInfo->WindowSize.X > Value) + { gpStateInfo->WindowSize.X = (SHORT)Value; UpdateItem(hDlg, IDD_WINDOW_WIDTH, Value); } break; case IDD_SCRBUF_HEIGHT: gpStateInfo->ScreenBufferSize.Y = (SHORT)Value; - if (gpStateInfo->WindowSize.Y > Value) { + if (gpStateInfo->WindowSize.Y > Value) + { gpStateInfo->WindowSize.Y = (SHORT)Value; UpdateItem(hDlg, IDD_WINDOW_HEIGHT, Value); } @@ -215,14 +225,16 @@ BOOL UpdateStateInfo(HWND hDlg, UINT Item, int Value) gpStateInfo->WindowSize.X = (SHORT)Value; // If we're in V2 mode with wrap text on OR if the buffer is smaller than the window, adjust the buffer to match. - if ((g_fForceV2 && gpStateInfo->fWrapText) || gpStateInfo->ScreenBufferSize.X < Value) { + if ((g_fForceV2 && gpStateInfo->fWrapText) || gpStateInfo->ScreenBufferSize.X < Value) + { gpStateInfo->ScreenBufferSize.X = (SHORT)Value; UpdateItem(hDlg, IDD_SCRBUF_WIDTH, Value); } break; case IDD_WINDOW_HEIGHT: gpStateInfo->WindowSize.Y = (SHORT)Value; - if (gpStateInfo->ScreenBufferSize.Y < Value) { + if (gpStateInfo->ScreenBufferSize.Y < Value) + { gpStateInfo->ScreenBufferSize.Y = (SHORT)Value; UpdateItem(hDlg, IDD_SCRBUF_HEIGHT, Value); } @@ -252,23 +264,23 @@ BOOL UpdateStateInfo(HWND hDlg, UINT Item, int Value) break; case IDD_COLOR_SCREEN_TEXT: gpStateInfo->ScreenAttributes = - (gpStateInfo->ScreenAttributes & 0xF0) | - (Value & 0x0F); + (gpStateInfo->ScreenAttributes & 0xF0) | + (Value & 0x0F); break; case IDD_COLOR_SCREEN_BKGND: gpStateInfo->ScreenAttributes = - (gpStateInfo->ScreenAttributes & 0x0F) | - (WORD)(Value << 4); + (gpStateInfo->ScreenAttributes & 0x0F) | + (WORD)(Value << 4); break; case IDD_COLOR_POPUP_TEXT: gpStateInfo->PopupAttributes = - (gpStateInfo->PopupAttributes & 0xF0) | - (Value & 0x0F); + (gpStateInfo->PopupAttributes & 0xF0) | + (Value & 0x0F); break; case IDD_COLOR_POPUP_BKGND: gpStateInfo->PopupAttributes = - (gpStateInfo->PopupAttributes & 0x0F) | - (WORD)(Value << 4); + (gpStateInfo->PopupAttributes & 0x0F) | + (WORD)(Value << 4); break; case IDD_COLOR_1: case IDD_COLOR_2: @@ -317,7 +329,8 @@ BOOL UpdateStateInfo(HWND hDlg, UINT Item, int Value) if (g_hTerminalDlg != INVALID_HANDLE_VALUE) { CheckRadioButton(g_hTerminalDlg, - IDD_TERMINAL_LEGACY_CURSOR, IDD_TERMINAL_SOLIDBOX, + IDD_TERMINAL_LEGACY_CURSOR, + IDD_TERMINAL_SOLIDBOX, IDD_TERMINAL_LEGACY_CURSOR); } @@ -330,7 +343,8 @@ BOOL UpdateStateInfo(HWND hDlg, UINT Item, int Value) if (g_hTerminalDlg != INVALID_HANDLE_VALUE) { CheckRadioButton(g_hTerminalDlg, - IDD_TERMINAL_LEGACY_CURSOR, IDD_TERMINAL_SOLIDBOX, + IDD_TERMINAL_LEGACY_CURSOR, + IDD_TERMINAL_SOLIDBOX, IDD_TERMINAL_LEGACY_CURSOR); } @@ -343,7 +357,8 @@ BOOL UpdateStateInfo(HWND hDlg, UINT Item, int Value) if (g_hTerminalDlg != INVALID_HANDLE_VALUE) { CheckRadioButton(g_hTerminalDlg, - IDD_TERMINAL_LEGACY_CURSOR, IDD_TERMINAL_SOLIDBOX, + IDD_TERMINAL_LEGACY_CURSOR, + IDD_TERMINAL_SOLIDBOX, IDD_TERMINAL_LEGACY_CURSOR); } @@ -376,7 +391,7 @@ PWSTR TranslateConsoleTitle(_In_ PCWSTR pwszConsoleTitle) size_t cbConsoleTitle; size_t cbSystemRoot; - LPWSTR pwszSysRoot = new(std::nothrow) wchar_t[MAX_PATH]; + LPWSTR pwszSysRoot = new (std::nothrow) wchar_t[MAX_PATH]; if (nullptr != pwszSysRoot) { if (0 != GetWindowsDirectoryW(pwszSysRoot, MAX_PATH)) @@ -390,7 +405,7 @@ PWSTR TranslateConsoleTitle(_In_ PCWSTR pwszConsoleTitle) if (fUnexpand && cchConsoleTitle >= cchSystemRoot && -#pragma prefast(suppress:26018, "We've guaranteed that cchSystemRoot is equal to or smaller than cchConsoleTitle in size.") +#pragma prefast(suppress : 26018, "We've guaranteed that cchSystemRoot is equal to or smaller than cchConsoleTitle in size.") (CSTR_EQUAL == CompareStringOrdinal(pwszConsoleTitle, cchSystemRoot, pwszSysRoot, cchSystemRoot, TRUE))) { cbConsoleTitle -= cbSystemRoot; @@ -412,14 +427,14 @@ PWSTR TranslateConsoleTitle(_In_ PCWSTR pwszConsoleTitle) } memmove(TranslatedConsoleTitle, SYSTEM_ROOT, cbSystemRoot); - TranslatedConsoleTitle += (cbSystemRoot / sizeof(WCHAR)); // skip by characters -- not bytes + TranslatedConsoleTitle += (cbSystemRoot / sizeof(WCHAR)); // skip by characters -- not bytes for (UINT i = 0; i < cbConsoleTitle; i += sizeof(WCHAR)) { -#pragma prefast(suppress:26018, "We are reading the null portion of the buffer on purpose and will escape on reaching it below.") +#pragma prefast(suppress : 26018, "We are reading the null portion of the buffer on purpose and will escape on reaching it below.") if (fSubstitute && *pwszConsoleTitle == '\\') { -#pragma prefast(suppress:26019, "Console title must contain system root if this path was followed.") +#pragma prefast(suppress : 26019, "Console title must contain system root if this path was followed.") *TranslatedConsoleTitle++ = (WCHAR)'_'; } else @@ -449,33 +464,33 @@ UINT CALLBACK PropSheetPageProc(_In_ HWND hWnd, _In_ UINT uMsg, _Inout_ LPPROPSH static UINT cRefs = 0; switch (uMsg) { - case PSPCB_ADDREF: - { - cRefs++; - break; - } + case PSPCB_ADDREF: + { + cRefs++; + break; + } - case PSPCB_RELEASE: + case PSPCB_RELEASE: + { + cRefs--; + if (cRefs == 0) { - cRefs--; - if (cRefs == 0) + if (gpStateInfo->UpdateValues) { - if (gpStateInfo->UpdateValues) - { - // only persist settings if they've changed - SaveConsoleSettingsIfNeeded(hWnd); - } - - UninitializeConsoleState(); + // only persist settings if they've changed + SaveConsoleSettingsIfNeeded(hWnd); } - break; + + UninitializeConsoleState(); } + break; + } } return 1; } -BOOL PopulatePropSheetPageArray(_Out_writes_(cPsps) PROPSHEETPAGE *pPsp, const size_t cPsps, const BOOL fRegisterCallbacks) +BOOL PopulatePropSheetPageArray(_Out_writes_(cPsps) PROPSHEETPAGE* pPsp, const size_t cPsps, const BOOL fRegisterCallbacks) { BOOL fRet = (cPsps == NUMBER_OF_PAGES); if (fRet) @@ -489,8 +504,8 @@ BOOL PopulatePropSheetPageArray(_Out_writes_(cPsps) PROPSHEETPAGE *pPsp, const s PROPSHEETPAGE* const pColorsPage = &(pPsp[COLORS_PAGE_INDEX]); PROPSHEETPAGE* const pTerminalPage = &(pPsp[TERMINAL_PAGE_INDEX]); - pOptionsPage->dwSize = sizeof(PROPSHEETPAGE); - pOptionsPage->hInstance = ghInstance; + pOptionsPage->dwSize = sizeof(PROPSHEETPAGE); + pOptionsPage->hInstance = ghInstance; if (g_fIsComCtlV6Present) { pOptionsPage->pszTemplate = (gpStateInfo->Defaults) ? MAKEINTRESOURCE(DID_SETTINGS) : MAKEINTRESOURCE(DID_SETTINGS2); @@ -499,38 +514,38 @@ BOOL PopulatePropSheetPageArray(_Out_writes_(cPsps) PROPSHEETPAGE *pPsp, const s { pOptionsPage->pszTemplate = (gpStateInfo->Defaults) ? MAKEINTRESOURCE(DID_SETTINGS_COMCTL5) : MAKEINTRESOURCE(DID_SETTINGS2_COMCTL5); } - pOptionsPage->pfnDlgProc = SettingsDlgProc; - pOptionsPage->lParam = OPTIONS_PAGE_INDEX; - pOptionsPage->dwFlags = PSP_DEFAULT; + pOptionsPage->pfnDlgProc = SettingsDlgProc; + pOptionsPage->lParam = OPTIONS_PAGE_INDEX; + pOptionsPage->dwFlags = PSP_DEFAULT; - pFontPage->dwSize = sizeof(PROPSHEETPAGE); - pFontPage->hInstance = ghInstance; + pFontPage->dwSize = sizeof(PROPSHEETPAGE); + pFontPage->hInstance = ghInstance; pFontPage->pszTemplate = MAKEINTRESOURCE(DID_FONTDLG); - pFontPage->pfnDlgProc = FontDlgProc; - pFontPage->lParam = FONT_PAGE_INDEX; - pOptionsPage->dwFlags = PSP_DEFAULT; + pFontPage->pfnDlgProc = FontDlgProc; + pFontPage->lParam = FONT_PAGE_INDEX; + pOptionsPage->dwFlags = PSP_DEFAULT; - pLayoutPage->dwSize = sizeof(PROPSHEETPAGE); - pLayoutPage->hInstance = ghInstance; + pLayoutPage->dwSize = sizeof(PROPSHEETPAGE); + pLayoutPage->hInstance = ghInstance; pLayoutPage->pszTemplate = MAKEINTRESOURCE(DID_SCRBUFSIZE); - pLayoutPage->pfnDlgProc = ScreenSizeDlgProc; - pLayoutPage->lParam = LAYOUT_PAGE_INDEX; - pOptionsPage->dwFlags = PSP_DEFAULT; + pLayoutPage->pfnDlgProc = ScreenSizeDlgProc; + pLayoutPage->lParam = LAYOUT_PAGE_INDEX; + pOptionsPage->dwFlags = PSP_DEFAULT; - pColorsPage->dwSize = sizeof(PROPSHEETPAGE); - pColorsPage->hInstance = ghInstance; + pColorsPage->dwSize = sizeof(PROPSHEETPAGE); + pColorsPage->hInstance = ghInstance; pColorsPage->pszTemplate = MAKEINTRESOURCE(DID_COLOR); - pColorsPage->pfnDlgProc = ColorDlgProc; - pColorsPage->lParam = COLORS_PAGE_INDEX; - pOptionsPage->dwFlags = PSP_DEFAULT; + pColorsPage->pfnDlgProc = ColorDlgProc; + pColorsPage->lParam = COLORS_PAGE_INDEX; + pOptionsPage->dwFlags = PSP_DEFAULT; if (g_fForceV2) { - pTerminalPage->dwSize = sizeof(PROPSHEETPAGE); - pTerminalPage->hInstance = ghInstance; + pTerminalPage->dwSize = sizeof(PROPSHEETPAGE); + pTerminalPage->hInstance = ghInstance; pTerminalPage->pszTemplate = MAKEINTRESOURCE(DID_TERMINAL); - pTerminalPage->pfnDlgProc = TerminalDlgProc; - pTerminalPage->lParam = TERMINAL_PAGE_INDEX; - pTerminalPage->dwFlags = PSP_DEFAULT; + pTerminalPage->pfnDlgProc = TerminalDlgProc; + pTerminalPage->lParam = TERMINAL_PAGE_INDEX; + pTerminalPage->dwFlags = PSP_DEFAULT; } // Register callbacks if requested (used for file property sheet purposes) @@ -556,7 +571,7 @@ INT_PTR ConsolePropertySheet(__in HWND hWnd, __in PCONSOLE_STATE_INFO pStateInfo PROPSHEETPAGE psp[NUMBER_OF_PAGES]; PROPSHEETHEADER psh; INT_PTR Result = IDCANCEL; - WCHAR awchBuffer[MAX_PATH] = {0}; + WCHAR awchBuffer[MAX_PATH] = { 0 }; gpStateInfo = pStateInfo; @@ -573,7 +588,8 @@ INT_PTR ConsolePropertySheet(__in HWND hWnd, __in PCONSOLE_STATE_INFO pStateInfo // // Initialize the state information. // - if (gpStateInfo->Defaults) { + if (gpStateInfo->Defaults) + { InitRegistryValues(pStateInfo); GetRegistryValues(pStateInfo); } @@ -608,9 +624,12 @@ INT_PTR ConsolePropertySheet(__in HWND hWnd, __in PCONSOLE_STATE_INFO pStateInfo psh.dwSize = sizeof(PROPSHEETHEADER); psh.dwFlags = PSH_PROPTITLE | PSH_USEHICON | PSH_PROPSHEETPAGE | PSH_NOAPPLYNOW | PSH_USECALLBACK | PSH_NOCONTEXTHELP; - if (gpStateInfo->Defaults) { + if (gpStateInfo->Defaults) + { LoadString(ghInstance, IDS_TITLE, awchBuffer, ARRAYSIZE(awchBuffer)); - } else { + } + else + { awchBuffer[0] = L'"'; ExpandEnvironmentStrings(gpStateInfo->OriginalTitle, &awchBuffer[1], @@ -641,8 +660,10 @@ INT_PTR ConsolePropertySheet(__in HWND hWnd, __in PCONSOLE_STATE_INFO pStateInfo SaveConsoleSettingsIfNeeded(hWnd); gpStateInfo->UpdateValues = fUpdatedValues; - if (!gpStateInfo->Defaults) { - if (gpStateInfo->OriginalTitle != NULL) { + if (!gpStateInfo->Defaults) + { + if (gpStateInfo->OriginalTitle != NULL) + { HeapFree(GetProcessHeap(), 0, gpStateInfo->OriginalTitle); } } @@ -659,51 +680,50 @@ void RegisterClasses(HINSTANCE hModule) { WNDCLASS wc; wc.lpszClassName = TEXT("SimpleColor"); - wc.hInstance = hModule; - wc.lpfnWndProc = SimpleColorControlProc; - wc.hCursor = LoadCursor(NULL, IDC_ARROW); - wc.hIcon = NULL; - wc.lpszMenuName = NULL; - wc.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1); - wc.style = CS_HREDRAW | CS_VREDRAW; - wc.cbClsExtra = 0; - wc.cbWndExtra = 0; + wc.hInstance = hModule; + wc.lpfnWndProc = SimpleColorControlProc; + wc.hCursor = LoadCursor(NULL, IDC_ARROW); + wc.hIcon = NULL; + wc.lpszMenuName = NULL; + wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); + wc.style = CS_HREDRAW | CS_VREDRAW; + wc.cbClsExtra = 0; + wc.cbWndExtra = 0; RegisterClass(&wc); wc.lpszClassName = TEXT("ColorTableColor"); - wc.hInstance = hModule; - wc.lpfnWndProc = ColorTableControlProc; - wc.hCursor = LoadCursor(NULL, IDC_ARROW); - wc.hIcon = NULL; - wc.lpszMenuName = NULL; - wc.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1); - wc.style = CS_HREDRAW | CS_VREDRAW; - wc.cbClsExtra = 0; - wc.cbWndExtra = 0; + wc.hInstance = hModule; + wc.lpfnWndProc = ColorTableControlProc; + wc.hCursor = LoadCursor(NULL, IDC_ARROW); + wc.hIcon = NULL; + wc.lpszMenuName = NULL; + wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); + wc.style = CS_HREDRAW | CS_VREDRAW; + wc.cbClsExtra = 0; + wc.cbWndExtra = 0; RegisterClass(&wc); wc.lpszClassName = TEXT("WOAWinPreview"); - wc.lpfnWndProc = PreviewWndProc; - wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND + 1); - wc.style = 0; + wc.lpfnWndProc = PreviewWndProc; + wc.hbrBackground = (HBRUSH)(COLOR_BACKGROUND + 1); + wc.style = 0; RegisterClass(&wc); wc.lpszClassName = TEXT("WOAFontPreview"); - wc.lpfnWndProc = FontPreviewWndProc; - wc.hbrBackground = (HBRUSH) GetStockObject(BLACK_BRUSH); - wc.style = 0; + wc.lpfnWndProc = FontPreviewWndProc; + wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); + wc.style = 0; RegisterClass(&wc); } void UnregisterClasses(HINSTANCE hModule) { - UnregisterClass(TEXT("cpColor"), hModule); - UnregisterClass(TEXT("WOAWinPreview"), hModule); + UnregisterClass(TEXT("cpColor"), hModule); + UnregisterClass(TEXT("WOAWinPreview"), hModule); UnregisterClass(TEXT("WOAFontPreview"), hModule); } -[[nodiscard]] -HRESULT FindFontAndUpdateState() +[[nodiscard]] HRESULT FindFontAndUpdateState() { g_currentFontIndex = FindCreateFont(gpStateInfo->FontFamily, gpStateInfo->FaceName, diff --git a/src/propsheet/console.h b/src/propsheet/console.h index 4af41492e..8094ce31d 100644 --- a/src/propsheet/console.h +++ b/src/propsheet/console.h @@ -33,12 +33,13 @@ Revision History: // Icon ID. // -#define IDI_CONSOLE 1 +#define IDI_CONSOLE 1 // // String table constants // +// clang-format off #define IDS_NAME 1 #define IDS_INFO 2 #define IDS_TITLE 3 @@ -57,68 +58,51 @@ Revision History: // unused 16 #define IDS_TOOLTIP_OPACITY 17 #define IDS_TOOLTIP_INTERCEPT_COPY_PASTE 18 +// clang-format on -void -MakeAltRasterFont( +void MakeAltRasterFont( __in UINT CodePage, - __out COORD *AltFontSize, - __out BYTE *AltFontFamily, - __out ULONG *AltFontIndex, + __out COORD* AltFontSize, + __out BYTE* AltFontFamily, + __out ULONG* AltFontIndex, __out_ecount(LF_FACESIZE) LPTSTR AltFaceName); -[[nodiscard]] -NTSTATUS InitializeDbcsMisc(VOID); +[[nodiscard]] NTSTATUS InitializeDbcsMisc(VOID); -BYTE -CodePageToCharSet( - UINT CodePage - ); +BYTE CodePageToCharSet( + UINT CodePage); -BOOL -ShouldAllowAllMonoTTFonts(); +BOOL ShouldAllowAllMonoTTFonts(); LPTTFONTLIST SearchTTFont( __in_opt LPCTSTR ptszFace, - BOOL fCodePage, - UINT CodePage - ); + BOOL fCodePage, + UINT CodePage); -BOOL -IsAvailableTTFont( - LPCTSTR ptszFace - ); +BOOL IsAvailableTTFont( + LPCTSTR ptszFace); -BOOL -IsAvailableTTFontCP( +BOOL IsAvailableTTFontCP( LPCTSTR ptszFace, - UINT CodePage - ); + UINT CodePage); -BOOL -IsDisableBoldTTFont( - LPCTSTR ptszFace - ); +BOOL IsDisableBoldTTFont( + LPCTSTR ptszFace); LPTSTR GetAltFaceName( - LPCTSTR ptszFace - ); + LPCTSTR ptszFace); -[[nodiscard]] -NTSTATUS DestroyDbcsMisc(VOID); +[[nodiscard]] NTSTATUS DestroyDbcsMisc(VOID); -int -LanguageListCreate( +int LanguageListCreate( HWND hDlg, - UINT CodePage - ); + UINT CodePage); -int -LanguageDisplay( +int LanguageDisplay( HWND hDlg, - UINT CodePage - ) ; + UINT CodePage); // // Function prototypes @@ -152,15 +136,13 @@ VOID SetRegistryValues( PCONSOLE_STATE_INFO StateInfo, DWORD dwPage); -[[nodiscard]] -LRESULT CALLBACK FontPreviewWndProc( +[[nodiscard]] LRESULT CALLBACK FontPreviewWndProc( HWND hWnd, UINT wMsg, WPARAM wParam, LPARAM lParam); -[[nodiscard]] -LRESULT CALLBACK PreviewWndProc( +[[nodiscard]] LRESULT CALLBACK PreviewWndProc( HWND hWnd, UINT wMsg, WPARAM wParam, @@ -178,10 +160,9 @@ BOOL UpdateStateInfo( BOOL InitializeConsoleState(); void UninitializeConsoleState(); void UpdateApplyButton(const HWND hDlg); -[[nodiscard]] -HRESULT FindFontAndUpdateState(); +[[nodiscard]] HRESULT FindFontAndUpdateState(); -BOOL PopulatePropSheetPageArray(_Out_writes_(cPsps) PROPSHEETPAGE *pPsp, const size_t cPsps, const BOOL fRegisterCallbacks); +BOOL PopulatePropSheetPageArray(_Out_writes_(cPsps) PROPSHEETPAGE* pPsp, const size_t cPsps, const BOOL fRegisterCallbacks); void CreateAndAssociateToolTipToControl(const UINT dlgItem, const HWND hDlg, const UINT idsToolTip); @@ -192,16 +173,17 @@ void Undo(HWND hControlWindow); // // Macros // -#define AttrToRGB(Attr) (gpStateInfo->ColorTable[(Attr) & 0x0F]) +#define AttrToRGB(Attr) (gpStateInfo->ColorTable[(Attr)&0x0F]) #define ScreenTextColor(pStateInfo) \ - (AttrToRGB(LOBYTE(pStateInfo->ScreenAttributes) & 0x0F)) + (AttrToRGB(LOBYTE(pStateInfo->ScreenAttributes) & 0x0F)) #define ScreenBkColor(pStateInfo) \ - (AttrToRGB(LOBYTE(pStateInfo->ScreenAttributes >> 4))) + (AttrToRGB(LOBYTE(pStateInfo->ScreenAttributes >> 4))) #define PopupTextColor(pStateInfo) \ - (AttrToRGB(LOBYTE(pStateInfo->PopupAttributes) & 0x0F)) + (AttrToRGB(LOBYTE(pStateInfo->PopupAttributes) & 0x0F)) #define PopupBkColor(pStateInfo) \ - (AttrToRGB(LOBYTE(pStateInfo->PopupAttributes >> 4))) + (AttrToRGB(LOBYTE(pStateInfo->PopupAttributes >> 4))) +// clang-format off #if DBG #define _DBGFONTS 0x00000001 #define _DBGFONTS2 0x00000002 @@ -220,17 +202,18 @@ void Undo(HWND hControlWindow); #define DBGCHARS(_params_) #define DBGOUTPUT(_params_) #endif +// clang-format on // Macro definitions that handle codepages // -#define CP_US (UINT)437 -#define CP_JPN (UINT)932 -#define CP_WANSUNG (UINT)949 -#define CP_TC (UINT)950 -#define CP_SC (UINT)936 +#define CP_US (UINT)437 +#define CP_JPN (UINT)932 +#define CP_WANSUNG (UINT)949 +#define CP_TC (UINT)950 +#define CP_SC (UINT)936 -#define IsBilingualCP(cp) ((cp)==CP_JPN || (cp)==CP_WANSUNG) -#define IsEastAsianCP(cp) ((cp)==CP_JPN || (cp)==CP_WANSUNG || (cp)==CP_TC || (cp)==CP_SC) +#define IsBilingualCP(cp) ((cp) == CP_JPN || (cp) == CP_WANSUNG) +#define IsEastAsianCP(cp) ((cp) == CP_JPN || (cp) == CP_WANSUNG || (cp) == CP_TC || (cp) == CP_SC) const unsigned int TRANSPARENCY_RANGE_MIN = 0x4D; diff --git a/src/propsheet/dbcs.cpp b/src/propsheet/dbcs.cpp index c02f9e6ef..9937ab934 100644 --- a/src/propsheet/dbcs.cpp +++ b/src/propsheet/dbcs.cpp @@ -23,29 +23,26 @@ Revision History: #include #pragma hdrstop -void -MakeAltRasterFont( +void MakeAltRasterFont( __in UINT CodePage, - __out COORD *AltFontSize, - __out BYTE *AltFontFamily, - __out ULONG *AltFontIndex, - __out_ecount(LF_FACESIZE) LPTSTR AltFaceName - ) + __out COORD* AltFontSize, + __out BYTE* AltFontFamily, + __out ULONG* AltFontIndex, + __out_ecount(LF_FACESIZE) LPTSTR AltFaceName) { DWORD i; DWORD Find; ULONG FontIndex; COORD FontSize = FontInfo[DefaultFontIndex].Size; COORD FontDelta; - BOOL fDbcsCharSet = IS_ANY_DBCS_CHARSET( CodePageToCharSet( CodePage ) ); + BOOL fDbcsCharSet = IS_ANY_DBCS_CHARSET(CodePageToCharSet(CodePage)); FontIndex = 0; Find = (DWORD)-1; - for (i=0; i < NumberOfFonts; i++) + for (i = 0; i < NumberOfFonts; i++) { if (!TM_IS_TT_FONT(FontInfo[i].Family) && - IS_ANY_DBCS_CHARSET(FontInfo[i].tmCharSet) == fDbcsCharSet - ) + IS_ANY_DBCS_CHARSET(FontInfo[i].tmCharSet) == fDbcsCharSet) { FontDelta.X = (SHORT)abs(FontSize.X - FontInfo[i].Size.X); FontDelta.Y = (SHORT)abs(FontSize.Y - FontInfo[i].Size.Y); @@ -65,21 +62,20 @@ MakeAltRasterFont( DBGFONTS(("MakeAltRasterFont : AltFontIndex = %ld\n", *AltFontIndex)); } -[[nodiscard]] -NTSTATUS -InitializeDbcsMisc( - VOID) +[[nodiscard]] NTSTATUS + InitializeDbcsMisc( + VOID) { return TrueTypeFontList::s_Initialize(); } -BYTE -CodePageToCharSet( +BYTE CodePageToCharSet( UINT CodePage) { CHARSETINFO csi; - if (!TranslateCharsetInfo((DWORD *)IntToPtr(CodePage), &csi, TCI_SRCCODEPAGE)) { + if (!TranslateCharsetInfo((DWORD*)IntToPtr(CodePage), &csi, TCI_SRCCODEPAGE)) + { csi.ciCharset = OEM_CHARSET; } @@ -89,46 +85,51 @@ CodePageToCharSet( LPTTFONTLIST SearchTTFont( __in_opt LPCTSTR ptszFace, - BOOL fCodePage, - UINT CodePage - ) + BOOL fCodePage, + UINT CodePage) { return TrueTypeFontList::s_SearchByName(ptszFace, fCodePage, CodePage); } -BOOL -IsAvailableTTFont( +BOOL IsAvailableTTFont( LPCTSTR ptszFace) { - if (SearchTTFont(ptszFace, FALSE, 0)) { + if (SearchTTFont(ptszFace, FALSE, 0)) + { return TRUE; - } else { + } + else + { return FALSE; } } -BOOL -IsAvailableTTFontCP( +BOOL IsAvailableTTFontCP( LPCTSTR ptszFace, UINT CodePage) { - if (SearchTTFont(ptszFace, TRUE, CodePage)) { + if (SearchTTFont(ptszFace, TRUE, CodePage)) + { return TRUE; - } else { + } + else + { return FALSE; } } -BOOL -IsDisableBoldTTFont( +BOOL IsDisableBoldTTFont( LPCTSTR ptszFace) { LPTTFONTLIST pTTFontList; pTTFontList = SearchTTFont(ptszFace, FALSE, 0); - if (pTTFontList != NULL) { + if (pTTFontList != NULL) + { return pTTFontList->fDisableBold; - } else { + } + else + { return FALSE; } } @@ -140,12 +141,15 @@ GetAltFaceName( LPTTFONTLIST pTTFontList; pTTFontList = SearchTTFont(ptszFace, FALSE, 0); - if (pTTFontList != NULL) { - if (wcscmp(ptszFace, pTTFontList->FaceName1) == 0) { + if (pTTFontList != NULL) + { + if (wcscmp(ptszFace, pTTFontList->FaceName1) == 0) + { return pTTFontList->FaceName2; } - if (wcscmp(ptszFace, pTTFontList->FaceName2) == 0) { + if (wcscmp(ptszFace, pTTFontList->FaceName2) == 0) + { return pTTFontList->FaceName1; } } @@ -153,19 +157,16 @@ GetAltFaceName( return NULL; } -[[nodiscard]] -NTSTATUS -DestroyDbcsMisc( - VOID) +[[nodiscard]] NTSTATUS + DestroyDbcsMisc( + VOID) { return TrueTypeFontList::s_Destroy(); } -int -LanguageListCreate( +int LanguageListCreate( HWND hDlg, - UINT CodePage - ) + UINT CodePage) /*++ @@ -229,7 +230,6 @@ LanguageListCreate( return iRet; } - int LanguageDisplay(HWND hDlg, UINT CodePage) { CPINFOEX cpinfo; @@ -243,11 +243,9 @@ int LanguageDisplay(HWND hDlg, UINT CodePage) } // For a given codepage, determine what the default truetype font should be -[[nodiscard]] -NTSTATUS GetTTFontFaceForCodePage(const UINT uiCodePage, // the codepage to examine (note: not charset) - _Out_writes_(cchFaceName) PWSTR pszFaceName, // where to write the facename we find - const size_t cchFaceName) // space available in pszFaceName +[[nodiscard]] NTSTATUS GetTTFontFaceForCodePage(const UINT uiCodePage, // the codepage to examine (note: not charset) + _Out_writes_(cchFaceName) PWSTR pszFaceName, // where to write the facename we find + const size_t cchFaceName) // space available in pszFaceName { return TrueTypeFontList::s_SearchByCodePage(uiCodePage, pszFaceName, cchFaceName); } - diff --git a/src/propsheet/dialogs.h b/src/propsheet/dialogs.h index 8bf113973..763aff876 100644 --- a/src/propsheet/dialogs.h +++ b/src/propsheet/dialogs.h @@ -21,6 +21,8 @@ Revision History: #pragma once +// clang-format off + #define DID_SETTINGS 100 // unused 101 // unused 102 @@ -159,6 +161,4 @@ Revision History: #define BM_TRUETYPE_ICON 1000 - - - +// clang-format on diff --git a/src/propsheet/dll.cpp b/src/propsheet/dll.cpp index 7f7ae4737..75e80e11d 100644 --- a/src/propsheet/dll.cpp +++ b/src/propsheet/dll.cpp @@ -7,7 +7,8 @@ using namespace Microsoft::WRL; #if !defined(__WRL_WINRT_STRICT__) _Check_return_ -STDAPI DllGetClassObject(_In_ REFCLSID rclsid, _In_ REFIID riid, _Outptr_ void** ppv) + STDAPI + DllGetClassObject(_In_ REFCLSID rclsid, _In_ REFIID riid, _Outptr_ void** ppv) { return Module::GetModule().GetClassObject(rclsid, riid, ppv); } diff --git a/src/propsheet/font.h b/src/propsheet/font.h index c76f86e38..8cf120d31 100644 --- a/src/propsheet/font.h +++ b/src/propsheet/font.h @@ -26,6 +26,7 @@ Revision History: #define INITIAL_FONTS 20 #define FONT_INCREMENT 3 +// clang-format off #define EF_NEW 0x0001 // a newly available face #define EF_OLD 0x0002 // a previously available face #define EF_ENUMERATED 0x0004 // all sizes have been enumerated @@ -33,6 +34,7 @@ Revision History: #define EF_TTFONT 0x0010 // a TT face #define EF_DEFFACE 0x0020 // the default face #define EF_DBCSFONT 0x0040 // the DBCS font +// clang-format on /* * FONT_INFO @@ -47,68 +49,65 @@ Revision History: * * The SizeDesired is {0, 0} if the font is a raster font. */ -typedef struct _FONT_INFO { +typedef struct _FONT_INFO +{ HFONT hFont; - COORD Size; // font size obtained - COORD SizeWant; // 0;0 if Raster font - LONG Weight; + COORD Size; // font size obtained + COORD SizeWant; // 0;0 if Raster font + LONG Weight; LPTSTR FaceName; - BYTE Family; - BYTE tmCharSet; + BYTE Family; + BYTE tmCharSet; } FONT_INFO, *PFONT_INFO; #pragma warning(push) -#pragma warning(disable:4200) // nonstandard extension used : zero-sized array in struct/union +#pragma warning(disable : 4200) // nonstandard extension used : zero-sized array in struct/union -typedef struct tagFACENODE { - struct tagFACENODE *pNext; - DWORD dwFlag; - TCHAR atch[]; +typedef struct tagFACENODE +{ + struct tagFACENODE* pNext; + DWORD dwFlag; + TCHAR atch[]; } FACENODE, *PFACENODE; #pragma warning(pop) -#define TM_IS_TT_FONT(x) (((x) & TMPF_TRUETYPE) == TMPF_TRUETYPE) -#define IS_BOLD(w) ((w) >= FW_SEMIBOLD) -#define SIZE_EQUAL(s1, s2) (((s1).X == (s2).X) && ((s1).Y == (s2).Y)) +#define TM_IS_TT_FONT(x) (((x)&TMPF_TRUETYPE) == TMPF_TRUETYPE) +#define IS_BOLD(w) ((w) >= FW_SEMIBOLD) +#define SIZE_EQUAL(s1, s2) (((s1).X == (s2).X) && ((s1).Y == (s2).Y)) #define POINTS_PER_INCH 72 #define MIN_PIXEL_HEIGHT 5 #define MAX_PIXEL_HEIGHT 72 - // // Function prototypes // VOID -InitializeFonts(VOID); + InitializeFonts(VOID); VOID -DestroyFonts(VOID); + DestroyFonts(VOID); -[[nodiscard]] -NTSTATUS +[[nodiscard]] NTSTATUS EnumerateFonts(DWORD Flags); -int -FindCreateFont( +int FindCreateFont( __in DWORD Family, __in_ecount(LF_FACESIZE) LPWSTR ptszFace, __in COORD Size, __in LONG Weight, __in UINT CodePage); -BOOL -DoFontEnum( +BOOL DoFontEnum( __in_opt HDC hDC, __in_ecount_opt(LF_FACESIZE) LPTSTR ptszFace, __in_ecount_opt(nTTPoints) PSHORT pTTPoints, __in UINT nTTPoints); -[[nodiscard]] -NTSTATUS GetTTFontFaceForCodePage(const UINT uiCodePage, - _Out_writes_(cchFaceName) PWSTR pszFaceName, - const size_t cchFaceName); +[[nodiscard]] NTSTATUS GetTTFontFaceForCodePage(const UINT uiCodePage, + _Out_writes_(cchFaceName) PWSTR pszFaceName, + const size_t cchFaceName); bool IsFontSizeCustom(__in PCWSTR pwszFaceName, __in const SHORT sSize); void CreateSizeForAllTTFonts(__in const SHORT sSize); diff --git a/src/propsheet/fontdlg.cpp b/src/propsheet/fontdlg.cpp index 9be6e0932..8dd0511cb 100644 --- a/src/propsheet/fontdlg.cpp +++ b/src/propsheet/fontdlg.cpp @@ -51,17 +51,15 @@ void RecreateFontHandles(const HWND hWnd); /* ----- Globals ----- */ HBITMAP hbmTT = NULL; // handle of TT logo bitmap -BITMAP bmTT; // attributes of TT source bitmap +BITMAP bmTT; // attributes of TT source bitmap BOOL gbPointSizeError = FALSE; BOOL gbBold = FALSE; BOOL gbUserChoseBold = FALSE; // TRUE if bold state was due to user choice -BOOL -SelectCurrentFont( +BOOL SelectCurrentFont( HWND hDlg, - int FontIndex - ); + int FontIndex); // Globals strings loaded from resource WCHAR wszSelectedFont[CCH_SELECTEDFONT + 1]; @@ -84,7 +82,7 @@ UINT GetItemHeight(const HWND hDlg) HFONT hFont = GetWindowFont(hDlg); if (hFont) { - hFont = (HFONT) SelectObject(hDC, hFont); + hFont = (HFONT)SelectObject(hDC, hFont); } TEXTMETRIC tm; GetTextMetrics(hDC, &tm); @@ -99,7 +97,7 @@ UINT GetItemHeight(const HWND hDlg) // The V1 console doesn't support arbitrary TTF fonts, so only allow the enumeration of all TT fonts in the conditions below: BOOL ShouldAllowAllMonoTTFonts() { - return (gpStateInfo->fIsV2Console || // allow if connected to a v2 conhost or + return (gpStateInfo->fIsV2Console || // allow if connected to a v2 conhost or (gpStateInfo->Defaults && g_fForceV2)); // we're in defaults and v2 is turned on } @@ -134,7 +132,7 @@ BOOL IsBoldOnlyTTFont(_In_ PCWSTR pwszTTFace, _In_opt_ PCWSTR pwszAltTTFace) // only care if this TT font's name matches if ((0 != lstrcmp(FontInfo[i].FaceName, pwszTTFace)) && // wrong face name and - (pwszAltTTFace == NULL || // either pwszAltTTFace is NULL or + (pwszAltTTFace == NULL || // either pwszAltTTFace is NULL or (0 != lstrcmp(FontInfo[i].FaceName, pwszAltTTFace)))) // pwszAltTTFace is wrong too { // A TrueType font, but not the one we're interested in @@ -216,8 +214,7 @@ FontDlgProc( HWND hDlg, UINT wMsg, WPARAM wParam, - LPARAM lParam - ) + LPARAM lParam) /*++ @@ -232,29 +229,27 @@ FontDlgProc( int FontIndex = g_currentFontIndex; // init to keep compiler happy BOOL bLB; - switch (wMsg) { + switch (wMsg) + { case WM_INITDIALOG: /* * Load the font description strings */ - LoadString(ghInstance, IDS_RASTERFONT, - wszRasterFonts, ARRAYSIZE(wszRasterFonts)); + LoadString(ghInstance, IDS_RASTERFONT, wszRasterFonts, ARRAYSIZE(wszRasterFonts)); DBGFONTS(("wszRasterFonts = \"%ls\"\n", wszRasterFonts)); - LoadString(ghInstance, IDS_SELECTEDFONT, - wszSelectedFont, ARRAYSIZE(wszSelectedFont)); + LoadString(ghInstance, IDS_SELECTEDFONT, wszSelectedFont, ARRAYSIZE(wszSelectedFont)); DBGFONTS(("wszSelectedFont = \"%ls\"\n", wszSelectedFont)); /* Save current font size as dialog window's user data */ - if (g_fEastAsianSystem) { - SetWindowLongPtr(hDlg, GWLP_USERDATA, - MAKELONG(FontInfo[g_currentFontIndex].tmCharSet, - FontInfo[g_currentFontIndex].Size.Y)); - } else { - SetWindowLongPtr(hDlg, GWLP_USERDATA, - MAKELONG(FontInfo[g_currentFontIndex].Size.X, - FontInfo[g_currentFontIndex].Size.Y)); + if (g_fEastAsianSystem) + { + SetWindowLongPtr(hDlg, GWLP_USERDATA, MAKELONG(FontInfo[g_currentFontIndex].tmCharSet, FontInfo[g_currentFontIndex].Size.Y)); + } + else + { + SetWindowLongPtr(hDlg, GWLP_USERDATA, MAKELONG(FontInfo[g_currentFontIndex].Size.X, FontInfo[g_currentFontIndex].Size.Y)); } if (g_fHostedInFileProperties || gpStateInfo->Defaults) @@ -325,7 +320,8 @@ FontDlgProc( return TRUE; case WM_PAINT: - if (fChangeCodePage) { + if (fChangeCodePage) + { fChangeCodePage = FALSE; /* Create the list of suitable fonts */ @@ -356,41 +352,43 @@ FontDlgProc( switch (HIWORD(wParam)) { case LBN_SELCHANGE: -RedoFontListAndPreview: + RedoFontListAndPreview: + { + // if the font we're switching away from is a bold-only TT font, and the user didn't explicitly ask + // for bold earlier, then unset bold. note that we're depending on the fact that by this point + // FontIndex hasn't yet been updated to refer to the new font that the user selected. + if (IS_BOLD(FontInfo[FontIndex].Weight) && + IsBoldOnlyTTFont(FontInfo[FontIndex].FaceName, NULL) && + !gbUserChoseBold) { - // if the font we're switching away from is a bold-only TT font, and the user didn't explicitly ask - // for bold earlier, then unset bold. note that we're depending on the fact that by this point - // FontIndex hasn't yet been updated to refer to the new font that the user selected. - if (IS_BOLD(FontInfo[FontIndex].Weight) && - IsBoldOnlyTTFont(FontInfo[FontIndex].FaceName, NULL) && - !gbUserChoseBold) - { - gbBold = FALSE; - } - - WCHAR atchNewFace[LF_FACESIZE]; - LONG l; - - DBGFONTS(("LBN_SELCHANGE from FACENAME\n")); - l = (LONG)SendDlgItemMessage(hDlg, IDD_FACENAME, LB_GETCURSEL, 0, 0L); - bLB = (BOOL)SendDlgItemMessage(hDlg, IDD_FACENAME, LB_GETITEMDATA, l, 0L); - if (!bLB) { - SendDlgItemMessage(hDlg, IDD_FACENAME, LB_GETTEXT, l, (LPARAM)atchNewFace); - DBGFONTS(("LBN_EDITUPDATE, got TT face \"%ls\"\n", atchNewFace)); - } - FontIndex = FontListCreate(hDlg, - bLB ? NULL : atchNewFace, - FALSE); - SelectCurrentSize(hDlg, bLB, FontIndex); - PreviewUpdate(hDlg, bLB); - UpdateApplyButton(hDlg); - return TRUE; + gbBold = FALSE; } + + WCHAR atchNewFace[LF_FACESIZE]; + LONG l; + + DBGFONTS(("LBN_SELCHANGE from FACENAME\n")); + l = (LONG)SendDlgItemMessage(hDlg, IDD_FACENAME, LB_GETCURSEL, 0, 0L); + bLB = (BOOL)SendDlgItemMessage(hDlg, IDD_FACENAME, LB_GETITEMDATA, l, 0L); + if (!bLB) + { + SendDlgItemMessage(hDlg, IDD_FACENAME, LB_GETTEXT, l, (LPARAM)atchNewFace); + DBGFONTS(("LBN_EDITUPDATE, got TT face \"%ls\"\n", atchNewFace)); + } + FontIndex = FontListCreate(hDlg, + bLB ? NULL : atchNewFace, + FALSE); + SelectCurrentSize(hDlg, bLB, FontIndex); + PreviewUpdate(hDlg, bLB); + UpdateApplyButton(hDlg); + return TRUE; + } } break; case IDD_POINTSLIST: - switch (HIWORD(wParam)) { + switch (HIWORD(wParam)) + { case CBN_SELCHANGE: DBGFONTS(("CBN_SELCHANGE from POINTSLIST\n")); PreviewUpdate(hDlg, FALSE); @@ -399,10 +397,12 @@ RedoFontListAndPreview: case CBN_KILLFOCUS: DBGFONTS(("CBN_KILLFOCUS from POINTSLIST\n")); - if (!gbPointSizeError) { + if (!gbPointSizeError) + { hWndFocus = GetFocus(); if (hWndFocus != NULL && IsChild(hDlg, hWndFocus) && - hWndFocus != GetDlgItem(hDlg, IDCANCEL)) { + hWndFocus != GetDlgItem(hDlg, IDCANCEL)) + { AddCustomFontSizeToListIfNeeded(hDlg); PreviewUpdate(hDlg, FALSE); } @@ -410,13 +410,14 @@ RedoFontListAndPreview: return TRUE; default: - DBGFONTS(("unhandled CBN_%x from POINTSLIST\n",HIWORD(wParam))); + DBGFONTS(("unhandled CBN_%x from POINTSLIST\n", HIWORD(wParam))); break; } break; case IDD_PIXELSLIST: - switch (HIWORD(wParam)) { + switch (HIWORD(wParam)) + { case LBN_SELCHANGE: DBGFONTS(("LBN_SELCHANGE from PIXELSLIST\n")); PreviewUpdate(hDlg, TRUE); @@ -435,15 +436,18 @@ RedoFontListAndPreview: case WM_NOTIFY: { - const PSHNOTIFY * const pshn = (LPPSHNOTIFY)lParam; - switch (pshn->hdr.code) { + const PSHNOTIFY* const pshn = (LPPSHNOTIFY)lParam; + switch (pshn->hdr.code) + { case PSN_KILLACTIVE: // // If the TT combo box is visible, update selection // hWndList = GetDlgItem(hDlg, IDD_POINTSLIST); - if (hWndList != NULL && IsWindowVisible(hWndList)) { - if (!PreviewUpdate(hDlg, FALSE)) { + if (hWndList != NULL && IsWindowVisible(hWndList)) + { + if (!PreviewUpdate(hDlg, FALSE)) + { SetDlgMsgResult(hDlg, PSN_KILLACTIVE, TRUE); return TRUE; } @@ -452,10 +456,13 @@ RedoFontListAndPreview: FontIndex = g_currentFontIndex; - if (FontInfo[FontIndex].SizeWant.Y == 0) { + if (FontInfo[FontIndex].SizeWant.Y == 0) + { // Raster Font, so save actual size gpStateInfo->FontSize = FontInfo[FontIndex].Size; - } else { + } + else + { // TT Font, so save desired size gpStateInfo->FontSize = FontInfo[FontIndex].SizeWant; } @@ -495,7 +502,8 @@ RedoFontListAndPreview: /* * Delete the TrueType logo bitmap */ - if (hbmTT != NULL) { + if (hbmTT != NULL) + { DeleteObject(hbmTT); hbmTT = NULL; } @@ -534,26 +542,35 @@ void AddFontSizesToList(PCWSTR pwszTTFace, int iLastShowY = 0; int nSameSize = 0; - for (ULONG i = 0; i < NumberOfFonts; i++) { - if (!fRasterFont == !TM_IS_TT_FONT(FontInfo[i].Family)) { + for (ULONG i = 0; i < NumberOfFonts; i++) + { + if (!fRasterFont == !TM_IS_TT_FONT(FontInfo[i].Family)) + { DBGFONTS((" Font %x not right type\n", i)); continue; } - if (fDbcsCharSet) { - if (!IS_DBCS_OR_OEM_CHARSET(FontInfo[i].tmCharSet)) { + if (fDbcsCharSet) + { + if (!IS_DBCS_OR_OEM_CHARSET(FontInfo[i].tmCharSet)) + { DBGFONTS((" Font %x not right type for DBCS character set\n", i)); continue; } - } else { - if (IS_ANY_DBCS_CHARSET(FontInfo[i].tmCharSet)) { + } + else + { + if (IS_ANY_DBCS_CHARSET(FontInfo[i].tmCharSet)) + { DBGFONTS((" Font %x not right type for SBCS character set\n", i)); continue; } } - if (!fRasterFont) { + if (!fRasterFont) + { if ((0 != lstrcmp(FontInfo[i].FaceName, pwszTTFace)) && - (0 != lstrcmp(FontInfo[i].FaceName, pwszAltTTFace))) { + (0 != lstrcmp(FontInfo[i].FaceName, pwszAltTTFace))) + { /* * A TrueType font, but not the one we're interested in, * so don't add it to the list of point sizes. @@ -564,41 +581,56 @@ void AddFontSizesToList(PCWSTR pwszTTFace, // if we're being asked to add bold fonts, add unconditionally according to weight. Otherwise, only this // entry to the list of it's in line with user choice. Raster fonts aren't available in bold. - if (!fAddBoldFonts && gbBold != IS_BOLD(FontInfo[i].Weight)) { + if (!fAddBoldFonts && gbBold != IS_BOLD(FontInfo[i].Weight)) + { DBGFONTS((" Font %x has weight %d, but we wanted %sbold\n", - i, FontInfo[i].Weight, gbBold ? "" : "not ")); + i, + FontInfo[i].Weight, + gbBold ? "" : "not ")); continue; } } int ShowX; - if (FontInfo[i].SizeWant.X > 0) { + if (FontInfo[i].SizeWant.X > 0) + { ShowX = FontInfo[i].SizeWant.X; - } else { + } + else + { ShowX = FontInfo[i].Size.X; } int ShowY; - if (FontInfo[i].SizeWant.Y > 0) { + if (FontInfo[i].SizeWant.Y > 0) + { ShowY = FontInfo[i].SizeWant.Y; - } else { + } + else + { ShowY = FontInfo[i].Size.Y; } /* * Add the size description string to the end of the right list */ - if (TM_IS_TT_FONT(FontInfo[i].Family)) { + if (TM_IS_TT_FONT(FontInfo[i].Family)) + { // point size StringCchPrintf(wszText, ARRAYSIZE(wszText), TEXT("%2d"), FontInfo[i].SizeWant.Y); - } else { + } + else + { // pixel size - if ((iLastShowX == ShowX) && (iLastShowY == ShowY)) { + if ((iLastShowX == ShowX) && (iLastShowY == ShowY)) + { nSameSize++; - } else { + } + else + { iLastShowX = ShowX; iLastShowY = ShowY; nSameSize = 0; @@ -610,7 +642,8 @@ void AddFontSizesToList(PCWSTR pwszTTFace, * be visible and exists off the edge of the list */ if (((dwExStyle & WS_EX_RIGHT) && !(dwExStyle & WS_EX_LAYOUTRTL)) || - (!(dwExStyle & WS_EX_RIGHT) && (dwExStyle & WS_EX_LAYOUTRTL))) { + (!(dwExStyle & WS_EX_RIGHT) && (dwExStyle & WS_EX_LAYOUTRTL))) + { // flip it so that the hidden part be at the far left StringCchPrintf(wszText, ARRAYSIZE(wszText), @@ -618,7 +651,9 @@ void AddFontSizesToList(PCWSTR pwszTTFace, nSameSize, ShowX, ShowY); - } else { + } + else + { StringCchPrintf(wszText, ARRAYSIZE(wszText), TEXT("%2d x %2d #%d"), @@ -629,13 +664,15 @@ void AddFontSizesToList(PCWSTR pwszTTFace, } LONG lListIndex = lcbFINDSTRINGEXACT(hWndShow, fRasterFont, wszText); - if (lListIndex == LB_ERR) { + if (lListIndex == LB_ERR) + { lListIndex = lcbADDSTRING(hWndShow, fRasterFont, wszText); } DBGFONTS((" added %ls to %sSLIST(%p) index %lx\n", wszText, fRasterFont ? "PIXEL" : "POINT", - hWndShow, lListIndex)); + hWndShow, + lListIndex)); lcbSETITEMDATA(hWndShow, fRasterFont, (DWORD)lListIndex, i); } } @@ -648,39 +685,42 @@ void AddFontSizesToList(PCWSTR pwszTTFace, Returns FontIndex of selected font (LB_ERR if none) --*/ -int -FontListCreate( +int FontListCreate( __in HWND hDlg, __in_ecount_opt(LF_FACESIZE) LPWSTR pwszTTFace, __in BOOL bNewFaceList) { LONG lListIndex; ULONG i; - HWND hWndShow; // List or Combo box - HWND hWndHide; // Combo or List box + HWND hWndShow; // List or Combo box + HWND hWndHide; // Combo or List box HWND hWndFaceCombo; BOOL bLB; - UINT CodePage = gpStateInfo->CodePage; - BOOL fFindTTFont = FALSE; + UINT CodePage = gpStateInfo->CodePage; + BOOL fFindTTFont = FALSE; LPWSTR pwszAltTTFace; LONG_PTR dwExStyle; FAIL_FAST_IF(!(OEMCP != 0)); // must be initialized bLB = ((pwszTTFace == nullptr) || (pwszTTFace[0] == TEXT('\0'))); - if (bLB) { + if (bLB) + { pwszAltTTFace = NULL; - } else { - if (ShouldAllowAllMonoTTFonts() || IsAvailableTTFont(pwszTTFace)) { + } + else + { + if (ShouldAllowAllMonoTTFonts() || IsAvailableTTFont(pwszTTFace)) + { pwszAltTTFace = GetAltFaceName(pwszTTFace); - } else { + } + else + { pwszAltTTFace = pwszTTFace; } } - DBGFONTS(("FontListCreate %p, %s, %s new FaceList\n", hDlg, - bLB ? "Raster" : "TrueType", - bNewFaceList ? "Make" : "No" )); + DBGFONTS(("FontListCreate %p, %s, %s new FaceList\n", hDlg, bLB ? "Raster" : "TrueType", bNewFaceList ? "Make" : "No")); /* * This only enumerates face names and font sizes if necessary. @@ -694,7 +734,8 @@ FontListCreate( DBGFONTS((" Create %s fonts\n", bLB ? "Raster" : "TrueType")); - if (bNewFaceList) { + if (bNewFaceList) + { PFACENODE panFace; hWndFaceCombo = GetDlgItem(hDlg, IDD_FACENAME); @@ -709,11 +750,14 @@ FontListCreate( // now enumerate all of the new truetype font face names we've loaded that are appropriate for our codepage. add them to // the faces list. if we find an exact match for pwszTTFace or pwszAltTTFace, note that in fFindTTFont. - for (panFace = gpFaceNames; panFace; panFace = panFace->pNext) { - if ((panFace->dwFlag & (EF_TTFONT|EF_NEW)) != (EF_TTFONT|EF_NEW)) { + for (panFace = gpFaceNames; panFace; panFace = panFace->pNext) + { + if ((panFace->dwFlag & (EF_TTFONT | EF_NEW)) != (EF_TTFONT | EF_NEW)) + { continue; } - if (!g_fEastAsianSystem && (panFace->dwFlag & EF_DBCSFONT)) { + if (!g_fEastAsianSystem && (panFace->dwFlag & EF_DBCSFONT)) + { continue; } @@ -721,38 +765,44 @@ FontListCreate( // face dialog list -- this is handled in DoFontEnum by using the FontEnumForV2Console enumerator if (ShouldAllowAllMonoTTFonts() || (g_fEastAsianSystem && IsAvailableTTFontCP(panFace->atch, CodePage)) || - (!g_fEastAsianSystem && IsAvailableTTFontCP(panFace->atch, 0))) { - + (!g_fEastAsianSystem && IsAvailableTTFontCP(panFace->atch, 0))) + { if (!bLB && (lstrcmp(pwszTTFace, panFace->atch) == 0 || - lstrcmp(pwszAltTTFace, panFace->atch) == 0)) { + lstrcmp(pwszAltTTFace, panFace->atch) == 0)) + { fFindTTFont = TRUE; } lListIndex = (LONG)SendMessage(hWndFaceCombo, LB_ADDSTRING, 0, (LPARAM)panFace->atch); SendMessage(hWndFaceCombo, LB_SETITEMDATA, lListIndex, FALSE); DBGFONTS(("Added \"%ls\", set Item Data %d = FALSE\n", - panFace->atch, lListIndex)); + panFace->atch, + lListIndex)); } } // if we haven't found the specific TT font we're looking for, choose *any* TT font that's appropriate for our // codepage - if (!bLB && !fFindTTFont) { - for (panFace = gpFaceNames; panFace; panFace = panFace->pNext) { - if ((panFace->dwFlag & (EF_TTFONT | EF_NEW)) != (EF_TTFONT | EF_NEW)) { + if (!bLB && !fFindTTFont) + { + for (panFace = gpFaceNames; panFace; panFace = panFace->pNext) + { + if ((panFace->dwFlag & (EF_TTFONT | EF_NEW)) != (EF_TTFONT | EF_NEW)) + { continue; } - if (!g_fEastAsianSystem && (panFace->dwFlag & EF_DBCSFONT)) { + if (!g_fEastAsianSystem && (panFace->dwFlag & EF_DBCSFONT)) + { continue; } - if (( g_fEastAsianSystem && IsAvailableTTFontCP(panFace->atch, CodePage)) || + if ((g_fEastAsianSystem && IsAvailableTTFontCP(panFace->atch, CodePage)) || (!g_fEastAsianSystem && IsAvailableTTFontCP(panFace->atch, 0))) { - - if (lstrcmp(pwszTTFace, panFace->atch) != 0) { + if (lstrcmp(pwszTTFace, panFace->atch) != 0) + { // found a reasonably appropriate font that isn't the one being requested (we couldn't find that // one). use this one instead. StringCchCopy(pwszTTFace, @@ -773,11 +823,14 @@ FontListCreate( * For JAPAN, We uses "MS Gothic" TT font. * So, Bold of this font is not 1:2 width between SBCS:DBCS. */ - if (g_fEastAsianSystem && IsDisableBoldTTFont(pwszTTFace)) { + if (g_fEastAsianSystem && IsDisableBoldTTFont(pwszTTFace)) + { EnableWindow(hWndShow, FALSE); gbBold = FALSE; CheckDlgButton(hDlg, IDD_BOLDFONT, FALSE); - } else { + } + else + { CheckDlgButton(hDlg, IDD_BOLDFONT, (bLB || !gbBold) ? FALSE : TRUE); EnableWindow(hWndShow, bLB ? FALSE : TRUE); } @@ -796,12 +849,14 @@ FontListCreate( // if we're building a new face list (basically any time we're not handling a selection change), empty the contents // of the pixel size list (raster) or point size list (TT) as appropriate. - if (bNewFaceList) { + if (bNewFaceList) + { lcbRESETCONTENT(hWndShow, bLB); } dwExStyle = GetWindowLongPtr(hWndShow, GWL_EXSTYLE); - if ((dwExStyle & WS_EX_LAYOUTRTL) && !(dwExStyle & WS_EX_RTLREADING)) { + if ((dwExStyle & WS_EX_LAYOUTRTL) && !(dwExStyle & WS_EX_RTLREADING)) + { // if mirrored RTL Reading means LTR !! SetWindowLongPtr(hWndShow, GWL_EXSTYLE, dwExStyle | WS_EX_RTLREADING); } @@ -837,7 +892,6 @@ FontListCreate( return i; } - /** DrawItemFontList * * Answer the WM_DRAWITEM message sent from the font list box or @@ -858,38 +912,48 @@ VOID DrawItemFontList(const HWND hDlg, const LPDRAWITEMSTRUCT lpdis) WCHAR wszFace[LF_FACESIZE]; HBITMAP hOld; int dy, dxttbmp; - HBRUSH hbrFill; + HBRUSH hbrFill; HWND hWndItem; BOOL bLB; - if ((int)lpdis->itemID < 0) { + if ((int)lpdis->itemID < 0) + { return; } hDC = lpdis->hDC; - if (lpdis->itemAction & ODA_FOCUS) { - if (lpdis->itemState & ODS_SELECTED) { + if (lpdis->itemAction & ODA_FOCUS) + { + if (lpdis->itemState & ODS_SELECTED) + { DrawFocusRect(hDC, &lpdis->rcItem); } - } else { - if (lpdis->itemState & ODS_SELECTED) { + } + else + { + if (lpdis->itemState & ODS_SELECTED) + { rgbText = SetTextColor(hDC, GetSysColor(COLOR_HIGHLIGHTTEXT)); rgbBack = SetBkColor(hDC, rgbFill = GetSysColor(COLOR_HIGHLIGHT)); - } else { + } + else + { rgbText = SetTextColor(hDC, GetSysColor(COLOR_WINDOWTEXT)); rgbBack = SetBkColor(hDC, rgbFill = GetSysColor(COLOR_WINDOW)); } // draw selection background hbrFill = CreateSolidBrush(rgbFill); - if (hbrFill) { + if (hbrFill) + { FillRect(hDC, &lpdis->rcItem, hbrFill); DeleteObject(hbrFill); } // get the string hWndItem = lpdis->hwndItem; - if (!IsWindow(hWndItem)) { + if (!IsWindow(hWndItem)) + { return; } @@ -901,7 +965,8 @@ VOID DrawItemFontList(const HWND hDlg, const LPDRAWITEMSTRUCT lpdis) * are fonts their lengths are the same. Third, a buffer overrun here * isn't really interesting from a security perspective, anyway. */ - if (SendMessage(hWndItem, LB_GETTEXTLEN, lpdis->itemID, 0) >= ARRAYSIZE(wszFace)) { + if (SendMessage(hWndItem, LB_GETTEXTLEN, lpdis->itemID, 0) >= ARRAYSIZE(wszFace)) + { return; } @@ -909,25 +974,22 @@ VOID DrawItemFontList(const HWND hDlg, const LPDRAWITEMSTRUCT lpdis) bLB = (BOOL)SendMessage(hWndItem, LB_GETITEMDATA, lpdis->itemID, 0L); dxttbmp = bLB ? 0 : bmTT.bmWidth; - DBGFONTS(("DrawItemFontList must redraw \"%ls\" %s\n", wszFace, - bLB ? "Raster" : "TrueType")); + DBGFONTS(("DrawItemFontList must redraw \"%ls\" %s\n", wszFace, bLB ? "Raster" : "TrueType")); // draw the text - TabbedTextOut(hDC, lpdis->rcItem.left + dxttbmp, - lpdis->rcItem.top, wszFace, - (UINT)wcslen(wszFace), 0, NULL, dxttbmp); + TabbedTextOut(hDC, lpdis->rcItem.left + dxttbmp, lpdis->rcItem.top, wszFace, (UINT)wcslen(wszFace), 0, NULL, dxttbmp); // and the TT bitmap if needed - if (!bLB) { + if (!bLB) + { hdcMem = CreateCompatibleDC(hDC); - if (hdcMem) { - hOld = (HBITMAP) SelectObject(hdcMem, hbmTT); + if (hdcMem) + { + hOld = (HBITMAP)SelectObject(hdcMem, hbmTT); dy = ((lpdis->rcItem.bottom - lpdis->rcItem.top) - bmTT.bmHeight) / 2; - BitBlt(hDC, lpdis->rcItem.left, lpdis->rcItem.top + dy, - dxttbmp, GetItemHeight(hDlg), hdcMem, - 0, 0, SRCINVERT); + BitBlt(hDC, lpdis->rcItem.left, lpdis->rcItem.top + dy, dxttbmp, GetItemHeight(hDlg), hdcMem, 0, 0, SRCINVERT); if (hOld) SelectObject(hdcMem, hOld); @@ -938,18 +1000,17 @@ VOID DrawItemFontList(const HWND hDlg, const LPDRAWITEMSTRUCT lpdis) SetTextColor(hDC, rgbText); SetBkColor(hDC, rgbBack); - if (lpdis->itemState & ODS_FOCUS) { + if (lpdis->itemState & ODS_FOCUS) + { DrawFocusRect(hDC, &lpdis->rcItem); } } } - -UINT -GetPointSizeInRange( - HWND hDlg, - INT Min, - INT Max) +UINT GetPointSizeInRange( + HWND hDlg, + INT Min, + INT Max) /*++ Routine Description: @@ -968,9 +1029,11 @@ Return Value: int nTmp = 0; BOOL bOK; - if (GetDlgItemText(hDlg, IDD_POINTSLIST, szBuf, ARRAYSIZE(szBuf))) { + if (GetDlgItemText(hDlg, IDD_POINTSLIST, szBuf, ARRAYSIZE(szBuf))) + { nTmp = GetDlgItemInt(hDlg, IDD_POINTSLIST, &bOK, TRUE); - if (bOK && nTmp >= Min && nTmp <= Max) { + if (bOK && nTmp >= Min && nTmp <= Max) + { return nTmp; } } @@ -978,18 +1041,15 @@ Return Value: return 0; } - /* ----- Preview routines ----- */ -[[nodiscard]] -LRESULT -CALLBACK -FontPreviewWndProc( - HWND hWnd, - UINT wMessage, - WPARAM wParam, - LPARAM lParam - ) +[[nodiscard]] LRESULT + CALLBACK + FontPreviewWndProc( + HWND hWnd, + UINT wMessage, + WPARAM wParam, + LPARAM lParam) /* FontPreviewWndProc * Handles the font preview window @@ -1004,7 +1064,8 @@ FontPreviewWndProc( COLORREF rgbText; COLORREF rgbBk; - switch (wMessage) { + switch (wMessage) + { case WM_ERASEBKGND: break; @@ -1012,22 +1073,23 @@ FontPreviewWndProc( BeginPaint(hWnd, &ps); /* Draw the font sample */ - if (GetWindowLong(hWnd, GWL_ID) == IDD_COLOR_POPUP_COLORS) { + if (GetWindowLong(hWnd, GWL_ID) == IDD_COLOR_POPUP_COLORS) + { rgbText = GetNearestColor(ps.hdc, PopupTextColor(gpStateInfo)); rgbBk = GetNearestColor(ps.hdc, PopupBkColor(gpStateInfo)); - } else { + } + else + { rgbText = GetNearestColor(ps.hdc, ScreenTextColor(gpStateInfo)); rgbBk = GetNearestColor(ps.hdc, ScreenBkColor(gpStateInfo)); } SetTextColor(ps.hdc, rgbText); SetBkColor(ps.hdc, rgbBk); GetClientRect(hWnd, &rect); - hfontOld = (HFONT) SelectObject(ps.hdc, FontInfo[g_currentFontIndex].hFont); + hfontOld = (HFONT)SelectObject(ps.hdc, FontInfo[g_currentFontIndex].hFont); hbrNew = CreateSolidBrush(rgbBk); - hbrOld = (HBRUSH) SelectObject(ps.hdc, hbrNew); - PatBlt(ps.hdc, rect.left, rect.top, - rect.right - rect.left, rect.bottom - rect.top, - PATCOPY); + hbrOld = (HBRUSH)SelectObject(ps.hdc, hbrNew); + PatBlt(ps.hdc, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, PATCOPY); InflateRect(&rect, -2, -2); DrawText(ps.hdc, g_szPreviewText, -1, &rect, 0); SelectObject(ps.hdc, hbrOld); @@ -1048,7 +1110,6 @@ FontPreviewWndProc( return 0L; } - /* * Get the font index for a new font * If necessary, attempt to create the font. @@ -1059,8 +1120,7 @@ FontPreviewWndProc( * NULL or TEXT("") - use DefaultFaceName * Size: Must match SizeWant or actual Size. */ -int -FindCreateFont( +int FindCreateFont( __in DWORD Family, __in_ecount(LF_FACESIZE) LPWSTR pwszFace, __in COORD Size, @@ -1074,7 +1134,7 @@ FindCreateFont( BOOL bFontOK; WCHAR AltFaceName[LF_FACESIZE]; COORD AltFontSize; - BYTE AltFontFamily; + BYTE AltFontFamily; ULONG AltFontIndex = 0, i; LPWSTR pwszAltFace; @@ -1083,32 +1143,50 @@ FindCreateFont( FAIL_FAST_IF(!(OEMCP != 0)); DBGFONTS(("FindCreateFont Family=%x %ls (%d,%d) %d %d %x\n", - Family, pwszFace, Size.X, Size.Y, Weight, CodePage, CharSet)); + Family, + pwszFace, + Size.X, + Size.Y, + Weight, + CodePage, + CharSet)); - if (g_fEastAsianSystem) { - if (IS_DBCS_OR_OEM_CHARSET(CharSet)) { - if (pwszFace == NULL || *pwszFace == TEXT('\0')) { + if (g_fEastAsianSystem) + { + if (IS_DBCS_OR_OEM_CHARSET(CharSet)) + { + if (pwszFace == NULL || *pwszFace == TEXT('\0')) + { pwszFace = DefaultFaceName; } - if (Size.Y == 0) { + if (Size.Y == 0) + { Size = DefaultFontSize; } - } else { + } + else + { MakeAltRasterFont(CodePage, &AltFontSize, &AltFontFamily, &AltFontIndex, AltFaceName); - if (pwszFace == NULL || *pwszFace == TEXT('\0')) { + if (pwszFace == NULL || *pwszFace == TEXT('\0')) + { pwszFace = AltFaceName; } - if (Size.Y == 0) { + if (Size.Y == 0) + { Size.X = AltFontSize.X; Size.Y = AltFontSize.Y; } } - } else { - if (pwszFace == NULL || *pwszFace == TEXT('\0')) { + } + else + { + if (pwszFace == NULL || *pwszFace == TEXT('\0')) + { pwszFace = DefaultFaceName; } - if (Size.Y == 0) { + if (Size.Y == 0) + { Size = DefaultFontSize; } } @@ -1117,7 +1195,7 @@ FindCreateFont( if (wcscmp(pwszFace, DEFAULT_TT_FONT_FACENAME) == 0) { // retrieve default font face name for this codepage, and then set it as our current face - WCHAR szDefaultCodepageTTFont[LF_FACESIZE] = {0}; + WCHAR szDefaultCodepageTTFont[LF_FACESIZE] = { 0 }; if (NT_SUCCESS(GetTTFontFaceForCodePage(CodePage, szDefaultCodepageTTFont, ARRAYSIZE(szDefaultCodepageTTFont))) && NT_SUCCESS(StringCchCopyW(DefaultTTFaceName, ARRAYSIZE(DefaultTTFaceName), szDefaultCodepageTTFont))) { @@ -1126,9 +1204,12 @@ FindCreateFont( } } - if (ShouldAllowAllMonoTTFonts() || IsAvailableTTFont(pwszFace)) { + if (ShouldAllowAllMonoTTFonts() || IsAvailableTTFont(pwszFace)) + { pwszAltFace = GetAltFaceName(pwszFace); - } else { + } + else + { pwszAltFace = pwszFace; } @@ -1136,11 +1217,13 @@ FindCreateFont( * Try to find the exact font */ TryFindExactFont: - for (i = 0; i < NumberOfFonts; i++) { + for (i = 0; i < NumberOfFonts; i++) + { /* * If looking for a particular Family, skip non-matches */ - if (Family != 0 && (BYTE)Family != FontInfo[i].Family) { + if (Family != 0 && (BYTE)Family != FontInfo[i].Family) + { continue; } @@ -1148,20 +1231,23 @@ TryFindExactFont: * Skip non-matching sizes */ if ((FontInfo[i].SizeWant.Y != Size.Y) && - !SIZE_EQUAL(FontInfo[i].Size, Size)) { + !SIZE_EQUAL(FontInfo[i].Size, Size)) + { continue; } /* * Skip non-matching weights */ - if ((Weight != 0) && (Weight != FontInfo[i].Weight)) { + if ((Weight != 0) && (Weight != FontInfo[i].Weight)) + { continue; } if (!TM_IS_TT_FONT(FontInfo[i].Family) && (FontInfo[i].tmCharSet != CharSet && - !(FontInfo[i].tmCharSet == OEM_CHARSET && g_fEastAsianSystem))) { + !(FontInfo[i].tmCharSet == OEM_CHARSET && g_fEastAsianSystem))) + { continue; } @@ -1171,31 +1257,41 @@ TryFindExactFont: * it is a raster font, consider it. */ if ((pwszFace == NULL) || (pwszFace[0] == TEXT('\0')) || - (lstrcmp(FontInfo[i].FaceName, pwszFace) == 0) || - (lstrcmp(FontInfo[i].FaceName, pwszAltFace) == 0)) { + (lstrcmp(FontInfo[i].FaceName, pwszFace) == 0) || + (lstrcmp(FontInfo[i].FaceName, pwszAltFace) == 0)) + { FontIndex = i; goto FoundFont; - } else if (!TM_IS_TT_FONT(FontInfo[i].Family)) { + } + else if (!TM_IS_TT_FONT(FontInfo[i].Family)) + { FontIndex = i; } } - if (FontIndex == NOT_CREATED_NOR_FOUND) { + if (FontIndex == NOT_CREATED_NOR_FOUND) + { /* * Didn't find the exact font, so try to create it */ - if (Size.Y < 0) { + if (Size.Y < 0) + { Size.Y = -Size.Y; } bFontOK = DoFontEnum(NULL, pwszFace, &Size.Y, 1); - if (bFontOK) { + if (bFontOK) + { DBGFONTS(("FindCreateFont created font!\n")); FontIndex = CREATED_BUT_NOT_FOUND; goto TryFindExactFont; - } else { + } + else + { DBGFONTS(("FindCreateFont failed to create font!\n")); } - } else if (FontIndex >= 0) { + } + else if (FontIndex >= 0) + { // a close Raster Font fit - only the name doesn't match. goto FoundFont; } @@ -1204,47 +1300,60 @@ TryFindExactFont: * Failed to find exact match, even after enumeration, so now try to find * a font of same family and same size or bigger. */ - for (i = 0; i < NumberOfFonts; i++) { - if (g_fEastAsianSystem) { - if (Family != 0 && (BYTE)Family != FontInfo[i].Family) { + for (i = 0; i < NumberOfFonts; i++) + { + if (g_fEastAsianSystem) + { + if (Family != 0 && (BYTE)Family != FontInfo[i].Family) + { continue; } if (!TM_IS_TT_FONT(FontInfo[i].Family) && - FontInfo[i].tmCharSet != CharSet) { + FontInfo[i].tmCharSet != CharSet) + { continue; } - } else { - if ((BYTE)Family != FontInfo[i].Family) { - continue; } + else + { + if ((BYTE)Family != FontInfo[i].Family) + { + continue; + } } - if (FontInfo[i].Size.Y >= Size.Y && FontInfo[i].Size.X >= Size.X) { + if (FontInfo[i].Size.Y >= Size.Y && FontInfo[i].Size.X >= Size.X) + { // Same family, size >= desired. FontIndex = i; break; } } - if (FontIndex < 0) { + if (FontIndex < 0) + { DBGFONTS(("FindCreateFont defaults!\n")); - if (g_fEastAsianSystem) { - if (CodePage == OEMCP) { + if (g_fEastAsianSystem) + { + if (CodePage == OEMCP) + { FontIndex = DefaultFontIndex; - } else { + } + else + { FontIndex = AltFontIndex; } - } else { - FontIndex = DefaultFontIndex; + } + else + { + FontIndex = DefaultFontIndex; } } FoundFont: FAIL_FAST_IF(!(FontIndex < (int)NumberOfFonts)); - DBGFONTS(("FindCreateFont returns %x : %ls (%d,%d)\n", FontIndex, - FontInfo[FontIndex].FaceName, - FontInfo[FontIndex].Size.X, FontInfo[FontIndex].Size.Y)); + DBGFONTS(("FindCreateFont returns %x : %ls (%d,%d)\n", FontIndex, FontInfo[FontIndex].FaceName, FontInfo[FontIndex].Size.X, FontInfo[FontIndex].Size.Y)); return FontIndex; #undef NOT_CREATED_NOR_FOUND @@ -1259,31 +1368,37 @@ FoundFont: * Returns * FontIndex : Index into FontInfo[] cache */ -int -SelectCurrentSize(HWND hDlg, BOOL bLB, int FontIndex) +int SelectCurrentSize(HWND hDlg, BOOL bLB, int FontIndex) { int iCB; HWND hWndList; DBGFONTS(("SelectCurrentSize %p %s %x\n", - hDlg, bLB ? "Raster" : "TrueType", FontIndex)); + hDlg, + bLB ? "Raster" : "TrueType", + FontIndex)); hWndList = GetDlgItem(hDlg, bLB ? IDD_PIXELSLIST : IDD_POINTSLIST); iCB = lcbGETCOUNT(hWndList, bLB); DBGFONTS((" Count of items in %p = %lx\n", hWndList, iCB)); - if (FontIndex >= 0) { + if (FontIndex >= 0) + { /* * look for FontIndex */ - while (iCB > 0) { + while (iCB > 0) + { iCB--; - if (lcbGETITEMDATA(hWndList, bLB, iCB) == FontIndex) { + if (lcbGETITEMDATA(hWndList, bLB, iCB) == FontIndex) + { lcbSETCURSEL(hWndList, bLB, iCB); break; } } - } else { + } + else + { /* * Look for a reasonable default size: looking backwards, find * the first one same height or smaller. @@ -1292,10 +1407,11 @@ SelectCurrentSize(HWND hDlg, BOOL bLB, int FontIndex) if (g_fEastAsianSystem && bLB && - FontInfo[g_currentFontIndex].tmCharSet != LOBYTE(LOWORD(Size))) { + FontInfo[g_currentFontIndex].tmCharSet != LOBYTE(LOWORD(Size))) + { WCHAR AltFaceName[LF_FACESIZE]; COORD AltFontSize; - BYTE AltFontFamily; + BYTE AltFontFamily; ULONG AltFontIndex = 0; MakeAltRasterFont(gpStateInfo->CodePage, @@ -1304,18 +1420,24 @@ SelectCurrentSize(HWND hDlg, BOOL bLB, int FontIndex) &AltFontIndex, AltFaceName); - while (iCB > 0) { + while (iCB > 0) + { iCB--; - if (lcbGETITEMDATA(hWndList, bLB, iCB) == (int)AltFontIndex) { + if (lcbGETITEMDATA(hWndList, bLB, iCB) == (int)AltFontIndex) + { lcbSETCURSEL(hWndList, bLB, iCB); break; } } - } else { - while (iCB > 0) { + } + else + { + while (iCB > 0) + { iCB--; FontIndex = lcbGETITEMDATA(hWndList, bLB, iCB); - if (FontInfo[FontIndex].Size.Y <= HIWORD(Size)) { + if (FontInfo[FontIndex].Size.Y <= HIWORD(Size)) + { lcbSETCURSEL(hWndList, bLB, iCB); break; } @@ -1327,9 +1449,7 @@ SelectCurrentSize(HWND hDlg, BOOL bLB, int FontIndex) return FontIndex; } - -BOOL -SelectCurrentFont( +BOOL SelectCurrentFont( HWND hDlg, int FontIndex) { @@ -1349,11 +1469,8 @@ SelectCurrentFont( return bLB; } - -BOOL -PreviewInit( - HWND hDlg - ) +BOOL PreviewInit( + HWND hDlg) /* PreviewInit * Prepares the preview code, sizing the window and the dialog to @@ -1376,7 +1493,8 @@ PreviewInit( gpStateInfo->CodePage); DBGFONTS(("Changing Font Number from %d to %d\n", - g_currentFontIndex, nFont)); + g_currentFontIndex, + nFont)); FAIL_FAST_IF(!((ULONG)nFont < NumberOfFonts)); g_currentFontIndex = nFont; @@ -1391,12 +1509,9 @@ PreviewInit( return SelectCurrentFont(hDlg, nFont); } - -BOOL -PreviewUpdate( +BOOL PreviewUpdate( HWND hDlg, - BOOL bLB - ) + BOOL bLB) /*++ @@ -1414,8 +1529,7 @@ PreviewUpdate( HWND hWndList; DWORD_PTR Parameters[2]; - DBGFONTS(("PreviewUpdate hDlg=%p, %s\n", hDlg, - bLB ? "Raster" : "TrueType")); + DBGFONTS(("PreviewUpdate hDlg=%p, %s\n", hDlg, bLB ? "Raster" : "TrueType")); hWndList = GetDlgItem(hDlg, bLB ? IDD_PIXELSLIST : IDD_POINTSLIST); @@ -1424,7 +1538,8 @@ PreviewUpdate( */ lIndex = lcbGETCURSEL(hWndList, bLB); DBGFONTS(("PreviewUpdate GETCURSEL gets %x\n", lIndex)); - if ((lIndex < 0) && !bLB) { + if ((lIndex < 0) && !bLB) + { COORD NewSize; lIndex = (LONG)SendDlgItemMessage(hDlg, IDD_FACENAME, LB_GETCURSEL, 0, 0L); @@ -1432,7 +1547,8 @@ PreviewUpdate( NewSize.X = 0; NewSize.Y = (SHORT)GetPointSizeInRange(hDlg, MIN_PIXEL_HEIGHT, MAX_PIXEL_HEIGHT); - if (NewSize.Y == 0) { + if (NewSize.Y == 0) + { WCHAR wszBuf[60]; /* * Use wszText, wszBuf to put up an error msg for bad point size @@ -1446,7 +1562,7 @@ PreviewUpdate( MAX_PIXEL_HEIGHT); GetWindowText(hDlg, wszBuf, ARRAYSIZE(wszBuf)); - MessageBox(hDlg, wszText, wszBuf, MB_OK|MB_ICONINFORMATION); + MessageBox(hDlg, wszText, wszBuf, MB_OK | MB_ICONINFORMATION); SetFocus(hWndList); gbPointSizeError = FALSE; return FALSE; @@ -1457,11 +1573,14 @@ PreviewUpdate( NewSize, 0, gpStateInfo->CodePage); - } else { + } + else + { FontIndex = lcbGETITEMDATA(hWndList, bLB, lIndex); } - if (FontIndex < 0) { + if (FontIndex < 0) + { FontIndex = DefaultFontIndex; } @@ -1469,11 +1588,13 @@ PreviewUpdate( * If we've selected a new font, tell the property sheet we've changed */ FAIL_FAST_IF(!((ULONG)FontIndex < NumberOfFonts)); - if ((ULONG)FontIndex >= NumberOfFonts) { + if ((ULONG)FontIndex >= NumberOfFonts) + { FontIndex = 0; } - if (g_currentFontIndex != (ULONG)FontIndex) { + if (g_currentFontIndex != (ULONG)FontIndex) + { g_currentFontIndex = FontIndex; } diff --git a/src/propsheet/fontdlg.h b/src/propsheet/fontdlg.h index 4957cb6b0..4ff7fe351 100644 --- a/src/propsheet/fontdlg.h +++ b/src/propsheet/fontdlg.h @@ -26,12 +26,11 @@ Revision History: /* ----- Literals ----- */ -#define MAXDIMENSTRING 40 // max text in combo box -#define DX_TTBITMAP 20 -#define DY_TTBITMAP 12 -#define CCH_RASTERFONTS 24 -#define CCH_SELECTEDFONT 30 - +#define MAXDIMENSTRING 40 // max text in combo box +#define DX_TTBITMAP 20 +#define DY_TTBITMAP 12 +#define CCH_RASTERFONTS 24 +#define CCH_SELECTEDFONT 30 /* ----- Macros ----- */ /* @@ -47,31 +46,30 @@ Revision History: * */ #define lcbRESETCONTENT(hWnd, bLB) \ - SendMessage(hWnd, bLB ? LB_RESETCONTENT : CB_RESETCONTENT, 0, 0L) + SendMessage(hWnd, bLB ? LB_RESETCONTENT : CB_RESETCONTENT, 0, 0L) #define lcbGETTEXT(hWnd, bLB, w) \ - SendMessage(hWnd, bLB ? LB_GETTEXT : CB_GETLBTEXT, w, 0L) + SendMessage(hWnd, bLB ? LB_GETTEXT : CB_GETLBTEXT, w, 0L) #define lcbFINDSTRINGEXACT(hWnd, bLB, pwsz) \ - (LONG)SendMessage(hWnd, bLB ? LB_FINDSTRINGEXACT : CB_FINDSTRINGEXACT, \ - (WPARAM)-1, (LPARAM)pwsz) + (LONG) SendMessage(hWnd, bLB ? LB_FINDSTRINGEXACT : CB_FINDSTRINGEXACT, (WPARAM)-1, (LPARAM)pwsz) #define lcbADDSTRING(hWnd, bLB, pwsz) \ - (LONG)SendMessage(hWnd, bLB ? LB_ADDSTRING : CB_ADDSTRING, 0, (LPARAM)pwsz) + (LONG) SendMessage(hWnd, bLB ? LB_ADDSTRING : CB_ADDSTRING, 0, (LPARAM)pwsz) #define lcbSETITEMDATA(hWnd, bLB, w, nFont) \ - SendMessage(hWnd, bLB ? LB_SETITEMDATA : CB_SETITEMDATA, w, nFont) + SendMessage(hWnd, bLB ? LB_SETITEMDATA : CB_SETITEMDATA, w, nFont) #define lcbGETITEMDATA(hWnd, bLB, w) \ - (LONG)SendMessage(hWnd, bLB ? LB_GETITEMDATA : CB_GETITEMDATA, w, 0L) + (LONG) SendMessage(hWnd, bLB ? LB_GETITEMDATA : CB_GETITEMDATA, w, 0L) #define lcbGETCOUNT(hWnd, bLB) \ - (LONG)SendMessage(hWnd, bLB ? LB_GETCOUNT : CB_GETCOUNT, 0, 0L) + (LONG) SendMessage(hWnd, bLB ? LB_GETCOUNT : CB_GETCOUNT, 0, 0L) #define lcbGETCURSEL(hWnd, bLB) \ - (LONG)SendMessage(hWnd, bLB ? LB_GETCURSEL : CB_GETCURSEL, 0, 0L) + (LONG) SendMessage(hWnd, bLB ? LB_GETCURSEL : CB_GETCURSEL, 0, 0L) #define lcbSETCURSEL(hWnd, bLB, w) \ - SendMessage(hWnd, bLB ? LB_SETCURSEL : CB_SETCURSEL, w, 0L) + SendMessage(hWnd, bLB ? LB_SETCURSEL : CB_SETCURSEL, w, 0L) #endif /* #ifndef FONTDLG_H */ diff --git a/src/propsheet/globals.cpp b/src/propsheet/globals.cpp index b7f424632..a47b0d4bf 100644 --- a/src/propsheet/globals.cpp +++ b/src/propsheet/globals.cpp @@ -10,7 +10,7 @@ LONG gcyScreen; BOOL g_fForceV2; BOOL g_fEditKeys; -BYTE g_bPreviewOpacity = 0x00; //sentinel value for initial test on dialog entry. Once initialized, won't be less than TRANSPARENCY_RANGE_MIN +BYTE g_bPreviewOpacity = 0x00; //sentinel value for initial test on dialog entry. Once initialized, won't be less than TRANSPARENCY_RANGE_MIN BOOL g_fHostedInFileProperties = FALSE; @@ -18,14 +18,14 @@ UINT OEMCP; BOOL g_fEastAsianSystem; bool g_fIsComCtlV6Present; -const wchar_t g_szPreviewText[] = \ - L"C:\\WINDOWS> dir \n" \ - L"SYSTEM 10-01-99 5:00a\n" \ - L"SYSTEM32 10-01-99 5:00a\n" \ - L"README TXT 26926 10-01-99 5:00a\n" \ - L"WINDOWS BMP 46080 10-01-99 5:00a\n" \ - L"NOTEPAD EXE 337232 10-01-99 5:00a\n" \ - L"CLOCK AVI 39594 10-01-99 5:00p\n" \ +const wchar_t g_szPreviewText[] = + L"C:\\WINDOWS> dir \n" + L"SYSTEM 10-01-99 5:00a\n" + L"SYSTEM32 10-01-99 5:00a\n" + L"README TXT 26926 10-01-99 5:00a\n" + L"WINDOWS BMP 46080 10-01-99 5:00a\n" + L"NOTEPAD EXE 337232 10-01-99 5:00a\n" + L"CLOCK AVI 39594 10-01-99 5:00p\n" L"WIN INI 7005 10-01-99 5:00a\n"; BOOL fChangeCodePage = FALSE; @@ -33,7 +33,7 @@ BOOL fChangeCodePage = FALSE; WCHAR DefaultFaceName[LF_FACESIZE]; WCHAR DefaultTTFaceName[LF_FACESIZE]; COORD DefaultFontSize; -BYTE DefaultFontFamily; +BYTE DefaultFontFamily; ULONG DefaultFontIndex = 0; ULONG g_currentFontIndex = 0; @@ -45,7 +45,7 @@ PFACENODE gpFaceNames = NULL; BOOL g_fSettingsDlgInitialized = FALSE; -BOOL InEM_UNDO=FALSE; +BOOL InEM_UNDO = FALSE; // These values are used to "remember" the colors across a disable/re-enable, // so that if we disable the setting then re-enable it, we can re-initalize diff --git a/src/propsheet/globals.h b/src/propsheet/globals.h index b3128dbe0..8a75fb1ac 100644 --- a/src/propsheet/globals.h +++ b/src/propsheet/globals.h @@ -15,29 +15,29 @@ #pragma once #include "font.h" -extern HINSTANCE ghInstance; +extern HINSTANCE ghInstance; extern PCONSOLE_STATE_INFO gpStateInfo; extern PFONT_INFO FontInfo; -extern ULONG NumberOfFonts; -extern ULONG FontInfoLength; -extern ULONG g_currentFontIndex; -extern ULONG DefaultFontIndex; -extern WCHAR DefaultFaceName[LF_FACESIZE]; -extern WCHAR DefaultTTFaceName[LF_FACESIZE]; -extern COORD DefaultFontSize; -extern BYTE DefaultFontFamily; +extern ULONG NumberOfFonts; +extern ULONG FontInfoLength; +extern ULONG g_currentFontIndex; +extern ULONG DefaultFontIndex; +extern WCHAR DefaultFaceName[LF_FACESIZE]; +extern WCHAR DefaultTTFaceName[LF_FACESIZE]; +extern COORD DefaultFontSize; +extern BYTE DefaultFontFamily; extern const wchar_t g_szPreviewText[]; //Initial default fonts and face names -extern PFACENODE gpFaceNames; +extern PFACENODE gpFaceNames; -extern BOOL gbEnumerateFaces; -extern LONG gcxScreen; -extern LONG gcyScreen; -extern BOOL g_fForceV2; -extern BOOL g_fEditKeys; -extern BYTE g_bPreviewOpacity ; -extern BOOL g_fHostedInFileProperties; +extern BOOL gbEnumerateFaces; +extern LONG gcxScreen; +extern LONG gcyScreen; +extern BOOL g_fForceV2; +extern BOOL g_fEditKeys; +extern BYTE g_bPreviewOpacity; +extern BOOL g_fHostedInFileProperties; extern UINT OEMCP; extern BOOL g_fEastAsianSystem; diff --git a/src/propsheet/init.cpp b/src/propsheet/init.cpp index c6b6e7365..0b31bffc4 100644 --- a/src/propsheet/init.cpp +++ b/src/propsheet/init.cpp @@ -4,10 +4,8 @@ #include "precomp.h" #include "cpl_core.h" - HINSTANCE ghInstance; - /*************************************************************\ * DllInitialize() * @@ -23,7 +21,8 @@ BOOL WINAPI DllMain( DWORD dwReason, LPVOID /*lpvReserved*/) { - if (dwReason != DLL_PROCESS_ATTACH) { + if (dwReason != DLL_PROCESS_ATTACH) + { return TRUE; } @@ -34,7 +33,6 @@ BOOL WINAPI DllMain( return TRUE; } - /*************************************************************\ * CPlApplet() * @@ -57,13 +55,13 @@ LONG CPlApplet( LPNEWCPLINFO lpCPlInfo; INITCOMMONCONTROLSEX iccex; - switch (wMsg) { - + switch (wMsg) + { case CPL_INIT: iccex.dwSize = sizeof(iccex); - iccex.dwICC = ICC_WIN95_CLASSES; - InitCommonControlsEx( &iccex ); + iccex.dwICC = ICC_WIN95_CLASSES; + InitCommonControlsEx(&iccex); return InitializeConsoleState(); @@ -77,7 +75,7 @@ LONG CPlApplet( lpOldCPlInfo->idIcon = IDI_CONSOLE; lpOldCPlInfo->idName = IDS_NAME; lpOldCPlInfo->idInfo = IDS_INFO; - lpOldCPlInfo->lData = 0; + lpOldCPlInfo->lData = 0; return TRUE; case CPL_NEWINQUIRE: @@ -86,13 +84,13 @@ LONG CPlApplet( lpCPlInfo->hIcon = LoadIcon(NULL, MAKEINTRESOURCE(IDI_CONSOLE)); - if (!LoadString(ghInstance, IDS_NAME, lpCPlInfo->szName, - ARRAYSIZE(lpCPlInfo->szName))) { + if (!LoadString(ghInstance, IDS_NAME, lpCPlInfo->szName, ARRAYSIZE(lpCPlInfo->szName))) + { lpCPlInfo->szName[0] = TEXT('\0'); } - if (!LoadString(ghInstance, IDS_INFO, lpCPlInfo->szInfo, - ARRAYSIZE(lpCPlInfo->szInfo))) { + if (!LoadString(ghInstance, IDS_INFO, lpCPlInfo->szInfo, ARRAYSIZE(lpCPlInfo->szInfo))) + { lpCPlInfo->szInfo[0] = TEXT('\0'); } diff --git a/src/propsheet/menu.h b/src/propsheet/menu.h index b378388b7..0a743ded2 100644 --- a/src/propsheet/menu.h +++ b/src/propsheet/menu.h @@ -26,6 +26,5 @@ Revision History: #pragma once -#define CM_SETCOLOR (WM_USER+1) -#define CM_PREVIEW_UPDATE (WM_USER+2) - +#define CM_SETCOLOR (WM_USER + 1) +#define CM_PREVIEW_UPDATE (WM_USER + 2) diff --git a/src/propsheet/misc.cpp b/src/propsheet/misc.cpp index 8cd272754..97d14ca5d 100644 --- a/src/propsheet/misc.cpp +++ b/src/propsheet/misc.cpp @@ -28,12 +28,11 @@ Revision History: ULONG gDebugFlag = 0; #endif - #define MAX_FONT_INFO_ALLOC (ULONG_MAX / sizeof(FONT_INFO)) #define FE_ABANDONFONT 0 -#define FE_SKIPFONT 1 -#define FE_FONTOK 2 +#define FE_SKIPFONT 1 +#define FE_FONTOK 2 #define TERMINAL_FACENAME L"Terminal" @@ -41,7 +40,20 @@ ULONG gDebugFlag = 0; * TTPoints -- Initial font pixel heights for TT fonts */ SHORT TTPoints[] = { - 5, 6, 7, 8, 10, 12, 14, 16, 18, 20, 24, 28, 36, 72 + 5, + 6, + 7, + 8, + 10, + 12, + 14, + 16, + 18, + 20, + 24, + 28, + 36, + 72 }; /* @@ -49,11 +61,22 @@ SHORT TTPoints[] = { * So, This list except odd point size because font width is (SBCS:DBCS != 1:2). */ SHORT TTPointsDbcs[] = { - 6, 8, 10, 12, 14, 16, 18, 20, 24, 28, 36, 72 + 6, + 8, + 10, + 12, + 14, + 16, + 18, + 20, + 24, + 28, + 36, + 72 }; - -typedef struct _FONTENUMDATA { +typedef struct _FONTENUMDATA +{ HDC hDC; BOOL bFindFaces; ULONG ulFE; @@ -61,7 +84,6 @@ typedef struct _FONTENUMDATA { UINT nTTPoints; } FONTENUMDATA, *PFONTENUMDATA; - PFACENODE AddFaceNode( __in_ecount(LF_FACESIZE) LPCWSTR ptsz) @@ -72,8 +94,10 @@ AddFaceNode( /* * Is it already here? */ - for (ppTmp = &gpFaceNames; *ppTmp; ppTmp = &((*ppTmp)->pNext)) { - if (0 == lstrcmp(((*ppTmp)->atch), ptsz)) { + for (ppTmp = &gpFaceNames; *ppTmp; ppTmp = &((*ppTmp)->pNext)) + { + if (0 == lstrcmp(((*ppTmp)->atch), ptsz)) + { // already there ! return *ppTmp; } @@ -83,7 +107,8 @@ AddFaceNode( pNew = (PFACENODE)HeapAlloc(GetProcessHeap(), 0, sizeof(FACENODE) + ((cch + 1) * sizeof(WCHAR))); - if (pNew == NULL) { + if (pNew == NULL) + { return NULL; } @@ -94,15 +119,15 @@ AddFaceNode( return pNew; } - VOID -DestroyFaceNodes( - VOID) + DestroyFaceNodes( + VOID) { PFACENODE pNext, pTmp; pTmp = gpFaceNames; - while (pTmp != NULL) { + while (pTmp != NULL) + { pNext = pTmp->pNext; HeapFree(GetProcessHeap(), 0, pTmp); pTmp = pNext; @@ -152,7 +177,7 @@ void RecreateFontHandles(const HWND hWnd) // if the current font is a TrueType font if (TM_IS_TT_FONT(FontInfo[iCurrFont].Family)) { - LOGFONT lf = {0}; + LOGFONT lf = { 0 }; lf.lfWidth = GetDPIXScaledPixelSize(hWnd, FontInfo[iCurrFont].Size.X); lf.lfHeight = GetDPIYScaledPixelSize(hWnd, FontInfo[iCurrFont].Size.Y); lf.lfWeight = FontInfo[iCurrFont].Weight; @@ -176,13 +201,11 @@ void RecreateFontHandles(const HWND hWnd) } } - // Routine Description: // - Add the font described by the LOGFONT structure to the font table if // it's not already there. -int -AddFont( - ENUMLOGFONT *pelf, +int AddFont( + ENUMLOGFONT* pelf, NEWTEXTMETRIC* pntm, int nFontType, HDC hDC, @@ -208,9 +231,10 @@ AddFont( CreateBoldFont: pelf->elfLogFont.lfQuality = DEFAULT_QUALITY; hFont = CreateFontIndirect(&pelf->elfLogFont); - if (!hFont) { + if (!hFont) + { DBGFONTS((" REJECT font (can't create)\n")); - return FE_SKIPFONT; // same font in other sizes may still be suitable + return FE_SKIPFONT; // same font in other sizes may still be suitable } DBGFONTS2((" hFont = %p\n", hFont)); @@ -223,19 +247,26 @@ CreateBoldFont: SizeActual.Y = (SHORT)(tm.tmHeight + tm.tmExternalLeading); DBGFONTS2((" actual size %d,%d\n", SizeActual.X, SizeActual.Y)); tmFamily = tm.tmPitchAndFamily; - if (TM_IS_TT_FONT(tmFamily) && (SizeWant.Y >= 0)) { + if (TM_IS_TT_FONT(tmFamily) && (SizeWant.Y >= 0)) + { SizeToShow = SizeWant; - if (SizeWant.X == 0) { + if (SizeWant.X == 0) + { // Asking for zero width height gets a default aspect-ratio width. // It's better to show that width rather than 0. SizeToShow.X = SizeActual.X; } - } else { + } + else + { SizeToShow = SizeActual; } DBGFONTS2((" SizeToShow = (%d,%d), SizeActual = (%d,%d)\n", - SizeToShow.X, SizeToShow.Y, SizeActual.X, SizeActual.Y)); + SizeToShow.X, + SizeToShow.Y, + SizeActual.X, + SizeActual.Y)); /* * NOW, determine whether this font entry has already been cached @@ -246,31 +277,43 @@ CreateBoldFont: * 2) By height (as shown) * 3) By width (as shown) */ - for (nFont = 0; nFont < NumberOfFonts; ++nFont) { + for (nFont = 0; nFont < NumberOfFonts; ++nFont) + { COORD SizeShown; - if (FontInfo[nFont].hFont == NULL) { + if (FontInfo[nFont].hFont == NULL) + { DBGFONTS(("! Font %x has a NULL hFont\n", nFont)); continue; } - if (FontInfo[nFont].SizeWant.X > 0) { + if (FontInfo[nFont].SizeWant.X > 0) + { SizeShown.X = FontInfo[nFont].SizeWant.X; - } else { + } + else + { SizeShown.X = FontInfo[nFont].Size.X; } - if (FontInfo[nFont].SizeWant.Y > 0) { + if (FontInfo[nFont].SizeWant.Y > 0) + { // This is a font specified by cell height. SizeShown.Y = FontInfo[nFont].SizeWant.Y; - } else { + } + else + { SizeShown.Y = FontInfo[nFont].Size.Y; - if (FontInfo[nFont].SizeWant.Y < 0) { + if (FontInfo[nFont].SizeWant.Y < 0) + { // This is a TT font specified by character height. - if (SizeWant.Y < 0 && SizeWant.Y > FontInfo[nFont].SizeWant.Y) { + if (SizeWant.Y < 0 && SizeWant.Y > FontInfo[nFont].SizeWant.Y) + { // Requested pixelheight is smaller than this one. DBGFONTS(("INSERT %d pt at %x, before %d pt\n", - -SizeWant.Y, nFont, -FontInfo[nFont].SizeWant.Y)); + -SizeWant.Y, + nFont, + -FontInfo[nFont].SizeWant.Y)); break; } } @@ -292,14 +335,13 @@ CreateBoldFont: return FE_FONTOK; } - if ((SizeToShow.Y < SizeShown.Y) || - (SizeToShow.Y == SizeShown.Y && SizeToShow.X < SizeShown.X)) { + (SizeToShow.Y == SizeShown.Y && SizeToShow.X < SizeShown.X)) + { /* * This new font is smaller than nFont */ - DBGFONTS(("INSERT at %x, SizeToShow = (%d,%d)\n", nFont, - SizeToShow.X,SizeToShow.Y)); + DBGFONTS(("INSERT at %x, SizeToShow = (%d,%d)\n", nFont, SizeToShow.X, SizeToShow.Y)); break; } } @@ -307,7 +349,8 @@ CreateBoldFont: /* * If we have to grow our font table, do it. */ - if (NumberOfFonts == FontInfoLength) { + if (NumberOfFonts == FontInfoLength) + { PFONT_INFO Temp = NULL; FontInfoLength += FONT_INCREMENT; @@ -319,9 +362,10 @@ CreateBoldFont: sizeof(FONT_INFO) * FontInfoLength); } - if (Temp == NULL) { + if (Temp == NULL) + { FontInfoLength -= FONT_INCREMENT; - return FE_ABANDONFONT; // no point enumerating more - no memory! + return FE_ABANDONFONT; // no point enumerating more - no memory! } FontInfo = Temp; } @@ -330,8 +374,9 @@ CreateBoldFont: * The font we are adding should be inserted into the list, if it is * smaller than the last one. */ - if (nFont < NumberOfFonts) { - RtlMoveMemory(&FontInfo[nFont+1], + if (nFont < NumberOfFonts) + { + RtlMoveMemory(&FontInfo[nFont + 1], &FontInfo[nFont], sizeof(FONT_INFO) * (NumberOfFonts - nFont)); } @@ -340,12 +385,14 @@ CreateBoldFont: * If we're adding a truetype font for the V2 console, secretly swap out the current hFont with one that's scaled * appropriately for DPI */ - if (nFontType == TRUETYPE_FONTTYPE && gpStateInfo->fIsV2Console) { + if (nFontType == TRUETYPE_FONTTYPE && gpStateInfo->fIsV2Console) + { DeleteObject(hFont); pelf->elfLogFont.lfWidth = GetDPIXScaledPixelSize(gpStateInfo->hWnd, SizeOriginal.X); pelf->elfLogFont.lfHeight = GetDPIYScaledPixelSize(gpStateInfo->hWnd, SizeOriginal.Y); hFont = CreateFontIndirect(&pelf->elfLogFont); - if (!hFont) { + if (!hFont) + { return FE_SKIPFONT; } } @@ -356,9 +403,12 @@ CreateBoldFont: FontInfo[nFont].hFont = hFont; FontInfo[nFont].Family = tmFamily; FontInfo[nFont].Size = SizeActual; - if (TM_IS_TT_FONT(tmFamily)) { + if (TM_IS_TT_FONT(tmFamily)) + { FontInfo[nFont].SizeWant = SizeWant; - } else { + } + else + { FontInfo[nFont].SizeWant.X = 0; FontInfo[nFont].SizeWant.Y = 0; } @@ -373,34 +423,35 @@ CreateBoldFont: /* * If this is a true type font, create a bold version too. */ - if (nFontType == TRUETYPE_FONTTYPE && !IS_BOLD(FontInfo[nFont].Weight)) { - pelf->elfLogFont.lfWeight = FW_BOLD; - pelf->elfLogFont.lfWidth = SizeOriginal.X; - pelf->elfLogFont.lfHeight = SizeOriginal.Y; - fCreatingBoldFont = TRUE; - goto CreateBoldFont; + if (nFontType == TRUETYPE_FONTTYPE && !IS_BOLD(FontInfo[nFont].Weight)) + { + pelf->elfLogFont.lfWeight = FW_BOLD; + pelf->elfLogFont.lfWidth = SizeOriginal.X; + pelf->elfLogFont.lfHeight = SizeOriginal.Y; + fCreatingBoldFont = TRUE; + goto CreateBoldFont; } - return FE_FONTOK; // and continue enumeration + return FE_FONTOK; // and continue enumeration } - VOID -InitializeFonts( - VOID) + InitializeFonts( + VOID) { - LOG_IF_FAILED(EnumerateFonts(EF_DEFFACE)); // Just the Default font + LOG_IF_FAILED(EnumerateFonts(EF_DEFFACE)); // Just the Default font } - VOID -DestroyFonts( - VOID) + DestroyFonts( + VOID) { ULONG FontIndex; - if (FontInfo != NULL) { - for (FontIndex = 0; FontIndex < NumberOfFonts; FontIndex++) { + if (FontInfo != NULL) + { + for (FontIndex = 0; FontIndex < NumberOfFonts; FontIndex++) + { DeleteObject(FontInfo[FontIndex].hFont); } HeapFree(GetProcessHeap(), 0, FontInfo); @@ -420,7 +471,7 @@ DestroyFonts( * Is called exactly once by GDI for each font in the system. This * routine is used to store the FONT_INFO structure. */ -int CALLBACK FontEnumForV2Console(ENUMLOGFONT *pelf, NEWTEXTMETRIC *pntm, int nFontType, LPARAM lParam) +int CALLBACK FontEnumForV2Console(ENUMLOGFONT* pelf, NEWTEXTMETRIC* pntm, int nFontType, LPARAM lParam) { FAIL_FAST_IF(!(ShouldAllowAllMonoTTFonts())); UINT i; @@ -429,11 +480,13 @@ int CALLBACK FontEnumForV2Console(ENUMLOGFONT *pelf, NEWTEXTMETRIC *pntm, int nF PFONTENUMDATA pfed = (PFONTENUMDATA)lParam; DBGFONTS((" FontEnum \"%ls\" (%d,%d) weight 0x%lx(%d) %x -- %s\n", - ptszFace, - pelf->elfLogFont.lfWidth, pelf->elfLogFont.lfHeight, - pelf->elfLogFont.lfWeight, pelf->elfLogFont.lfWeight, - pelf->elfLogFont.lfCharSet, - pfed->bFindFaces ? "Finding Faces" : "Creating Fonts")); + ptszFace, + pelf->elfLogFont.lfWidth, + pelf->elfLogFont.lfHeight, + pelf->elfLogFont.lfWeight, + pelf->elfLogFont.lfWeight, + pelf->elfLogFont.lfCharSet, + pfed->bFindFaces ? "Finding Faces" : "Creating Fonts")); // reject non-monospaced fonts if (!(pelf->elfLogFont.lfPitchAndFamily & FIXED_PITCH)) @@ -472,41 +525,50 @@ int CALLBACK FontEnumForV2Console(ENUMLOGFONT *pelf, NEWTEXTMETRIC *pntm, int nF } // reject East Asian TT fonts that aren't East Asian charset. - if (g_fEastAsianSystem && (nFontType == TRUETYPE_FONTTYPE) && !IS_ANY_DBCS_CHARSET(pelf->elfLogFont.lfCharSet)) { + if (g_fEastAsianSystem && (nFontType == TRUETYPE_FONTTYPE) && !IS_ANY_DBCS_CHARSET(pelf->elfLogFont.lfCharSet)) + { DBGFONTS((" REJECT face (East Asian charset, but not East Asian TT)\n")); - return FE_SKIPFONT; // should be enumerate next charset. + return FE_SKIPFONT; // should be enumerate next charset. } // reject East Asian TT fonts on non-East Asian systems if (!g_fEastAsianSystem && (nFontType == TRUETYPE_FONTTYPE) && IS_ANY_DBCS_CHARSET(pelf->elfLogFont.lfCharSet)) { DBGFONTS((" REJECT face (East Asian TT and not East Asian charset)\n")); - return FE_SKIPFONT; // should be enumerate next charset. + return FE_SKIPFONT; // should be enumerate next charset. } /* * Add or find the facename */ pFN = AddFaceNode(ptszFace); - if (pFN == NULL) { + if (pFN == NULL) + { return FE_ABANDONFONT; } - if (pfed->bFindFaces) { + if (pfed->bFindFaces) + { DWORD dwFontType; - if (nFontType == TRUETYPE_FONTTYPE) { + if (nFontType == TRUETYPE_FONTTYPE) + { DBGFONTS(("NEW TT FACE %ls\n", ptszFace)); dwFontType = EF_TTFONT; - } else if (nFontType == RASTER_FONTTYPE) { - DBGFONTS(("NEW OEM FACE %ls\n",ptszFace)); + } + else if (nFontType == RASTER_FONTTYPE) + { + DBGFONTS(("NEW OEM FACE %ls\n", ptszFace)); dwFontType = EF_OEMFONT; - } else { + } + else + { dwFontType = 0; } pFN->dwFlag |= dwFontType | EF_NEW; - if (IS_ANY_DBCS_CHARSET(pelf->elfLogFont.lfCharSet)) { + if (IS_ANY_DBCS_CHARSET(pelf->elfLogFont.lfCharSet)) + { pFN->dwFlag |= EF_DBCSFONT; } return FE_SKIPFONT; @@ -516,24 +578,30 @@ int CALLBACK FontEnumForV2Console(ENUMLOGFONT *pelf, NEWTEXTMETRIC *pntm, int nF * Add the font to the table. If this is a true type font, add the * sizes from the array. Otherwise, just add the size we got. */ - if (nFontType & TRUETYPE_FONTTYPE) { - for (i = 0; i < pfed->nTTPoints; i++) { + if (nFontType & TRUETYPE_FONTTYPE) + { + for (i = 0; i < pfed->nTTPoints; i++) + { pelf->elfLogFont.lfHeight = pfed->pTTPoints[i]; - pelf->elfLogFont.lfWidth = 0; + pelf->elfLogFont.lfWidth = 0; pelf->elfLogFont.lfWeight = pntm->tmWeight; pfed->ulFE |= AddFont(pelf, pntm, nFontType, pfed->hDC, pFN); - if (pfed->ulFE == FE_ABANDONFONT) { + if (pfed->ulFE == FE_ABANDONFONT) + { return FE_ABANDONFONT; } } - } else { + } + else + { pfed->ulFE |= AddFont(pelf, pntm, nFontType, pfed->hDC, pFN); - if (pfed->ulFE == FE_ABANDONFONT) { + if (pfed->ulFE == FE_ABANDONFONT) + { return FE_ABANDONFONT; } } - return FE_FONTOK; // and continue enumeration + return FE_FONTOK; // and continue enumeration } /* @@ -546,12 +614,12 @@ int CALLBACK FontEnumForV2Console(ENUMLOGFONT *pelf, NEWTEXTMETRIC *pntm, int nF * routine is used to store the FONT_INFO structure. */ int -CALLBACK -FontEnum( - ENUMLOGFONT *pelf, - NEWTEXTMETRIC *pntm, - int nFontType, - LPARAM lParam) + CALLBACK + FontEnum( + ENUMLOGFONT* pelf, + NEWTEXTMETRIC* pntm, + int nFontType, + LPARAM lParam) { UINT i; LPCTSTR ptszFace = pelf->elfLogFont.lfFaceName; @@ -559,24 +627,25 @@ FontEnum( PFONTENUMDATA pfed = (PFONTENUMDATA)lParam; DBGFONTS((" FontEnum \"%ls\" (%d,%d) weight 0x%lx(%d) %x -- %s\n", - ptszFace, - pelf->elfLogFont.lfWidth, pelf->elfLogFont.lfHeight, - pelf->elfLogFont.lfWeight, pelf->elfLogFont.lfWeight, - pelf->elfLogFont.lfCharSet, - pfed->bFindFaces ? "Finding Faces" : "Creating Fonts")); + ptszFace, + pelf->elfLogFont.lfWidth, + pelf->elfLogFont.lfHeight, + pelf->elfLogFont.lfWeight, + pelf->elfLogFont.lfWeight, + pelf->elfLogFont.lfCharSet, + pfed->bFindFaces ? "Finding Faces" : "Creating Fonts")); // // reject variable width and italic fonts, also tt fonts with neg ac // - if - ( - !(pelf->elfLogFont.lfPitchAndFamily & FIXED_PITCH) || - (pelf->elfLogFont.lfItalic) || - !(pntm->ntmFlags & NTM_NONNEGATIVE_AC) - ) + if ( + !(pelf->elfLogFont.lfPitchAndFamily & FIXED_PITCH) || + (pelf->elfLogFont.lfItalic) || + !(pntm->ntmFlags & NTM_NONNEGATIVE_AC)) { - if (! IsAvailableTTFont(ptszFace)) { + if (!IsAvailableTTFont(ptszFace)) + { DBGFONTS((" REJECT face (dbcs, variable pitch, italic, or neg a&c)\n")); return pfed->bFindFaces ? FE_SKIPFONT : FE_ABANDONFONT; } @@ -591,7 +660,8 @@ FontEnum( */ if ((nFontType == TRUETYPE_FONTTYPE) && - ((pelf->elfLogFont.lfPitchAndFamily & 0xf0) != FF_MODERN)) { + ((pelf->elfLogFont.lfPitchAndFamily & 0xf0) != FF_MODERN)) + { DBGFONTS((" REJECT face (TT but not FF_MODERN)\n")); return pfed->bFindFaces ? FE_SKIPFONT : FE_ABANDONFONT; } @@ -600,8 +670,9 @@ FontEnum( * reject non-TT fonts that aren't OEM */ if ((nFontType != TRUETYPE_FONTTYPE) && - (!g_fEastAsianSystem || !IS_ANY_DBCS_CHARSET(pelf->elfLogFont.lfCharSet)) && - (pelf->elfLogFont.lfCharSet != OEM_CHARSET)) { + (!g_fEastAsianSystem || !IS_ANY_DBCS_CHARSET(pelf->elfLogFont.lfCharSet)) && + (pelf->elfLogFont.lfCharSet != OEM_CHARSET)) + { DBGFONTS((" REJECT face (not TT nor OEM)\n")); return FE_SKIPFONT; } @@ -631,42 +702,50 @@ FontEnum( */ if (IsAvailableTTFont(ptszFace) && !IS_ANY_DBCS_CHARSET(pelf->elfLogFont.lfCharSet) && - !IsAvailableTTFontCP(ptszFace,0) - ) { + !IsAvailableTTFontCP(ptszFace, 0)) + { DBGFONTS((" REJECT face (East Asian TT and not East Asian charset)\n")); - return FE_SKIPFONT; // should be enumerate next charset. + return FE_SKIPFONT; // should be enumerate next charset. } /* * Add or find the facename */ pFN = AddFaceNode(ptszFace); - if (pFN == NULL) { + if (pFN == NULL) + { return FE_ABANDONFONT; } - if (pfed->bFindFaces) { + if (pfed->bFindFaces) + { DWORD dwFontType; - if (nFontType == TRUETYPE_FONTTYPE) { + if (nFontType == TRUETYPE_FONTTYPE) + { DBGFONTS(("NEW TT FACE %ls\n", ptszFace)); dwFontType = EF_TTFONT; - } else if (nFontType == RASTER_FONTTYPE) { - DBGFONTS(("NEW OEM FACE %ls\n",ptszFace)); + } + else if (nFontType == RASTER_FONTTYPE) + { + DBGFONTS(("NEW OEM FACE %ls\n", ptszFace)); dwFontType = EF_OEMFONT; - } else { + } + else + { dwFontType = 0; } pFN->dwFlag |= dwFontType | EF_NEW; - if (IS_ANY_DBCS_CHARSET(pelf->elfLogFont.lfCharSet)) { + if (IS_ANY_DBCS_CHARSET(pelf->elfLogFont.lfCharSet)) + { pFN->dwFlag |= EF_DBCSFONT; } return FE_SKIPFONT; } - - if (IS_BOLD(pelf->elfLogFont.lfWeight)) { + if (IS_BOLD(pelf->elfLogFont.lfWeight)) + { DBGFONTS2((" A bold font (weight %d)\n", pelf->elfLogFont.lfWeight)); // return FE_SKIPFONT; } @@ -675,28 +754,33 @@ FontEnum( * Add the font to the table. If this is a true type font, add the * sizes from the array. Otherwise, just add the size we got. */ - if (nFontType & TRUETYPE_FONTTYPE) { - for (i = 0; i < pfed->nTTPoints; i++) { + if (nFontType & TRUETYPE_FONTTYPE) + { + for (i = 0; i < pfed->nTTPoints; i++) + { pelf->elfLogFont.lfHeight = pfed->pTTPoints[i]; - pelf->elfLogFont.lfWidth = 0; + pelf->elfLogFont.lfWidth = 0; pelf->elfLogFont.lfWeight = 400; pfed->ulFE |= AddFont(pelf, pntm, nFontType, pfed->hDC, pFN); - if (pfed->ulFE == FE_ABANDONFONT) { + if (pfed->ulFE == FE_ABANDONFONT) + { return FE_ABANDONFONT; } } - } else { + } + else + { pfed->ulFE |= AddFont(pelf, pntm, nFontType, pfed->hDC, pFN); - if (pfed->ulFE == FE_ABANDONFONT) { + if (pfed->ulFE == FE_ABANDONFONT) + { return FE_ABANDONFONT; } } - return FE_FONTOK; // and continue enumeration + return FE_FONTOK; // and continue enumeration } -BOOL -DoFontEnum( +BOOL DoFontEnum( __in_opt HDC hDC, __in_ecount_opt(LF_FACESIZE) LPTSTR ptszFace, __in_ecount_opt(nTTPoints) PSHORT pTTPoints, @@ -707,7 +791,8 @@ DoFontEnum( LOGFONT LogFont; DBGFONTS(("DoFontEnum \"%ls\"\n", ptszFace)); - if (hDC == NULL) { + if (hDC == NULL) + { hDC = CreateCompatibleDC(NULL); bDeleteDC = TRUE; } @@ -719,13 +804,15 @@ DoFontEnum( fed.nTTPoints = nTTPoints; RtlZeroMemory(&LogFont, sizeof(LOGFONT)); LogFont.lfCharSet = DEFAULT_CHARSET; - if (ptszFace != nullptr) { + if (ptszFace != nullptr) + { StringCchCopy(LogFont.lfFaceName, LF_FACESIZE, ptszFace); if (NumberOfFonts == 0 && // We've yet to enumerate fonts g_fEastAsianSystem && // And we're currently using a CJK codepage !IS_ANY_DBCS_CHARSET(CodePageToCharSet(OEMCP)) && // But the system codepage *isn't* CJK - 0 == lstrcmp(ptszFace, TERMINAL_FACENAME)) { // and we're looking at the raster font + 0 == lstrcmp(ptszFace, TERMINAL_FACENAME)) + { // and we're looking at the raster font // In this specific scenario, the raster font will only be enumerated if we ask for OEM_CHARSET rather than // a CJK charset @@ -738,16 +825,15 @@ DoFontEnum( * character set. */ EnumFontFamiliesEx(hDC, &LogFont, (FONTENUMPROC)((ShouldAllowAllMonoTTFonts()) ? FontEnumForV2Console : FontEnum), (LPARAM)&fed, 0); - if (bDeleteDC) { + if (bDeleteDC) + { DeleteDC(hDC); } return (fed.ulFE & FE_FONTOK) != 0; } - -VOID -RemoveFace(__in_ecount(LF_FACESIZE) LPCTSTR ptszFace) +VOID RemoveFace(__in_ecount(LF_FACESIZE) LPCTSTR ptszFace) { DWORD i; int nToRemove = 0; @@ -762,7 +848,8 @@ RemoveFace(__in_ecount(LF_FACESIZE) LPCTSTR ptszFace) { BOOL bDeleted = DeleteObject(FontInfo[i].hFont); DBGFONTS(("RemoveFace: hFont %p was %sdeleted\n", - FontInfo[i].hFont, bDeleted ? "" : "NOT ")); + FontInfo[i].hFont, + bDeleted ? "" : "NOT ")); bDeleted; // to fix x86 build complaining FontInfo[i].hFont = NULL; nToRemove++; @@ -773,8 +860,8 @@ RemoveFace(__in_ecount(LF_FACESIZE) LPCTSTR ptszFace) * Shuffle from FontInfo[i] down nToRemove slots. */ RtlMoveMemory(&FontInfo[i - nToRemove], - &FontInfo[i], - sizeof(FONT_INFO)*(NumberOfFonts - i)); + &FontInfo[i], + sizeof(FONT_INFO) * (NumberOfFonts - i)); NumberOfFonts -= nToRemove; i -= nToRemove; nToRemove = 0; @@ -838,8 +925,7 @@ void CreateSizeForAllTTFonts(__in const SHORT sSize) } } -[[nodiscard]] -NTSTATUS +[[nodiscard]] NTSTATUS EnumerateFonts( DWORD Flags) { @@ -853,14 +939,16 @@ EnumerateFonts( dwFontType = (EF_TTFONT | EF_OEMFONT | EF_DEFFACE) & Flags; - if (FontInfo == NULL) { + if (FontInfo == NULL) + { // // allocate memory for the font array // NumberOfFonts = 0; FontInfo = (PFONT_INFO)HeapAlloc(GetProcessHeap(), 0, sizeof(FONT_INFO) * INITIAL_FONTS); - if (FontInfo == NULL) { + if (FontInfo == NULL) + { return STATUS_NO_MEMORY; } @@ -869,36 +957,39 @@ EnumerateFonts( hDC = CreateCompatibleDC(NULL); - if (Flags & EF_DEFFACE) { + if (Flags & EF_DEFFACE) + { SelectObject(hDC, GetStockObject(OEM_FIXED_FONT)); GetTextMetrics(hDC, &tm); GetTextFace(hDC, LF_FACESIZE, DefaultFaceName); DefaultFontSize.X = (SHORT)(tm.tmMaxCharWidth); - DefaultFontSize.Y = (SHORT)(tm.tmHeight+tm.tmExternalLeading); + DefaultFontSize.Y = (SHORT)(tm.tmHeight + tm.tmExternalLeading); DefaultFontFamily = tm.tmPitchAndFamily; - if (IS_ANY_DBCS_CHARSET(tm.tmCharSet)) { + if (IS_ANY_DBCS_CHARSET(tm.tmCharSet)) + { DefaultFontSize.X /= 2; } - DBGFONTS(("Default (OEM) Font %ls (%d,%d) CharSet 0x%02X\n", DefaultFaceName, - DefaultFontSize.X, DefaultFontSize.Y, - tm.tmCharSet)); + DBGFONTS(("Default (OEM) Font %ls (%d,%d) CharSet 0x%02X\n", DefaultFaceName, DefaultFontSize.X, DefaultFontSize.Y, tm.tmCharSet)); // Make sure we are going to enumerate the OEM face. pFN = AddFaceNode(DefaultFaceName); - if (pFN != NULL) { + if (pFN != NULL) + { pFN->dwFlag |= EF_DEFFACE | EF_OEMFONT; } } - if (gbEnumerateFaces) { + if (gbEnumerateFaces) + { /* * Set the EF_OLD bit and clear the EF_NEW bit * for all previously available faces */ - for (pFN = gpFaceNames; pFN; pFN = pFN->pNext) { + for (pFN = gpFaceNames; pFN; pFN = pFN->pNext) + { pFN->dwFlag |= EF_OLD; pFN->dwFlag &= ~EF_NEW; } @@ -915,36 +1006,37 @@ EnumerateFonts( // Use DoFontEnum to get all fonts from the system. Our FontEnum // proc puts just the ones we want into an array // - for (pFN = gpFaceNames; pFN; pFN = pFN->pNext) { - DBGFONTS(("\"%ls\" is %s%s%s%s%s%s\n", pFN->atch, - pFN->dwFlag & EF_NEW ? "NEW " : " ", - pFN->dwFlag & EF_OLD ? "OLD " : " ", - pFN->dwFlag & EF_ENUMERATED ? "ENUMERATED " : " ", - pFN->dwFlag & EF_OEMFONT ? "OEMFONT " : " ", - pFN->dwFlag & EF_TTFONT ? "TTFONT " : " ", - pFN->dwFlag & EF_DEFFACE ? "DEFFACE " : " ")); + for (pFN = gpFaceNames; pFN; pFN = pFN->pNext) + { + DBGFONTS(("\"%ls\" is %s%s%s%s%s%s\n", pFN->atch, pFN->dwFlag & EF_NEW ? "NEW " : " ", pFN->dwFlag & EF_OLD ? "OLD " : " ", pFN->dwFlag & EF_ENUMERATED ? "ENUMERATED " : " ", pFN->dwFlag & EF_OEMFONT ? "OEMFONT " : " ", pFN->dwFlag & EF_TTFONT ? "TTFONT " : " ", pFN->dwFlag & EF_DEFFACE ? "DEFFACE " : " ")); - if ((pFN->dwFlag & (EF_OLD|EF_NEW)) == EF_OLD) { + if ((pFN->dwFlag & (EF_OLD | EF_NEW)) == EF_OLD) + { // The face is no longer available RemoveFace(pFN->atch); pFN->dwFlag &= ~EF_ENUMERATED; continue; } - if ((pFN->dwFlag & dwFontType) == 0) { + if ((pFN->dwFlag & dwFontType) == 0) + { // not the kind of face we want continue; } - if (pFN->dwFlag & EF_ENUMERATED) { + if (pFN->dwFlag & EF_ENUMERATED) + { // we already enumerated this face continue; } - if (pFN->dwFlag & EF_TTFONT) { - if (g_fEastAsianSystem && !IsAvailableTTFontCP(pFN->atch,0)) + if (pFN->dwFlag & EF_TTFONT) + { + if (g_fEastAsianSystem && !IsAvailableTTFontCP(pFN->atch, 0)) DoFontEnum(hDC, pFN->atch, TTPointsDbcs, ARRAYSIZE(TTPointsDbcs)); else DoFontEnum(hDC, pFN->atch, TTPoints, ARRAYSIZE(TTPoints)); - } else { + } + else + { DoFontEnum(hDC, pFN->atch, NULL, 0); } pFN->dwFlag |= EF_ENUMERATED; @@ -959,28 +1051,38 @@ EnumerateFonts( DeleteDC(hDC); - if (g_fEastAsianSystem) { - for (FontIndex = 0; FontIndex < NumberOfFonts; FontIndex++) { + if (g_fEastAsianSystem) + { + for (FontIndex = 0; FontIndex < NumberOfFonts; FontIndex++) + { if (FontInfo[FontIndex].Size.X == DefaultFontSize.X && FontInfo[FontIndex].Size.Y == DefaultFontSize.Y && IS_DBCS_OR_OEM_CHARSET(FontInfo[FontIndex].tmCharSet) && - FontInfo[FontIndex].Family == DefaultFontFamily) { + FontInfo[FontIndex].Family == DefaultFontFamily) + { break; } } - } else { - for (FontIndex = 0; FontIndex < NumberOfFonts; FontIndex++) { + } + else + { + for (FontIndex = 0; FontIndex < NumberOfFonts; FontIndex++) + { if (FontInfo[FontIndex].Size.X == DefaultFontSize.X && FontInfo[FontIndex].Size.Y == DefaultFontSize.Y && - FontInfo[FontIndex].Family == DefaultFontFamily) { + FontInfo[FontIndex].Family == DefaultFontFamily) + { break; } } } - if (FontIndex < NumberOfFonts) { + if (FontIndex < NumberOfFonts) + { DefaultFontIndex = FontIndex; - } else { + } + else + { DefaultFontIndex = 0; } diff --git a/src/propsheet/precomp.h b/src/propsheet/precomp.h index 4b053c598..d860743c0 100644 --- a/src/propsheet/precomp.h +++ b/src/propsheet/precomp.h @@ -17,7 +17,6 @@ #define DEFINE_CONSOLEV2_PROPERTIES #define INC_OLE2 - // This includes a lot of common headers needed by both the host and the propsheet // including: windows.h, winuser, ntstatus, assert, and the DDK #include "HostAndPropsheetIncludes.h" @@ -52,7 +51,7 @@ // This is currently bubbling up the source tree to our branch #ifndef WM_DPICHANGED_BEFOREPARENT -#define WM_DPICHANGED_BEFOREPARENT 0x02E2 +#define WM_DPICHANGED_BEFOREPARENT 0x02E2 #endif // When on a non-CJK machine using the raster font in a CJK codepage (e.g. "chcp 932"), the raster font is enumerated as diff --git a/src/propsheet/preview.cpp b/src/propsheet/preview.cpp index bc214c292..d4e88f806 100644 --- a/src/propsheet/preview.cpp +++ b/src/propsheet/preview.cpp @@ -22,11 +22,9 @@ Revision History: #include "precomp.h" #pragma hdrstop - /* ----- Equates ----- */ -#define PREVIEW_HSCROLL 0x01 -#define PREVIEW_VSCROLL 0x02 - +#define PREVIEW_HSCROLL 0x01 +#define PREVIEW_VSCROLL 0x02 /* ----- Prototypes ----- */ @@ -39,16 +37,14 @@ LONG AspectScale( LONG n2, LONG m); - /* ----- Globals ----- */ POINT NonClientSize; RECT WindowRect; DWORD PreviewFlags; - VOID -UpdatePreviewRect(VOID) + UpdatePreviewRect(VOID) /*++ @@ -62,7 +58,7 @@ UpdatePreviewRect(VOID) POINT WindowSize; PFONT_INFO lpFont; HMONITOR hMonitor; - MONITORINFO mi = {0}; + MONITORINFO mi = { 0 }; /* * Get the font pointer @@ -72,8 +68,8 @@ UpdatePreviewRect(VOID) /* * Get the window size */ - MinSize.x = (GetSystemMetrics(SM_CXMIN)-NonClientSize.x) / lpFont->Size.X; - MinSize.y = (GetSystemMetrics(SM_CYMIN)-NonClientSize.y) / lpFont->Size.Y; + MinSize.x = (GetSystemMetrics(SM_CXMIN) - NonClientSize.x) / lpFont->Size.X; + MinSize.y = (GetSystemMetrics(SM_CYMIN) - NonClientSize.y) / lpFont->Size.Y; MaxSize.x = GetSystemMetrics(SM_CXFULLSCREEN) / lpFont->Size.X; MaxSize.y = GetSystemMetrics(SM_CYFULLSCREEN) / lpFont->Size.Y; WindowSize.x = max(MinSize.x, min(MaxSize.x, gpStateInfo->WindowSize.X)); @@ -86,12 +82,14 @@ UpdatePreviewRect(VOID) WindowRect.left = gpStateInfo->WindowPosX; WindowRect.top = gpStateInfo->WindowPosY; WindowRect.right = WindowSize.x * lpFont->Size.X + NonClientSize.x; - if (WindowRect.right < NonClientSize.x * 2) { + if (WindowRect.right < NonClientSize.x * 2) + { WindowRect.right = NonClientSize.x * 2; } WindowRect.right += WindowRect.left; WindowRect.bottom = WindowSize.y * lpFont->Size.Y + NonClientSize.y; - if (WindowRect.bottom < NonClientSize.y * 2) { + if (WindowRect.bottom < NonClientSize.y * 2) + { WindowRect.bottom = NonClientSize.y * 2; } WindowRect.bottom += WindowRect.top; @@ -108,29 +106,33 @@ UpdatePreviewRect(VOID) /* * Convert window rectangle to monitor relative coordinates */ - WindowRect.right -= WindowRect.left; - WindowRect.left -= mi.rcWork.left; + WindowRect.right -= WindowRect.left; + WindowRect.left -= mi.rcWork.left; WindowRect.bottom -= WindowRect.top; - WindowRect.top -= mi.rcWork.top; + WindowRect.top -= mi.rcWork.top; /* * Update the display flags */ - if (WindowSize.x < gpStateInfo->ScreenBufferSize.X) { + if (WindowSize.x < gpStateInfo->ScreenBufferSize.X) + { PreviewFlags |= PREVIEW_HSCROLL; - } else { + } + else + { PreviewFlags &= ~PREVIEW_HSCROLL; } - if (WindowSize.y < gpStateInfo->ScreenBufferSize.Y) { + if (WindowSize.y < gpStateInfo->ScreenBufferSize.Y) + { PreviewFlags |= PREVIEW_VSCROLL; - } else { + } + else + { PreviewFlags &= ~PREVIEW_VSCROLL; } } - -VOID -InvalidatePreviewRect(HWND hWnd) +VOID InvalidatePreviewRect(HWND hWnd) /*++ @@ -151,9 +153,9 @@ InvalidatePreviewRect(HWND hWnd) * Get the dimensions of the preview "window" and scale it to the * preview "screen" */ - rectWin.left = WindowRect.left; - rectWin.top = WindowRect.top; - rectWin.right = WindowRect.left + WindowRect.right; + rectWin.left = WindowRect.left; + rectWin.top = WindowRect.top; + rectWin.right = WindowRect.left + WindowRect.right; rectWin.bottom = WindowRect.top + WindowRect.bottom; AspectPoint(&rectPreview, (POINT*)&rectWin.left); AspectPoint(&rectPreview, (POINT*)&rectWin.right); @@ -164,12 +166,9 @@ InvalidatePreviewRect(HWND hWnd) InvalidateRect(hWnd, &rectWin, FALSE); } - -VOID -PreviewPaint( +VOID PreviewPaint( PAINTSTRUCT* pPS, - HWND hWnd - ) + HWND hWnd) /*++ @@ -215,7 +214,7 @@ PreviewPaint( ptButton.x = GetSystemMetrics(SM_CXSIZE); ptButton.y = GetSystemMetrics(SM_CYSIZE); AspectPoint(&rectPreview, &ptButton); - ptButton.y *= 2; /* Double the computed size for "looks" */ + ptButton.y *= 2; /* Double the computed size for "looks" */ ptScroll.x = GetSystemMetrics(SM_CXVSCROLL); ptScroll.y = GetSystemMetrics(SM_CYHSCROLL); AspectPoint(&rectPreview, &ptScroll); @@ -227,19 +226,19 @@ PreviewPaint( hBitmap = CreateCompatibleBitmap(pPS->hdc, rectPreview.right, rectPreview.bottom); - hBitmapOld = (HBITMAP) SelectObject(hDC, hBitmap); + hBitmapOld = (HBITMAP)SelectObject(hDC, hBitmap); /* * Create the brushes */ - hbrBorder = CreateSolidBrush(GetSysColor(COLOR_ACTIVEBORDER)); - hbrTitle = CreateSolidBrush(GetSysColor(COLOR_ACTIVECAPTION)); - hbrFrame = CreateSolidBrush(GetSysColor(COLOR_WINDOWFRAME)); - hbrButton = CreateSolidBrush(GetSysColor(COLOR_BTNFACE)); - hbrScroll = CreateSolidBrush(GetSysColor(COLOR_SCROLLBAR)); + hbrBorder = CreateSolidBrush(GetSysColor(COLOR_ACTIVEBORDER)); + hbrTitle = CreateSolidBrush(GetSysColor(COLOR_ACTIVECAPTION)); + hbrFrame = CreateSolidBrush(GetSysColor(COLOR_WINDOWFRAME)); + hbrButton = CreateSolidBrush(GetSysColor(COLOR_BTNFACE)); + hbrScroll = CreateSolidBrush(GetSysColor(COLOR_SCROLLBAR)); hbrDesktop = CreateSolidBrush(GetSysColor(COLOR_BACKGROUND)); - rgbClient = GetNearestColor(hDC, ScreenBkColor(gpStateInfo)); - hbrClient = CreateSolidBrush(rgbClient); + rgbClient = GetNearestColor(hDC, ScreenBkColor(gpStateInfo)); + hbrClient = CreateSolidBrush(rgbClient); /* * Erase the clipping area @@ -249,60 +248,43 @@ PreviewPaint( /* * Fill in the whole window with the client brush */ - hbrOld = (HBRUSH) SelectObject(hDC, hbrClient); - PatBlt(hDC, rectWin.left, rectWin.top, - rectWin.right - 1, rectWin.bottom - 1, PATCOPY); + hbrOld = (HBRUSH)SelectObject(hDC, hbrClient); + PatBlt(hDC, rectWin.left, rectWin.top, rectWin.right - 1, rectWin.bottom - 1, PATCOPY); /* * Fill in the caption bar */ SelectObject(hDC, hbrTitle); - PatBlt(hDC, rectWin.left + 3, rectWin.top + 3, - rectWin.right - 7, ptButton.y - 2, PATCOPY); + PatBlt(hDC, rectWin.left + 3, rectWin.top + 3, rectWin.right - 7, ptButton.y - 2, PATCOPY); /* * Draw the "buttons" */ SelectObject(hDC, hbrButton); - PatBlt(hDC, rectWin.left + 3, rectWin.top + 3, - ptButton.x, ptButton.y - 2, PATCOPY); - PatBlt(hDC, rectWin.left + rectWin.right - 4 - ptButton.x, - rectWin.top + 3, - ptButton.x, ptButton.y - 2, PATCOPY); - PatBlt(hDC, rectWin.left + rectWin.right - 4 - 2 * ptButton.x - 1, - rectWin.top + 3, - ptButton.x, ptButton.y - 2, PATCOPY); + PatBlt(hDC, rectWin.left + 3, rectWin.top + 3, ptButton.x, ptButton.y - 2, PATCOPY); + PatBlt(hDC, rectWin.left + rectWin.right - 4 - ptButton.x, rectWin.top + 3, ptButton.x, ptButton.y - 2, PATCOPY); + PatBlt(hDC, rectWin.left + rectWin.right - 4 - 2 * ptButton.x - 1, rectWin.top + 3, ptButton.x, ptButton.y - 2, PATCOPY); SelectObject(hDC, hbrFrame); - PatBlt(hDC, rectWin.left + 3 + ptButton.x, rectWin.top + 3, - 1, ptButton.y - 2, PATCOPY); - PatBlt(hDC, rectWin.left + rectWin.right - 4 - ptButton.x - 1, - rectWin.top + 3, - 1, ptButton.y - 2, PATCOPY); - PatBlt(hDC, rectWin.left + rectWin.right - 4 - 2 * ptButton.x - 2, - rectWin.top + 3, - 1, ptButton.y - 2, PATCOPY); + PatBlt(hDC, rectWin.left + 3 + ptButton.x, rectWin.top + 3, 1, ptButton.y - 2, PATCOPY); + PatBlt(hDC, rectWin.left + rectWin.right - 4 - ptButton.x - 1, rectWin.top + 3, 1, ptButton.y - 2, PATCOPY); + PatBlt(hDC, rectWin.left + rectWin.right - 4 - 2 * ptButton.x - 2, rectWin.top + 3, 1, ptButton.y - 2, PATCOPY); /* * Draw the scrollbars */ SelectObject(hDC, hbrScroll); - if (PreviewFlags & PREVIEW_HSCROLL) { - PatBlt(hDC, rectWin.left + 3, - rectWin.top + rectWin.bottom - 4 - ptScroll.y, - rectWin.right - 7, ptScroll.y, PATCOPY); + if (PreviewFlags & PREVIEW_HSCROLL) + { + PatBlt(hDC, rectWin.left + 3, rectWin.top + rectWin.bottom - 4 - ptScroll.y, rectWin.right - 7, ptScroll.y, PATCOPY); } - if (PreviewFlags & PREVIEW_VSCROLL) { - PatBlt(hDC, rectWin.left + rectWin.right - 4 - ptScroll.x, - rectWin.top + 1 + ptButton.y + 1, - ptScroll.x, rectWin.bottom - 6 - ptButton.y, PATCOPY); - if (PreviewFlags & PREVIEW_HSCROLL) { + if (PreviewFlags & PREVIEW_VSCROLL) + { + PatBlt(hDC, rectWin.left + rectWin.right - 4 - ptScroll.x, rectWin.top + 1 + ptButton.y + 1, ptScroll.x, rectWin.bottom - 6 - ptButton.y, PATCOPY); + if (PreviewFlags & PREVIEW_HSCROLL) + { SelectObject(hDC, hbrFrame); - PatBlt(hDC, rectWin.left + rectWin.right - 5 - ptScroll.x, - rectWin.top + rectWin.bottom - 4 - ptScroll.y, - 1, ptScroll.y, PATCOPY); - PatBlt(hDC, rectWin.left + rectWin.right - 4 - ptScroll.x, - rectWin.top + rectWin.bottom - 5 - ptScroll.y, - ptScroll.x, 1, PATCOPY); + PatBlt(hDC, rectWin.left + rectWin.right - 5 - ptScroll.x, rectWin.top + rectWin.bottom - 4 - ptScroll.y, 1, ptScroll.y, PATCOPY); + PatBlt(hDC, rectWin.left + rectWin.right - 4 - ptScroll.x, rectWin.top + rectWin.bottom - 5 - ptScroll.y, ptScroll.x, 1, PATCOPY); } } @@ -310,48 +292,34 @@ PreviewPaint( * Draw the interior window frame and caption frame */ SelectObject(hDC, hbrFrame); - PatBlt(hDC, rectWin.left + 2, rectWin.top + 2, - 1, rectWin.bottom - 5, PATCOPY); - PatBlt(hDC, rectWin.left + 2, rectWin.top + 2, - rectWin.right - 5, 1, PATCOPY); - PatBlt(hDC, rectWin.left + 2, rectWin.top + rectWin.bottom - 4, - rectWin.right - 5, 1, PATCOPY); - PatBlt(hDC, rectWin.left + rectWin.right - 4, rectWin.top + 2, - 1, rectWin.bottom - 5, PATCOPY); - PatBlt(hDC, rectWin.left + 2, rectWin.top + 1 + ptButton.y, - rectWin.right - 5, 1, PATCOPY); + PatBlt(hDC, rectWin.left + 2, rectWin.top + 2, 1, rectWin.bottom - 5, PATCOPY); + PatBlt(hDC, rectWin.left + 2, rectWin.top + 2, rectWin.right - 5, 1, PATCOPY); + PatBlt(hDC, rectWin.left + 2, rectWin.top + rectWin.bottom - 4, rectWin.right - 5, 1, PATCOPY); + PatBlt(hDC, rectWin.left + rectWin.right - 4, rectWin.top + 2, 1, rectWin.bottom - 5, PATCOPY); + PatBlt(hDC, rectWin.left + 2, rectWin.top + 1 + ptButton.y, rectWin.right - 5, 1, PATCOPY); /* * Draw the border */ SelectObject(hDC, hbrBorder); - PatBlt(hDC, rectWin.left + 1, rectWin.top + 1, - 1, rectWin.bottom - 3, PATCOPY); - PatBlt(hDC, rectWin.left + 1, rectWin.top + 1, - rectWin.right - 3, 1, PATCOPY); - PatBlt(hDC, rectWin.left + 1, rectWin.top + rectWin.bottom - 3, - rectWin.right - 3, 1, PATCOPY); - PatBlt(hDC, rectWin.left + rectWin.right - 3, rectWin.top + 1, - 1, rectWin.bottom - 3, PATCOPY); + PatBlt(hDC, rectWin.left + 1, rectWin.top + 1, 1, rectWin.bottom - 3, PATCOPY); + PatBlt(hDC, rectWin.left + 1, rectWin.top + 1, rectWin.right - 3, 1, PATCOPY); + PatBlt(hDC, rectWin.left + 1, rectWin.top + rectWin.bottom - 3, rectWin.right - 3, 1, PATCOPY); + PatBlt(hDC, rectWin.left + rectWin.right - 3, rectWin.top + 1, 1, rectWin.bottom - 3, PATCOPY); /* * Draw the exterior window frame */ SelectObject(hDC, hbrFrame); - PatBlt(hDC, rectWin.left, rectWin.top, - 1, rectWin.bottom - 1, PATCOPY); - PatBlt(hDC, rectWin.left, rectWin.top, - rectWin.right - 1, 1, PATCOPY); - PatBlt(hDC, rectWin.left, rectWin.top + rectWin.bottom - 2, - rectWin.right - 1, 1, PATCOPY); - PatBlt(hDC, rectWin.left + rectWin.right - 2, rectWin.top, - 1, rectWin.bottom - 1, PATCOPY); + PatBlt(hDC, rectWin.left, rectWin.top, 1, rectWin.bottom - 1, PATCOPY); + PatBlt(hDC, rectWin.left, rectWin.top, rectWin.right - 1, 1, PATCOPY); + PatBlt(hDC, rectWin.left, rectWin.top + rectWin.bottom - 2, rectWin.right - 1, 1, PATCOPY); + PatBlt(hDC, rectWin.left + rectWin.right - 2, rectWin.top, 1, rectWin.bottom - 1, PATCOPY); /* * Copy the memory device context to the screen device context */ - BitBlt(pPS->hdc, 0, 0, rectPreview.right, rectPreview.bottom, - hDC, 0, 0, SRCCOPY); + BitBlt(pPS->hdc, 0, 0, rectPreview.right, rectPreview.bottom, hDC, 0, 0, SRCCOPY); /* * Clean up everything @@ -369,15 +337,13 @@ PreviewPaint( DeleteDC(hDC); } -[[nodiscard]] -LRESULT -CALLBACK -PreviewWndProc( - HWND hWnd, - UINT wMessage, - WPARAM wParam, - LPARAM lParam - ) +[[nodiscard]] LRESULT + CALLBACK + PreviewWndProc( + HWND hWnd, + UINT wMessage, + WPARAM wParam, + LPARAM lParam) /* * PreviewWndProc @@ -391,7 +357,8 @@ PreviewWndProc( int cx; int cy; - switch (wMessage) { + switch (wMessage) + { case WM_CREATE: /* * Figure out space used by non-client area @@ -412,7 +379,8 @@ PreviewWndProc( lpcs = (LPCREATESTRUCT)lParam; cx = lpcs->cx; cy = AspectScale(gcyScreen, gcxScreen, cx); - if (cy > lpcs->cy) { + if (cy > lpcs->cy) + { cy = lpcs->cy; cx = AspectScale(gcxScreen, gcyScreen, cy); } @@ -435,10 +403,11 @@ PreviewWndProc( GetWindowRect(hWnd, &rcWindow); cx = rcWindow.right - rcWindow.left; cy = AspectScale(gcyScreen, gcxScreen, cx); - if (cy != rcWindow.bottom - rcWindow.top) { + if (cy != rcWindow.bottom - rcWindow.top) + { SetWindowPos(hWnd, NULL, 0, 0, cx, cy, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER); } - + InvalidatePreviewRect(hWnd); break; @@ -448,7 +417,6 @@ PreviewWndProc( return 0L; } - /* AspectScale * Performs the following calculation in LONG arithmetic to avoid * overflow: diff --git a/src/propsheet/registry.cpp b/src/propsheet/registry.cpp index 4034ec24e..2914ae099 100644 --- a/src/propsheet/registry.cpp +++ b/src/propsheet/registry.cpp @@ -27,7 +27,7 @@ Revision History: #include "../inc/conattrs.hpp" #pragma hdrstop -#define CONSOLE_REGISTRY_CURRENTPAGE (L"CurrentPage") +#define CONSOLE_REGISTRY_CURRENTPAGE (L"CurrentPage") extern BOOL g_fEditKeys; @@ -59,8 +59,8 @@ Return Value: VOID InitRegistryValues( __out PCONSOLE_STATE_INFO pStateInfo) { - pStateInfo->ScreenAttributes = 0x07; // white on black - pStateInfo->PopupAttributes = 0xf5; // purple on white + pStateInfo->ScreenAttributes = 0x07; // white on black + pStateInfo->PopupAttributes = 0xf5; // purple on white pStateInfo->InsertMode = FALSE; pStateInfo->QuickEdit = FALSE; pStateInfo->FullScreen = FALSE; @@ -81,6 +81,7 @@ VOID InitRegistryValues( pStateInfo->NumberOfHistoryBuffers = 4; pStateInfo->HistoryNoDup = 0; + // clang-format off if (pStateInfo->fIsV2Console) { // if we're servicing a v2 console instance, default to the new color defaults @@ -120,6 +121,7 @@ VOID InitRegistryValues( pStateInfo->ColorTable[14] = RGB(0xFF,0xFF,0 ); pStateInfo->ColorTable[15] = RGB(0xFF,0xFF,0xFF); } + // clang-format on pStateInfo->CodePage = OEMCP; pStateInfo->hWnd = NULL; @@ -130,7 +132,7 @@ VOID InitRegistryValues( pStateInfo->fWrapText = TRUE; pStateInfo->fFilterOnPaste = TRUE; pStateInfo->fCtrlKeyShortcutsDisabled = FALSE; - pStateInfo->fLineSelection= TRUE; + pStateInfo->fLineSelection = TRUE; pStateInfo->bWindowTransparency = BYTE_MAX; pStateInfo->CursorType = 0; pStateInfo->CursorColor = INVALID_COLOR; @@ -174,7 +176,8 @@ DWORD GetRegistryValues( // Status = RegistrySerialization::s_OpenConsoleKey(&hCurrentUserKey, &hConsoleKey); - if (!NT_SUCCESS(Status)) { + if (!NT_SUCCESS(Status)) + { return 0; } @@ -183,14 +186,16 @@ DWORD GetRegistryValues( // page and bail out. // - if (pStateInfo == nullptr) { + if (pStateInfo == nullptr) + { Status = RegistrySerialization::s_QueryValue(hConsoleKey, CONSOLE_REGISTRY_CURRENTPAGE, sizeof(dwValue), REG_DWORD, (PBYTE)&dwValue, NULL); - if (NT_SUCCESS(Status)) { + if (NT_SUCCESS(Status)) + { dwRet = dwValue; } @@ -200,13 +205,17 @@ DWORD GetRegistryValues( // // Open the console title subkey unless we're changing the defaults. // - if (pStateInfo->Defaults) { + if (pStateInfo->Defaults) + { hTitleKey = hConsoleKey; - } else { + } + else + { Status = RegistrySerialization::s_OpenKey(hConsoleKey, pStateInfo->OriginalTitle, &hTitleKey); - if (!NT_SUCCESS(Status)) { + if (!NT_SUCCESS(Status)) + { RegCloseKey(hConsoleKey); RegCloseKey(hCurrentUserKey); return 0; @@ -223,7 +232,8 @@ DWORD GetRegistryValues( REG_DWORD, (PBYTE)&dwValue, NULL); - if (NT_SUCCESS(Status)) { + if (NT_SUCCESS(Status)) + { pStateInfo->ScreenAttributes = (WORD)dwValue; } @@ -237,7 +247,8 @@ DWORD GetRegistryValues( REG_DWORD, (PBYTE)&dwValue, NULL); - if (NT_SUCCESS(Status)) { + if (NT_SUCCESS(Status)) + { pStateInfo->PopupAttributes = (WORD)dwValue; } @@ -245,7 +256,8 @@ DWORD GetRegistryValues( // Initial color table // - for (i = 0; i < 16; i++) { + for (i = 0; i < 16; i++) + { StringCchPrintf(awchBuffer, ARRAYSIZE(awchBuffer), CONSOLE_REGISTRY_COLORTABLE, @@ -256,7 +268,8 @@ DWORD GetRegistryValues( REG_DWORD, (PBYTE)&dwValue, NULL); - if (NT_SUCCESS(Status)) { + if (NT_SUCCESS(Status)) + { pStateInfo->ColorTable[i] = dwValue; } } @@ -270,7 +283,8 @@ DWORD GetRegistryValues( REG_DWORD, (PBYTE)&dwValue, NULL); - if (NT_SUCCESS(Status)) { + if (NT_SUCCESS(Status)) + { pStateInfo->InsertMode = !!dwValue; } @@ -283,7 +297,8 @@ DWORD GetRegistryValues( REG_DWORD, (PBYTE)&dwValue, NULL); - if (NT_SUCCESS(Status)) { + if (NT_SUCCESS(Status)) + { pStateInfo->QuickEdit = !!dwValue; } @@ -298,9 +313,11 @@ DWORD GetRegistryValues( REG_DWORD, (PBYTE)&dwValue, NULL); - if (NT_SUCCESS(Status)) { - if (IsValidCodePage(dwValue)) { - pStateInfo->CodePage = (UINT) dwValue; + if (NT_SUCCESS(Status)) + { + if (IsValidCodePage(dwValue)) + { + pStateInfo->CodePage = (UINT)dwValue; } } @@ -313,7 +330,8 @@ DWORD GetRegistryValues( REG_DWORD, (PBYTE)&dwValue, NULL); - if (NT_SUCCESS(Status)) { + if (NT_SUCCESS(Status)) + { pStateInfo->ScreenBufferSize.X = LOWORD(dwValue); pStateInfo->ScreenBufferSize.Y = HIWORD(dwValue); } @@ -327,7 +345,8 @@ DWORD GetRegistryValues( REG_DWORD, (PBYTE)&dwValue, NULL); - if (NT_SUCCESS(Status)) { + if (NT_SUCCESS(Status)) + { pStateInfo->WindowSize.X = LOWORD(dwValue); pStateInfo->WindowSize.Y = HIWORD(dwValue); } @@ -341,7 +360,8 @@ DWORD GetRegistryValues( REG_DWORD, (PBYTE)&dwValue, NULL); - if (NT_SUCCESS(Status)) { + if (NT_SUCCESS(Status)) + { pStateInfo->WindowPosX = (SHORT)LOWORD(dwValue); pStateInfo->WindowPosY = (SHORT)HIWORD(dwValue); pStateInfo->AutoPosition = FALSE; @@ -357,7 +377,8 @@ DWORD GetRegistryValues( REG_DWORD, (PBYTE)&dwValue, NULL); - if (NT_SUCCESS(Status)) { + if (NT_SUCCESS(Status)) + { pStateInfo->FontSize.X = LOWORD(dwValue); pStateInfo->FontSize.Y = HIWORD(dwValue); } @@ -371,7 +392,8 @@ DWORD GetRegistryValues( REG_DWORD, (PBYTE)&dwValue, NULL); - if (NT_SUCCESS(Status)) { + if (NT_SUCCESS(Status)) + { pStateInfo->FontFamily = dwValue; } @@ -384,7 +406,8 @@ DWORD GetRegistryValues( REG_DWORD, (PBYTE)&dwValue, NULL); - if (NT_SUCCESS(Status)) { + if (NT_SUCCESS(Status)) + { pStateInfo->FontWeight = dwValue; } @@ -397,7 +420,8 @@ DWORD GetRegistryValues( REG_SZ, (PBYTE)awchBuffer, NULL); - if (NT_SUCCESS(Status)) { + if (NT_SUCCESS(Status)) + { RtlCopyMemory(pStateInfo->FaceName, awchBuffer, sizeof(awchBuffer)); } @@ -410,7 +434,8 @@ DWORD GetRegistryValues( REG_DWORD, (PBYTE)&dwValue, NULL); - if (NT_SUCCESS(Status)) { + if (NT_SUCCESS(Status)) + { pStateInfo->CursorSize = dwValue; } @@ -423,7 +448,8 @@ DWORD GetRegistryValues( REG_DWORD, (PBYTE)&dwValue, NULL); - if (NT_SUCCESS(Status)) { + if (NT_SUCCESS(Status)) + { pStateInfo->HistoryBufferSize = dwValue; } @@ -436,7 +462,8 @@ DWORD GetRegistryValues( REG_DWORD, (PBYTE)&dwValue, NULL); - if (NT_SUCCESS(Status)) { + if (NT_SUCCESS(Status)) + { pStateInfo->NumberOfHistoryBuffers = dwValue; } @@ -449,7 +476,8 @@ DWORD GetRegistryValues( REG_DWORD, (PBYTE)&dwValue, NULL); - if (NT_SUCCESS(Status)) { + if (NT_SUCCESS(Status)) + { pStateInfo->HistoryNoDup = dwValue; } @@ -462,7 +490,8 @@ DWORD GetRegistryValues( REG_DWORD, (PBYTE)&dwValue, NULL); - if (NT_SUCCESS(Status)) { + if (NT_SUCCESS(Status)) + { pStateInfo->fWrapText = dwValue; } @@ -475,7 +504,8 @@ DWORD GetRegistryValues( REG_DWORD, (PBYTE)&dwValue, NULL); - if (NT_SUCCESS(Status)) { + if (NT_SUCCESS(Status)) + { pStateInfo->fFilterOnPaste = dwValue; } @@ -488,7 +518,8 @@ DWORD GetRegistryValues( REG_DWORD, (PBYTE)&dwValue, NULL); - if (NT_SUCCESS(Status)) { + if (NT_SUCCESS(Status)) + { pStateInfo->fCtrlKeyShortcutsDisabled = dwValue; } @@ -501,7 +532,8 @@ DWORD GetRegistryValues( REG_DWORD, (PBYTE)&dwValue, NULL); - if (NT_SUCCESS(Status)) { + if (NT_SUCCESS(Status)) + { pStateInfo->fLineSelection = dwValue; } @@ -514,7 +546,8 @@ DWORD GetRegistryValues( REG_DWORD, (PBYTE)&dwValue, NULL); - if (NT_SUCCESS(Status)) { + if (NT_SUCCESS(Status)) + { if (dwValue <= BYTE_MAX) { pStateInfo->bWindowTransparency = (BYTE)dwValue; @@ -528,7 +561,8 @@ DWORD GetRegistryValues( REG_DWORD, (PBYTE)&dwValue, NULL); - if (NT_SUCCESS(Status)) { + if (NT_SUCCESS(Status)) + { pStateInfo->CursorColor = dwValue; } // Initial Cursor Shape @@ -562,7 +596,8 @@ DWORD GetRegistryValues( REG_DWORD, (PBYTE)&dwValue, NULL); - if (NT_SUCCESS(Status)) { + if (NT_SUCCESS(Status)) + { pStateInfo->DefaultForeground = dwValue; } @@ -573,7 +608,8 @@ DWORD GetRegistryValues( REG_DWORD, (PBYTE)&dwValue, NULL); - if (NT_SUCCESS(Status)) { + if (NT_SUCCESS(Status)) + { pStateInfo->DefaultBackground = dwValue; } @@ -584,7 +620,8 @@ DWORD GetRegistryValues( REG_DWORD, (PBYTE)&dwValue, NULL); - if (NT_SUCCESS(Status)) { + if (NT_SUCCESS(Status)) + { pStateInfo->TerminalScrolling = dwValue; } @@ -592,7 +629,8 @@ DWORD GetRegistryValues( // Close the registry keys // - if (hTitleKey != hConsoleKey) { + if (hTitleKey != hConsoleKey) + { RegCloseKey(hTitleKey); } @@ -655,7 +693,8 @@ VOID SetRegistryValues( // Status = RegistrySerialization::s_OpenConsoleKey(&hCurrentUserKey, &hConsoleKey); - if (!NT_SUCCESS(Status)) { + if (!NT_SUCCESS(Status)) + { return; } @@ -671,13 +710,17 @@ VOID SetRegistryValues( // // Open the console title subkey unless we're changing the defaults. // - if (pStateInfo->Defaults) { + if (pStateInfo->Defaults) + { hTitleKey = hConsoleKey; - } else { + } + else + { Status = RegistrySerialization::s_CreateKey(hConsoleKey, - pStateInfo->OriginalTitle, - &hTitleKey); - if (!NT_SUCCESS(Status)) { + pStateInfo->OriginalTitle, + &hTitleKey); + if (!NT_SUCCESS(Status)) + { RegCloseKey(hConsoleKey); RegCloseKey(hCurrentUserKey); return; @@ -702,7 +745,8 @@ VOID SetRegistryValues( REG_DWORD, (BYTE*)&dwValue, sizeof(dwValue))); - for (i = 0; i < 16; i++) { + for (i = 0; i < 16; i++) + { dwValue = pStateInfo->ColorTable[i]; if (SUCCEEDED(StringCchPrintf(awchBuffer, ARRAYSIZE(awchBuffer), CONSOLE_REGISTRY_COLORTABLE, i))) { @@ -735,8 +779,9 @@ VOID SetRegistryValues( sizeof(dwValue))); FAIL_FAST_IF(!(OEMCP != 0)); - if (g_fEastAsianSystem) { - dwValue = (DWORD) pStateInfo->CodePage; + if (g_fEastAsianSystem) + { + dwValue = (DWORD)pStateInfo->CodePage; LOG_IF_FAILED(RegistrySerialization::s_UpdateValue(hConsoleKey, hTitleKey, CONSOLE_REGISTRY_CODEPAGE, @@ -775,7 +820,8 @@ VOID SetRegistryValues( // Save window position // - if (pStateInfo->AutoPosition) { + if (pStateInfo->AutoPosition) + { LOG_IF_FAILED(RegistrySerialization::s_DeleteValue(hTitleKey, CONSOLE_REGISTRY_WINDOWPOS)); } else @@ -950,7 +996,8 @@ VOID SetRegistryValues( // // Close the registry keys // - if (hTitleKey != hConsoleKey) { + if (hTitleKey != hConsoleKey) + { RegCloseKey(hTitleKey); } diff --git a/src/propsheet/util.cpp b/src/propsheet/util.cpp index 3da2dc7bf..9a2093caa 100644 --- a/src/propsheet/util.cpp +++ b/src/propsheet/util.cpp @@ -8,13 +8,13 @@ // Version detection code for ComCtl32 copied/adapter from // https://msdn.microsoft.com/en-us/library/windows/desktop/hh298349(v=vs.85).aspx#DllGetVersion -#define PACKVERSION(major,minor) MAKELONG(minor,major) +#define PACKVERSION(major, minor) MAKELONG(minor, major) static DWORD GetVersion(_In_ PCWSTR pwszDllName) { DWORD dwVersion = 0; - // We have to call for ComCtl32.dll without a path name so Fusion SxS will redirect us + // We have to call for ComCtl32.dll without a path name so Fusion SxS will redirect us // if it thinks we are manifested properly and Fusion is enabled in this process space. HINSTANCE const hinstDll = LoadLibrary(pwszDllName); @@ -22,13 +22,13 @@ static DWORD GetVersion(_In_ PCWSTR pwszDllName) { DLLGETVERSIONPROC const pDllGetVersion = (DLLGETVERSIONPROC)GetProcAddress(hinstDll, "DllGetVersion"); - // Because some DLLs might not implement this function, you must test for - // it explicitly. Depending on the particular DLL, the lack of a DllGetVersion - // function can be a useful indicator of the version. + // Because some DLLs might not implement this function, you must test for + // it explicitly. Depending on the particular DLL, the lack of a DllGetVersion + // function can be a useful indicator of the version. if (nullptr != pDllGetVersion) { - DLLVERSIONINFO dvi = {0}; + DLLVERSIONINFO dvi = { 0 }; dvi.cbSize = sizeof(dvi); if (SUCCEEDED((*pDllGetVersion)(&dvi))) @@ -36,7 +36,7 @@ static DWORD GetVersion(_In_ PCWSTR pwszDllName) dwVersion = PACKVERSION(dvi.dwMajorVersion, dvi.dwMinorVersion); } } - + FreeLibrary(hinstDll); } return dwVersion; diff --git a/src/propslib/RegistrySerialization.cpp b/src/propslib/RegistrySerialization.cpp index 9cf08bf1b..627fbcb5e 100644 --- a/src/propslib/RegistrySerialization.cpp +++ b/src/propslib/RegistrySerialization.cpp @@ -15,19 +15,20 @@ DWORD RegistrySerialization::ToWin32RegistryType(const _RegPropertyType type) { switch (type) { - case _RegPropertyType::Boolean: - case _RegPropertyType::Dword: - case _RegPropertyType::Word: - case _RegPropertyType::Byte: - case _RegPropertyType::Coordinate: - return REG_DWORD; - case _RegPropertyType::String: - return REG_SZ; - default: - return REG_NONE; + case _RegPropertyType::Boolean: + case _RegPropertyType::Dword: + case _RegPropertyType::Word: + case _RegPropertyType::Byte: + case _RegPropertyType::Coordinate: + return REG_DWORD; + case _RegPropertyType::String: + return REG_SZ; + default: + return REG_NONE; } } +// clang-format off // Registry settings to load (not all of them, some are special) const RegistrySerialization::_RegPropertyMap RegistrySerialization::s_PropertyMappings[] = { @@ -77,6 +78,8 @@ const RegistrySerialization::_RegPropertyMap RegistrySerialization::s_GlobalProp }; const size_t RegistrySerialization::s_GlobalPropMappingsSize = ARRAYSIZE(s_GlobalPropMappings); +// clang-format off + // Routine Description: // - Reads number from the registry and applies it to the given property if the value exists // Supports: Dword, Word, Byte, Boolean, and Coordinate diff --git a/src/propslib/RegistrySerialization.hpp b/src/propslib/RegistrySerialization.hpp index 57221e748..0f36c74fc 100644 --- a/src/propslib/RegistrySerialization.hpp +++ b/src/propslib/RegistrySerialization.hpp @@ -25,56 +25,46 @@ class Settings; class RegistrySerialization { public: - // The following registry methods remain public for DBCS and EUDC lookups. - [[nodiscard]] - static NTSTATUS s_OpenKey(_In_opt_ HKEY const hKey, _In_ PCWSTR const pwszSubKey, _Out_ HKEY* const phResult); + [[nodiscard]] static NTSTATUS s_OpenKey(_In_opt_ HKEY const hKey, _In_ PCWSTR const pwszSubKey, _Out_ HKEY* const phResult); - [[nodiscard]] - static NTSTATUS s_QueryValue(const HKEY hKey, - _In_ PCWSTR const pwszValueName, - const DWORD cbValueLength, - const DWORD regType, - _Out_writes_bytes_(cbValueLength) BYTE* const pbData, - _Out_opt_ _Out_range_(0, cbValueLength) DWORD* const pcbDataLength); + [[nodiscard]] static NTSTATUS s_QueryValue(const HKEY hKey, + _In_ PCWSTR const pwszValueName, + const DWORD cbValueLength, + const DWORD regType, + _Out_writes_bytes_(cbValueLength) BYTE* const pbData, + _Out_opt_ _Out_range_(0, cbValueLength) DWORD* const pcbDataLength); - [[nodiscard]] - static NTSTATUS s_EnumValue(const HKEY hKey, - const DWORD dwIndex, - const DWORD cbValueLength, - _Out_writes_bytes_(cbValueLength) PWSTR const pwszValueName, - const DWORD cbDataLength, - _Out_writes_bytes_(cbDataLength) BYTE* const pbData); + [[nodiscard]] static NTSTATUS s_EnumValue(const HKEY hKey, + const DWORD dwIndex, + const DWORD cbValueLength, + _Out_writes_bytes_(cbValueLength) PWSTR const pwszValueName, + const DWORD cbDataLength, + _Out_writes_bytes_(cbDataLength) BYTE* const pbData); - [[nodiscard]] - static NTSTATUS s_OpenConsoleKey(_Out_ HKEY* phCurrentUserKey, _Out_ HKEY* phConsoleKey); + [[nodiscard]] static NTSTATUS s_OpenConsoleKey(_Out_ HKEY* phCurrentUserKey, _Out_ HKEY* phConsoleKey); - [[nodiscard]] - static NTSTATUS s_CreateKey(const HKEY hKey, _In_ PCWSTR const pwszSubKey, _Out_ HKEY* const phResult); + [[nodiscard]] static NTSTATUS s_CreateKey(const HKEY hKey, _In_ PCWSTR const pwszSubKey, _Out_ HKEY* const phResult); - [[nodiscard]] - static NTSTATUS s_DeleteValue(const HKEY hKey, _In_ PCWSTR const pwszValueName); + [[nodiscard]] static NTSTATUS s_DeleteValue(const HKEY hKey, _In_ PCWSTR const pwszValueName); - [[nodiscard]] - static NTSTATUS s_SetValue(const HKEY hKey, - _In_ PCWSTR const pwszValueName, - const DWORD dwType, - _In_reads_bytes_(cbDataLength) BYTE* const pbData, - const DWORD cbDataLength); + [[nodiscard]] static NTSTATUS s_SetValue(const HKEY hKey, + _In_ PCWSTR const pwszValueName, + const DWORD dwType, + _In_reads_bytes_(cbDataLength) BYTE* const pbData, + const DWORD cbDataLength); - [[nodiscard]] - static NTSTATUS s_UpdateValue(const HKEY hConsoleKey, - const HKEY hKey, - _In_ PCWSTR const pwszValueName, - const DWORD dwType, - _In_reads_bytes_(dwDataLength) BYTE* pbData, - const DWORD dwDataLength); + [[nodiscard]] static NTSTATUS s_UpdateValue(const HKEY hConsoleKey, + const HKEY hKey, + _In_ PCWSTR const pwszValueName, + const DWORD dwType, + _In_reads_bytes_(dwDataLength) BYTE* pbData, + const DWORD dwDataLength); - [[nodiscard]] - static NTSTATUS s_OpenCurrentUserConsoleTitleKey(_In_ PCWSTR const title, - _Out_ HKEY* phCurrentUserKey, - _Out_ HKEY* phConsoleKey, - _Out_ HKEY* phTitleKey ); + [[nodiscard]] static NTSTATUS s_OpenCurrentUserConsoleTitleKey(_In_ PCWSTR const title, + _Out_ HKEY* phCurrentUserKey, + _Out_ HKEY* phConsoleKey, + _Out_ HKEY* phTitleKey); enum _RegPropertyType { @@ -95,17 +85,16 @@ public: DWORD const dwFieldOffset; size_t const cbFieldSize; _RegPropertyMap( - _RegPropertyType const propertyType, - PCWSTR pwszValueName, - DWORD const dwFieldOffset, - size_t const cbFieldSize - ) : + _RegPropertyType const propertyType, + PCWSTR pwszValueName, + DWORD const dwFieldOffset, + size_t const cbFieldSize) : propertyType(propertyType), pwszValueName(pwszValueName), dwFieldOffset(dwFieldOffset), cbFieldSize(cbFieldSize){}; - _RegPropertyMap & operator=( const _RegPropertyMap & ) { return *this; } + _RegPropertyMap& operator=(const _RegPropertyMap&) { return *this; } } RegPropertyMap; static const RegPropertyMap s_PropertyMappings[]; @@ -114,9 +103,6 @@ public: static const RegPropertyMap s_GlobalPropMappings[]; static const size_t RegistrySerialization::s_GlobalPropMappingsSize; - [[nodiscard]] - static NTSTATUS s_LoadRegDword(const HKEY hKey, const _RegPropertyMap* const pPropMap, _In_ Settings* const pSettings); - [[nodiscard]] - static NTSTATUS s_LoadRegString(const HKEY hKey, const _RegPropertyMap* const pPropMap, _In_ Settings* const pSettings); - + [[nodiscard]] static NTSTATUS s_LoadRegDword(const HKEY hKey, const _RegPropertyMap* const pPropMap, _In_ Settings* const pSettings); + [[nodiscard]] static NTSTATUS s_LoadRegString(const HKEY hKey, const _RegPropertyMap* const pPropMap, _In_ Settings* const pSettings); }; diff --git a/src/propslib/ShortcutSerialization.cpp b/src/propslib/ShortcutSerialization.cpp index b0731b8e6..a514de7c0 100644 --- a/src/propslib/ShortcutSerialization.cpp +++ b/src/propslib/ShortcutSerialization.cpp @@ -10,19 +10,19 @@ #pragma hdrstop -void ShortcutSerialization::s_InitPropVarFromBool(_In_ BOOL fVal, _Out_ PROPVARIANT *ppropvar) +void ShortcutSerialization::s_InitPropVarFromBool(_In_ BOOL fVal, _Out_ PROPVARIANT* ppropvar) { ppropvar->vt = VT_BOOL; ppropvar->boolVal = fVal ? VARIANT_TRUE : VARIANT_FALSE; } -void ShortcutSerialization::s_InitPropVarFromByte(_In_ BYTE bVal, _Out_ PROPVARIANT *ppropvar) +void ShortcutSerialization::s_InitPropVarFromByte(_In_ BYTE bVal, _Out_ PROPVARIANT* ppropvar) { ppropvar->vt = VT_I2; ppropvar->iVal = bVal; } -void ShortcutSerialization::s_InitPropVarFromDword(_In_ DWORD dwVal, _Out_ PROPVARIANT *ppropvar) +void ShortcutSerialization::s_InitPropVarFromDword(_In_ DWORD dwVal, _Out_ PROPVARIANT* ppropvar) { // A DWORD is a 4-byte unsigned int value, so use the ui4 member. // DO NOT use VT_UINT, that doesn't work with PROPVARIANTs. @@ -32,7 +32,9 @@ void ShortcutSerialization::s_InitPropVarFromDword(_In_ DWORD dwVal, _Out_ PROPV ppropvar->ulVal = dwVal; } -void ShortcutSerialization::s_SetLinkPropertyBoolValue(_In_ IPropertyStore *pps, _In_ REFPROPERTYKEY refPropKey,const BOOL fVal) +void ShortcutSerialization::s_SetLinkPropertyBoolValue(_In_ IPropertyStore* pps, + _In_ REFPROPERTYKEY refPropKey, + const BOOL fVal) { PROPVARIANT propvarBool; s_InitPropVarFromBool(fVal, &propvarBool); @@ -40,7 +42,9 @@ void ShortcutSerialization::s_SetLinkPropertyBoolValue(_In_ IPropertyStore *pps, PropVariantClear(&propvarBool); } -void ShortcutSerialization::s_SetLinkPropertyByteValue(_In_ IPropertyStore *pps, _In_ REFPROPERTYKEY refPropKey,const BYTE bVal) +void ShortcutSerialization::s_SetLinkPropertyByteValue(_In_ IPropertyStore* pps, + _In_ REFPROPERTYKEY refPropKey, + const BYTE bVal) { PROPVARIANT propvarByte; s_InitPropVarFromByte(bVal, &propvarByte); @@ -48,7 +52,7 @@ void ShortcutSerialization::s_SetLinkPropertyByteValue(_In_ IPropertyStore *pps, PropVariantClear(&propvarByte); } -void ShortcutSerialization::s_SetLinkPropertyDwordValue(_Inout_ IPropertyStore *pps, +void ShortcutSerialization::s_SetLinkPropertyDwordValue(_Inout_ IPropertyStore* pps, _In_ REFPROPERTYKEY refPropKey, const DWORD dwVal) { @@ -58,8 +62,9 @@ void ShortcutSerialization::s_SetLinkPropertyDwordValue(_Inout_ IPropertyStore * PropVariantClear(&propvarDword); } -[[nodiscard]] -HRESULT ShortcutSerialization::s_GetPropertyBoolValue(_In_ IPropertyStore * const pPropStore, _In_ REFPROPERTYKEY refPropKey, _Out_ BOOL * const pfValue) +[[nodiscard]] HRESULT ShortcutSerialization::s_GetPropertyBoolValue(_In_ IPropertyStore* const pPropStore, + _In_ REFPROPERTYKEY refPropKey, + _Out_ BOOL* const pfValue) { PROPVARIANT propvar; HRESULT hr = pPropStore->GetValue(refPropKey, &propvar); @@ -73,8 +78,9 @@ HRESULT ShortcutSerialization::s_GetPropertyBoolValue(_In_ IPropertyStore * cons return hr; } -[[nodiscard]] -HRESULT ShortcutSerialization::s_GetPropertyByteValue(_In_ IPropertyStore * const pPropStore, _In_ REFPROPERTYKEY refPropKey, _Out_ BYTE * const pbValue) +[[nodiscard]] HRESULT ShortcutSerialization::s_GetPropertyByteValue(_In_ IPropertyStore* const pPropStore, + _In_ REFPROPERTYKEY refPropKey, + _Out_ BYTE* const pbValue) { PROPVARIANT propvar; HRESULT hr = pPropStore->GetValue(refPropKey, &propvar); @@ -97,8 +103,9 @@ HRESULT ShortcutSerialization::s_GetPropertyByteValue(_In_ IPropertyStore * cons return hr; } -[[nodiscard]] -HRESULT ShortcutSerialization::s_GetPropertyDwordValue(_Inout_ IPropertyStore * const pPropStore, _In_ REFPROPERTYKEY refPropKey, _Out_ DWORD * const pdwValue) +[[nodiscard]] HRESULT ShortcutSerialization::s_GetPropertyDwordValue(_Inout_ IPropertyStore* const pPropStore, + _In_ REFPROPERTYKEY refPropKey, + _Out_ DWORD* const pdwValue) { PROPVARIANT propvar; HRESULT hr = pPropStore->GetValue(refPropKey, &propvar); @@ -117,15 +124,15 @@ HRESULT ShortcutSerialization::s_GetPropertyDwordValue(_Inout_ IPropertyStore * return hr; } -[[nodiscard]] -HRESULT ShortcutSerialization::s_PopulateV1Properties(_In_ IShellLink * const pslConsole, _In_ PCONSOLE_STATE_INFO pStateInfo) +[[nodiscard]] HRESULT ShortcutSerialization::s_PopulateV1Properties(_In_ IShellLink* const pslConsole, + _In_ PCONSOLE_STATE_INFO pStateInfo) { - IShellLinkDataList *pConsoleLnkDataList; + IShellLinkDataList* pConsoleLnkDataList; HRESULT hr = pslConsole->QueryInterface(IID_PPV_ARGS(&pConsoleLnkDataList)); if (SUCCEEDED(hr)) { // get/apply standard console properties - NT_CONSOLE_PROPS *pNtConsoleProps = nullptr; + NT_CONSOLE_PROPS* pNtConsoleProps = nullptr; hr = pConsoleLnkDataList->CopyDataBlock(NT_CONSOLE_PROPS_SIG, reinterpret_cast(&pNtConsoleProps)); if (SUCCEEDED(hr)) { @@ -155,7 +162,7 @@ HRESULT ShortcutSerialization::s_PopulateV1Properties(_In_ IShellLink * const ps // get/apply international console properties if (SUCCEEDED(hr)) { - NT_FE_CONSOLE_PROPS *pNtFEConsoleProps; + NT_FE_CONSOLE_PROPS* pNtFEConsoleProps; if (SUCCEEDED(pConsoleLnkDataList->CopyDataBlock(NT_FE_CONSOLE_PROPS_SIG, reinterpret_cast(&pNtFEConsoleProps)))) { pNtFEConsoleProps->uCodePage = pStateInfo->CodePage; @@ -169,10 +176,10 @@ HRESULT ShortcutSerialization::s_PopulateV1Properties(_In_ IShellLink * const ps return hr; } -[[nodiscard]] -HRESULT ShortcutSerialization::s_PopulateV2Properties(_In_ IShellLink * const pslConsole, _In_ PCONSOLE_STATE_INFO pStateInfo) +[[nodiscard]] HRESULT ShortcutSerialization::s_PopulateV2Properties(_In_ IShellLink* const pslConsole, + _In_ PCONSOLE_STATE_INFO pStateInfo) { - IPropertyStore *pPropStoreLnk; + IPropertyStore* pPropStoreLnk; HRESULT hr = pslConsole->QueryInterface(IID_PPV_ARGS(&pPropStoreLnk)); if (SUCCEEDED(hr)) { @@ -199,7 +206,7 @@ HRESULT ShortcutSerialization::s_PopulateV2Properties(_In_ IShellLink * const ps hr = s_GetPropertyDwordValue(pPropStoreLnk, PKEY_Console_CursorType, &placeholder); if (SUCCEEDED(hr)) { - pStateInfo->CursorType = (unsigned int) placeholder; + pStateInfo->CursorType = (unsigned int)placeholder; } } if (SUCCEEDED(hr)) @@ -231,7 +238,9 @@ HRESULT ShortcutSerialization::s_PopulateV2Properties(_In_ IShellLink * const ps // Given a shortcut filename, determine what title we should use. Under normal circumstances, we rely on the shell to // provide the correct title. However, if that fails, we'll just use the shortcut filename minus the extension. -void ShortcutSerialization::s_GetLinkTitle(_In_ PCWSTR pwszShortcutFilename, _Out_writes_(cchShortcutTitle) PWSTR pwszShortcutTitle, const size_t cchShortcutTitle) +void ShortcutSerialization::s_GetLinkTitle(_In_ PCWSTR pwszShortcutFilename, + _Out_writes_(cchShortcutTitle) PWSTR pwszShortcutTitle, + const size_t cchShortcutTitle) { NTSTATUS Status = (cchShortcutTitle > 0) ? STATUS_SUCCESS : STATUS_INVALID_PARAMETER_2; if (NT_SUCCESS(Status)) @@ -243,7 +252,7 @@ void ShortcutSerialization::s_GetLinkTitle(_In_ PCWSTR pwszShortcutFilename, _Ou if (NT_SUCCESS(Status)) { // Now load the localized title for the shortcut - IShellItem *psi; + IShellItem* psi; HRESULT hrShellItem = SHCreateItemFromParsingName(pwszShortcutFilename, nullptr, IID_PPV_ARGS(&psi)); if (SUCCEEDED(hrShellItem)) { @@ -273,16 +282,18 @@ void ShortcutSerialization::s_GetLinkTitle(_In_ PCWSTR pwszShortcutFilename, _Ou } // Given a shortcut filename, retrieve IShellLink and IPersistFile itf ptrs, and ensure that the link is loaded. -[[nodiscard]] -HRESULT ShortcutSerialization::s_GetLoadedShellLinkForShortcut(_In_ PCWSTR pwszShortcutFileName, const DWORD dwMode, _COM_Outptr_ IShellLink **ppsl, _COM_Outptr_ IPersistFile **ppPf) +[[nodiscard]] HRESULT ShortcutSerialization::s_GetLoadedShellLinkForShortcut(_In_ PCWSTR pwszShortcutFileName, + const DWORD dwMode, + _COM_Outptr_ IShellLink** ppsl, + _COM_Outptr_ IPersistFile** ppPf) { *ppsl = nullptr; *ppPf = nullptr; - IShellLink * psl; + IShellLink* psl; HRESULT hr = SHCoCreateInstance(NULL, &CLSID_ShellLink, NULL, IID_PPV_ARGS(&psl)); if (SUCCEEDED(hr)) { - IPersistFile * pPf; + IPersistFile* pPf; hr = psl->QueryInterface(IID_PPV_ARGS(&pPf)); if (SUCCEEDED(hr)) { @@ -309,11 +320,10 @@ HRESULT ShortcutSerialization::s_GetLoadedShellLinkForShortcut(_In_ PCWSTR pwszS } // Retrieves console-only properties from the shortcut file specified in pStateInfo. Used by the console properties sheet. -[[nodiscard]] -NTSTATUS ShortcutSerialization::s_GetLinkConsoleProperties(_Inout_ PCONSOLE_STATE_INFO pStateInfo) +[[nodiscard]] NTSTATUS ShortcutSerialization::s_GetLinkConsoleProperties(_Inout_ PCONSOLE_STATE_INFO pStateInfo) { - IShellLink * psl; - IPersistFile * ppf; + IShellLink* psl; + IPersistFile* ppf; HRESULT hr = s_GetLoadedShellLinkForShortcut(pStateInfo->LinkTitle, STGM_READ, &psl, &ppf); if (SUCCEEDED(hr)) { @@ -330,16 +340,15 @@ NTSTATUS ShortcutSerialization::s_GetLinkConsoleProperties(_Inout_ PCONSOLE_STAT } // Retrieves all shortcut properties from the file specified in pStateInfo. Used by conhostv2.dll -[[nodiscard]] -NTSTATUS ShortcutSerialization::s_GetLinkValues(_Inout_ PCONSOLE_STATE_INFO pStateInfo, - _Out_ BOOL * const pfReadConsoleProperties, - _Out_writes_opt_(cchShortcutTitle) PWSTR pwszShortcutTitle, - const size_t cchShortcutTitle, - _Out_writes_opt_(cchIconLocation) PWSTR pwszIconLocation, - const size_t cchIconLocation, - _Out_opt_ int * const piIcon, - _Out_opt_ int * const piShowCmd, - _Out_opt_ WORD * const pwHotKey) +[[nodiscard]] NTSTATUS ShortcutSerialization::s_GetLinkValues(_Inout_ PCONSOLE_STATE_INFO pStateInfo, + _Out_ BOOL* const pfReadConsoleProperties, + _Out_writes_opt_(cchShortcutTitle) PWSTR pwszShortcutTitle, + const size_t cchShortcutTitle, + _Out_writes_opt_(cchIconLocation) PWSTR pwszIconLocation, + const size_t cchIconLocation, + _Out_opt_ int* const piIcon, + _Out_opt_ int* const piShowCmd, + _Out_opt_ WORD* const pwHotKey) { *pfReadConsoleProperties = false; @@ -353,8 +362,8 @@ NTSTATUS ShortcutSerialization::s_GetLinkValues(_Inout_ PCONSOLE_STATE_INFO pSta pwszIconLocation[0] = L'\0'; } - IShellLink * psl; - IPersistFile * ppf; + IShellLink* psl; + IPersistFile* ppf; HRESULT hr = s_GetLoadedShellLinkForShortcut(pStateInfo->LinkTitle, STGM_READ, &psl, &ppf); if (SUCCEEDED(hr)) { @@ -400,7 +409,6 @@ NTSTATUS ShortcutSerialization::s_GetLinkValues(_Inout_ PCONSOLE_STATE_INFO pSta return (SUCCEEDED(hr)) ? STATUS_SUCCESS : STATUS_UNSUCCESSFUL; } - /** Writes the console properties out to the link it was opened from. Arguments: @@ -408,42 +416,43 @@ Arguments: Return Value: A status code if something failed or S_OK */ -[[nodiscard]] -NTSTATUS ShortcutSerialization::s_SetLinkValues(_In_ PCONSOLE_STATE_INFO pStateInfo, const BOOL fEastAsianSystem, const BOOL fForceV2) +[[nodiscard]] NTSTATUS ShortcutSerialization::s_SetLinkValues(_In_ PCONSOLE_STATE_INFO pStateInfo, + const BOOL fEastAsianSystem, + const BOOL fForceV2) { - IShellLinkW * psl; - IPersistFile * ppf; + IShellLinkW* psl; + IPersistFile* ppf; HRESULT hr = s_GetLoadedShellLinkForShortcut(pStateInfo->LinkTitle, STGM_READWRITE | STGM_SHARE_EXCLUSIVE, &psl, &ppf); if (SUCCEEDED(hr)) { - IShellLinkDataList * psldl; + IShellLinkDataList* psldl; hr = psl->QueryInterface(IID_PPV_ARGS(&psldl)); if (SUCCEEDED(hr)) { // Now the link is loaded, generate new console settings section to replace the one in the link. NT_CONSOLE_PROPS props; - ((LPDBLIST)&props)->cbSize = sizeof(props); + ((LPDBLIST)&props)->cbSize = sizeof(props); ((LPDBLIST)&props)->dwSignature = NT_CONSOLE_PROPS_SIG; - props.wFillAttribute = pStateInfo->ScreenAttributes; - props.wPopupFillAttribute = pStateInfo->PopupAttributes; - props.dwScreenBufferSize = pStateInfo->ScreenBufferSize; - props.dwWindowSize = pStateInfo->WindowSize; - props.dwWindowOrigin.X = (SHORT)pStateInfo->WindowPosX; - props.dwWindowOrigin.Y = (SHORT)pStateInfo->WindowPosY; - props.nFont = 0; - props.nInputBufferSize = 0; - props.dwFontSize = pStateInfo->FontSize; - props.uFontFamily = pStateInfo->FontFamily; - props.uFontWeight = pStateInfo->FontWeight; + props.wFillAttribute = pStateInfo->ScreenAttributes; + props.wPopupFillAttribute = pStateInfo->PopupAttributes; + props.dwScreenBufferSize = pStateInfo->ScreenBufferSize; + props.dwWindowSize = pStateInfo->WindowSize; + props.dwWindowOrigin.X = (SHORT)pStateInfo->WindowPosX; + props.dwWindowOrigin.Y = (SHORT)pStateInfo->WindowPosY; + props.nFont = 0; + props.nInputBufferSize = 0; + props.dwFontSize = pStateInfo->FontSize; + props.uFontFamily = pStateInfo->FontFamily; + props.uFontWeight = pStateInfo->FontWeight; CopyMemory(props.FaceName, pStateInfo->FaceName, sizeof(props.FaceName)); - props.uCursorSize = pStateInfo->CursorSize; - props.bFullScreen = pStateInfo->FullScreen; - props.bQuickEdit = pStateInfo->QuickEdit; - props.bInsertMode = pStateInfo->InsertMode; - props.bAutoPosition = pStateInfo->AutoPosition; - props.uHistoryBufferSize = pStateInfo->HistoryBufferSize; - props.uNumberOfHistoryBuffers = pStateInfo->NumberOfHistoryBuffers; - props.bHistoryNoDup = pStateInfo->HistoryNoDup; + props.uCursorSize = pStateInfo->CursorSize; + props.bFullScreen = pStateInfo->FullScreen; + props.bQuickEdit = pStateInfo->QuickEdit; + props.bInsertMode = pStateInfo->InsertMode; + props.bAutoPosition = pStateInfo->AutoPosition; + props.uHistoryBufferSize = pStateInfo->HistoryBufferSize; + props.uNumberOfHistoryBuffers = pStateInfo->NumberOfHistoryBuffers; + props.bHistoryNoDup = pStateInfo->HistoryNoDup; CopyMemory(props.ColorTable, pStateInfo->ColorTable, sizeof(props.ColorTable)); // Store the changes back into the link... @@ -456,9 +465,9 @@ NTSTATUS ShortcutSerialization::s_SetLinkValues(_In_ PCONSOLE_STATE_INFO pStateI if (SUCCEEDED(hr) && fEastAsianSystem) { NT_FE_CONSOLE_PROPS fe_props; - ((LPDBLIST)&fe_props)->cbSize = sizeof(fe_props); + ((LPDBLIST)&fe_props)->cbSize = sizeof(fe_props); ((LPDBLIST)&fe_props)->dwSignature = NT_FE_CONSOLE_PROPS_SIG; - fe_props.uCodePage = pStateInfo->CodePage; + fe_props.uCodePage = pStateInfo->CodePage; hr = psldl->RemoveDataBlock(NT_FE_CONSOLE_PROPS_SIG); if (SUCCEEDED(hr)) @@ -469,7 +478,7 @@ NTSTATUS ShortcutSerialization::s_SetLinkValues(_In_ PCONSOLE_STATE_INFO pStateI if (SUCCEEDED(hr)) { - IPropertyStore * pps; + IPropertyStore* pps; hr = psl->QueryInterface(IID_IPropertyStore, reinterpret_cast(&pps)); if (SUCCEEDED(hr)) { diff --git a/src/propslib/ShortcutSerialization.hpp b/src/propslib/ShortcutSerialization.hpp index fe0501b52..27183b09c 100644 --- a/src/propslib/ShortcutSerialization.hpp +++ b/src/propslib/ShortcutSerialization.hpp @@ -24,54 +24,43 @@ Revision History: class ShortcutSerialization { public: - [[nodiscard]] - static NTSTATUS s_SetLinkValues(_In_ PCONSOLE_STATE_INFO pStateInfo, const BOOL fEastAsianSystem, const BOOL fForceV2); - [[nodiscard]] - static NTSTATUS s_GetLinkConsoleProperties(_Inout_ PCONSOLE_STATE_INFO pStateInfo); - [[nodiscard]] - static NTSTATUS s_GetLinkValues(_Inout_ PCONSOLE_STATE_INFO pStateInfo, - _Out_ BOOL * const pfReadConsoleProperties, - _Out_writes_opt_(cchShortcutTitle) PWSTR pwszShortcutTitle, - const size_t cchShortcutTitle, - _Out_writes_opt_(cchIconLocation) PWSTR pwszIconLocation, - const size_t cchIconLocation, - _Out_opt_ int * const piIcon, - _Out_opt_ int * const piShowCmd, - _Out_opt_ WORD * const pwHotKey); + [[nodiscard]] static NTSTATUS s_SetLinkValues(_In_ PCONSOLE_STATE_INFO pStateInfo, const BOOL fEastAsianSystem, const BOOL fForceV2); + [[nodiscard]] static NTSTATUS s_GetLinkConsoleProperties(_Inout_ PCONSOLE_STATE_INFO pStateInfo); + [[nodiscard]] static NTSTATUS s_GetLinkValues(_Inout_ PCONSOLE_STATE_INFO pStateInfo, + _Out_ BOOL* const pfReadConsoleProperties, + _Out_writes_opt_(cchShortcutTitle) PWSTR pwszShortcutTitle, + const size_t cchShortcutTitle, + _Out_writes_opt_(cchIconLocation) PWSTR pwszIconLocation, + const size_t cchIconLocation, + _Out_opt_ int* const piIcon, + _Out_opt_ int* const piShowCmd, + _Out_opt_ WORD* const pwHotKey); private: + static void s_InitPropVarFromBool(_In_ BOOL fVal, _Out_ PROPVARIANT* ppropvar); + static void s_InitPropVarFromByte(_In_ BYTE bVal, _Out_ PROPVARIANT* ppropvar); + static void s_InitPropVarFromDword(_In_ DWORD dwVal, _Out_ PROPVARIANT* ppropvar); + static void s_SetLinkPropertyBoolValue(_In_ IPropertyStore* pps, _In_ REFPROPERTYKEY refPropKey, const BOOL fVal); + static void s_SetLinkPropertyByteValue(_In_ IPropertyStore* pps, _In_ REFPROPERTYKEY refPropKey, const BYTE bVal); + static void s_SetLinkPropertyDwordValue(_In_ IPropertyStore* pps, _In_ REFPROPERTYKEY refPropKey, const DWORD dwVal); - static void s_InitPropVarFromBool(_In_ BOOL fVal, _Out_ PROPVARIANT *ppropvar); - static void s_InitPropVarFromByte(_In_ BYTE bVal, _Out_ PROPVARIANT *ppropvar); - static void s_InitPropVarFromDword(_In_ DWORD dwVal, _Out_ PROPVARIANT *ppropvar); + [[nodiscard]] static HRESULT s_GetPropertyBoolValue(_In_ IPropertyStore* const pPropStore, + _In_ REFPROPERTYKEY refPropKey, + _Out_ BOOL* const pfValue); + [[nodiscard]] static HRESULT s_GetPropertyByteValue(_In_ IPropertyStore* const pPropStore, + _In_ REFPROPERTYKEY refPropKey, + _Out_ BYTE* const pbValue); + [[nodiscard]] static HRESULT s_GetPropertyDwordValue(_In_ IPropertyStore* const pPropStore, + _In_ REFPROPERTYKEY refPropKey, + _Out_ DWORD* const pdwValue); - static void s_SetLinkPropertyBoolValue(_In_ IPropertyStore *pps, _In_ REFPROPERTYKEY refPropKey,const BOOL fVal); - static void s_SetLinkPropertyByteValue(_In_ IPropertyStore *pps, _In_ REFPROPERTYKEY refPropKey,const BYTE bVal); - static void s_SetLinkPropertyDwordValue(_In_ IPropertyStore *pps, _In_ REFPROPERTYKEY refPropKey,const DWORD dwVal); - - [[nodiscard]] - static HRESULT s_GetPropertyBoolValue(_In_ IPropertyStore * const pPropStore, - _In_ REFPROPERTYKEY refPropKey, - _Out_ BOOL * const pfValue); - [[nodiscard]] - static HRESULT s_GetPropertyByteValue(_In_ IPropertyStore * const pPropStore, - _In_ REFPROPERTYKEY refPropKey, - _Out_ BYTE * const pbValue); - [[nodiscard]] - static HRESULT s_GetPropertyDwordValue(_In_ IPropertyStore * const pPropStore, - _In_ REFPROPERTYKEY refPropKey, - _Out_ DWORD * const pdwValue); - - [[nodiscard]] - static HRESULT s_PopulateV1Properties(_In_ IShellLink * const pslConsole, _In_ PCONSOLE_STATE_INFO pStateInfo); - [[nodiscard]] - static HRESULT s_PopulateV2Properties(_In_ IShellLink * const pslConsole, _In_ PCONSOLE_STATE_INFO pStateInfo); + [[nodiscard]] static HRESULT s_PopulateV1Properties(_In_ IShellLink* const pslConsole, _In_ PCONSOLE_STATE_INFO pStateInfo); + [[nodiscard]] static HRESULT s_PopulateV2Properties(_In_ IShellLink* const pslConsole, _In_ PCONSOLE_STATE_INFO pStateInfo); static void s_GetLinkTitle(_In_ PCWSTR pwszShortcutFilename, _Out_writes_(cchShortcutTitle) PWSTR pwszShortcutTitle, const size_t cchShortcutTitle); - [[nodiscard]] - static HRESULT s_GetLoadedShellLinkForShortcut(_In_ PCWSTR pwszShortcutFileName, - const DWORD dwMode, - _COM_Outptr_ IShellLink **ppsl, - _COM_Outptr_ IPersistFile **ppPf); + [[nodiscard]] static HRESULT s_GetLoadedShellLinkForShortcut(_In_ PCWSTR pwszShortcutFileName, + const DWORD dwMode, + _COM_Outptr_ IShellLink** ppsl, + _COM_Outptr_ IPersistFile** ppPf); }; diff --git a/src/propslib/TrueTypeFontList.cpp b/src/propslib/TrueTypeFontList.cpp index 53873afee..3e824859f 100644 --- a/src/propslib/TrueTypeFontList.cpp +++ b/src/propslib/TrueTypeFontList.cpp @@ -13,8 +13,7 @@ SINGLE_LIST_ENTRY TrueTypeFontList::s_ttFontList; -WORD -ConvertStringToDec( +WORD ConvertStringToDec( __in LPTSTR lpch) { TCHAR ch; @@ -33,8 +32,7 @@ ConvertStringToDec( return val; } -[[nodiscard]] -NTSTATUS TrueTypeFontList::s_Initialize() +[[nodiscard]] NTSTATUS TrueTypeFontList::s_Initialize() { HKEY hkRegistry; WCHAR awchValue[512]; @@ -48,10 +46,12 @@ NTSTATUS TrueTypeFontList::s_Initialize() NTSTATUS Status = RegistrySerialization::s_OpenKey(HKEY_LOCAL_MACHINE, MACHINE_REGISTRY_CONSOLE_TTFONT_WIN32_PATH, &hkRegistry); - if (NT_SUCCESS(Status)) { + if (NT_SUCCESS(Status)) + { LPTTFONTLIST pTTFontList; - for (dwIndex = 0; ; dwIndex++) { + for (dwIndex = 0;; dwIndex++) + { Status = RegistrySerialization::s_EnumValue(hkRegistry, dwIndex, sizeof(awchValue), @@ -59,28 +59,33 @@ NTSTATUS TrueTypeFontList::s_Initialize() sizeof(awchData), (PBYTE)awchData); - if (Status == ERROR_NO_MORE_ITEMS) { + if (Status == ERROR_NO_MORE_ITEMS) + { Status = STATUS_SUCCESS; break; } - if (!NT_SUCCESS(Status)) { + if (!NT_SUCCESS(Status)) + { break; } pTTFontList = (TTFONTLIST*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(TTFONTLIST)); - if (pTTFontList == nullptr) { + if (pTTFontList == nullptr) + { break; } pTTFontList->List.Next = nullptr; pTTFontList->CodePage = ConvertStringToDec(awchValue); pwsz = awchData; - if (*pwsz == BOLD_MARK) { + if (*pwsz == BOLD_MARK) + { pTTFontList->fDisableBold = TRUE; pwsz++; } - else { + else + { pTTFontList->fDisableBold = FALSE; } @@ -96,13 +101,14 @@ NTSTATUS TrueTypeFontList::s_Initialize() // Validate that pwsz must be pointing to a position in awchData array after the movement. if (pwsz >= awchData && pwsz < (awchData + ARRAYSIZE(awchData))) { - if (*pwsz == BOLD_MARK) { + if (*pwsz == BOLD_MARK) + { pTTFontList->fDisableBold = TRUE; pwsz++; } StringCchCopyW(pTTFontList->FaceName2, - ARRAYSIZE(pTTFontList->FaceName2), - pwsz); + ARRAYSIZE(pTTFontList->FaceName2), + pwsz); } } @@ -115,13 +121,14 @@ NTSTATUS TrueTypeFontList::s_Initialize() return STATUS_SUCCESS; } -[[nodiscard]] -NTSTATUS TrueTypeFontList::s_Destroy() +[[nodiscard]] NTSTATUS TrueTypeFontList::s_Destroy() { - while (s_ttFontList.Next != nullptr) { + while (s_ttFontList.Next != nullptr) + { LPTTFONTLIST pTTFontList = (LPTTFONTLIST)PopEntryList(&s_ttFontList); - if (pTTFontList != nullptr) { + if (pTTFontList != nullptr) + { HeapFree(GetProcessHeap(), 0, pTTFontList); } } @@ -137,12 +144,15 @@ LPTTFONTLIST TrueTypeFontList::s_SearchByName(_In_opt_ LPCWSTR pwszFace, { PSINGLE_LIST_ENTRY pTemp = s_ttFontList.Next; - if (pwszFace) { - while (pTemp != nullptr) { + if (pwszFace) + { + while (pTemp != nullptr) + { LPTTFONTLIST pTTFontList = (LPTTFONTLIST)pTemp; if (wcscmp(pwszFace, pTTFontList->FaceName1) == 0 || - wcscmp(pwszFace, pTTFontList->FaceName2) == 0) { + wcscmp(pwszFace, pTTFontList->FaceName2) == 0) + { if (fCodePage) if (pTTFontList->CodePage == CodePage) return pTTFontList; @@ -159,10 +169,9 @@ LPTTFONTLIST TrueTypeFontList::s_SearchByName(_In_opt_ LPCWSTR pwszFace, return nullptr; } -[[nodiscard]] -NTSTATUS TrueTypeFontList::s_SearchByCodePage(const UINT uiCodePage, - _Out_writes_(cchFaceName) PWSTR pwszFaceName, - const size_t cchFaceName) +[[nodiscard]] NTSTATUS TrueTypeFontList::s_SearchByCodePage(const UINT uiCodePage, + _Out_writes_(cchFaceName) PWSTR pwszFaceName, + const size_t cchFaceName) { NTSTATUS status = STATUS_SUCCESS; BOOL fFontFound = FALSE; diff --git a/src/propslib/TrueTypeFontList.hpp b/src/propslib/TrueTypeFontList.hpp index 533a344cd..8094c1cd0 100644 --- a/src/propslib/TrueTypeFontList.hpp +++ b/src/propslib/TrueTypeFontList.hpp @@ -20,17 +20,14 @@ class TrueTypeFontList public: static SINGLE_LIST_ENTRY s_ttFontList; - [[nodiscard]] - static NTSTATUS s_Initialize(); - [[nodiscard]] - static NTSTATUS s_Destroy(); + [[nodiscard]] static NTSTATUS s_Initialize(); + [[nodiscard]] static NTSTATUS s_Destroy(); static LPTTFONTLIST s_SearchByName(_In_opt_ LPCWSTR pwszFace, _In_ BOOL fCodePage, _In_ UINT CodePage); - [[nodiscard]] - static NTSTATUS s_SearchByCodePage(const UINT uiCodePage, - _Out_writes_(cchFaceName) PWSTR pwszFaceName, - const size_t cchFaceName); + [[nodiscard]] static NTSTATUS s_SearchByCodePage(const UINT uiCodePage, + _Out_writes_(cchFaceName) PWSTR pwszFaceName, + const size_t cchFaceName); }; diff --git a/src/propslib/precomp.h b/src/propslib/precomp.h index faa32bc91..c2a0f5c86 100644 --- a/src/propslib/precomp.h +++ b/src/propslib/precomp.h @@ -10,14 +10,14 @@ // From ntdef.h, but that can't be included or it'll fight over PROBE_ALIGNMENT and other such arch specific defs typedef _Return_type_success_(return >= 0) LONG NTSTATUS; -/*lint -save -e624 */ // Don't complain about different typedefs. -typedef NTSTATUS *PNTSTATUS; -/*lint -restore */ // Resume checking for different typedefs. +/*lint -save -e624 */ // Don't complain about different typedefs. +typedef NTSTATUS* PNTSTATUS; +/*lint -restore */ // Resume checking for different typedefs. #define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0) #define INLINE_NTSTATUS_FROM_WIN32 1 // Must use inline NTSTATUS or it will call the wrapped function twice. #pragma warning(push) -#pragma warning(disable:4430) // Must disable 4430 "default int" warning for C++ because ntstatus.h is inflexible SDK definition. +#pragma warning(disable : 4430) // Must disable 4430 "default int" warning for C++ because ntstatus.h is inflexible SDK definition. #include #pragma warning(pop) @@ -39,34 +39,29 @@ typedef NTSTATUS *PNTSTATUS; #include "conpropsp.hpp" -#pragma region Definitions from DDK (wdm.h) +#pragma region Definitions from DDK(wdm.h) FORCEINLINE PSINGLE_LIST_ENTRY PopEntryList( - _Inout_ PSINGLE_LIST_ENTRY ListHead -) + _Inout_ PSINGLE_LIST_ENTRY ListHead) { - PSINGLE_LIST_ENTRY FirstEntry; FirstEntry = ListHead->Next; - if (FirstEntry != NULL) { + if (FirstEntry != NULL) + { ListHead->Next = FirstEntry->Next; } return FirstEntry; } - FORCEINLINE -VOID -PushEntryList( +VOID PushEntryList( _Inout_ PSINGLE_LIST_ENTRY ListHead, - _Inout_ __drv_aliasesMem PSINGLE_LIST_ENTRY Entry -) + _Inout_ __drv_aliasesMem PSINGLE_LIST_ENTRY Entry) { - Entry->Next = ListHead->Next; ListHead->Next = Entry; return; diff --git a/src/renderer/base/Cluster.cpp b/src/renderer/base/Cluster.cpp index b639faf2b..a2aa8139f 100644 --- a/src/renderer/base/Cluster.cpp +++ b/src/renderer/base/Cluster.cpp @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. - #include "precomp.h" #include "../inc/Cluster.hpp" diff --git a/src/renderer/base/FontInfoBase.cpp b/src/renderer/base/FontInfoBase.cpp index a3337b075..7328f955c 100644 --- a/src/renderer/base/FontInfoBase.cpp +++ b/src/renderer/base/FontInfoBase.cpp @@ -1,14 +1,12 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. - #include "precomp.h" #include #include "..\inc\FontInfoBase.hpp" - bool operator==(const FontInfoBase& a, const FontInfoBase& b) { return (wcscmp(a._wszFaceName, b._wszFaceName) == 0 && @@ -23,10 +21,10 @@ FontInfoBase::FontInfoBase(_In_ PCWSTR const pwszFaceName, const LONG lWeight, const bool fSetDefaultRasterFont, const UINT uiCodePage) : - _bFamily(bFamily), - _lWeight(lWeight), - _fDefaultRasterSetFromEngine(fSetDefaultRasterFont), - _uiCodePage(uiCodePage) + _bFamily(bFamily), + _lWeight(lWeight), + _fDefaultRasterSetFromEngine(fSetDefaultRasterFont), + _uiCodePage(uiCodePage) { if (nullptr != pwszFaceName) { @@ -36,7 +34,7 @@ FontInfoBase::FontInfoBase(_In_ PCWSTR const pwszFaceName, ValidateFont(); } -FontInfoBase::FontInfoBase(const FontInfoBase &fibFont) : +FontInfoBase::FontInfoBase(const FontInfoBase& fibFont) : FontInfoBase(fibFont.GetFaceName(), fibFont.GetFamily(), fibFont.GetWeight(), diff --git a/src/renderer/base/FontInfoDesired.cpp b/src/renderer/base/FontInfoDesired.cpp index 641783153..1bc5b88c2 100644 --- a/src/renderer/base/FontInfoDesired.cpp +++ b/src/renderer/base/FontInfoDesired.cpp @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. - #include "precomp.h" #include "..\inc\FontInfoDesired.hpp" @@ -28,14 +27,14 @@ FontInfoDesired::FontInfoDesired(_In_ PCWSTR const pwszFaceName, const LONG lWeight, const COORD coordSizeDesired, const UINT uiCodePage) : - FontInfoBase(pwszFaceName, bFamily, lWeight, false, uiCodePage), - _coordSizeDesired(coordSizeDesired) + FontInfoBase(pwszFaceName, bFamily, lWeight, false, uiCodePage), + _coordSizeDesired(coordSizeDesired) { } FontInfoDesired::FontInfoDesired(const FontInfo& fiFont) : - FontInfoBase(fiFont), - _coordSizeDesired(fiFont.GetUnscaledSize()) + FontInfoBase(fiFont), + _coordSizeDesired(fiFont.GetUnscaledSize()) { } @@ -48,5 +47,5 @@ bool FontInfoDesired::IsDefaultRasterFont() const // OR the face name is empty with a size of 0x0 or 8x12. return WasDefaultRasterSetFromEngine() || (wcsnlen_s(GetFaceName(), LF_FACESIZE) == 0 && ((_coordSizeDesired.X == 0 && _coordSizeDesired.Y == 0) || - (_coordSizeDesired.X == 8 && _coordSizeDesired.Y == 12))); + (_coordSizeDesired.X == 8 && _coordSizeDesired.Y == 12))); } diff --git a/src/renderer/base/RenderEngineBase.cpp b/src/renderer/base/RenderEngineBase.cpp index 68c86c562..88d32710e 100644 --- a/src/renderer/base/RenderEngineBase.cpp +++ b/src/renderer/base/RenderEngineBase.cpp @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. - #include "precomp.h" #include "../inc/RenderEngineBase.hpp" #pragma hdrstop @@ -12,7 +11,6 @@ RenderEngineBase::RenderEngineBase() : _titleChanged(false), _lastFrameTitle(L"") { - } HRESULT RenderEngineBase::InvalidateTitle(const std::wstring& proposedTitle) noexcept diff --git a/src/renderer/base/fontinfo.cpp b/src/renderer/base/fontinfo.cpp index ddfe2e98a..1fbbf6cf2 100644 --- a/src/renderer/base/fontinfo.cpp +++ b/src/renderer/base/fontinfo.cpp @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. - #include "precomp.h" #include "..\inc\FontInfo.hpp" @@ -19,19 +18,18 @@ FontInfo::FontInfo(_In_ PCWSTR const pwszFaceName, const COORD coordSize, const UINT uiCodePage, const bool fSetDefaultRasterFont /*= false*/) : - FontInfoBase(pwszFaceName, bFamily, lWeight, fSetDefaultRasterFont, uiCodePage), - _coordSize(coordSize), - _coordSizeUnscaled(coordSize) + FontInfoBase(pwszFaceName, bFamily, lWeight, fSetDefaultRasterFont, uiCodePage), + _coordSize(coordSize), + _coordSizeUnscaled(coordSize) { ValidateFont(); } FontInfo::FontInfo(const FontInfo& fiFont) : - FontInfoBase(fiFont), - _coordSize(fiFont.GetSize()), - _coordSizeUnscaled(fiFont.GetUnscaledSize()) + FontInfoBase(fiFont), + _coordSize(fiFont.GetSize()), + _coordSizeUnscaled(fiFont.GetUnscaledSize()) { - } COORD FontInfo::GetUnscaledSize() const @@ -44,7 +42,6 @@ COORD FontInfo::GetSize() const return _coordSize; } - void FontInfo::SetFromEngine(_In_ PCWSTR const pwszFaceName, const BYTE bFamily, const LONG lWeight, @@ -92,7 +89,7 @@ void FontInfo::_ValidateCoordSize() } #pragma warning(push) -#pragma warning(suppress:4356) +#pragma warning(suppress : 4356) Microsoft::Console::Render::IFontDefaultList* FontInfo::s_pFontDefaultList; #pragma warning(pop) diff --git a/src/renderer/base/precomp.h b/src/renderer/base/precomp.h index 5069f6214..d6d1d0018 100644 --- a/src/renderer/base/precomp.h +++ b/src/renderer/base/precomp.h @@ -29,5 +29,4 @@ Abstract: typedef _Return_type_success_(return >= 0) long NTSTATUS; #endif -#define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0) - +#define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0) diff --git a/src/renderer/base/renderer.cpp b/src/renderer/base/renderer.cpp index f5a1c2016..2dffc9a15 100644 --- a/src/renderer/base/renderer.cpp +++ b/src/renderer/base/renderer.cpp @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. - #include "precomp.h" #include "renderer.hpp" @@ -27,7 +26,6 @@ Renderer::Renderer(IRenderData* pData, _pThread{ std::move(thread) }, _destructing{ false } { - _srViewportPrevious = { 0 }; for (size_t i = 0; i < cEngines; i++) @@ -55,8 +53,7 @@ Renderer::~Renderer() // - // Return Value: // - HRESULT S_OK, GDI error, Safe Math error, or state/argument errors. -[[nodiscard]] -HRESULT Renderer::PaintFrame() +[[nodiscard]] HRESULT Renderer::PaintFrame() { if (_destructing) { @@ -71,15 +68,12 @@ HRESULT Renderer::PaintFrame() return S_OK; } - -[[nodiscard]] -HRESULT Renderer::_PaintFrameForEngine(_In_ IRenderEngine* const pEngine) +[[nodiscard]] HRESULT Renderer::_PaintFrameForEngine(_In_ IRenderEngine* const pEngine) { FAIL_FAST_IF_NULL(pEngine); // This is a programming error. Fail fast. _pData->LockConsole(); - auto unlock = wil::scope_exit([&]() - { + auto unlock = wil::scope_exit([&]() { _pData->UnlockConsole(); }); @@ -98,8 +92,7 @@ HRESULT Renderer::_PaintFrameForEngine(_In_ IRenderEngine* const pEngine) return S_OK; } - auto endPaint = wil::scope_exit([&]() - { + auto endPaint = wil::scope_exit([&]() { LOG_IF_FAILED(pEngine->EndPaint()); }); @@ -429,8 +422,7 @@ void Renderer::TriggerFontChange(const int iDpi, const FontInfoDesired& FontInfo // - pFontInfo - Data that will be fixed up/filled on return with the chosen font data. // Return Value: // - S_OK if set successfully or relevant GDI error via HRESULT. -[[nodiscard]] -HRESULT Renderer::GetProposedFont(const int iDpi, const FontInfoDesired& FontInfoDesired, _Out_ FontInfo& FontInfo) +[[nodiscard]] HRESULT Renderer::GetProposedFont(const int iDpi, const FontInfoDesired& FontInfoDesired, _Out_ FontInfo& FontInfo) { // If there's no head, return E_FAIL. The caller should decide how to // handle this. @@ -521,8 +513,7 @@ void Renderer::WaitForPaintCompletionAndDisable(const DWORD dwTimeoutMs) // - // Return Value: // - -[[nodiscard]] -HRESULT Renderer::_PaintBackground(_In_ IRenderEngine* const pEngine) +[[nodiscard]] HRESULT Renderer::_PaintBackground(_In_ IRenderEngine* const pEngine) { return pEngine->PaintBackground(); } @@ -747,7 +738,6 @@ void Renderer::_PaintCursor(_In_ IRenderEngine* const pEngine) // Draw it within the viewport LOG_IF_FAILED(pEngine->PaintCursor(options)); - } } @@ -861,8 +851,7 @@ void Renderer::_PaintSelection(_In_ IRenderEngine* const pEngine) // (Usually only happens when the default is changed, not when each individual color is swapped in a multi-color run.) // Return Value: // - -[[nodiscard]] -HRESULT Renderer::_UpdateDrawingBrushes(_In_ IRenderEngine* const pEngine, const TextAttribute textAttributes, const bool isSettingDefaultBrushes) +[[nodiscard]] HRESULT Renderer::_UpdateDrawingBrushes(_In_ IRenderEngine* const pEngine, const TextAttribute textAttributes, const bool isSettingDefaultBrushes) { const COLORREF rgbForeground = _pData->GetForegroundColor(textAttributes); const COLORREF rgbBackground = _pData->GetBackgroundColor(textAttributes); @@ -884,8 +873,7 @@ HRESULT Renderer::_UpdateDrawingBrushes(_In_ IRenderEngine* const pEngine, const // - // Return Value: // - -[[nodiscard]] -HRESULT Renderer::_PerformScrolling(_In_ IRenderEngine* const pEngine) +[[nodiscard]] HRESULT Renderer::_PerformScrolling(_In_ IRenderEngine* const pEngine) { return pEngine->ScrollFrame(); } diff --git a/src/renderer/base/renderer.hpp b/src/renderer/base/renderer.hpp index e5c586809..52ecd295a 100644 --- a/src/renderer/base/renderer.hpp +++ b/src/renderer/base/renderer.hpp @@ -35,20 +35,17 @@ namespace Microsoft::Console::Render const size_t cEngines, std::unique_ptr thread); - [[nodiscard]] - static HRESULT s_CreateInstance(IRenderData* pData, - _In_reads_(cEngines) IRenderEngine** const rgpEngines, - const size_t cEngines, - _Outptr_result_nullonfailure_ Renderer** const ppRenderer); + [[nodiscard]] static HRESULT s_CreateInstance(IRenderData* pData, + _In_reads_(cEngines) IRenderEngine** const rgpEngines, + const size_t cEngines, + _Outptr_result_nullonfailure_ Renderer** const ppRenderer); - [[nodiscard]] - static HRESULT s_CreateInstance(IRenderData* pData, - _Outptr_result_nullonfailure_ Renderer** const ppRenderer); + [[nodiscard]] static HRESULT s_CreateInstance(IRenderData* pData, + _Outptr_result_nullonfailure_ Renderer** const ppRenderer); virtual ~Renderer() override; - [[nodiscard]] - HRESULT PaintFrame(); + [[nodiscard]] HRESULT PaintFrame(); void TriggerSystemRedraw(const RECT* const prcDirtyClient) override; void TriggerRedraw(const Microsoft::Console::Types::Viewport& region) override; @@ -68,10 +65,9 @@ namespace Microsoft::Console::Render const FontInfoDesired& FontInfoDesired, _Out_ FontInfo& FontInfo) override; - [[nodiscard]] - HRESULT GetProposedFont(const int iDpi, - const FontInfoDesired& FontInfoDesired, - _Out_ FontInfo& FontInfo) override; + [[nodiscard]] HRESULT GetProposedFont(const int iDpi, + const FontInfoDesired& FontInfoDesired, + _Out_ FontInfo& FontInfo) override; bool IsGlyphWideByFont(const std::wstring_view glyph) override; @@ -90,13 +86,11 @@ namespace Microsoft::Console::Render void _NotifyPaintFrame(); - [[nodiscard]] - HRESULT _PaintFrameForEngine(_In_ IRenderEngine* const pEngine); + [[nodiscard]] HRESULT _PaintFrameForEngine(_In_ IRenderEngine* const pEngine); bool _CheckViewportAndScroll(); - [[nodiscard]] - HRESULT _PaintBackground(_In_ IRenderEngine* const pEngine); + [[nodiscard]] HRESULT _PaintBackground(_In_ IRenderEngine* const pEngine); void _PaintBufferOutput(_In_ IRenderEngine* const pEngine); @@ -117,19 +111,16 @@ namespace Microsoft::Console::Render void _PaintOverlays(_In_ IRenderEngine* const pEngine); void _PaintOverlay(IRenderEngine& engine, const RenderOverlay& overlay); - [[nodiscard]] - HRESULT _UpdateDrawingBrushes(_In_ IRenderEngine* const pEngine, const TextAttribute attr, const bool isSettingDefaultBrushes); + [[nodiscard]] HRESULT _UpdateDrawingBrushes(_In_ IRenderEngine* const pEngine, const TextAttribute attr, const bool isSettingDefaultBrushes); - [[nodiscard]] - HRESULT _PerformScrolling(_In_ IRenderEngine* const pEngine); + [[nodiscard]] HRESULT _PerformScrolling(_In_ IRenderEngine* const pEngine); SMALL_RECT _srViewportPrevious; std::vector _GetSelectionRects() const; std::vector _previousSelection; - [[nodiscard]] - HRESULT _PaintTitle(IRenderEngine* const pEngine); + [[nodiscard]] HRESULT _PaintTitle(IRenderEngine* const pEngine); // Helper functions to diagnose issues with painting and layout. // These are only actually effective/on in Debug builds when the flag is set using an attached debugger. diff --git a/src/renderer/base/thread.cpp b/src/renderer/base/thread.cpp index 4c7fc0e1b..0248de47c 100644 --- a/src/renderer/base/thread.cpp +++ b/src/renderer/base/thread.cpp @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. - #include "precomp.h" #include "thread.hpp" @@ -18,7 +17,6 @@ RenderThread::RenderThread() : _fKeepRunning(true), _hPaintEnabledEvent(nullptr) { - } RenderThread::~RenderThread() @@ -60,8 +58,7 @@ RenderThread::~RenderThread() // Return Value: // - S_OK if we succeeded, else an HRESULT corresponding to a failure to create // an Event or Thread. -[[nodiscard]] -HRESULT RenderThread::Initialize(IRenderer* const pRendererParent) noexcept +[[nodiscard]] HRESULT RenderThread::Initialize(IRenderer* const pRendererParent) noexcept { _pRenderer = pRendererParent; @@ -70,10 +67,10 @@ HRESULT RenderThread::Initialize(IRenderer* const pRendererParent) noexcept if (SUCCEEDED(hr)) { HANDLE hEvent = CreateEventW(nullptr, // non-inheritable security attributes - FALSE, // auto reset event - FALSE, // initially unsignaled - nullptr // no name - ); + FALSE, // auto reset event + FALSE, // initially unsignaled + nullptr // no name + ); if (hEvent == nullptr) { @@ -88,8 +85,8 @@ HRESULT RenderThread::Initialize(IRenderer* const pRendererParent) noexcept if (SUCCEEDED(hr)) { HANDLE hPaintEnabledEvent = CreateEventW(nullptr, - TRUE, // manual reset event - FALSE, // initially signaled + TRUE, // manual reset event + FALSE, // initially signaled nullptr); if (hPaintEnabledEvent == nullptr) @@ -105,8 +102,8 @@ HRESULT RenderThread::Initialize(IRenderer* const pRendererParent) noexcept if (SUCCEEDED(hr)) { HANDLE hPaintCompletedEvent = CreateEventW(nullptr, - TRUE, // manual reset event - TRUE, // initially signaled + TRUE, // manual reset event + TRUE, // initially signaled nullptr); if (hPaintCompletedEvent == nullptr) @@ -121,13 +118,13 @@ HRESULT RenderThread::Initialize(IRenderer* const pRendererParent) noexcept if (SUCCEEDED(hr)) { - HANDLE hThread = CreateThread(nullptr, // non-inheritable security attributes - 0, // use default stack size + HANDLE hThread = CreateThread(nullptr, // non-inheritable security attributes + 0, // use default stack size s_ThreadProc, this, - 0, // create immediately - nullptr // we don't need the thread ID - ); + 0, // create immediately + nullptr // we don't need the thread ID + ); if (hThread == nullptr) { diff --git a/src/renderer/base/thread.hpp b/src/renderer/base/thread.hpp index 831473303..7dd20535c 100644 --- a/src/renderer/base/thread.hpp +++ b/src/renderer/base/thread.hpp @@ -25,14 +25,13 @@ namespace Microsoft::Console::Render RenderThread(); virtual ~RenderThread() override; - [[nodiscard]] - HRESULT Initialize(_In_ IRenderer* const pRendererParent) noexcept; + [[nodiscard]] HRESULT Initialize(_In_ IRenderer* const pRendererParent) noexcept; void NotifyPaint() override; void EnablePainting() override; void WaitForPaintCompletionAndDisable(const DWORD dwTimeoutMs) override; - + private: static DWORD WINAPI s_ThreadProc(_In_ LPVOID lpParameter); DWORD WINAPI _ThreadProc(); diff --git a/src/renderer/dx/CustomTextLayout.cpp b/src/renderer/dx/CustomTextLayout.cpp index 6557703cd..d3715d999 100644 --- a/src/renderer/dx/CustomTextLayout.cpp +++ b/src/renderer/dx/CustomTextLayout.cpp @@ -55,8 +55,7 @@ CustomTextLayout::CustomTextLayout(IDWriteFactory2* const factory, // - columns - The number of columns the layout should consume when done. // Return Value: // - S_OK or suitable DirectX/DirectWrite/Direct2D result code. -[[nodiscard]] -HRESULT STDMETHODCALLTYPE CustomTextLayout::GetColumns(_Out_ UINT32* columns) +[[nodiscard]] HRESULT STDMETHODCALLTYPE CustomTextLayout::GetColumns(_Out_ UINT32* columns) { *columns = 0; @@ -64,7 +63,7 @@ HRESULT STDMETHODCALLTYPE CustomTextLayout::GetColumns(_Out_ UINT32* columns) RETURN_IF_FAILED(_ShapeGlyphRuns()); const auto totalAdvance = std::accumulate(_glyphAdvances.cbegin(), _glyphAdvances.cend(), 0.0f); - + *columns = static_cast(ceil(totalAdvance / _width)); return S_OK; @@ -85,11 +84,10 @@ HRESULT STDMETHODCALLTYPE CustomTextLayout::GetColumns(_Out_ UINT32* columns) // - originY - Y pixel point of top left corner on final surface for drawing // Return Value: // - S_OK or suitable DirectX/DirectWrite/Direct2D result code. -[[nodiscard]] -HRESULT STDMETHODCALLTYPE CustomTextLayout::Draw(_In_opt_ void* clientDrawingContext, - _In_ IDWriteTextRenderer* renderer, - FLOAT originX, - FLOAT originY) +[[nodiscard]] HRESULT STDMETHODCALLTYPE CustomTextLayout::Draw(_In_opt_ void* clientDrawingContext, + _In_ IDWriteTextRenderer* renderer, + FLOAT originX, + FLOAT originY) { RETURN_IF_FAILED(_AnalyzeRuns()); RETURN_IF_FAILED(_ShapeGlyphRuns()); @@ -109,8 +107,7 @@ HRESULT STDMETHODCALLTYPE CustomTextLayout::Draw(_In_opt_ void* clientDrawingCon // - - Uses internal state // Return Value: // - S_OK or suitable DirectWrite or STL error code -[[nodiscard]] -HRESULT CustomTextLayout::_AnalyzeRuns() noexcept +[[nodiscard]] HRESULT CustomTextLayout::_AnalyzeRuns() noexcept { try { @@ -173,8 +170,7 @@ HRESULT CustomTextLayout::_AnalyzeRuns() noexcept // - - Uses internal state // Return Value: // - S_OK or suitable DirectWrite or STL error code -[[nodiscard]] -HRESULT CustomTextLayout::_ShapeGlyphRuns() noexcept +[[nodiscard]] HRESULT CustomTextLayout::_ShapeGlyphRuns() noexcept { try { @@ -221,8 +217,7 @@ HRESULT CustomTextLayout::_ShapeGlyphRuns() noexcept // - On output, the position that should be used by the next call as its start position // Return Value: // - S_OK or suitable DirectWrite or STL error code -[[nodiscard]] -HRESULT CustomTextLayout::_ShapeGlyphRun(const UINT32 runIndex, UINT32& glyphStart) noexcept +[[nodiscard]] HRESULT CustomTextLayout::_ShapeGlyphRun(const UINT32 runIndex, UINT32& glyphStart) noexcept { try { @@ -262,7 +257,7 @@ HRESULT CustomTextLayout::_ShapeGlyphRun(const UINT32 runIndex, UINT32& glyphSta _glyphIndices.resize(totalGlyphsArrayCount); } - std::vector textProps(textLength); + std::vector textProps(textLength); std::vector glyphProps(maxGlyphCount); // Get the glyphs from the text, retrying if needed. @@ -276,21 +271,20 @@ HRESULT CustomTextLayout::_ShapeGlyphRun(const UINT32 runIndex, UINT32& glyphSta &_text[textStart], textLength, run.fontFace.Get(), - run.isSideways, // isSideways, - WI_IsFlagSet(run.bidiLevel, 1), // isRightToLeft + run.isSideways, // isSideways, + WI_IsFlagSet(run.bidiLevel, 1), // isRightToLeft &run.script, _localeName.data(), (run.isNumberSubstituted) ? _numberSubstitution.Get() : nullptr, - nullptr, // features - nullptr, // featureLengths - 0, // featureCount - maxGlyphCount, // maxGlyphCount + nullptr, // features + nullptr, // featureLengths + 0, // featureCount + maxGlyphCount, // maxGlyphCount &_glyphClusters[textStart], &textProps[0], &_glyphIndices[glyphStart], &glyphProps[0], - &actualGlyphCount - ); + &actualGlyphCount); tries++; if (hr == E_NOT_SUFFICIENT_BUFFER) @@ -329,15 +323,14 @@ HRESULT CustomTextLayout::_ShapeGlyphRun(const UINT32 runIndex, UINT32& glyphSta run.fontFace.Get(), fontSize, run.isSideways, - (run.bidiLevel & 1), // isRightToLeft + (run.bidiLevel & 1), // isRightToLeft &run.script, _localeName.data(), - NULL, // features - NULL, // featureRangeLengths - 0, // featureRanges + NULL, // features + NULL, // featureRangeLengths + 0, // featureRanges &_glyphAdvances[glyphStart], - &_glyphOffsets[glyphStart] - ); + &_glyphOffsets[glyphStart]); RETURN_IF_FAILED(hr); @@ -357,8 +350,7 @@ HRESULT CustomTextLayout::_ShapeGlyphRun(const UINT32 runIndex, UINT32& glyphSta // - - Uses internal state // Return Value: // - S_OK or suitable DirectWrite or STL error code -[[nodiscard]] -HRESULT CustomTextLayout::_CorrectGlyphRuns() noexcept +[[nodiscard]] HRESULT CustomTextLayout::_CorrectGlyphRuns() noexcept { try { @@ -379,8 +371,7 @@ HRESULT CustomTextLayout::_CorrectGlyphRuns() noexcept // - runIndex - The ID number of the internal runs array to use while shaping // Return Value: // - S_OK or suitable DirectWrite or STL error code -[[nodiscard]] -HRESULT CustomTextLayout::_CorrectGlyphRun(const UINT32 runIndex) noexcept +[[nodiscard]] HRESULT CustomTextLayout::_CorrectGlyphRun(const UINT32 runIndex) noexcept { try { @@ -436,7 +427,7 @@ HRESULT CustomTextLayout::_CorrectGlyphRun(const UINT32 runIndex) noexcept // the width (and height) of the glyph will shrink to fit the monospace cell box. // This pattern is copied from the DxRenderer's algorithm for figuring out the font height for a specific width - // and was advised by the DirectWrite team. + // and was advised by the DirectWrite team. const float widthAdvance = static_cast(advanceInDesignUnits) / metrics.designUnitsPerEm; const auto fontSizeWant = advanceExpected / widthAdvance; run.fontScale = fontSizeWant / _format->GetFontSize(); @@ -462,7 +453,6 @@ HRESULT CustomTextLayout::_CorrectGlyphRun(const UINT32 runIndex) noexcept return S_OK; } - // Routine Description: // - Takes the analyzed and shaped textual information from the layout process and // forwards it into the given renderer in a run-by-run fashion. @@ -471,12 +461,11 @@ HRESULT CustomTextLayout::_CorrectGlyphRun(const UINT32 runIndex) noexcept // while attempting to graphically place the text onto the screen // - renderer - The interface to be used for actually putting text onto the screen // - origin - pixel point of top left corner on final surface for drawing -// Return Value: +// Return Value: // - S_OK or suitable DirectX/DirectWrite/Direct2D result code. -[[nodiscard]] -HRESULT CustomTextLayout::_DrawGlyphRuns(_In_opt_ void* clientDrawingContext, - IDWriteTextRenderer* renderer, - const D2D_POINT_2F origin) noexcept +[[nodiscard]] HRESULT CustomTextLayout::_DrawGlyphRuns(_In_opt_ void* clientDrawingContext, + IDWriteTextRenderer* renderer, + const D2D_POINT_2F origin) noexcept { try { @@ -529,7 +518,7 @@ HRESULT CustomTextLayout::_DrawGlyphRuns(_In_opt_ void* clientDrawingContext, } // Routine Description: -// - Estimates the maximum number of glyph indices needed to hold a string of +// - Estimates the maximum number of glyph indices needed to hold a string of // a given length. This is the formula given in the Uniscribe SDK and should // cover most cases. Degenerate cases will require a reallocation. // Arguments: @@ -537,8 +526,7 @@ HRESULT CustomTextLayout::_DrawGlyphRuns(_In_opt_ void* clientDrawingContext, // Return Value: // - An estimate of how many glyph spaces may be required in the shaping arrays // to hold the data from a string of the given length. -[[nodiscard]] -UINT32 CustomTextLayout::_EstimateGlyphCount(const UINT32 textLength) noexcept +[[nodiscard]] UINT32 CustomTextLayout::_EstimateGlyphCount(const UINT32 textLength) noexcept { // This formula is from https://docs.microsoft.com/en-us/windows/desktop/api/dwrite/nf-dwrite-idwritetextanalyzer-getglyphs // and is the recommended formula for estimating buffer size for glyph count. @@ -556,10 +544,9 @@ UINT32 CustomTextLayout::_EstimateGlyphCount(const UINT32 textLength) noexcept // - textLength - The characters available at/after the textString pointer (string length). // Return Value: // - S_OK or appropriate STL/GSL failure code. -[[nodiscard]] -HRESULT STDMETHODCALLTYPE CustomTextLayout::GetTextAtPosition(UINT32 textPosition, - _Outptr_result_buffer_(*textLength) WCHAR const** textString, - _Out_ UINT32* textLength) +[[nodiscard]] HRESULT STDMETHODCALLTYPE CustomTextLayout::GetTextAtPosition(UINT32 textPosition, + _Outptr_result_buffer_(*textLength) WCHAR const** textString, + _Out_ UINT32* textLength) { *textString = nullptr; *textLength = 0; @@ -583,10 +570,9 @@ HRESULT STDMETHODCALLTYPE CustomTextLayout::GetTextAtPosition(UINT32 textPositio // - textLength - The characters available at/after the textString pointer (string length). // Return Value: // - S_OK or appropriate STL/GSL failure code. -[[nodiscard]] -HRESULT STDMETHODCALLTYPE CustomTextLayout::GetTextBeforePosition(UINT32 textPosition, - _Outptr_result_buffer_(*textLength) WCHAR const** textString, - _Out_ UINT32* textLength) +[[nodiscard]] HRESULT STDMETHODCALLTYPE CustomTextLayout::GetTextBeforePosition(UINT32 textPosition, + _Outptr_result_buffer_(*textLength) WCHAR const** textString, + _Out_ UINT32* textLength) { *textString = nullptr; *textLength = 0; @@ -607,8 +593,7 @@ HRESULT STDMETHODCALLTYPE CustomTextLayout::GetTextBeforePosition(UINT32 textPos // - // Return Value: // - The reading direction held for this layout from construction -[[nodiscard]] -DWRITE_READING_DIRECTION STDMETHODCALLTYPE CustomTextLayout::GetParagraphReadingDirection() +[[nodiscard]] DWRITE_READING_DIRECTION STDMETHODCALLTYPE CustomTextLayout::GetParagraphReadingDirection() { return _readingDirection; } @@ -622,10 +607,9 @@ DWRITE_READING_DIRECTION STDMETHODCALLTYPE CustomTextLayout::GetParagraphReading // - localeName - Zero terminated string of the locale name. // Return Value: // - S_OK or appropriate STL/GSL failure code. -[[nodiscard]] -HRESULT STDMETHODCALLTYPE CustomTextLayout::GetLocaleName(UINT32 textPosition, - _Out_ UINT32* textLength, - _Outptr_result_z_ WCHAR const** localeName) +[[nodiscard]] HRESULT STDMETHODCALLTYPE CustomTextLayout::GetLocaleName(UINT32 textPosition, + _Out_ UINT32* textLength, + _Outptr_result_z_ WCHAR const** localeName) { *localeName = _localeName.data(); *textLength = gsl::narrow(_text.size()) - textPosition; @@ -635,17 +619,16 @@ HRESULT STDMETHODCALLTYPE CustomTextLayout::GetLocaleName(UINT32 textPosition, // Routine Description: // - Implementation of IDWriteTextAnalysisSource::GetNumberSubstitution -// - Retrieves the number substitution object name to apply to this text. +// - Retrieves the number substitution object name to apply to this text. // Arguments: // - textPosition - The index of the first character in the held string for which layout information is needed // - textLength - How many characters of the string from the index that the returned locale applies to // - numberSubstitution - Object to use for substituting numbers inside the determined range // Return Value: // - S_OK or appropriate STL/GSL failure code. -[[nodiscard]] -HRESULT STDMETHODCALLTYPE CustomTextLayout::GetNumberSubstitution(UINT32 textPosition, - _Out_ UINT32* textLength, - _COM_Outptr_ IDWriteNumberSubstitution** numberSubstitution) +[[nodiscard]] HRESULT STDMETHODCALLTYPE CustomTextLayout::GetNumberSubstitution(UINT32 textPosition, + _Out_ UINT32* textLength, + _COM_Outptr_ IDWriteNumberSubstitution** numberSubstitution) { *numberSubstitution = nullptr; *textLength = gsl::narrow(_text.size()) - textPosition; @@ -665,10 +648,9 @@ HRESULT STDMETHODCALLTYPE CustomTextLayout::GetNumberSubstitution(UINT32 textPos // - scriptAnalysis - The analysis information for all glyphs starting at position for length. // Return Value: // - S_OK or appropriate STL/GSL failure code. -[[nodiscard]] -HRESULT STDMETHODCALLTYPE CustomTextLayout::SetScriptAnalysis(UINT32 textPosition, - UINT32 textLength, - _In_ DWRITE_SCRIPT_ANALYSIS const* scriptAnalysis) +[[nodiscard]] HRESULT STDMETHODCALLTYPE CustomTextLayout::SetScriptAnalysis(UINT32 textPosition, + UINT32 textLength, + _In_ DWRITE_SCRIPT_ANALYSIS const* scriptAnalysis) { try { @@ -695,10 +677,9 @@ HRESULT STDMETHODCALLTYPE CustomTextLayout::SetScriptAnalysis(UINT32 textPositio // - scriptAnalysis - The analysis information for all glyphs starting at position for length. // Return Value: // - S_OK or appropriate STL/GSL failure code. -[[nodiscard]] -HRESULT STDMETHODCALLTYPE CustomTextLayout::SetLineBreakpoints(UINT32 textPosition, - UINT32 textLength, - _In_reads_(textLength) DWRITE_LINE_BREAKPOINT const* lineBreakpoints) +[[nodiscard]] HRESULT STDMETHODCALLTYPE CustomTextLayout::SetLineBreakpoints(UINT32 textPosition, + UINT32 textLength, + _In_reads_(textLength) DWRITE_LINE_BREAKPOINT const* lineBreakpoints) { try { @@ -724,11 +705,10 @@ HRESULT STDMETHODCALLTYPE CustomTextLayout::SetLineBreakpoints(UINT32 textPositi // - resolvedLevel - The analysis information for all glyphs starting at position for length. // Return Value: // - S_OK or appropriate STL/GSL failure code. -[[nodiscard]] -HRESULT STDMETHODCALLTYPE CustomTextLayout::SetBidiLevel(UINT32 textPosition, - UINT32 textLength, - UINT8 /*explicitLevel*/, - UINT8 resolvedLevel) +[[nodiscard]] HRESULT STDMETHODCALLTYPE CustomTextLayout::SetBidiLevel(UINT32 textPosition, + UINT32 textLength, + UINT8 /*explicitLevel*/, + UINT8 resolvedLevel) { try { @@ -755,10 +735,9 @@ HRESULT STDMETHODCALLTYPE CustomTextLayout::SetBidiLevel(UINT32 textPosition, // - numberSubstitution - The analysis information for all glyphs starting at position for length. // Return Value: // - S_OK or appropriate STL/GSL failure code. -[[nodiscard]] -HRESULT STDMETHODCALLTYPE CustomTextLayout::SetNumberSubstitution(UINT32 textPosition, - UINT32 textLength, - _In_ IDWriteNumberSubstitution* numberSubstitution) +[[nodiscard]] HRESULT STDMETHODCALLTYPE CustomTextLayout::SetNumberSubstitution(UINT32 textPosition, + UINT32 textLength, + _In_ IDWriteNumberSubstitution* numberSubstitution) { try { @@ -778,17 +757,16 @@ HRESULT STDMETHODCALLTYPE CustomTextLayout::SetNumberSubstitution(UINT32 textPos #pragma region internal methods for mimicing text analyzer pattern but for font fallback // Routine Description: -// - Mimics an IDWriteTextAnalyser but for font fallback calculations. +// - Mimics an IDWriteTextAnalyser but for font fallback calculations. // Arguments: // - source - a text analysis source to retrieve substrings of the text to be analyzed // - textPosition - the index to start the substring operation // - textLength - the length of the substring operation // Result: // - S_OK, STL/GSL errors, or a suitable DirectWrite failure code on font fallback analysis. -[[nodiscard]] -HRESULT STDMETHODCALLTYPE CustomTextLayout::_AnalyzeFontFallback(IDWriteTextAnalysisSource* const source, - UINT32 textPosition, - UINT32 textLength) +[[nodiscard]] HRESULT STDMETHODCALLTYPE CustomTextLayout::_AnalyzeFontFallback(IDWriteTextAnalysisSource* const source, + UINT32 textPosition, + UINT32 textLength) { try { @@ -857,11 +835,10 @@ HRESULT STDMETHODCALLTYPE CustomTextLayout::_AnalyzeFontFallback(IDWriteTextAnal // - font - the font that applies to the substring range // - scale - the scale of the font to apply // - S_OK or appropriate STL/GSL failure code. -[[nodiscard]] -HRESULT STDMETHODCALLTYPE CustomTextLayout::_SetMappedFont(UINT32 textPosition, - UINT32 textLength, - _In_ IDWriteFont* const font, - FLOAT const scale) +[[nodiscard]] HRESULT STDMETHODCALLTYPE CustomTextLayout::_SetMappedFont(UINT32 textPosition, + UINT32 textLength, + _In_ IDWriteFont* const font, + FLOAT const scale) { try { @@ -906,11 +883,8 @@ HRESULT STDMETHODCALLTYPE CustomTextLayout::_SetMappedFont(UINT32 textPosition, // - The starting index is implicit based on the currently chosen run. // Return Value: // - reference to the run needed to store analysis data -[[nodiscard]] -CustomTextLayout::LinkedRun& CustomTextLayout::_FetchNextRun(UINT32& textLength) +[[nodiscard]] CustomTextLayout::LinkedRun& CustomTextLayout::_FetchNextRun(UINT32& textLength) { - - const auto originalRunIndex = _runIndex; auto& run = _runs.at(originalRunIndex); @@ -949,18 +923,13 @@ CustomTextLayout::LinkedRun& CustomTextLayout::_FetchNextRun(UINT32& textLength) // - - Updates internal state void CustomTextLayout::_SetCurrentRun(const UINT32 textPosition) { - - - if (_runIndex < _runs.size() - && _runs[_runIndex].ContainsTextPosition(textPosition)) + if (_runIndex < _runs.size() && _runs[_runIndex].ContainsTextPosition(textPosition)) { return; } _runIndex = static_cast( - std::find(_runs.begin(), _runs.end(), textPosition) - - _runs.begin() - ); + std::find(_runs.begin(), _runs.end(), textPosition) - _runs.begin()); } // Routine Description: @@ -971,7 +940,6 @@ void CustomTextLayout::_SetCurrentRun(const UINT32 textPosition) // - - Updates internal state, the back half will be selected after running void CustomTextLayout::_SplitCurrentRun(const UINT32 splitPosition) { - UINT32 runTextStart = _runs.at(_runIndex).textStart; if (splitPosition <= runTextStart) diff --git a/src/renderer/dx/CustomTextLayout.h b/src/renderer/dx/CustomTextLayout.h index fdd39a115..10544e3ea 100644 --- a/src/renderer/dx/CustomTextLayout.h +++ b/src/renderer/dx/CustomTextLayout.h @@ -14,10 +14,7 @@ namespace Microsoft::Console::Render { - class CustomTextLayout : public ::Microsoft::WRL::RuntimeClass<::Microsoft::WRL::RuntimeClassFlags<::Microsoft::WRL::ClassicCom | - ::Microsoft::WRL::InhibitFtmBase>, - IDWriteTextAnalysisSource, - IDWriteTextAnalysisSink> + class CustomTextLayout : public ::Microsoft::WRL::RuntimeClass<::Microsoft::WRL::RuntimeClassFlags<::Microsoft::WRL::ClassicCom | ::Microsoft::WRL::InhibitFtmBase>, IDWriteTextAnalysisSource, IDWriteTextAnalysisSink> { public: // Based on the Windows 7 SDK sample at https://github.com/pauldotknopf/WindowsSDK7-Samples/tree/master/multimedia/DirectWrite/CustomLayout @@ -29,60 +26,50 @@ namespace Microsoft::Console::Render const std::basic_string_view<::Microsoft::Console::Render::Cluster> clusters, size_t const width); - [[nodiscard]] - HRESULT STDMETHODCALLTYPE GetColumns(_Out_ UINT32* columns); + [[nodiscard]] HRESULT STDMETHODCALLTYPE GetColumns(_Out_ UINT32* columns); // IDWriteTextLayout methods (but we don't actually want to implement them all, so just this one matching the existing interface) - [[nodiscard]] - HRESULT STDMETHODCALLTYPE Draw(_In_opt_ void* clientDrawingContext, - _In_ IDWriteTextRenderer* renderer, - FLOAT originX, - FLOAT originY); + [[nodiscard]] HRESULT STDMETHODCALLTYPE Draw(_In_opt_ void* clientDrawingContext, + _In_ IDWriteTextRenderer* renderer, + FLOAT originX, + FLOAT originY); // IDWriteTextAnalysisSource methods - [[nodiscard]] - virtual HRESULT STDMETHODCALLTYPE GetTextAtPosition(UINT32 textPosition, - _Outptr_result_buffer_(*textLength) WCHAR const** textString, - _Out_ UINT32* textLength) override; - [[nodiscard]] - virtual HRESULT STDMETHODCALLTYPE GetTextBeforePosition(UINT32 textPosition, - _Outptr_result_buffer_(*textLength) WCHAR const** textString, - _Out_ UINT32* textLength) override; - [[nodiscard]] - virtual DWRITE_READING_DIRECTION STDMETHODCALLTYPE GetParagraphReadingDirection() override; - [[nodiscard]] - virtual HRESULT STDMETHODCALLTYPE GetLocaleName(UINT32 textPosition, - _Out_ UINT32* textLength, - _Outptr_result_z_ WCHAR const** localeName) override; - [[nodiscard]] - virtual HRESULT STDMETHODCALLTYPE GetNumberSubstitution(UINT32 textPosition, - _Out_ UINT32* textLength, - _COM_Outptr_ IDWriteNumberSubstitution** numberSubstitution) override; + [[nodiscard]] virtual HRESULT STDMETHODCALLTYPE GetTextAtPosition(UINT32 textPosition, + _Outptr_result_buffer_(*textLength) WCHAR const** textString, + _Out_ UINT32* textLength) override; + [[nodiscard]] virtual HRESULT STDMETHODCALLTYPE GetTextBeforePosition(UINT32 textPosition, + _Outptr_result_buffer_(*textLength) WCHAR const** textString, + _Out_ UINT32* textLength) override; + [[nodiscard]] virtual DWRITE_READING_DIRECTION STDMETHODCALLTYPE GetParagraphReadingDirection() override; + [[nodiscard]] virtual HRESULT STDMETHODCALLTYPE GetLocaleName(UINT32 textPosition, + _Out_ UINT32* textLength, + _Outptr_result_z_ WCHAR const** localeName) override; + [[nodiscard]] virtual HRESULT STDMETHODCALLTYPE GetNumberSubstitution(UINT32 textPosition, + _Out_ UINT32* textLength, + _COM_Outptr_ IDWriteNumberSubstitution** numberSubstitution) override; // IDWriteTextAnalysisSink methods - [[nodiscard]] - virtual HRESULT STDMETHODCALLTYPE SetScriptAnalysis(UINT32 textPosition, - UINT32 textLength, - _In_ DWRITE_SCRIPT_ANALYSIS const* scriptAnalysis) override; - [[nodiscard]] - virtual HRESULT STDMETHODCALLTYPE SetLineBreakpoints(UINT32 textPosition, - UINT32 textLength, - _In_reads_(textLength) DWRITE_LINE_BREAKPOINT const* lineBreakpoints) override; - [[nodiscard]] - virtual HRESULT STDMETHODCALLTYPE SetBidiLevel(UINT32 textPosition, - UINT32 textLength, - UINT8 explicitLevel, - UINT8 resolvedLevel) override; - [[nodiscard]] - virtual HRESULT STDMETHODCALLTYPE SetNumberSubstitution(UINT32 textPosition, - UINT32 textLength, - _In_ IDWriteNumberSubstitution* numberSubstitution) override; + [[nodiscard]] virtual HRESULT STDMETHODCALLTYPE SetScriptAnalysis(UINT32 textPosition, + UINT32 textLength, + _In_ DWRITE_SCRIPT_ANALYSIS const* scriptAnalysis) override; + [[nodiscard]] virtual HRESULT STDMETHODCALLTYPE SetLineBreakpoints(UINT32 textPosition, + UINT32 textLength, + _In_reads_(textLength) DWRITE_LINE_BREAKPOINT const* lineBreakpoints) override; + [[nodiscard]] virtual HRESULT STDMETHODCALLTYPE SetBidiLevel(UINT32 textPosition, + UINT32 textLength, + UINT8 explicitLevel, + UINT8 resolvedLevel) override; + [[nodiscard]] virtual HRESULT STDMETHODCALLTYPE SetNumberSubstitution(UINT32 textPosition, + UINT32 textLength, + _In_ IDWriteNumberSubstitution* numberSubstitution) override; + protected: // A single contiguous run of characters containing the same analysis results. struct Run { - Run() - : textStart(), + Run() : + textStart(), textLength(), glyphStart(), glyphCount(), @@ -92,12 +79,13 @@ namespace Microsoft::Console::Render isSideways(), fontFace{ nullptr }, fontScale{ 1.0 } - { } + { + } - UINT32 textStart; // starting text position of this run - UINT32 textLength; // number of contiguous code units covered - UINT32 glyphStart; // starting glyph in the glyphs array - UINT32 glyphCount; // number of glyphs associated with this run of text + UINT32 textStart; // starting text position of this run + UINT32 textLength; // number of contiguous code units covered + UINT32 glyphStart; // starting glyph in the glyphs array + UINT32 glyphCount; // number of glyphs associated with this run of text DWRITE_SCRIPT_ANALYSIS script; UINT8 bidiLevel; bool isNumberSubstituted; @@ -107,8 +95,7 @@ namespace Microsoft::Console::Render inline bool ContainsTextPosition(UINT32 desiredTextPosition) const { - return desiredTextPosition >= textStart - && desiredTextPosition < textStart + textLength; + return desiredTextPosition >= textStart && desiredTextPosition < textStart + textLength; } inline bool operator==(UINT32 desiredTextPosition) const @@ -121,41 +108,31 @@ namespace Microsoft::Console::Render // Single text analysis run, which points to the next run. struct LinkedRun : Run { - LinkedRun() - : nextRunIndex(0) - { } + LinkedRun() : + nextRunIndex(0) + { + } - UINT32 nextRunIndex; // index of next run + UINT32 nextRunIndex; // index of next run }; - [[nodiscard]] - LinkedRun& _FetchNextRun(UINT32& textLength); + [[nodiscard]] LinkedRun& _FetchNextRun(UINT32& textLength); void _SetCurrentRun(const UINT32 textPosition); void _SplitCurrentRun(const UINT32 splitPosition); - [[nodiscard]] - HRESULT STDMETHODCALLTYPE _AnalyzeFontFallback(IDWriteTextAnalysisSource* const source, UINT32 textPosition, UINT32 textLength); - [[nodiscard]] - HRESULT STDMETHODCALLTYPE _SetMappedFont(UINT32 textPosition, UINT32 textLength, IDWriteFont* const font, FLOAT const scale); + [[nodiscard]] HRESULT STDMETHODCALLTYPE _AnalyzeFontFallback(IDWriteTextAnalysisSource* const source, UINT32 textPosition, UINT32 textLength); + [[nodiscard]] HRESULT STDMETHODCALLTYPE _SetMappedFont(UINT32 textPosition, UINT32 textLength, IDWriteFont* const font, FLOAT const scale); - [[nodiscard]] - HRESULT _AnalyzeRuns() noexcept; - [[nodiscard]] - HRESULT _ShapeGlyphRuns() noexcept; - [[nodiscard]] - HRESULT _ShapeGlyphRun(const UINT32 runIndex, UINT32& glyphStart) noexcept; - [[nodiscard]] - HRESULT _CorrectGlyphRuns() noexcept; - [[nodiscard]] - HRESULT _CorrectGlyphRun(const UINT32 runIndex) noexcept; - [[nodiscard]] - HRESULT _DrawGlyphRuns(_In_opt_ void* clientDrawingContext, - IDWriteTextRenderer* renderer, - const D2D_POINT_2F origin) noexcept; - - [[nodiscard]] - static UINT32 _EstimateGlyphCount(const UINT32 textLength) noexcept; + [[nodiscard]] HRESULT _AnalyzeRuns() noexcept; + [[nodiscard]] HRESULT _ShapeGlyphRuns() noexcept; + [[nodiscard]] HRESULT _ShapeGlyphRun(const UINT32 runIndex, UINT32& glyphStart) noexcept; + [[nodiscard]] HRESULT _CorrectGlyphRuns() noexcept; + [[nodiscard]] HRESULT _CorrectGlyphRun(const UINT32 runIndex) noexcept; + [[nodiscard]] HRESULT _DrawGlyphRuns(_In_opt_ void* clientDrawingContext, + IDWriteTextRenderer* renderer, + const D2D_POINT_2F origin) noexcept; + [[nodiscard]] static UINT32 _EstimateGlyphCount(const UINT32 textLength) noexcept; private: const ::Microsoft::WRL::ComPtr _factory; diff --git a/src/renderer/dx/CustomTextRenderer.cpp b/src/renderer/dx/CustomTextRenderer.cpp index 8ab09321f..de96c701a 100644 --- a/src/renderer/dx/CustomTextRenderer.cpp +++ b/src/renderer/dx/CustomTextRenderer.cpp @@ -19,9 +19,8 @@ using namespace Microsoft::Console::Render; // - isDisabled - TRUE if we do not snap to nearest pixels. FALSE otherwise. // Return Value: // - S_OK -[[nodiscard]] -HRESULT CustomTextRenderer::IsPixelSnappingDisabled(void* /*clientDrawingContext*/, - _Out_ BOOL* isDisabled) +[[nodiscard]] HRESULT CustomTextRenderer::IsPixelSnappingDisabled(void* /*clientDrawingContext*/, + _Out_ BOOL* isDisabled) { *isDisabled = false; return S_OK; @@ -37,9 +36,8 @@ HRESULT CustomTextRenderer::IsPixelSnappingDisabled(void* /*clientDrawingContext // - pixelsPerDip - The number of pixels per DIP. 96 is standard DPI. // Return Value: // - S_OK -[[nodiscard]] -HRESULT CustomTextRenderer::GetPixelsPerDip(void* clientDrawingContext, - _Out_ FLOAT* pixelsPerDip) +[[nodiscard]] HRESULT CustomTextRenderer::GetPixelsPerDip(void* clientDrawingContext, + _Out_ FLOAT* pixelsPerDip) { DrawingContext* drawingContext = static_cast(clientDrawingContext); @@ -51,16 +49,15 @@ HRESULT CustomTextRenderer::GetPixelsPerDip(void* clientDrawingContext, // Routine Description: // - Implementation of IDWritePixelSnapping::GetCurrentTransform -// - Retrieves the the matrix transform to be used while laying pixels onto the +// - Retrieves the the matrix transform to be used while laying pixels onto the // drawing context // Arguments: // - clientDrawingContext - Pointer to structure of information required to draw // - transform - The matrix transform to use to adapt DIP representations into real monitor coordinates. // Return Value: // - S_OK -[[nodiscard]] -HRESULT CustomTextRenderer::GetCurrentTransform(void* clientDrawingContext, - DWRITE_MATRIX* transform) +[[nodiscard]] HRESULT CustomTextRenderer::GetCurrentTransform(void* clientDrawingContext, + DWRITE_MATRIX* transform) { DrawingContext* drawingContext = static_cast(clientDrawingContext); @@ -86,12 +83,11 @@ HRESULT CustomTextRenderer::GetCurrentTransform(void* clientDrawingContext, // - clientDrawingEffect - any special effect to pass along for rendering // Return Value: // - S_OK -[[nodiscard]] -HRESULT CustomTextRenderer::DrawUnderline(void* clientDrawingContext, - FLOAT baselineOriginX, - FLOAT baselineOriginY, - _In_ const DWRITE_UNDERLINE* underline, - IUnknown* clientDrawingEffect) +[[nodiscard]] HRESULT CustomTextRenderer::DrawUnderline(void* clientDrawingContext, + FLOAT baselineOriginX, + FLOAT baselineOriginY, + _In_ const DWRITE_UNDERLINE* underline, + IUnknown* clientDrawingEffect) { _FillRectangle(clientDrawingContext, clientDrawingEffect, @@ -119,12 +115,11 @@ HRESULT CustomTextRenderer::DrawUnderline(void* clientDrawingContext, // - clientDrawingEffect - any special effect to pass along for rendering // Return Value: // - S_OK -[[nodiscard]] -HRESULT CustomTextRenderer::DrawStrikethrough(void* clientDrawingContext, - FLOAT baselineOriginX, - FLOAT baselineOriginY, - _In_ const DWRITE_STRIKETHROUGH* strikethrough, - IUnknown* clientDrawingEffect) +[[nodiscard]] HRESULT CustomTextRenderer::DrawStrikethrough(void* clientDrawingContext, + FLOAT baselineOriginX, + FLOAT baselineOriginY, + _In_ const DWRITE_STRIKETHROUGH* strikethrough, + IUnknown* clientDrawingEffect) { _FillRectangle(clientDrawingContext, clientDrawingEffect, @@ -187,14 +182,13 @@ void CustomTextRenderer::_FillRectangle(void* clientDrawingContext, // - clientDrawingEffect - any special effect passed along for rendering // Return Value: // - S_OK or appropriate error from the delegated inline object's draw call -[[nodiscard]] -HRESULT CustomTextRenderer::DrawInlineObject(void* clientDrawingContext, - FLOAT originX, - FLOAT originY, - IDWriteInlineObject* inlineObject, - BOOL isSideways, - BOOL isRightToLeft, - IUnknown* clientDrawingEffect) +[[nodiscard]] HRESULT CustomTextRenderer::DrawInlineObject(void* clientDrawingContext, + FLOAT originX, + FLOAT originY, + IDWriteInlineObject* inlineObject, + BOOL isSideways, + BOOL isRightToLeft, + IUnknown* clientDrawingEffect) { return inlineObject->Draw(clientDrawingContext, this, @@ -223,8 +217,7 @@ HRESULT CustomTextRenderer::DrawInlineObject(void* clientDrawingContext, // - clientDrawingEffect - any special effect passed along for rendering // Return Value: // - S_OK, GSL/WIL/STL error, or appropriate DirectX/Direct2D/DirectWrite based error while drawing. -[[nodiscard]] -HRESULT CustomTextRenderer::DrawGlyphRun( +[[nodiscard]] HRESULT CustomTextRenderer::DrawGlyphRun( void* clientDrawingContext, FLOAT baselineOriginX, FLOAT baselineOriginY, @@ -345,8 +338,8 @@ HRESULT CustomTextRenderer::DrawGlyphRun( d2dContext4->DrawSvgGlyphRun(currentBaselineOrigin, &colorRun->glyphRun, drawingContext->foregroundBrush, - nullptr, // svgGlyphStyle - 0, // colorPaletteIndex + nullptr, // svgGlyphStyle + 0, // colorPaletteIndex measuringMode); } break; @@ -377,7 +370,6 @@ HRESULT CustomTextRenderer::DrawGlyphRun( { // This run specifies its own color. tempBrush->SetColor(colorRun->runColor); - } layerBrush = tempBrush.Get(); } @@ -410,13 +402,12 @@ HRESULT CustomTextRenderer::DrawGlyphRun( } #pragma endregion -[[nodiscard]] -HRESULT CustomTextRenderer::_DrawBasicGlyphRun(DrawingContext* clientDrawingContext, - D2D1_POINT_2F baselineOrigin, - DWRITE_MEASURING_MODE measuringMode, - _In_ const DWRITE_GLYPH_RUN* glyphRun, - _In_ const DWRITE_GLYPH_RUN_DESCRIPTION* glyphRunDescription, - ID2D1Brush* brush) +[[nodiscard]] HRESULT CustomTextRenderer::_DrawBasicGlyphRun(DrawingContext* clientDrawingContext, + D2D1_POINT_2F baselineOrigin, + DWRITE_MEASURING_MODE measuringMode, + _In_ const DWRITE_GLYPH_RUN* glyphRun, + _In_ const DWRITE_GLYPH_RUN_DESCRIPTION* glyphRunDescription, + ID2D1Brush* brush) { ::Microsoft::WRL::ComPtr d2dContext4; RETURN_IF_FAILED(clientDrawingContext->renderTarget->QueryInterface(d2dContext4.GetAddressOf())); @@ -424,7 +415,7 @@ HRESULT CustomTextRenderer::_DrawBasicGlyphRun(DrawingContext* clientDrawingCont // Using the context is the easiest/default way of drawing. d2dContext4->DrawGlyphRun(baselineOrigin, glyphRun, glyphRunDescription, brush, measuringMode); - // However, we could probably add options here and switch out to one of these other drawing methods (making it + // However, we could probably add options here and switch out to one of these other drawing methods (making it // conditional based on the IUnknown* clientDrawingEffect or on some other switches and try these out instead: //_DrawBasicGlyphRunManually(clientDrawingContext, baselineOrigin, measuringMode, glyphRun, glyphRunDescription); @@ -433,12 +424,11 @@ HRESULT CustomTextRenderer::_DrawBasicGlyphRun(DrawingContext* clientDrawingCont return S_OK; } -[[nodiscard]] -HRESULT CustomTextRenderer::_DrawBasicGlyphRunManually(DrawingContext* clientDrawingContext, - D2D1_POINT_2F baselineOrigin, - DWRITE_MEASURING_MODE /*measuringMode*/, - _In_ const DWRITE_GLYPH_RUN* glyphRun, - _In_ const DWRITE_GLYPH_RUN_DESCRIPTION* /*glyphRunDescription*/) +[[nodiscard]] HRESULT CustomTextRenderer::_DrawBasicGlyphRunManually(DrawingContext* clientDrawingContext, + D2D1_POINT_2F baselineOrigin, + DWRITE_MEASURING_MODE /*measuringMode*/, + _In_ const DWRITE_GLYPH_RUN* glyphRun, + _In_ const DWRITE_GLYPH_RUN_DESCRIPTION* /*glyphRunDescription*/) { // This is regular text but manually ::Microsoft::WRL::ComPtr d2dFactory; @@ -458,8 +448,7 @@ HRESULT CustomTextRenderer::_DrawBasicGlyphRunManually(DrawingContext* clientDra glyphRun->glyphCount, glyphRun->isSideways, glyphRun->bidiLevel % 2, - geometrySink.Get() - ); + geometrySink.Get()); geometrySink->Close(); @@ -475,12 +464,11 @@ HRESULT CustomTextRenderer::_DrawBasicGlyphRunManually(DrawingContext* clientDra return S_OK; } -[[nodiscard]] -HRESULT CustomTextRenderer::_DrawGlowGlyphRun(DrawingContext* clientDrawingContext, - D2D1_POINT_2F baselineOrigin, - DWRITE_MEASURING_MODE /*measuringMode*/, - _In_ const DWRITE_GLYPH_RUN* glyphRun, - _In_ const DWRITE_GLYPH_RUN_DESCRIPTION* /*glyphRunDescription*/) +[[nodiscard]] HRESULT CustomTextRenderer::_DrawGlowGlyphRun(DrawingContext* clientDrawingContext, + D2D1_POINT_2F baselineOrigin, + DWRITE_MEASURING_MODE /*measuringMode*/, + _In_ const DWRITE_GLYPH_RUN* glyphRun, + _In_ const DWRITE_GLYPH_RUN_DESCRIPTION* /*glyphRunDescription*/) { // This is glow text manually ::Microsoft::WRL::ComPtr d2dFactory; @@ -500,8 +488,7 @@ HRESULT CustomTextRenderer::_DrawGlowGlyphRun(DrawingContext* clientDrawingConte glyphRun->glyphCount, glyphRun->isSideways, glyphRun->bidiLevel % 2, - geometrySink.Get() - ); + geometrySink.Get()); geometrySink->Close(); @@ -512,7 +499,6 @@ HRESULT CustomTextRenderer::_DrawGlowGlyphRun(DrawingContext* clientDrawingConte &matrixAlign, transformedGeometry.GetAddressOf()); - ::Microsoft::WRL::ComPtr alignedGeometry; d2dFactory->CreateTransformedGeometry(pathGeometry.Get(), &matrixAlign, diff --git a/src/renderer/dx/CustomTextRenderer.h b/src/renderer/dx/CustomTextRenderer.h index 186f7dcc9..f64623c11 100644 --- a/src/renderer/dx/CustomTextRenderer.h +++ b/src/renderer/dx/CustomTextRenderer.h @@ -35,87 +35,78 @@ namespace Microsoft::Console::Render D2D1_DRAW_TEXT_OPTIONS options; }; - class CustomTextRenderer : public ::Microsoft::WRL::RuntimeClass<::Microsoft::WRL::RuntimeClassFlags<::Microsoft::WRL::ClassicCom | - ::Microsoft::WRL::InhibitFtmBase>, - IDWriteTextRenderer> + class CustomTextRenderer : public ::Microsoft::WRL::RuntimeClass<::Microsoft::WRL::RuntimeClassFlags<::Microsoft::WRL::ClassicCom | ::Microsoft::WRL::InhibitFtmBase>, IDWriteTextRenderer> { public: - // http://www.charlespetzold.com/blog/2014/01/Character-Formatting-Extensions-with-DirectWrite.html // https://docs.microsoft.com/en-us/windows/desktop/DirectWrite/how-to-implement-a-custom-text-renderer // IDWritePixelSnapping methods - [[nodiscard]] - virtual HRESULT STDMETHODCALLTYPE IsPixelSnappingDisabled(void* clientDrawingContext, - _Out_ BOOL* isDisabled) override; + [[nodiscard]] virtual HRESULT STDMETHODCALLTYPE IsPixelSnappingDisabled(void* clientDrawingContext, + _Out_ BOOL* isDisabled) override; - [[nodiscard]] - virtual HRESULT STDMETHODCALLTYPE GetPixelsPerDip(void* clientDrawingContext, - _Out_ FLOAT* pixelsPerDip) override; + [[nodiscard]] virtual HRESULT STDMETHODCALLTYPE GetPixelsPerDip(void* clientDrawingContext, + _Out_ FLOAT* pixelsPerDip) override; - [[nodiscard]] - virtual HRESULT STDMETHODCALLTYPE GetCurrentTransform(void* clientDrawingContext, - _Out_ DWRITE_MATRIX* transform) override; + [[nodiscard]] virtual HRESULT STDMETHODCALLTYPE GetCurrentTransform(void* clientDrawingContext, + _Out_ DWRITE_MATRIX* transform) override; // IDWriteTextRenderer methods - [[nodiscard]] - virtual HRESULT STDMETHODCALLTYPE DrawGlyphRun(void* clientDrawingContext, - FLOAT baselineOriginX, - FLOAT baselineOriginY, - DWRITE_MEASURING_MODE measuringMode, - _In_ const DWRITE_GLYPH_RUN* glyphRun, - _In_ const DWRITE_GLYPH_RUN_DESCRIPTION* glyphRunDescription, - IUnknown* clientDrawingEffect) override; + [[nodiscard]] virtual HRESULT STDMETHODCALLTYPE DrawGlyphRun(void* clientDrawingContext, + FLOAT baselineOriginX, + FLOAT baselineOriginY, + DWRITE_MEASURING_MODE measuringMode, + _In_ const DWRITE_GLYPH_RUN* glyphRun, + _In_ const DWRITE_GLYPH_RUN_DESCRIPTION* glyphRunDescription, + IUnknown* clientDrawingEffect) override; - [[nodiscard]] - virtual HRESULT STDMETHODCALLTYPE DrawUnderline(void* clientDrawingContext, - FLOAT baselineOriginX, - FLOAT baselineOriginY, - _In_ const DWRITE_UNDERLINE* underline, - IUnknown* clientDrawingEffect) override; + [[nodiscard]] virtual HRESULT STDMETHODCALLTYPE DrawUnderline(void* clientDrawingContext, + FLOAT baselineOriginX, + FLOAT baselineOriginY, + _In_ const DWRITE_UNDERLINE* underline, + IUnknown* clientDrawingEffect) override; - [[nodiscard]] - virtual HRESULT STDMETHODCALLTYPE DrawStrikethrough(void* clientDrawingContext, - FLOAT baselineOriginX, - FLOAT baselineOriginY, - _In_ const DWRITE_STRIKETHROUGH * strikethrough, - IUnknown* clientDrawingEffect) override; + [[nodiscard]] virtual HRESULT STDMETHODCALLTYPE DrawStrikethrough(void* clientDrawingContext, + FLOAT baselineOriginX, + FLOAT baselineOriginY, + _In_ const DWRITE_STRIKETHROUGH* strikethrough, + IUnknown* clientDrawingEffect) override; + + [[nodiscard]] virtual HRESULT STDMETHODCALLTYPE DrawInlineObject(void* clientDrawingContext, + FLOAT originX, + FLOAT originY, + IDWriteInlineObject* inlineObject, + BOOL isSideways, + BOOL isRightToLeft, + IUnknown* clientDrawingEffect) override; - [[nodiscard]] - virtual HRESULT STDMETHODCALLTYPE DrawInlineObject(void* clientDrawingContext, - FLOAT originX, - FLOAT originY, - IDWriteInlineObject* inlineObject, - BOOL isSideways, - BOOL isRightToLeft, - IUnknown* clientDrawingEffect) override; private: void _FillRectangle(void* clientDrawingContext, IUnknown* clientDrawingEffect, - float x, float y, float width, float thickness, + float x, + float y, + float width, + float thickness, DWRITE_READING_DIRECTION readingDirection, DWRITE_FLOW_DIRECTION flowDirection); - [[nodiscard]] - HRESULT _DrawBasicGlyphRun(DrawingContext* clientDrawingContext, - D2D1_POINT_2F baselineOrigin, - DWRITE_MEASURING_MODE measuringMode, - _In_ const DWRITE_GLYPH_RUN* glyphRun, - _In_ const DWRITE_GLYPH_RUN_DESCRIPTION* glyphRunDescription, - ID2D1Brush* brush); + [[nodiscard]] HRESULT _DrawBasicGlyphRun(DrawingContext* clientDrawingContext, + D2D1_POINT_2F baselineOrigin, + DWRITE_MEASURING_MODE measuringMode, + _In_ const DWRITE_GLYPH_RUN* glyphRun, + _In_ const DWRITE_GLYPH_RUN_DESCRIPTION* glyphRunDescription, + ID2D1Brush* brush); - [[nodiscard]] - HRESULT _DrawBasicGlyphRunManually(DrawingContext*clientDrawingContext, - D2D1_POINT_2F baselineOrigin, - DWRITE_MEASURING_MODE measuringMode, - _In_ const DWRITE_GLYPH_RUN* glyphRun, - _In_ const DWRITE_GLYPH_RUN_DESCRIPTION* glyphRunDescription); + [[nodiscard]] HRESULT _DrawBasicGlyphRunManually(DrawingContext* clientDrawingContext, + D2D1_POINT_2F baselineOrigin, + DWRITE_MEASURING_MODE measuringMode, + _In_ const DWRITE_GLYPH_RUN* glyphRun, + _In_ const DWRITE_GLYPH_RUN_DESCRIPTION* glyphRunDescription); - [[nodiscard]] - HRESULT _DrawGlowGlyphRun(DrawingContext* clientDrawingContext, - D2D1_POINT_2F baselineOrigin, - DWRITE_MEASURING_MODE measuringMode, - _In_ const DWRITE_GLYPH_RUN* glyphRun, - _In_ const DWRITE_GLYPH_RUN_DESCRIPTION* glyphRunDescription); + [[nodiscard]] HRESULT _DrawGlowGlyphRun(DrawingContext* clientDrawingContext, + D2D1_POINT_2F baselineOrigin, + DWRITE_MEASURING_MODE measuringMode, + _In_ const DWRITE_GLYPH_RUN* glyphRun, + _In_ const DWRITE_GLYPH_RUN_DESCRIPTION* glyphRunDescription); }; } diff --git a/src/renderer/dx/DxRenderer.cpp b/src/renderer/dx/DxRenderer.cpp index 3ebe25158..f9f9cbb22 100644 --- a/src/renderer/dx/DxRenderer.cpp +++ b/src/renderer/dx/DxRenderer.cpp @@ -50,8 +50,7 @@ DxEngine::DxEngine() : THROW_IF_FAILED(DWriteCreateFactory( DWRITE_FACTORY_TYPE_SHARED, __uuidof(_dwriteFactory), - reinterpret_cast(_dwriteFactory.GetAddressOf()) - )); + reinterpret_cast(_dwriteFactory.GetAddressOf()))); } // Routine Description: @@ -69,8 +68,7 @@ DxEngine::~DxEngine() // - Generally S_OK, but might return a DirectX or memory error if // resources need to be created or adjusted when enabling to prepare for draw // Can give invalid state if you enable an enabled class. -[[nodiscard]] -HRESULT DxEngine::Enable() noexcept +[[nodiscard]] HRESULT DxEngine::Enable() noexcept { return _EnableDisplayAccess(true); } @@ -82,8 +80,7 @@ HRESULT DxEngine::Enable() noexcept // Return Value: // - Should be OK. We might close/free resources, but that shouldn't error. // Can give invalid state if you disable a disabled class. -[[nodiscard]] -HRESULT DxEngine::Disable() noexcept +[[nodiscard]] HRESULT DxEngine::Disable() noexcept { return _EnableDisplayAccess(false); } @@ -96,14 +93,14 @@ HRESULT DxEngine::Disable() noexcept // Return Value: // - Generally OK. Can return invalid state if you set to the state that is already // active (enabling enabled, disabling disabled). -[[nodiscard]] -HRESULT DxEngine::_EnableDisplayAccess(const bool outputEnabled) noexcept +[[nodiscard]] HRESULT DxEngine::_EnableDisplayAccess(const bool outputEnabled) noexcept { // Invalid state if we're setting it to the same as what we already have. RETURN_HR_IF(E_NOT_VALID_STATE, outputEnabled == _isEnabled); _isEnabled = outputEnabled; - if (!_isEnabled) { + if (!_isEnabled) + { _ReleaseDeviceResources(); } @@ -122,8 +119,7 @@ HRESULT DxEngine::_EnableDisplayAccess(const bool outputEnabled) noexcept // - If false, we just set up the adapter. // Return Value: // - Could be any DirectX/D3D/D2D/DXGI/DWrite error or memory issue. -[[nodiscard]] -HRESULT DxEngine::_CreateDeviceResources(const bool createSwapChain) noexcept +[[nodiscard]] HRESULT DxEngine::_CreateDeviceResources(const bool createSwapChain) noexcept { if (_haveDeviceResources) { @@ -137,6 +133,7 @@ HRESULT DxEngine::_CreateDeviceResources(const bool createSwapChain) noexcept RETURN_IF_FAILED(_dxgiFactory2->EnumAdapters1(0, &_dxgiAdapter1)); const DWORD DeviceFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT | + // clang-format off // This causes problems for folks who do not have the whole DirectX SDK installed // when they try to run the rest of the project in debug mode. // As such, I'm leaving this flag here for people doing DX-specific work to toggle it @@ -145,8 +142,9 @@ HRESULT DxEngine::_CreateDeviceResources(const bool createSwapChain) noexcept // https://docs.microsoft.com/en-us/windows/desktop/direct3d11/overviews-direct3d-11-devices-layers // You can find out how to install it here: // https://docs.microsoft.com/en-us/windows/uwp/gaming/use-the-directx-runtime-and-visual-studio-graphics-diagnostic-features - // D3D11_CREATE_DEVICE_DEBUG | - D3D11_CREATE_DEVICE_SINGLETHREADED; + // clang-format on + // D3D11_CREATE_DEVICE_DEBUG | + D3D11_CREATE_DEVICE_SINGLETHREADED; D3D_FEATURE_LEVEL FeatureLevels[] = { D3D_FEATURE_LEVEL_11_1, @@ -171,8 +169,8 @@ HRESULT DxEngine::_CreateDeviceResources(const bool createSwapChain) noexcept _displaySizePixels = _GetClientSize(); - if (createSwapChain) { - + if (createSwapChain) + { DXGI_SWAP_CHAIN_DESC1 SwapChainDesc = { 0 }; SwapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; SwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; @@ -232,7 +230,8 @@ HRESULT DxEngine::_CreateDeviceResources(const bool createSwapChain) noexcept } _haveDeviceResources = true; - if (_isPainting) { + if (_isPainting) + { // TODO: MSFT: 21169176 - remove this or restore the "try a few times to render" code... I think _d2dRenderTarget->BeginDraw(); } @@ -248,8 +247,7 @@ HRESULT DxEngine::_CreateDeviceResources(const bool createSwapChain) noexcept return S_OK; } -[[nodiscard]] -HRESULT DxEngine::_PrepareRenderTarget() noexcept +[[nodiscard]] HRESULT DxEngine::_PrepareRenderTarget() noexcept { RETURN_IF_FAILED(_dxgiSwapChain->GetBuffer(0, IID_PPV_ARGS(&_dxgiSurface))); @@ -336,11 +334,10 @@ void DxEngine::_ReleaseDeviceResources() noexcept // - ppTextLayout - Location to receive new layout object // Return Value: // - S_OK if layout created successfully, otherwise a DirectWrite error -[[nodiscard]] -HRESULT DxEngine::_CreateTextLayout( +[[nodiscard]] HRESULT DxEngine::_CreateTextLayout( _In_reads_(stringLength) PCWCHAR string, _In_ size_t stringLength, - _Out_ IDWriteTextLayout **ppTextLayout) noexcept + _Out_ IDWriteTextLayout** ppTextLayout) noexcept { return _dwriteFactory->CreateTextLayout(string, static_cast(stringLength), @@ -357,16 +354,14 @@ HRESULT DxEngine::_CreateTextLayout( // - hwnd - Window handle // Return Value: // - S_OK -[[nodiscard]] -HRESULT DxEngine::SetHwnd(const HWND hwnd) noexcept +[[nodiscard]] HRESULT DxEngine::SetHwnd(const HWND hwnd) noexcept { _hwndTarget = hwnd; _chainMode = SwapChainMode::ForHwnd; return S_OK; } -[[nodiscard]] -HRESULT DxEngine::SetWindowSize(const SIZE Pixels) noexcept +[[nodiscard]] HRESULT DxEngine::SetWindowSize(const SIZE Pixels) noexcept { _sizeTarget = Pixels; @@ -396,8 +391,7 @@ Microsoft::WRL::ComPtr DxEngine::GetSwapChain() noexcept // - psrRegion - Character rectangle // Return Value: // - S_OK -[[nodiscard]] -HRESULT DxEngine::Invalidate(const SMALL_RECT* const psrRegion) noexcept +[[nodiscard]] HRESULT DxEngine::Invalidate(const SMALL_RECT* const psrRegion) noexcept { _InvalidOr(*psrRegion); return S_OK; @@ -409,8 +403,7 @@ HRESULT DxEngine::Invalidate(const SMALL_RECT* const psrRegion) noexcept // - pcoordCursor - single point in the character cell grid // Return Value: // - S_OK -[[nodiscard]] -HRESULT DxEngine::InvalidateCursor(const COORD* const pcoordCursor) noexcept +[[nodiscard]] HRESULT DxEngine::InvalidateCursor(const COORD* const pcoordCursor) noexcept { SMALL_RECT sr = Microsoft::Console::Types::Viewport::FromCoord(*pcoordCursor).ToInclusive(); return Invalidate(&sr); @@ -422,8 +415,7 @@ HRESULT DxEngine::InvalidateCursor(const COORD* const pcoordCursor) noexcept // - prcDirtyClient - pixel rectangle // Return Value: // - S_OK -[[nodiscard]] -HRESULT DxEngine::InvalidateSystem(const RECT* const prcDirtyClient) noexcept +[[nodiscard]] HRESULT DxEngine::InvalidateSystem(const RECT* const prcDirtyClient) noexcept { _InvalidOr(*prcDirtyClient); @@ -436,8 +428,7 @@ HRESULT DxEngine::InvalidateSystem(const RECT* const prcDirtyClient) noexcept // - rectangles - One or more rectangles describing character positions on the grid // Return Value: // - S_OK -[[nodiscard]] -HRESULT DxEngine::InvalidateSelection(const std::vector& rectangles) noexcept +[[nodiscard]] HRESULT DxEngine::InvalidateSelection(const std::vector& rectangles) noexcept { for (const auto& rect : rectangles) { @@ -454,8 +445,7 @@ HRESULT DxEngine::InvalidateSelection(const std::vector& rectangles) // - -Y is up, Y is down, -X is left, X is right. // Return Value: // - S_OK -[[nodiscard]] -HRESULT DxEngine::InvalidateScroll(const COORD* const pcoordDelta) noexcept +[[nodiscard]] HRESULT DxEngine::InvalidateScroll(const COORD* const pcoordDelta) noexcept { if (pcoordDelta->X != 0 || pcoordDelta->Y != 0) { @@ -503,8 +493,7 @@ HRESULT DxEngine::InvalidateScroll(const COORD* const pcoordDelta) noexcept // - // Return Value: // - S_OK -[[nodiscard]] -HRESULT DxEngine::InvalidateAll() noexcept +[[nodiscard]] HRESULT DxEngine::InvalidateAll() noexcept { const RECT screen = _GetDisplayRect(); _InvalidOr(screen); @@ -518,8 +507,7 @@ HRESULT DxEngine::InvalidateAll() noexcept // - pForcePaint - Always filled with false // Return Value: // - S_FALSE because we don't use this. -[[nodiscard]] -HRESULT DxEngine::InvalidateCircling(_Out_ bool* const pForcePaint) noexcept +[[nodiscard]] HRESULT DxEngine::InvalidateCircling(_Out_ bool* const pForcePaint) noexcept { *pForcePaint = false; return S_FALSE; @@ -531,8 +519,7 @@ HRESULT DxEngine::InvalidateCircling(_Out_ bool* const pForcePaint) noexcept // - // Return Value: // - X by Y area in pixels of the surface -[[nodiscard]] -SIZE DxEngine::_GetClientSize() const noexcept +[[nodiscard]] SIZE DxEngine::_GetClientSize() const noexcept { switch (_chainMode) { @@ -582,8 +569,7 @@ void _ScaleByFont(RECT& cellsToPixels, SIZE fontSize) noexcept // - // Return Value; // - Origin-placed rectangle representing the pixel size of the surface -[[nodiscard]] -RECT DxEngine::_GetDisplayRect() const noexcept +[[nodiscard]] RECT DxEngine::_GetDisplayRect() const noexcept { return { 0, 0, _displaySizePixels.cx, _displaySizePixels.cy }; } @@ -666,8 +652,7 @@ void DxEngine::_InvalidOr(RECT rc) noexcept // - pForcePaint - always filled with false. // Return Value: // - S_FALSE because this is unused. -[[nodiscard]] -HRESULT DxEngine::PrepareForTeardown(_Out_ bool* const pForcePaint) noexcept +[[nodiscard]] HRESULT DxEngine::PrepareForTeardown(_Out_ bool* const pForcePaint) noexcept { *pForcePaint = false; return S_FALSE; @@ -679,13 +664,13 @@ HRESULT DxEngine::PrepareForTeardown(_Out_ bool* const pForcePaint) noexcept // - // Return Value: // - Any DirectX error, a memory error, etc. -[[nodiscard]] -HRESULT DxEngine::StartPaint() noexcept +[[nodiscard]] HRESULT DxEngine::StartPaint() noexcept { FAIL_FAST_IF_FAILED(InvalidateAll()); RETURN_HR_IF(E_NOT_VALID_STATE, _isPainting); // invalid to start a paint while painting. - if (_isEnabled) { + if (_isEnabled) + { const auto clientSize = _GetClientSize(); if (!_haveDeviceResources) { @@ -714,20 +699,20 @@ HRESULT DxEngine::StartPaint() noexcept // - // Return Value: // - Any DirectX error, a memory error, etc. -[[nodiscard]] -HRESULT DxEngine::EndPaint() noexcept +[[nodiscard]] HRESULT DxEngine::EndPaint() noexcept { RETURN_HR_IF(E_INVALIDARG, !_isPainting); // invalid to end paint when we're not painting HRESULT hr = S_OK; - if (_haveDeviceResources) { + if (_haveDeviceResources) + { _isPainting = false; hr = _d2dRenderTarget->EndDraw(); - if (SUCCEEDED(hr)) { - + if (SUCCEEDED(hr)) + { if (_invalidScroll.cy != 0 || _invalidScroll.cx != 0) { _presentDirty = _invalidRect; @@ -775,8 +760,7 @@ HRESULT DxEngine::EndPaint() noexcept // - // Return Value: // - Any DirectX error, a memory error, etc. -[[nodiscard]] -HRESULT DxEngine::_CopyFrontToBack() noexcept +[[nodiscard]] HRESULT DxEngine::_CopyFrontToBack() noexcept { Microsoft::WRL::ComPtr backBuffer; Microsoft::WRL::ComPtr frontBuffer; @@ -796,8 +780,7 @@ HRESULT DxEngine::_CopyFrontToBack() noexcept // - // Return Value: // - S_OK or relevant DirectX error -[[nodiscard]] -HRESULT DxEngine::Present() noexcept +[[nodiscard]] HRESULT DxEngine::Present() noexcept { if (_presentReady) { @@ -822,8 +805,7 @@ HRESULT DxEngine::Present() noexcept // - // Return Value: // - S_OK -[[nodiscard]] -HRESULT DxEngine::ScrollFrame() noexcept +[[nodiscard]] HRESULT DxEngine::ScrollFrame() noexcept { return S_OK; } @@ -834,8 +816,7 @@ HRESULT DxEngine::ScrollFrame() noexcept // - // Return Value: // - S_OK -[[nodiscard]] -HRESULT DxEngine::PaintBackground() noexcept +[[nodiscard]] HRESULT DxEngine::PaintBackground() noexcept { /*_d2dRenderTarget->FillRectangle(D2D1::RectF((float)_invalidRect.left, (float)_invalidRect.top, @@ -859,10 +840,9 @@ HRESULT DxEngine::PaintBackground() noexcept // - fTrimLeft - Whether or not to trim off the left half of a double wide character // Return Value: // - S_OK or relevant DirectX error -[[nodiscard]] -HRESULT DxEngine::PaintBufferLine(std::basic_string_view const clusters, - COORD const coord, - const bool /*trimLeft*/) noexcept +[[nodiscard]] HRESULT DxEngine::PaintBufferLine(std::basic_string_view const clusters, + COORD const coord, + const bool /*trimLeft*/) noexcept { try { @@ -910,14 +890,13 @@ HRESULT DxEngine::PaintBufferLine(std::basic_string_view const clusters // - We will draw rightward (+X) from here // Return Value: // - S_OK or relevant DirectX error -[[nodiscard]] -HRESULT DxEngine::PaintBufferGridLines(GridLines const lines, - COLORREF const color, - size_t const cchLine, - COORD const coordTarget) noexcept +[[nodiscard]] HRESULT DxEngine::PaintBufferGridLines(GridLines const lines, + COLORREF const color, + size_t const cchLine, + COORD const coordTarget) noexcept { const auto existingColor = _d2dBrushForeground->GetColor(); - const auto restoreBrushOnExit = wil::scope_exit([&] {_d2dBrushForeground->SetColor(existingColor); }); + const auto restoreBrushOnExit = wil::scope_exit([&] { _d2dBrushForeground->SetColor(existingColor); }); _d2dBrushForeground->SetColor(D2D1::ColorF(color)); @@ -991,8 +970,7 @@ HRESULT DxEngine::PaintBufferGridLines(GridLines const lines, // - rect - Rectangle to invert or highlight to make the selection area // Return Value: // - S_OK or relevant DirectX error. -[[nodiscard]] -HRESULT DxEngine::PaintSelection(const SMALL_RECT rect) noexcept +[[nodiscard]] HRESULT DxEngine::PaintSelection(const SMALL_RECT rect) noexcept { const auto existingColor = _d2dBrushForeground->GetColor(); const auto selectionColor = D2D1::ColorF(_defaultForegroundColor.r, @@ -1001,7 +979,7 @@ HRESULT DxEngine::PaintSelection(const SMALL_RECT rect) noexcept 0.5f); _d2dBrushForeground->SetColor(selectionColor); - const auto resetColorOnExit = wil::scope_exit([&] {_d2dBrushForeground->SetColor(existingColor); }); + const auto resetColorOnExit = wil::scope_exit([&] { _d2dBrushForeground->SetColor(existingColor); }); RECT pixels; pixels.left = rect.Left * _glyphCell.cx; @@ -1034,8 +1012,7 @@ enum class CursorPaintType // - options - Packed options relevant to how to draw the cursor // Return Value: // - S_OK or relevant DirectX error. -[[nodiscard]] -HRESULT DxEngine::PaintCursor(const IRenderEngine::CursorOptions& options) noexcept +[[nodiscard]] HRESULT DxEngine::PaintCursor(const IRenderEngine::CursorOptions& options) noexcept { // if the cursor is off, do nothing - it should not be visible. if (!options.isOn) @@ -1130,12 +1107,11 @@ HRESULT DxEngine::PaintCursor(const IRenderEngine::CursorOptions& options) noexc // - isSettingDefaultBrushes - Lets us know that these are the default brushes to paint the swapchain background or selection // Return Value: // - S_OK or relevant DirectX error. -[[nodiscard]] -HRESULT DxEngine::UpdateDrawingBrushes(COLORREF const colorForeground, - COLORREF const colorBackground, - const WORD /*legacyColorAttribute*/, - const bool /*isBold*/, - bool const isSettingDefaultBrushes) noexcept +[[nodiscard]] HRESULT DxEngine::UpdateDrawingBrushes(COLORREF const colorForeground, + COLORREF const colorBackground, + const WORD /*legacyColorAttribute*/, + const bool /*isBold*/, + bool const isSettingDefaultBrushes) noexcept { _foregroundColor = _ColorFFromColorRef(colorForeground); _backgroundColor = _ColorFFromColorRef(colorBackground); @@ -1168,8 +1144,7 @@ HRESULT DxEngine::UpdateDrawingBrushes(COLORREF const colorForeground, // - fiFontInfo - Filled with the nearest font actually chosen for drawing // Return Value: // - S_OK or relevant DirectX error -[[nodiscard]] -HRESULT DxEngine::UpdateFont(const FontInfoDesired& pfiFontInfoDesired, FontInfo& fiFontInfo) noexcept +[[nodiscard]] HRESULT DxEngine::UpdateFont(const FontInfoDesired& pfiFontInfoDesired, FontInfo& fiFontInfo) noexcept { const auto hr = _GetProposedFont(pfiFontInfoDesired, fiFontInfo, @@ -1186,8 +1161,7 @@ HRESULT DxEngine::UpdateFont(const FontInfoDesired& pfiFontInfoDesired, FontInfo return hr; } -[[nodiscard]] -Viewport DxEngine::GetViewportInCharacters(const Viewport& viewInPixels) noexcept +[[nodiscard]] Viewport DxEngine::GetViewportInCharacters(const Viewport& viewInPixels) noexcept { short widthInChars = static_cast(viewInPixels.Width() / _glyphCell.cx); short heightInChars = static_cast(viewInPixels.Height() / _glyphCell.cy); @@ -1201,8 +1175,7 @@ Viewport DxEngine::GetViewportInCharacters(const Viewport& viewInPixels) noexcep // - iDpi - DPI // Return Value: // - S_OK -[[nodiscard]] -HRESULT DxEngine::UpdateDpi(int const iDpi) noexcept +[[nodiscard]] HRESULT DxEngine::UpdateDpi(int const iDpi) noexcept { _dpi = iDpi; @@ -1233,8 +1206,7 @@ float DxEngine::GetScaling() const noexcept // - srNewViewport - The bounds of the new viewport. // Return Value: // - HRESULT S_OK -[[nodiscard]] -HRESULT DxEngine::UpdateViewport(const SMALL_RECT /*srNewViewport*/) noexcept +[[nodiscard]] HRESULT DxEngine::UpdateViewport(const SMALL_RECT /*srNewViewport*/) noexcept { return S_OK; } @@ -1247,10 +1219,9 @@ HRESULT DxEngine::UpdateViewport(const SMALL_RECT /*srNewViewport*/) noexcept // - iDpi - // Return Value: // - S_OK -[[nodiscard]] -HRESULT DxEngine::GetProposedFont(const FontInfoDesired& pfiFontInfoDesired, - FontInfo& pfiFontInfo, - int const iDpi) noexcept +[[nodiscard]] HRESULT DxEngine::GetProposedFont(const FontInfoDesired& pfiFontInfoDesired, + FontInfo& pfiFontInfo, + int const iDpi) noexcept { Microsoft::WRL::ComPtr format; Microsoft::WRL::ComPtr analyzer; @@ -1270,8 +1241,7 @@ HRESULT DxEngine::GetProposedFont(const FontInfoDesired& pfiFontInfoDesired, // - // Return Value: // - Rectangle describing dirty area in characters. -[[nodiscard]] -SMALL_RECT DxEngine::GetDirtyRectInChars() noexcept +[[nodiscard]] SMALL_RECT DxEngine::GetDirtyRectInChars() noexcept { SMALL_RECT r; r.Top = (SHORT)(floor(_invalidRect.top / _glyphCell.cy)); @@ -1293,8 +1263,7 @@ SMALL_RECT DxEngine::GetDirtyRectInChars() noexcept // - // Return Value: // - Nearest integer short x and y values for each cell. -[[nodiscard]] -COORD DxEngine::_GetFontSize() const noexcept +[[nodiscard]] COORD DxEngine::_GetFontSize() const noexcept { return { (SHORT)(_glyphCell.cx), (SHORT)(_glyphCell.cy) }; } @@ -1305,8 +1274,7 @@ COORD DxEngine::_GetFontSize() const noexcept // - pFontSize - Filled with the font size. // Return Value: // - S_OK -[[nodiscard]] -HRESULT DxEngine::GetFontSize(_Out_ COORD* const pFontSize) noexcept +[[nodiscard]] HRESULT DxEngine::GetFontSize(_Out_ COORD* const pFontSize) noexcept { *pFontSize = _GetFontSize(); return S_OK; @@ -1319,24 +1287,23 @@ HRESULT DxEngine::GetFontSize(_Out_ COORD* const pFontSize) noexcept // - pResult - True if it should take two columns. False if it should take one. // Return Value: // - S_OK or relevant DirectWrite error. -[[nodiscard]] -HRESULT DxEngine::IsGlyphWideByFont(const std::wstring_view glyph, _Out_ bool* const pResult) noexcept +[[nodiscard]] HRESULT DxEngine::IsGlyphWideByFont(const std::wstring_view glyph, _Out_ bool* const pResult) noexcept { Cluster cluster(glyph, 0); // columns don't matter, we're doing analysis not layout. // Create the text layout CustomTextLayout layout(_dwriteFactory.Get(), - _dwriteTextAnalyzer.Get(), - _dwriteTextFormat.Get(), - _dwriteFontFace.Get(), - { &cluster, 1 }, - _glyphCell.cx); + _dwriteTextAnalyzer.Get(), + _dwriteTextFormat.Get(), + _dwriteFontFace.Get(), + { &cluster, 1 }, + _glyphCell.cx); UINT32 columns = 0; RETURN_IF_FAILED(layout.GetColumns(&columns)); *pResult = columns != 1; - + return S_OK; } @@ -1346,10 +1313,9 @@ HRESULT DxEngine::IsGlyphWideByFont(const std::wstring_view glyph, _Out_ bool* c // - newTitle: the new string to use for the title of the window // Return Value: // - S_OK -[[nodiscard]] -HRESULT DxEngine::_DoUpdateTitle(_In_ const std::wstring& /*newTitle*/) noexcept +[[nodiscard]] HRESULT DxEngine::_DoUpdateTitle(_In_ const std::wstring& /*newTitle*/) noexcept { - return PostMessageW(_hwndTarget, CM_UPDATE_TITLE, 0, (LPARAM)nullptr) ? S_OK : E_FAIL; + return PostMessageW(_hwndTarget, CM_UPDATE_TITLE, 0, (LPARAM) nullptr) ? S_OK : E_FAIL; } // Routine Description: @@ -1361,11 +1327,10 @@ HRESULT DxEngine::_DoUpdateTitle(_In_ const std::wstring& /*newTitle*/) noexcept // - style - Normal, italic, etc. // Return Value: // - Smart pointer holding interface reference for queryable font data. -[[nodiscard]] -Microsoft::WRL::ComPtr DxEngine::_FindFontFace(const std::wstring& familyName, - DWRITE_FONT_WEIGHT weight, - DWRITE_FONT_STRETCH stretch, - DWRITE_FONT_STYLE style) const +[[nodiscard]] Microsoft::WRL::ComPtr DxEngine::_FindFontFace(const std::wstring& familyName, + DWRITE_FONT_WEIGHT weight, + DWRITE_FONT_STRETCH stretch, + DWRITE_FONT_STYLE style) const { Microsoft::WRL::ComPtr fontFace; @@ -1401,13 +1366,12 @@ Microsoft::WRL::ComPtr DxEngine::_FindFontFace(const std::wstr // - dpi - The DPI of the screen // Return Value: // - S_OK or relevant DirectX error -[[nodiscard]] -HRESULT DxEngine::_GetProposedFont(const FontInfoDesired& desired, - FontInfo& actual, - const int dpi, - Microsoft::WRL::ComPtr& textFormat, - Microsoft::WRL::ComPtr& textAnalyzer, - Microsoft::WRL::ComPtr& fontFace) const noexcept +[[nodiscard]] HRESULT DxEngine::_GetProposedFont(const FontInfoDesired& desired, + FontInfo& actual, + const int dpi, + Microsoft::WRL::ComPtr& textFormat, + Microsoft::WRL::ComPtr& textAnalyzer, + Microsoft::WRL::ComPtr& fontFace) const noexcept { try { @@ -1548,7 +1512,6 @@ HRESULT DxEngine::_GetProposedFont(const FontInfoDesired& desired, false, scaled, unscaled); - } CATCH_RETURN(); @@ -1561,8 +1524,7 @@ HRESULT DxEngine::_GetProposedFont(const FontInfoDesired& desired, // - color - GDI color // Return Value: // - D2D color -[[nodiscard]] -D2D1_COLOR_F DxEngine::_ColorFFromColorRef(const COLORREF color) noexcept +[[nodiscard]] D2D1_COLOR_F DxEngine::_ColorFFromColorRef(const COLORREF color) noexcept { // Converts BGR color order to RGB. const UINT32 rgb = ((color & 0x0000FF) << 16) | (color & 0x00FF00) | ((color & 0xFF0000) >> 16); @@ -1592,8 +1554,7 @@ D2D1_COLOR_F DxEngine::_ColorFFromColorRef(const COLORREF color) noexcept // - color - Direct2D Color F // Return Value: // - DXGI RGBA -[[nodiscard]] -DXGI_RGBA DxEngine::s_RgbaFromColorF(const D2D1_COLOR_F color) noexcept +[[nodiscard]] DXGI_RGBA DxEngine::s_RgbaFromColorF(const D2D1_COLOR_F color) noexcept { DXGI_RGBA rgba; rgba.a = color.a; diff --git a/src/renderer/dx/DxRenderer.hpp b/src/renderer/dx/DxRenderer.hpp index 08e0da31d..831d198ed 100644 --- a/src/renderer/dx/DxRenderer.hpp +++ b/src/renderer/dx/DxRenderer.hpp @@ -34,96 +34,65 @@ namespace Microsoft::Console::Render // Used to release device resources so that another instance of // conhost can render to the screen (i.e. only one DirectX // application may control the screen at a time.) - [[nodiscard]] - HRESULT Enable() noexcept; - [[nodiscard]] - HRESULT Disable() noexcept; + [[nodiscard]] HRESULT Enable() noexcept; + [[nodiscard]] HRESULT Disable() noexcept; - [[nodiscard]] - HRESULT SetHwnd(const HWND hwnd) noexcept; + [[nodiscard]] HRESULT SetHwnd(const HWND hwnd) noexcept; - [[nodiscard]] - HRESULT SetWindowSize(const SIZE pixels) noexcept; + [[nodiscard]] HRESULT SetWindowSize(const SIZE pixels) noexcept; void SetCallback(std::function pfn); ::Microsoft::WRL::ComPtr GetSwapChain() noexcept; // IRenderEngine Members - [[nodiscard]] - HRESULT Invalidate(const SMALL_RECT* const psrRegion) noexcept override; - [[nodiscard]] - HRESULT InvalidateCursor(const COORD* const pcoordCursor) noexcept override; - [[nodiscard]] - HRESULT InvalidateSystem(const RECT* const prcDirtyClient) noexcept override; - [[nodiscard]] - HRESULT InvalidateSelection(const std::vector& rectangles) noexcept override; - [[nodiscard]] - HRESULT InvalidateScroll(const COORD* const pcoordDelta) noexcept override; - [[nodiscard]] - HRESULT InvalidateAll() noexcept override; - [[nodiscard]] - HRESULT InvalidateCircling(_Out_ bool* const pForcePaint) noexcept override; - [[nodiscard]] - HRESULT PrepareForTeardown(_Out_ bool* const pForcePaint) noexcept override; + [[nodiscard]] HRESULT Invalidate(const SMALL_RECT* const psrRegion) noexcept override; + [[nodiscard]] HRESULT InvalidateCursor(const COORD* const pcoordCursor) noexcept override; + [[nodiscard]] HRESULT InvalidateSystem(const RECT* const prcDirtyClient) noexcept override; + [[nodiscard]] HRESULT InvalidateSelection(const std::vector& rectangles) noexcept override; + [[nodiscard]] HRESULT InvalidateScroll(const COORD* const pcoordDelta) noexcept override; + [[nodiscard]] HRESULT InvalidateAll() noexcept override; + [[nodiscard]] HRESULT InvalidateCircling(_Out_ bool* const pForcePaint) noexcept override; + [[nodiscard]] HRESULT PrepareForTeardown(_Out_ bool* const pForcePaint) noexcept override; - [[nodiscard]] - HRESULT StartPaint() noexcept override; - [[nodiscard]] - HRESULT EndPaint() noexcept override; - [[nodiscard]] - HRESULT Present() noexcept override; + [[nodiscard]] HRESULT StartPaint() noexcept override; + [[nodiscard]] HRESULT EndPaint() noexcept override; + [[nodiscard]] HRESULT Present() noexcept override; - [[nodiscard]] - HRESULT ScrollFrame() noexcept override; + [[nodiscard]] HRESULT ScrollFrame() noexcept override; - [[nodiscard]] - HRESULT PaintBackground() noexcept override; - [[nodiscard]] - HRESULT PaintBufferLine(std::basic_string_view const clusters, - COORD const coord, - bool const fTrimLeft) noexcept override; + [[nodiscard]] HRESULT PaintBackground() noexcept override; + [[nodiscard]] HRESULT PaintBufferLine(std::basic_string_view const clusters, + COORD const coord, + bool const fTrimLeft) noexcept override; - [[nodiscard]] - HRESULT PaintBufferGridLines(GridLines const lines, COLORREF const color, size_t const cchLine, COORD const coordTarget) noexcept override; - [[nodiscard]] - HRESULT PaintSelection(const SMALL_RECT rect) noexcept override; + [[nodiscard]] HRESULT PaintBufferGridLines(GridLines const lines, COLORREF const color, size_t const cchLine, COORD const coordTarget) noexcept override; + [[nodiscard]] HRESULT PaintSelection(const SMALL_RECT rect) noexcept override; - [[nodiscard]] - HRESULT PaintCursor(const CursorOptions& options) noexcept override; + [[nodiscard]] HRESULT PaintCursor(const CursorOptions& options) noexcept override; - [[nodiscard]] - HRESULT UpdateDrawingBrushes(COLORREF const colorForeground, - COLORREF const colorBackground, - const WORD legacyColorAttribute, - const bool isBold, - bool const isSettingDefaultBrushes) noexcept override; - [[nodiscard]] - HRESULT UpdateFont(const FontInfoDesired& fiFontInfoDesired, FontInfo& fiFontInfo) noexcept override; - [[nodiscard]] - HRESULT UpdateDpi(int const iDpi) noexcept override; - [[nodiscard]] - HRESULT UpdateViewport(const SMALL_RECT srNewViewport) noexcept override; + [[nodiscard]] HRESULT UpdateDrawingBrushes(COLORREF const colorForeground, + COLORREF const colorBackground, + const WORD legacyColorAttribute, + const bool isBold, + bool const isSettingDefaultBrushes) noexcept override; + [[nodiscard]] HRESULT UpdateFont(const FontInfoDesired& fiFontInfoDesired, FontInfo& fiFontInfo) noexcept override; + [[nodiscard]] HRESULT UpdateDpi(int const iDpi) noexcept override; + [[nodiscard]] HRESULT UpdateViewport(const SMALL_RECT srNewViewport) noexcept override; - [[nodiscard]] - HRESULT GetProposedFont(const FontInfoDesired& fiFontInfoDesired, FontInfo& fiFontInfo, int const iDpi) noexcept override; + [[nodiscard]] HRESULT GetProposedFont(const FontInfoDesired& fiFontInfoDesired, FontInfo& fiFontInfo, int const iDpi) noexcept override; - [[nodiscard]] - SMALL_RECT GetDirtyRectInChars() noexcept override; + [[nodiscard]] SMALL_RECT GetDirtyRectInChars() noexcept override; - [[nodiscard]] - HRESULT GetFontSize(_Out_ COORD* const pFontSize) noexcept override; - [[nodiscard]] - HRESULT IsGlyphWideByFont(const std::wstring_view glyph, _Out_ bool* const pResult) noexcept override; + [[nodiscard]] HRESULT GetFontSize(_Out_ COORD* const pFontSize) noexcept override; + [[nodiscard]] HRESULT IsGlyphWideByFont(const std::wstring_view glyph, _Out_ bool* const pResult) noexcept override; - [[nodiscard]] - ::Microsoft::Console::Types::Viewport GetViewportInCharacters(const ::Microsoft::Console::Types::Viewport& viewInPixels) noexcept; + [[nodiscard]] ::Microsoft::Console::Types::Viewport GetViewportInCharacters(const ::Microsoft::Console::Types::Viewport& viewInPixels) noexcept; float GetScaling() const noexcept; protected: - [[nodiscard]] - HRESULT _DoUpdateTitle(_In_ const std::wstring& newTitle) noexcept override; + [[nodiscard]] HRESULT _DoUpdateTitle(_In_ const std::wstring& newTitle) noexcept override; private: enum class SwapChainMode @@ -153,8 +122,7 @@ namespace Microsoft::Console::Render D2D1_COLOR_F _foregroundColor; D2D1_COLOR_F _backgroundColor; - [[nodiscard]] - RECT _GetDisplayRect() const noexcept; + [[nodiscard]] RECT _GetDisplayRect() const noexcept; bool _isInvalidUsed; RECT _invalidRect; @@ -195,50 +163,39 @@ namespace Microsoft::Console::Render ::Microsoft::WRL::ComPtr _d2dBrushBackground; ::Microsoft::WRL::ComPtr _dxgiSwapChain; - [[nodiscard]] - HRESULT _CreateDeviceResources(const bool createSwapChain) noexcept; + [[nodiscard]] HRESULT _CreateDeviceResources(const bool createSwapChain) noexcept; - [[nodiscard]] - HRESULT _PrepareRenderTarget() noexcept; + [[nodiscard]] HRESULT _PrepareRenderTarget() noexcept; void _ReleaseDeviceResources() noexcept; - [[nodiscard]] - HRESULT _CreateTextLayout( + [[nodiscard]] HRESULT _CreateTextLayout( _In_reads_(StringLength) PCWCHAR String, _In_ size_t StringLength, - _Out_ IDWriteTextLayout **ppTextLayout) noexcept; + _Out_ IDWriteTextLayout** ppTextLayout) noexcept; - [[nodiscard]] - HRESULT _CopyFrontToBack() noexcept; + [[nodiscard]] HRESULT _CopyFrontToBack() noexcept; - [[nodiscard]] - HRESULT _EnableDisplayAccess(const bool outputEnabled) noexcept; + [[nodiscard]] HRESULT _EnableDisplayAccess(const bool outputEnabled) noexcept; - [[nodiscard]] - ::Microsoft::WRL::ComPtr _FindFontFace(const std::wstring& familyName, - DWRITE_FONT_WEIGHT weight, - DWRITE_FONT_STRETCH stretch, - DWRITE_FONT_STYLE style) const; + [[nodiscard]] ::Microsoft::WRL::ComPtr _FindFontFace(const std::wstring& familyName, + DWRITE_FONT_WEIGHT weight, + DWRITE_FONT_STRETCH stretch, + DWRITE_FONT_STYLE style) const; - [[nodiscard]] - HRESULT _GetProposedFont(const FontInfoDesired& desired, - FontInfo& actual, - const int dpi, - ::Microsoft::WRL::ComPtr& textFormat, - ::Microsoft::WRL::ComPtr& textAnalyzer, - ::Microsoft::WRL::ComPtr& fontFace) const noexcept; + [[nodiscard]] HRESULT _GetProposedFont(const FontInfoDesired& desired, + FontInfo& actual, + const int dpi, + ::Microsoft::WRL::ComPtr& textFormat, + ::Microsoft::WRL::ComPtr& textAnalyzer, + ::Microsoft::WRL::ComPtr& fontFace) const noexcept; - [[nodiscard]] - COORD _GetFontSize() const noexcept; + [[nodiscard]] COORD _GetFontSize() const noexcept; - [[nodiscard]] - SIZE _GetClientSize() const noexcept; + [[nodiscard]] SIZE _GetClientSize() const noexcept; - [[nodiscard]] - D2D1_COLOR_F _ColorFFromColorRef(const COLORREF color) noexcept; + [[nodiscard]] D2D1_COLOR_F _ColorFFromColorRef(const COLORREF color) noexcept; - [[nodiscard]] - static DXGI_RGBA s_RgbaFromColorF(const D2D1_COLOR_F color) noexcept; + [[nodiscard]] static DXGI_RGBA s_RgbaFromColorF(const D2D1_COLOR_F color) noexcept; }; } diff --git a/src/renderer/gdi/gdirenderer.hpp b/src/renderer/gdi/gdirenderer.hpp index 330c732f2..079c099dd 100644 --- a/src/renderer/gdi/gdirenderer.hpp +++ b/src/renderer/gdi/gdirenderer.hpp @@ -24,89 +24,62 @@ namespace Microsoft::Console::Render GdiEngine(); ~GdiEngine() override; - [[nodiscard]] - HRESULT SetHwnd(const HWND hwnd) noexcept; + [[nodiscard]] HRESULT SetHwnd(const HWND hwnd) noexcept; - [[nodiscard]] - HRESULT InvalidateSelection(const std::vector& rectangles) noexcept override; - [[nodiscard]] - HRESULT InvalidateScroll(const COORD* const pcoordDelta) noexcept override; - [[nodiscard]] - HRESULT InvalidateSystem(const RECT* const prcDirtyClient) noexcept override; - [[nodiscard]] - HRESULT Invalidate(const SMALL_RECT* const psrRegion) noexcept override; - [[nodiscard]] - HRESULT InvalidateCursor(const COORD* const pcoordCursor) noexcept override; - [[nodiscard]] - HRESULT InvalidateAll() noexcept override; - [[nodiscard]] - HRESULT InvalidateCircling(_Out_ bool* const pForcePaint) noexcept override; - [[nodiscard]] - HRESULT PrepareForTeardown(_Out_ bool* const pForcePaint) noexcept override; + [[nodiscard]] HRESULT InvalidateSelection(const std::vector& rectangles) noexcept override; + [[nodiscard]] HRESULT InvalidateScroll(const COORD* const pcoordDelta) noexcept override; + [[nodiscard]] HRESULT InvalidateSystem(const RECT* const prcDirtyClient) noexcept override; + [[nodiscard]] HRESULT Invalidate(const SMALL_RECT* const psrRegion) noexcept override; + [[nodiscard]] HRESULT InvalidateCursor(const COORD* const pcoordCursor) noexcept override; + [[nodiscard]] HRESULT InvalidateAll() noexcept override; + [[nodiscard]] HRESULT InvalidateCircling(_Out_ bool* const pForcePaint) noexcept override; + [[nodiscard]] HRESULT PrepareForTeardown(_Out_ bool* const pForcePaint) noexcept override; - [[nodiscard]] - HRESULT StartPaint() noexcept override; - [[nodiscard]] - HRESULT EndPaint() noexcept override; - [[nodiscard]] - HRESULT Present() noexcept override; + [[nodiscard]] HRESULT StartPaint() noexcept override; + [[nodiscard]] HRESULT EndPaint() noexcept override; + [[nodiscard]] HRESULT Present() noexcept override; - [[nodiscard]] - HRESULT ScrollFrame() noexcept override; + [[nodiscard]] HRESULT ScrollFrame() noexcept override; - [[nodiscard]] - HRESULT PaintBackground() noexcept override; - [[nodiscard]] - HRESULT PaintBufferLine(std::basic_string_view const clusters, - const COORD coord, - const bool trimLeft) noexcept override; - [[nodiscard]] - HRESULT PaintBufferGridLines(const GridLines lines, - const COLORREF color, - const size_t cchLine, - const COORD coordTarget) noexcept override; - [[nodiscard]] - HRESULT PaintSelection(const SMALL_RECT rect) noexcept override; + [[nodiscard]] HRESULT PaintBackground() noexcept override; + [[nodiscard]] HRESULT PaintBufferLine(std::basic_string_view const clusters, + const COORD coord, + const bool trimLeft) noexcept override; + [[nodiscard]] HRESULT PaintBufferGridLines(const GridLines lines, + const COLORREF color, + const size_t cchLine, + const COORD coordTarget) noexcept override; + [[nodiscard]] HRESULT PaintSelection(const SMALL_RECT rect) noexcept override; - [[nodiscard]] - HRESULT PaintCursor(const CursorOptions& options) noexcept override; + [[nodiscard]] HRESULT PaintCursor(const CursorOptions& options) noexcept override; - [[nodiscard]] - HRESULT UpdateDrawingBrushes(const COLORREF colorForeground, - const COLORREF colorBackground, - const WORD legacyColorAttribute, - const bool isBold, - const bool isSettingDefaultBrushes) noexcept override; - [[nodiscard]] - HRESULT UpdateFont(const FontInfoDesired& FontInfoDesired, - _Out_ FontInfo& FontInfo) noexcept override; - [[nodiscard]] - HRESULT UpdateDpi(const int iDpi) noexcept override; - [[nodiscard]] - HRESULT UpdateViewport(const SMALL_RECT srNewViewport) noexcept override; + [[nodiscard]] HRESULT UpdateDrawingBrushes(const COLORREF colorForeground, + const COLORREF colorBackground, + const WORD legacyColorAttribute, + const bool isBold, + const bool isSettingDefaultBrushes) noexcept override; + [[nodiscard]] HRESULT UpdateFont(const FontInfoDesired& FontInfoDesired, + _Out_ FontInfo& FontInfo) noexcept override; + [[nodiscard]] HRESULT UpdateDpi(const int iDpi) noexcept override; + [[nodiscard]] HRESULT UpdateViewport(const SMALL_RECT srNewViewport) noexcept override; - [[nodiscard]] - HRESULT GetProposedFont(const FontInfoDesired& FontDesired, - _Out_ FontInfo& Font, - const int iDpi) noexcept override; + [[nodiscard]] HRESULT GetProposedFont(const FontInfoDesired& FontDesired, + _Out_ FontInfo& Font, + const int iDpi) noexcept override; SMALL_RECT GetDirtyRectInChars() override; - [[nodiscard]] - HRESULT GetFontSize(_Out_ COORD* const pFontSize) noexcept override; - [[nodiscard]] - HRESULT IsGlyphWideByFont(const std::wstring_view glyph, _Out_ bool* const pResult) noexcept override; + [[nodiscard]] HRESULT GetFontSize(_Out_ COORD* const pFontSize) noexcept override; + [[nodiscard]] HRESULT IsGlyphWideByFont(const std::wstring_view glyph, _Out_ bool* const pResult) noexcept override; protected: - [[nodiscard]] - HRESULT _DoUpdateTitle(_In_ const std::wstring& newTitle) noexcept override; + [[nodiscard]] HRESULT _DoUpdateTitle(_In_ const std::wstring& newTitle) noexcept override; private: HWND _hwndTargetWindow; - [[nodiscard]] - static HRESULT s_SetWindowLongWHelper(const HWND hWnd, - const int nIndex, - const LONG dwNewLong) noexcept; + [[nodiscard]] static HRESULT s_SetWindowLongWHelper(const HWND hWnd, + const int nIndex, + const LONG dwNewLong) noexcept; bool _fPaintStarted; @@ -120,8 +93,7 @@ namespace Microsoft::Console::Render static const size_t s_cPolyTextCache = 80; POLYTEXTW _pPolyText[s_cPolyTextCache]; size_t _cPolyText; - [[nodiscard]] - HRESULT _FlushBufferLines() noexcept; + [[nodiscard]] HRESULT _FlushBufferLines() noexcept; std::vector cursorInvertRects; @@ -132,8 +104,7 @@ namespace Microsoft::Console::Render SIZE _szMemorySurface; HBITMAP _hbitmapMemorySurface; - [[nodiscard]] - HRESULT _PrepareMemoryBitmap(const HWND hwnd) noexcept; + [[nodiscard]] HRESULT _PrepareMemoryBitmap(const HWND hwnd) noexcept; SIZE _szInvalidScroll; RECT _rcInvalid; @@ -142,28 +113,20 @@ namespace Microsoft::Console::Render COLORREF _lastFg; COLORREF _lastBg; - [[nodiscard]] - HRESULT _InvalidCombine(const RECT* const prc) noexcept; - [[nodiscard]] - HRESULT _InvalidOffset(const POINT* const ppt) noexcept; - [[nodiscard]] - HRESULT _InvalidRestrict() noexcept; + [[nodiscard]] HRESULT _InvalidCombine(const RECT* const prc) noexcept; + [[nodiscard]] HRESULT _InvalidOffset(const POINT* const ppt) noexcept; + [[nodiscard]] HRESULT _InvalidRestrict() noexcept; - [[nodiscard]] - HRESULT _InvalidateRect(const RECT* const prc) noexcept; + [[nodiscard]] HRESULT _InvalidateRect(const RECT* const prc) noexcept; - [[nodiscard]] - HRESULT _PaintBackgroundColor(const RECT* const prc) noexcept; + [[nodiscard]] HRESULT _PaintBackgroundColor(const RECT* const prc) noexcept; static const ULONG s_ulMinCursorHeightPercent = 25; static const ULONG s_ulMaxCursorHeightPercent = 100; - [[nodiscard]] - HRESULT _ScaleByFont(const COORD* const pcoord, _Out_ POINT* const pPoint) const noexcept; - [[nodiscard]] - HRESULT _ScaleByFont(const SMALL_RECT* const psr, _Out_ RECT* const prc) const noexcept; - [[nodiscard]] - HRESULT _ScaleByFont(const RECT* const prc, _Out_ SMALL_RECT* const psr) const noexcept; + [[nodiscard]] HRESULT _ScaleByFont(const COORD* const pcoord, _Out_ POINT* const pPoint) const noexcept; + [[nodiscard]] HRESULT _ScaleByFont(const SMALL_RECT* const psr, _Out_ RECT* const prc) const noexcept; + [[nodiscard]] HRESULT _ScaleByFont(const RECT* const prc, _Out_ SMALL_RECT* const psr) const noexcept; static int s_ScaleByDpi(const int iPx, const int iDpi); static int s_ShrinkByDpi(const int iPx, const int iDpi); @@ -176,11 +139,10 @@ namespace Microsoft::Console::Render bool _IsFontTrueType() const; - [[nodiscard]] - HRESULT _GetProposedFont(const FontInfoDesired& FontDesired, - _Out_ FontInfo& Font, - const int iDpi, - _Inout_ wil::unique_hfont& hFont) noexcept; + [[nodiscard]] HRESULT _GetProposedFont(const FontInfoDesired& FontDesired, + _Out_ FontInfo& Font, + const int iDpi, + _Inout_ wil::unique_hfont& hFont) noexcept; COORD _GetFontSize() const; bool _IsMinimized() const; diff --git a/src/renderer/gdi/invalidate.cpp b/src/renderer/gdi/invalidate.cpp index 5ef3d7ab9..92243f7e6 100644 --- a/src/renderer/gdi/invalidate.cpp +++ b/src/renderer/gdi/invalidate.cpp @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. - #include "precomp.h" #include "gdirenderer.hpp" @@ -112,8 +111,8 @@ HRESULT GdiEngine::InvalidateAll() noexcept } // Method Description: -// - Notifies us that we're about to circle the buffer, giving us a chance to -// force a repaint before the buffer contents are lost. The GDI renderer +// - Notifies us that we're about to circle the buffer, giving us a chance to +// force a repaint before the buffer contents are lost. The GDI renderer // doesn't care if we lose text - we're only painting visible text anyways, // so we return false. // Arguments: @@ -127,8 +126,8 @@ HRESULT GdiEngine::InvalidateCircling(_Out_ bool* const pForcePaint) noexcept } // Method Description: -// - Notifies us that we're about to be torn down. This gives us a last chance -// to force a repaint before the buffer contents are lost. The GDI renderer +// - Notifies us that we're about to be torn down. This gives us a last chance +// to force a repaint before the buffer contents are lost. The GDI renderer // doesn't care if we lose text - we're only painting visible text anyways, // so we return false. // Arguments: diff --git a/src/renderer/gdi/math.cpp b/src/renderer/gdi/math.cpp index 522c251af..4e60ca6a5 100644 --- a/src/renderer/gdi/math.cpp +++ b/src/renderer/gdi/math.cpp @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. - #include "precomp.h" #include "gdirenderer.hpp" @@ -35,8 +34,7 @@ SMALL_RECT GdiEngine::GetDirtyRectInChars() // - pResult - recieves return value, True if it is full-width (2 wide). False if it is half-width (1 wide). // Return Value: // - S_OK -[[nodiscard]] -HRESULT GdiEngine::IsGlyphWideByFont(const std::wstring_view glyph, _Out_ bool* const pResult) noexcept +[[nodiscard]] HRESULT GdiEngine::IsGlyphWideByFont(const std::wstring_view glyph, _Out_ bool* const pResult) noexcept { bool isFullWidth = false; @@ -80,8 +78,7 @@ HRESULT GdiEngine::IsGlyphWideByFont(const std::wstring_view glyph, _Out_ bool* // - prc - Pixel region (RECT) for drawing to the client surface. // Return Value: // - S_OK or safe math failure value. -[[nodiscard]] -HRESULT GdiEngine::_ScaleByFont(const SMALL_RECT* const psr, _Out_ RECT* const prc) const noexcept +[[nodiscard]] HRESULT GdiEngine::_ScaleByFont(const SMALL_RECT* const psr, _Out_ RECT* const prc) const noexcept { COORD const coordFontSize = _GetFontSize(); RETURN_HR_IF(HRESULT_FROM_WIN32(ERROR_INVALID_STATE), coordFontSize.X == 0 || coordFontSize.Y == 0); @@ -104,8 +101,7 @@ HRESULT GdiEngine::_ScaleByFont(const SMALL_RECT* const psr, _Out_ RECT* const p // - ppt - Pixel coordinate (POINT) for drawing to the client surface. // Return Value: // - S_OK or safe math failure value. -[[nodiscard]] -HRESULT GdiEngine::_ScaleByFont(const COORD* const pcoord, _Out_ POINT* const pPoint) const noexcept +[[nodiscard]] HRESULT GdiEngine::_ScaleByFont(const COORD* const pcoord, _Out_ POINT* const pPoint) const noexcept { COORD const coordFontSize = _GetFontSize(); RETURN_HR_IF(HRESULT_FROM_WIN32(ERROR_INVALID_STATE), coordFontSize.X == 0 || coordFontSize.Y == 0); @@ -126,8 +122,7 @@ HRESULT GdiEngine::_ScaleByFont(const COORD* const pcoord, _Out_ POINT* const pP // - psr - Character region (SMALL_RECT) from the console text buffer. // Return Value: // - S_OK or safe math failure value. -[[nodiscard]] -HRESULT GdiEngine::_ScaleByFont(const RECT* const prc, _Out_ SMALL_RECT* const psr) const noexcept +[[nodiscard]] HRESULT GdiEngine::_ScaleByFont(const RECT* const prc, _Out_ SMALL_RECT* const psr) const noexcept { COORD const coordFontSize = _GetFontSize(); RETURN_HR_IF(HRESULT_FROM_WIN32(ERROR_INVALID_STATE), coordFontSize.X == 0 || coordFontSize.Y == 0); @@ -155,7 +150,6 @@ HRESULT GdiEngine::_ScaleByFont(const RECT* const prc, _Out_ SMALL_RECT* const p // C Conclusion = this works because our addition can never completely push us over to adding an additional ch to the rectangle. // So the algorithm below is using the C conclusion's math. - // Do math as long and fit to short at the end. LONG lRight = prc->right; LONG lBottom = prc->bottom; diff --git a/src/renderer/gdi/paint.cpp b/src/renderer/gdi/paint.cpp index fc303f3f3..b0f49e1ea 100644 --- a/src/renderer/gdi/paint.cpp +++ b/src/renderer/gdi/paint.cpp @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. - #include "precomp.h" #include #include "gdirenderer.hpp" @@ -18,8 +17,7 @@ using namespace Microsoft::Console::Render; // - // Return Value: // - S_OK if we started to paint. S_FALSE if we didn't need to paint. HRESULT error code if painting didn't start successfully. -[[nodiscard]] -HRESULT GdiEngine::StartPaint() noexcept +[[nodiscard]] HRESULT GdiEngine::StartPaint() noexcept { // If we have no handle, we don't need to paint. Return quickly. RETURN_HR_IF(S_FALSE, !_IsWindowValid()); @@ -64,8 +62,7 @@ HRESULT GdiEngine::StartPaint() noexcept // - // Return Value: // - S_OK, suitable GDI HRESULT error, error from Win32 windowing, or safemath error. -[[nodiscard]] -HRESULT GdiEngine::ScrollFrame() noexcept +[[nodiscard]] HRESULT GdiEngine::ScrollFrame() noexcept { // If we don't have any scrolling to do, return early. RETURN_HR_IF(S_OK, 0 == _szInvalidScroll.cx && 0 == _szInvalidScroll.cy); @@ -124,8 +121,7 @@ HRESULT GdiEngine::ScrollFrame() noexcept // - hwnd - Window handle to use for the DC properties when creating a memory DC and for checking the client area size. // Return Value: // - S_OK or suitable GDI HRESULT error. -[[nodiscard]] -HRESULT GdiEngine::_PrepareMemoryBitmap(const HWND hwnd) noexcept +[[nodiscard]] HRESULT GdiEngine::_PrepareMemoryBitmap(const HWND hwnd) noexcept { RECT rcClient; RETURN_HR_IF(E_FAIL, !(GetClientRect(hwnd, &rcClient))); @@ -191,8 +187,7 @@ HRESULT GdiEngine::_PrepareMemoryBitmap(const HWND hwnd) noexcept // - // Return Value: // - S_OK or suitable GDI HRESULT error. -[[nodiscard]] -HRESULT GdiEngine::EndPaint() noexcept +[[nodiscard]] HRESULT GdiEngine::EndPaint() noexcept { // If we try to end a paint that wasn't started, it's invalid. Return. RETURN_HR_IF(HRESULT_FROM_WIN32(ERROR_INVALID_STATE), !(_fPaintStarted)); @@ -230,8 +225,7 @@ HRESULT GdiEngine::EndPaint() noexcept // - // Return Value: // - S_FALSE since we do nothing. -[[nodiscard]] -HRESULT GdiEngine::Present() noexcept +[[nodiscard]] HRESULT GdiEngine::Present() noexcept { return S_FALSE; } @@ -242,8 +236,7 @@ HRESULT GdiEngine::Present() noexcept // - prc - Rectangle to fill with color // Return Value: // - S_OK or suitable GDI HRESULT error. -[[nodiscard]] -HRESULT GdiEngine::_PaintBackgroundColor(const RECT* const prc) noexcept +[[nodiscard]] HRESULT GdiEngine::_PaintBackgroundColor(const RECT* const prc) noexcept { wil::unique_hbrush hbr(GetStockBrush(DC_BRUSH)); RETURN_HR_IF_NULL(E_FAIL, hbr.get()); @@ -263,8 +256,7 @@ HRESULT GdiEngine::_PaintBackgroundColor(const RECT* const prc) noexcept // - // Return Value: // - S_OK or suitable GDI HRESULT error. -[[nodiscard]] -HRESULT GdiEngine::PaintBackground() noexcept +[[nodiscard]] HRESULT GdiEngine::PaintBackground() noexcept { if (_psInvalidData.fErase) { @@ -292,10 +284,9 @@ HRESULT GdiEngine::PaintBackground() noexcept // See: Win7: 390673, 447839 and then superseded by http://osgvsowi/638274 when FE/non-FE rendering condensed. //#define CONSOLE_EXTTEXTOUT_FLAGS ETO_OPAQUE | ETO_CLIPPED //#define MAX_POLY_LINES 80 -[[nodiscard]] -HRESULT GdiEngine::PaintBufferLine(std::basic_string_view const clusters, - const COORD coord, - const bool trimLeft) noexcept +[[nodiscard]] HRESULT GdiEngine::PaintBufferLine(std::basic_string_view const clusters, + const COORD coord, + const bool trimLeft) noexcept { try { @@ -326,7 +317,7 @@ HRESULT GdiEngine::PaintBufferLine(std::basic_string_view const cluster { const auto& cluster = clusters.at(i); - // Our GDI renderer hasn't and isn't going to handle things above U+FFFF or sequences. + // Our GDI renderer hasn't and isn't going to handle things above U+FFFF or sequences. // So replace anything complicated with a replacement character for drawing purposes. pwsPoly[i] = cluster.GetTextAsSingle(); rgdxPoly[i] = gsl::narrow(cluster.GetColumns()) * coordFontSize.X; @@ -407,8 +398,7 @@ HRESULT GdiEngine::PaintBufferLine(std::basic_string_view const cluster // - // Return Value: // - S_OK or E_FAIL if GDI failed. -[[nodiscard]] -HRESULT GdiEngine::_FlushBufferLines() noexcept +[[nodiscard]] HRESULT GdiEngine::_FlushBufferLines() noexcept { HRESULT hr = S_OK; @@ -449,8 +439,7 @@ HRESULT GdiEngine::_FlushBufferLines() noexcept // - coordTarget - The starting X/Y position of the first character to draw on. // Return Value: // - S_OK or suitable GDI HRESULT error or E_FAIL for GDI errors in functions that don't reliably return a specific error code. -[[nodiscard]] -HRESULT GdiEngine::PaintBufferGridLines(const GridLines lines, const COLORREF color, const size_t cchLine, const COORD coordTarget) noexcept +[[nodiscard]] HRESULT GdiEngine::PaintBufferGridLines(const GridLines lines, const COLORREF color, const size_t cchLine, const COORD coordTarget) noexcept { // Return early if there are no lines to paint. RETURN_HR_IF(S_OK, GridLines::None == lines); @@ -517,8 +506,7 @@ HRESULT GdiEngine::PaintBufferGridLines(const GridLines lines, const COLORREF co // - options - Parameters that affect the way that the cursor is drawn // Return Value: // - S_OK, suitable GDI HRESULT error, or safemath error, or E_FAIL in a GDI error where a specific error isn't set. -[[nodiscard]] -HRESULT GdiEngine::PaintCursor(const IRenderEngine::CursorOptions& options) noexcept +[[nodiscard]] HRESULT GdiEngine::PaintCursor(const IRenderEngine::CursorOptions& options) noexcept { // if the cursor is off, do nothing - it should not be visible. if (!options.isOn) @@ -641,8 +629,7 @@ HRESULT GdiEngine::PaintCursor(const IRenderEngine::CursorOptions& options) noex // - rect - Rectangle to invert or highlight to make the selection area // Return Value: // - S_OK or suitable GDI HRESULT error. -[[nodiscard]] -HRESULT GdiEngine::PaintSelection(const SMALL_RECT rect) noexcept +[[nodiscard]] HRESULT GdiEngine::PaintSelection(const SMALL_RECT rect) noexcept { LOG_IF_FAILED(_FlushBufferLines()); diff --git a/src/renderer/gdi/precomp.h b/src/renderer/gdi/precomp.h index 7afaf5c0f..4e463adb2 100644 --- a/src/renderer/gdi/precomp.h +++ b/src/renderer/gdi/precomp.h @@ -24,12 +24,15 @@ Abstract: typedef _Return_type_success_(return >= 0) long NTSTATUS; #endif -#define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0) +#define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0) //#include -#define STATUS_SUCCESS ((NTSTATUS)0x00000000L) // ntsubauth -#define FACILITY_NTWIN32 0x7 -__inline int NTSTATUS_FROM_WIN32(long x) { return x <= 0 ? (NTSTATUS)x : (NTSTATUS)(((x) & 0x0000FFFF) | (FACILITY_NTWIN32 << 16) | ERROR_SEVERITY_ERROR); } +#define STATUS_SUCCESS ((NTSTATUS)0x00000000L) // ntsubauth +#define FACILITY_NTWIN32 0x7 +__inline int NTSTATUS_FROM_WIN32(long x) +{ + return x <= 0 ? (NTSTATUS)x : (NTSTATUS)(((x)&0x0000FFFF) | (FACILITY_NTWIN32 << 16) | ERROR_SEVERITY_ERROR); +} #define NT_TESTNULL(var) (((var) == nullptr) ? STATUS_NO_MEMORY : STATUS_SUCCESS) #define NT_TESTNULL_GLE(var) (((var) == nullptr) ? NTSTATUS_FROM_WIN32(GetLastError()) : STATUS_SUCCESS); @@ -42,7 +45,7 @@ __inline int NTSTATUS_FROM_WIN32(long x) { return x <= 0 ? (NTSTATUS)x : (NTSTAT // SafeMath #pragma prefast(push) -#pragma prefast(disable:26071, "Range violation in Intsafe. Not ours.") +#pragma prefast(disable : 26071, "Range violation in Intsafe. Not ours.") #define ENABLE_INTSAFE_SIGNED_FUNCTIONS // Only unsigned intsafe math/casts available without this def #include #pragma prefast(pop) diff --git a/src/renderer/gdi/state.cpp b/src/renderer/gdi/state.cpp index 86adbe79f..b55dc12f0 100644 --- a/src/renderer/gdi/state.cpp +++ b/src/renderer/gdi/state.cpp @@ -102,8 +102,7 @@ GdiEngine::~GdiEngine() // - hwnd - Handle to the window on which we will be drawing. // Return Value: // - S_OK if set successfully or relevant GDI error via HRESULT. -[[nodiscard]] -HRESULT GdiEngine::SetHwnd(const HWND hwnd) noexcept +[[nodiscard]] HRESULT GdiEngine::SetHwnd(const HWND hwnd) noexcept { // First attempt to get the DC and create an appropriate DC HDC const hdcRealWindow = GetDC(hwnd); @@ -155,8 +154,7 @@ HRESULT GdiEngine::SetHwnd(const HWND hwnd) noexcept // - dwNewLong - Value to update in window structure // Return Value: // - S_OK or converted HRESULT from last Win32 error from SetWindowLongW -[[nodiscard]] -HRESULT GdiEngine::s_SetWindowLongWHelper(const HWND hWnd, const int nIndex, const LONG dwNewLong) noexcept +[[nodiscard]] HRESULT GdiEngine::s_SetWindowLongWHelper(const HWND hWnd, const int nIndex, const LONG dwNewLong) noexcept { // SetWindowLong has strange error handling. On success, it returns the previous Window Long value and doesn't modify the Last Error state. // To deal with this, we set the last error to 0/S_OK first, call it, and if the previous long was 0, we check if the error was non-zero before reporting. @@ -183,12 +181,11 @@ HRESULT GdiEngine::s_SetWindowLongWHelper(const HWND hWnd, const int nIndex, con // and the hung app background painting color // Return Value: // - S_OK if set successfully or relevant GDI error via HRESULT. -[[nodiscard]] -HRESULT GdiEngine::UpdateDrawingBrushes(const COLORREF colorForeground, - const COLORREF colorBackground, - const WORD /*legacyColorAttribute*/, - const bool /*isBold*/, - const bool isSettingDefaultBrushes) noexcept +[[nodiscard]] HRESULT GdiEngine::UpdateDrawingBrushes(const COLORREF colorForeground, + const COLORREF colorBackground, + const WORD /*legacyColorAttribute*/, + const bool /*isBold*/, + const bool isSettingDefaultBrushes) noexcept { RETURN_IF_FAILED(_FlushBufferLines()); @@ -226,8 +223,7 @@ HRESULT GdiEngine::UpdateDrawingBrushes(const COLORREF colorForeground, // - Font - reference to font information where the chosen font information will be populated. // Return Value: // - S_OK if set successfully or relevant GDI error via HRESULT. -[[nodiscard]] -HRESULT GdiEngine::UpdateFont(const FontInfoDesired& FontDesired, _Out_ FontInfo& Font) noexcept +[[nodiscard]] HRESULT GdiEngine::UpdateFont(const FontInfoDesired& FontDesired, _Out_ FontInfo& Font) noexcept { wil::unique_hfont hFont; RETURN_IF_FAILED(_GetProposedFont(FontDesired, Font, _iCurrentDpi, hFont)); @@ -266,8 +262,7 @@ HRESULT GdiEngine::UpdateFont(const FontInfoDesired& FontDesired, _Out_ FontInfo // - iDpi - The Dots Per Inch to use for scaling. We will use this relative to the system default DPI defined in Windows headers as a constant. // Return Value: // - HRESULT S_OK, GDI-based error code, or safemath error -[[nodiscard]] -HRESULT GdiEngine::UpdateDpi(const int iDpi) noexcept +[[nodiscard]] HRESULT GdiEngine::UpdateDpi(const int iDpi) noexcept { _iCurrentDpi = iDpi; return S_OK; @@ -280,8 +275,7 @@ HRESULT GdiEngine::UpdateDpi(const int iDpi) noexcept // - srNewViewport - The bounds of the new viewport. // Return Value: // - HRESULT S_OK -[[nodiscard]] -HRESULT GdiEngine::UpdateViewport(const SMALL_RECT /*srNewViewport*/) noexcept +[[nodiscard]] HRESULT GdiEngine::UpdateViewport(const SMALL_RECT /*srNewViewport*/) noexcept { return S_OK; } @@ -297,8 +291,7 @@ HRESULT GdiEngine::UpdateViewport(const SMALL_RECT /*srNewViewport*/) noexcept // - iDpi - The DPI we will have when rendering // Return Value: // - S_OK if set successfully or relevant GDI error via HRESULT. -[[nodiscard]] -HRESULT GdiEngine::GetProposedFont(const FontInfoDesired& FontDesired, _Out_ FontInfo& Font, const int iDpi) noexcept +[[nodiscard]] HRESULT GdiEngine::GetProposedFont(const FontInfoDesired& FontDesired, _Out_ FontInfo& Font, const int iDpi) noexcept { wil::unique_hfont hFont; return _GetProposedFont(FontDesired, Font, iDpi, hFont); @@ -311,11 +304,10 @@ HRESULT GdiEngine::GetProposedFont(const FontInfoDesired& FontDesired, _Out_ Fon // - newTitle: the new string to use for the title of the window // Return Value: // - S_OK if PostMessageW succeeded, otherwise E_FAIL -[[nodiscard]] -HRESULT GdiEngine::_DoUpdateTitle(_In_ const std::wstring& /*newTitle*/) noexcept +[[nodiscard]] HRESULT GdiEngine::_DoUpdateTitle(_In_ const std::wstring& /*newTitle*/) noexcept { // the CM_UPDATE_TITLE handler in windowproc will query the updated title. - return PostMessageW(_hwndTargetWindow, CM_UPDATE_TITLE, 0, (LPARAM)nullptr)? S_OK : E_FAIL; + return PostMessageW(_hwndTargetWindow, CM_UPDATE_TITLE, 0, (LPARAM) nullptr) ? S_OK : E_FAIL; } // Routine Description: @@ -330,11 +322,10 @@ HRESULT GdiEngine::_DoUpdateTitle(_In_ const std::wstring& /*newTitle*/) noexcep // - hFont - A smart pointer to receive a handle to a ready-to-use GDI font. // Return Value: // - S_OK if set successfully or relevant GDI error via HRESULT. -[[nodiscard]] -HRESULT GdiEngine::_GetProposedFont(const FontInfoDesired& FontDesired, - _Out_ FontInfo& Font, - const int iDpi, - _Inout_ wil::unique_hfont& hFont) noexcept +[[nodiscard]] HRESULT GdiEngine::_GetProposedFont(const FontInfoDesired& FontDesired, + _Out_ FontInfo& Font, + const int iDpi, + _Inout_ wil::unique_hfont& hFont) noexcept { wil::unique_hdc hdcTemp(CreateCompatibleDC(_hdcMemoryContext)); RETURN_HR_IF_NULL(E_FAIL, hdcTemp.get()); @@ -347,9 +338,9 @@ HRESULT GdiEngine::_GetProposedFont(const FontInfoDesired& FontDesired, { // We're being asked for the default raster font, which gets special handling. In particular, it's the font // returned by GetStockObject(OEM_FIXED_FONT). - // We do this because, for instance, if we ask GDI for an 8x12 OEM_FIXED_FONT, + // We do this because, for instance, if we ask GDI for an 8x12 OEM_FIXED_FONT, // it may very well decide to choose Courier New instead of the Terminal raster. -#pragma prefast(suppress:38037, "raster fonts get special handling, we need to get it this way") +#pragma prefast(suppress : 38037, "raster fonts get special handling, we need to get it this way") hFont.reset((HFONT)GetStockObject(OEM_FIXED_FONT)); } else @@ -390,7 +381,7 @@ HRESULT GdiEngine::_GetProposedFont(const FontInfoDesired& FontDesired, else { CHARSETINFO csi; - if (!TranslateCharsetInfo((DWORD *)IntToPtr(FontDesired.GetCodePage()), &csi, TCI_SRCCODEPAGE)) + if (!TranslateCharsetInfo((DWORD*)IntToPtr(FontDesired.GetCodePage()), &csi, TCI_SRCCODEPAGE)) { // if we failed to translate from codepage to charset, choose our charset depending on what kind of font we're // dealing with. Raster Fonts need to be presented with the OEM charset, while TT fonts need to be ANSI. @@ -476,8 +467,7 @@ HRESULT GdiEngine::_GetProposedFont(const FontInfoDesired& FontDesired, // - pFontSize - recieves the current X by Y size of the font. // Return Value: // - S_OK -[[nodiscard]] -HRESULT GdiEngine::GetFontSize(_Out_ COORD* const pFontSize) noexcept +[[nodiscard]] HRESULT GdiEngine::GetFontSize(_Out_ COORD* const pFontSize) noexcept { *pFontSize = _GetFontSize(); return S_OK; @@ -526,5 +516,5 @@ bool GdiEngine::_IsFontTrueType() const bool GdiEngine::_IsWindowValid() const { return _hwndTargetWindow != INVALID_HANDLE_VALUE && - _hwndTargetWindow != nullptr; + _hwndTargetWindow != nullptr; } diff --git a/src/renderer/gdi/tool/main.cpp b/src/renderer/gdi/tool/main.cpp index c68011daf..1317fbbe4 100644 --- a/src/renderer/gdi/tool/main.cpp +++ b/src/renderer/gdi/tool/main.cpp @@ -3,7 +3,7 @@ #include #include "wincon.h" -int CALLBACK EnumFontFamiliesExProc( ENUMLOGFONTEX *lpelfe, NEWTEXTMETRICEX *lpntme, int FontType, LPARAM lParam ) +int CALLBACK EnumFontFamiliesExProc(ENUMLOGFONTEX* lpelfe, NEWTEXTMETRICEX* lpntme, int FontType, LPARAM lParam) { lParam; FontType; @@ -13,7 +13,7 @@ int CALLBACK EnumFontFamiliesExProc( ENUMLOGFONTEX *lpelfe, NEWTEXTMETRICEX *lpn { // skip non-monospace fonts // NOTE: this is weird/backwards and the presence of this flag means non-monospace and the absence means monospace. - return 1; + return 1; } if (lpelfe->elfFullName[0] == L'@') @@ -25,7 +25,7 @@ int CALLBACK EnumFontFamiliesExProc( ENUMLOGFONTEX *lpelfe, NEWTEXTMETRICEX *lpn { return 1; // skip device type fonts. we're only going to do raster and truetype. } - + if (FontType & RASTER_FONTTYPE) { if (wcscmp(lpelfe->elfFullName, L"Terminal") != 0) @@ -42,12 +42,12 @@ int CALLBACK EnumFontFamiliesExProc( ENUMLOGFONTEX *lpelfe, NEWTEXTMETRICEX *lpn return 1; } - int __cdecl wmain( int argc, wchar_t** argv ) +int __cdecl wmain(int argc, wchar_t** argv) { argc; argv; - HDC hDC = GetDC( NULL ); + HDC hDC = GetDC(NULL); /*LOGFONTW lf = { 0, 0, 0, 0, 0, 0, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 0, L"Courier New" };*/ @@ -57,8 +57,7 @@ int CALLBACK EnumFontFamiliesExProc( ENUMLOGFONTEX *lpelfe, NEWTEXTMETRICEX *lpn lf.lfFaceName[0] = L'\0'; // enumerate all font names lf.lfPitchAndFamily = 0; // required by API. - - EnumFontFamiliesExW( hDC, &lf, (FONTENUMPROC)EnumFontFamiliesExProc, 0, 0 ); - ReleaseDC( NULL, hDC ); + EnumFontFamiliesExW(hDC, &lf, (FONTENUMPROC)EnumFontFamiliesExProc, 0, 0); + ReleaseDC(NULL, hDC); return 0; } diff --git a/src/renderer/inc/FontInfo.hpp b/src/renderer/inc/FontInfo.hpp index 0afc8fbf4..db92a23f3 100644 --- a/src/renderer/inc/FontInfo.hpp +++ b/src/renderer/inc/FontInfo.hpp @@ -35,7 +35,7 @@ public: const UINT uiCodePage, const bool fSetDefaultRasterFont = false); - FontInfo(const FontInfo &fiFont); + FontInfo(const FontInfo& fiFont); COORD GetSize() const; COORD GetUnscaledSize() const; @@ -62,5 +62,4 @@ private: bool operator==(const FontInfo& a, const FontInfo& b); - // SET AND UNSET CONSOLE_OEMFONT_DISPLAY unless we can get rid of the stupid recoding in the conhost side. diff --git a/src/renderer/inc/FontInfoBase.hpp b/src/renderer/inc/FontInfoBase.hpp index 1f3906adf..c36030d0b 100644 --- a/src/renderer/inc/FontInfoBase.hpp +++ b/src/renderer/inc/FontInfoBase.hpp @@ -32,7 +32,7 @@ public: const bool fSetDefaultRasterFont, const UINT uiCodePage); - FontInfoBase(const FontInfoBase &fibFont); + FontInfoBase(const FontInfoBase& fibFont); ~FontInfoBase(); diff --git a/src/renderer/inc/FontInfoDesired.hpp b/src/renderer/inc/FontInfoDesired.hpp index b64464307..31ef88e75 100644 --- a/src/renderer/inc/FontInfoDesired.hpp +++ b/src/renderer/inc/FontInfoDesired.hpp @@ -21,7 +21,6 @@ Author(s): #include "FontInfoBase.hpp" #include "FontInfo.hpp" - class FontInfoDesired : public FontInfoBase { public: @@ -31,7 +30,7 @@ public: const COORD coordSizeDesired, const UINT uiCodePage); - FontInfoDesired(const FontInfo &fiFont); + FontInfoDesired(const FontInfo& fiFont); COORD GetEngineSize() const; bool IsDefaultRasterFont() const; diff --git a/src/renderer/inc/IFontDefaultList.hpp b/src/renderer/inc/IFontDefaultList.hpp index c889f9a22..d3100ec42 100644 --- a/src/renderer/inc/IFontDefaultList.hpp +++ b/src/renderer/inc/IFontDefaultList.hpp @@ -18,9 +18,8 @@ namespace Microsoft::Console::Render class IFontDefaultList { public: - [[nodiscard]] - virtual HRESULT RetrieveDefaultFontNameForCodepage(const UINT uiCodePage, - _Out_writes_(cchFaceName) PWSTR pwszFaceName, - const size_t cchFaceName) = 0; + [[nodiscard]] virtual HRESULT RetrieveDefaultFontNameForCodepage(const UINT uiCodePage, + _Out_writes_(cchFaceName) PWSTR pwszFaceName, + const size_t cchFaceName) = 0; }; } diff --git a/src/renderer/inc/IRenderEngine.hpp b/src/renderer/inc/IRenderEngine.hpp index d87ba4154..2399ab6a3 100644 --- a/src/renderer/inc/IRenderEngine.hpp +++ b/src/renderer/inc/IRenderEngine.hpp @@ -23,7 +23,6 @@ namespace Microsoft::Console::Render class IRenderEngine { public: - enum GridLines { None = 0x0, @@ -65,83 +64,57 @@ namespace Microsoft::Console::Render virtual ~IRenderEngine() = 0; - [[nodiscard]] - virtual HRESULT StartPaint() noexcept = 0; - [[nodiscard]] - virtual HRESULT EndPaint() noexcept = 0; - [[nodiscard]] - virtual HRESULT Present() noexcept = 0; + [[nodiscard]] virtual HRESULT StartPaint() noexcept = 0; + [[nodiscard]] virtual HRESULT EndPaint() noexcept = 0; + [[nodiscard]] virtual HRESULT Present() noexcept = 0; - [[nodiscard]] - virtual HRESULT PrepareForTeardown(_Out_ bool* const pForcePaint) noexcept = 0; + [[nodiscard]] virtual HRESULT PrepareForTeardown(_Out_ bool* const pForcePaint) noexcept = 0; - [[nodiscard]] - virtual HRESULT ScrollFrame() noexcept = 0; + [[nodiscard]] virtual HRESULT ScrollFrame() noexcept = 0; - [[nodiscard]] - virtual HRESULT Invalidate(const SMALL_RECT* const psrRegion) noexcept = 0; - [[nodiscard]] - virtual HRESULT InvalidateCursor(const COORD* const pcoordCursor) noexcept = 0; - [[nodiscard]] - virtual HRESULT InvalidateSystem(const RECT* const prcDirtyClient) noexcept = 0; - [[nodiscard]] - virtual HRESULT InvalidateSelection(const std::vector& rectangles) noexcept = 0; - [[nodiscard]] - virtual HRESULT InvalidateScroll(const COORD* const pcoordDelta) noexcept = 0; - [[nodiscard]] - virtual HRESULT InvalidateAll() noexcept = 0; - [[nodiscard]] - virtual HRESULT InvalidateCircling(_Out_ bool* const pForcePaint) noexcept = 0; + [[nodiscard]] virtual HRESULT Invalidate(const SMALL_RECT* const psrRegion) noexcept = 0; + [[nodiscard]] virtual HRESULT InvalidateCursor(const COORD* const pcoordCursor) noexcept = 0; + [[nodiscard]] virtual HRESULT InvalidateSystem(const RECT* const prcDirtyClient) noexcept = 0; + [[nodiscard]] virtual HRESULT InvalidateSelection(const std::vector& rectangles) noexcept = 0; + [[nodiscard]] virtual HRESULT InvalidateScroll(const COORD* const pcoordDelta) noexcept = 0; + [[nodiscard]] virtual HRESULT InvalidateAll() noexcept = 0; + [[nodiscard]] virtual HRESULT InvalidateCircling(_Out_ bool* const pForcePaint) noexcept = 0; - [[nodiscard]] - virtual HRESULT InvalidateTitle(const std::wstring& proposedTitle) noexcept = 0; + [[nodiscard]] virtual HRESULT InvalidateTitle(const std::wstring& proposedTitle) noexcept = 0; - [[nodiscard]] - virtual HRESULT PaintBackground() noexcept = 0; - [[nodiscard]] - virtual HRESULT PaintBufferLine(std::basic_string_view const clusters, - const COORD coord, - const bool fTrimLeft) noexcept = 0; - [[nodiscard]] - virtual HRESULT PaintBufferGridLines(const GridLines lines, - const COLORREF color, - const size_t cchLine, - const COORD coordTarget) noexcept = 0; - [[nodiscard]] - virtual HRESULT PaintSelection(const SMALL_RECT rect) noexcept = 0; + [[nodiscard]] virtual HRESULT PaintBackground() noexcept = 0; + [[nodiscard]] virtual HRESULT PaintBufferLine(std::basic_string_view const clusters, + const COORD coord, + const bool fTrimLeft) noexcept = 0; + [[nodiscard]] virtual HRESULT PaintBufferGridLines(const GridLines lines, + const COLORREF color, + const size_t cchLine, + const COORD coordTarget) noexcept = 0; + [[nodiscard]] virtual HRESULT PaintSelection(const SMALL_RECT rect) noexcept = 0; - [[nodiscard]] - virtual HRESULT PaintCursor(const CursorOptions& options) noexcept = 0; + [[nodiscard]] virtual HRESULT PaintCursor(const CursorOptions& options) noexcept = 0; - [[nodiscard]] - virtual HRESULT UpdateDrawingBrushes(const COLORREF colorForeground, - const COLORREF colorBackground, - const WORD legacyColorAttribute, - const bool isBold, - const bool isSettingDefaultBrushes) noexcept = 0; - [[nodiscard]] - virtual HRESULT UpdateFont(const FontInfoDesired& FontInfoDesired, - _Out_ FontInfo& FontInfo) noexcept = 0; - [[nodiscard]] - virtual HRESULT UpdateDpi(const int iDpi) noexcept = 0; - [[nodiscard]] - virtual HRESULT UpdateViewport(const SMALL_RECT srNewViewport) noexcept = 0; + [[nodiscard]] virtual HRESULT UpdateDrawingBrushes(const COLORREF colorForeground, + const COLORREF colorBackground, + const WORD legacyColorAttribute, + const bool isBold, + const bool isSettingDefaultBrushes) noexcept = 0; + [[nodiscard]] virtual HRESULT UpdateFont(const FontInfoDesired& FontInfoDesired, + _Out_ FontInfo& FontInfo) noexcept = 0; + [[nodiscard]] virtual HRESULT UpdateDpi(const int iDpi) noexcept = 0; + [[nodiscard]] virtual HRESULT UpdateViewport(const SMALL_RECT srNewViewport) noexcept = 0; - [[nodiscard]] - virtual HRESULT GetProposedFont(const FontInfoDesired& FontInfoDesired, - _Out_ FontInfo& FontInfo, - const int iDpi) noexcept = 0; + [[nodiscard]] virtual HRESULT GetProposedFont(const FontInfoDesired& FontInfoDesired, + _Out_ FontInfo& FontInfo, + const int iDpi) noexcept = 0; virtual SMALL_RECT GetDirtyRectInChars() = 0; - [[nodiscard]] - virtual HRESULT GetFontSize(_Out_ COORD* const pFontSize) noexcept = 0; - [[nodiscard]] - virtual HRESULT IsGlyphWideByFont(const std::wstring_view glyph, _Out_ bool* const pResult) noexcept = 0; - [[nodiscard]] - virtual HRESULT UpdateTitle(const std::wstring& newTitle) noexcept = 0; + [[nodiscard]] virtual HRESULT GetFontSize(_Out_ COORD* const pFontSize) noexcept = 0; + [[nodiscard]] virtual HRESULT IsGlyphWideByFont(const std::wstring_view glyph, _Out_ bool* const pResult) noexcept = 0; + [[nodiscard]] virtual HRESULT UpdateTitle(const std::wstring& newTitle) noexcept = 0; }; - inline Microsoft::Console::Render::IRenderEngine::~IRenderEngine() { } + inline Microsoft::Console::Render::IRenderEngine::~IRenderEngine() {} } DEFINE_ENUM_FLAG_OPERATORS(Microsoft::Console::Render::IRenderEngine::GridLines) diff --git a/src/renderer/inc/IRenderTarget.hpp b/src/renderer/inc/IRenderTarget.hpp index 78f22d2f1..1d1223b12 100644 --- a/src/renderer/inc/IRenderTarget.hpp +++ b/src/renderer/inc/IRenderTarget.hpp @@ -39,6 +39,6 @@ namespace Microsoft::Console::Render virtual void TriggerTitleChange() = 0; }; - inline Microsoft::Console::Render::IRenderTarget::~IRenderTarget() { } + inline Microsoft::Console::Render::IRenderTarget::~IRenderTarget() {} } diff --git a/src/renderer/inc/IRenderThread.hpp b/src/renderer/inc/IRenderThread.hpp index 69189bd30..4a390ef31 100644 --- a/src/renderer/inc/IRenderThread.hpp +++ b/src/renderer/inc/IRenderThread.hpp @@ -24,5 +24,5 @@ namespace Microsoft::Console::Render virtual void WaitForPaintCompletionAndDisable(const DWORD dwTimeoutMs) = 0; }; - inline Microsoft::Console::Render::IRenderThread::~IRenderThread() { }; + inline Microsoft::Console::Render::IRenderThread::~IRenderThread(){}; } diff --git a/src/renderer/inc/IRenderer.hpp b/src/renderer/inc/IRenderer.hpp index e23a5d8e2..883223b09 100644 --- a/src/renderer/inc/IRenderer.hpp +++ b/src/renderer/inc/IRenderer.hpp @@ -26,8 +26,7 @@ namespace Microsoft::Console::Render public: virtual ~IRenderer() = 0; - [[nodiscard]] - virtual HRESULT PaintFrame() = 0; + [[nodiscard]] virtual HRESULT PaintFrame() = 0; virtual void TriggerSystemRedraw(const RECT* const prcDirtyClient) = 0; @@ -47,10 +46,9 @@ namespace Microsoft::Console::Render const FontInfoDesired& FontInfoDesired, _Out_ FontInfo& FontInfo) = 0; - [[nodiscard]] - virtual HRESULT GetProposedFont(const int iDpi, - const FontInfoDesired& FontInfoDesired, - _Out_ FontInfo& FontInfo) = 0; + [[nodiscard]] virtual HRESULT GetProposedFont(const int iDpi, + const FontInfoDesired& FontInfoDesired, + _Out_ FontInfo& FontInfo) = 0; virtual bool IsGlyphWideByFont(const std::wstring_view glyph) = 0; @@ -60,6 +58,6 @@ namespace Microsoft::Console::Render virtual void AddRenderEngine(_In_ IRenderEngine* const pEngine) = 0; }; - inline Microsoft::Console::Render::IRenderer::~IRenderer() { } + inline Microsoft::Console::Render::IRenderer::~IRenderer() {} } diff --git a/src/renderer/inc/RenderEngineBase.hpp b/src/renderer/inc/RenderEngineBase.hpp index 49df4d7c3..dad43c5c5 100644 --- a/src/renderer/inc/RenderEngineBase.hpp +++ b/src/renderer/inc/RenderEngineBase.hpp @@ -27,20 +27,16 @@ namespace Microsoft::Console::Render RenderEngineBase(); virtual ~RenderEngineBase() = 0; - [[nodiscard]] - HRESULT InvalidateTitle(const std::wstring& proposedTitle) noexcept override; + [[nodiscard]] HRESULT InvalidateTitle(const std::wstring& proposedTitle) noexcept override; - [[nodiscard]] - HRESULT UpdateTitle(const std::wstring& newTitle) noexcept override; + [[nodiscard]] HRESULT UpdateTitle(const std::wstring& newTitle) noexcept override; protected: - [[nodiscard]] - virtual HRESULT _DoUpdateTitle(const std::wstring& newTitle) noexcept = 0; + [[nodiscard]] virtual HRESULT _DoUpdateTitle(const std::wstring& newTitle) noexcept = 0; bool _titleChanged; std::wstring _lastFrameTitle; - }; - inline Microsoft::Console::Render::RenderEngineBase::~RenderEngineBase() { } + inline Microsoft::Console::Render::RenderEngineBase::~RenderEngineBase() {} } diff --git a/src/renderer/vt/VtSequences.cpp b/src/renderer/vt/VtSequences.cpp index ea74337c4..2990331a2 100644 --- a/src/renderer/vt/VtSequences.cpp +++ b/src/renderer/vt/VtSequences.cpp @@ -14,8 +14,7 @@ using namespace Microsoft::Console::Render; // - // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT VtEngine::_StopCursorBlinking() noexcept +[[nodiscard]] HRESULT VtEngine::_StopCursorBlinking() noexcept { return _Write("\x1b[?12l"); } @@ -27,8 +26,7 @@ HRESULT VtEngine::_StopCursorBlinking() noexcept // - // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT VtEngine::_StartCursorBlinking() noexcept +[[nodiscard]] HRESULT VtEngine::_StartCursorBlinking() noexcept { return _Write("\x1b[?12h"); } @@ -39,8 +37,7 @@ HRESULT VtEngine::_StartCursorBlinking() noexcept // - // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT VtEngine::_HideCursor() noexcept +[[nodiscard]] HRESULT VtEngine::_HideCursor() noexcept { return _Write("\x1b[?25l"); } @@ -51,8 +48,7 @@ HRESULT VtEngine::_HideCursor() noexcept // - // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT VtEngine::_ShowCursor() noexcept +[[nodiscard]] HRESULT VtEngine::_ShowCursor() noexcept { return _Write("\x1b[?25h"); } @@ -64,8 +60,7 @@ HRESULT VtEngine::_ShowCursor() noexcept // - // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT VtEngine::_EraseLine() noexcept +[[nodiscard]] HRESULT VtEngine::_EraseLine() noexcept { // The default no-param action of erase line is erase to the right. // telnet client doesn't understand the parameterized version, @@ -84,8 +79,7 @@ HRESULT VtEngine::_EraseLine() noexcept // - chars: a number of characters to erase (by overwriting with space) // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT VtEngine::_EraseCharacter(const short chars) noexcept +[[nodiscard]] HRESULT VtEngine::_EraseCharacter(const short chars) noexcept { static const std::string format = "\x1b[%dX"; @@ -98,10 +92,8 @@ HRESULT VtEngine::_EraseCharacter(const short chars) noexcept // - chars: a number of characters to move cursor right by. // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT VtEngine::_CursorForward(const short chars) noexcept +[[nodiscard]] HRESULT VtEngine::_CursorForward(const short chars) noexcept { - static const std::string format = "\x1b[%dC"; return _WriteFormattedString(&format, chars); @@ -114,8 +106,7 @@ HRESULT VtEngine::_CursorForward(const short chars) noexcept // - // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT VtEngine::_ClearScreen() noexcept +[[nodiscard]] HRESULT VtEngine::_ClearScreen() noexcept { return _Write("\x1b[2J"); } @@ -128,8 +119,7 @@ HRESULT VtEngine::_ClearScreen() noexcept // - fInsertLine: true iff we should insert the lines, false to delete them. // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT VtEngine::_InsertDeleteLine(const short sLines, const bool fInsertLine) noexcept +[[nodiscard]] HRESULT VtEngine::_InsertDeleteLine(const short sLines, const bool fInsertLine) noexcept { if (sLines <= 0) { @@ -151,8 +141,7 @@ HRESULT VtEngine::_InsertDeleteLine(const short sLines, const bool fInsertLine) // - sLines: a number of lines to insert // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT VtEngine::_DeleteLine(const short sLines) noexcept +[[nodiscard]] HRESULT VtEngine::_DeleteLine(const short sLines) noexcept { return _InsertDeleteLine(sLines, false); } @@ -164,8 +153,7 @@ HRESULT VtEngine::_DeleteLine(const short sLines) noexcept // - sLines: a number of lines to insert // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT VtEngine::_InsertLine(const short sLines) noexcept +[[nodiscard]] HRESULT VtEngine::_InsertLine(const short sLines) noexcept { return _InsertDeleteLine(sLines, true); } @@ -178,8 +166,7 @@ HRESULT VtEngine::_InsertLine(const short sLines) noexcept // - coord: Console coordinates to move the cursor to. // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT VtEngine::_CursorPosition(const COORD coord) noexcept +[[nodiscard]] HRESULT VtEngine::_CursorPosition(const COORD coord) noexcept { static const std::string cursorFormat = "\x1b[%d;%dH"; @@ -197,8 +184,7 @@ HRESULT VtEngine::_CursorPosition(const COORD coord) noexcept // - // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT VtEngine::_CursorHome() noexcept +[[nodiscard]] HRESULT VtEngine::_CursorHome() noexcept { return _Write("\x1b[H"); } @@ -209,8 +195,7 @@ HRESULT VtEngine::_CursorHome() noexcept // - isBold: If true, we'll embolden the text. Otherwise we'll debolden the text. // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT VtEngine::_SetGraphicsBoldness(const bool isBold) noexcept +[[nodiscard]] HRESULT VtEngine::_SetGraphicsBoldness(const bool isBold) noexcept { const std::string fmt = isBold ? "\x1b[1m" : "\x1b[22m"; return _Write(fmt); @@ -222,8 +207,7 @@ HRESULT VtEngine::_SetGraphicsBoldness(const bool isBold) noexcept // // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT VtEngine::_SetGraphicsDefault() noexcept +[[nodiscard]] HRESULT VtEngine::_SetGraphicsDefault() noexcept { return _Write("\x1b[m"); } @@ -235,9 +219,8 @@ HRESULT VtEngine::_SetGraphicsDefault() noexcept // - fIsForeground: true if we should emit the foreground sequence, false for background // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT VtEngine::_SetGraphicsRendition16Color(const WORD wAttr, - const bool fIsForeground) noexcept +[[nodiscard]] HRESULT VtEngine::_SetGraphicsRendition16Color(const WORD wAttr, + const bool fIsForeground) noexcept { static const std::string fmt = "\x1b[%dm"; @@ -253,12 +236,12 @@ HRESULT VtEngine::_SetGraphicsRendition16Color(const WORD wAttr, // terminals display the bright color when displaying bolded text. // By specifying the boldness and brightness seperately, we'll make sure the // terminal has an accurate representation of our buffer. - const int vtIndex = 30 - + (fIsForeground? 0 : 10) - + ((WI_IsFlagSet(wAttr, FOREGROUND_INTENSITY)) ? 60 : 0) - + (WI_IsFlagSet(wAttr, FOREGROUND_RED) ? 1 : 0) - + (WI_IsFlagSet(wAttr, FOREGROUND_GREEN) ? 2 : 0) - + (WI_IsFlagSet(wAttr, FOREGROUND_BLUE) ? 4 : 0); + const int vtIndex = 30 + + (fIsForeground ? 0 : 10) + + ((WI_IsFlagSet(wAttr, FOREGROUND_INTENSITY)) ? 60 : 0) + + (WI_IsFlagSet(wAttr, FOREGROUND_RED) ? 1 : 0) + + (WI_IsFlagSet(wAttr, FOREGROUND_GREEN) ? 2 : 0) + + (WI_IsFlagSet(wAttr, FOREGROUND_BLUE) ? 4 : 0); return _WriteFormattedString(&fmt, vtIndex); } @@ -271,13 +254,12 @@ HRESULT VtEngine::_SetGraphicsRendition16Color(const WORD wAttr, // - fIsForeground: true if we should emit the foreground sequence, false for background // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT VtEngine::_SetGraphicsRenditionRGBColor(const COLORREF color, - const bool fIsForeground) noexcept +[[nodiscard]] HRESULT VtEngine::_SetGraphicsRenditionRGBColor(const COLORREF color, + const bool fIsForeground) noexcept { const std::string fmt = fIsForeground ? - "\x1b[38;2;%d;%d;%dm" : - "\x1b[48;2;%d;%d;%dm"; + "\x1b[38;2;%d;%d;%dm" : + "\x1b[48;2;%d;%d;%dm"; DWORD const r = GetRValue(color); DWORD const g = GetGValue(color); @@ -293,8 +275,7 @@ HRESULT VtEngine::_SetGraphicsRenditionRGBColor(const COLORREF color, // - fIsForeground: true if we should emit the foreground sequence, false for background // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT VtEngine::_SetGraphicsRenditionDefaultColor(const bool fIsForeground) noexcept +[[nodiscard]] HRESULT VtEngine::_SetGraphicsRenditionDefaultColor(const bool fIsForeground) noexcept { const std::string fmt = fIsForeground ? ("\x1b[39m") : ("\x1b[49m"); @@ -308,8 +289,7 @@ HRESULT VtEngine::_SetGraphicsRenditionDefaultColor(const bool fIsForeground) no // - sHeight: number of rows the terminal should display // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT VtEngine::_ResizeWindow(const short sWidth, const short sHeight) noexcept +[[nodiscard]] HRESULT VtEngine::_ResizeWindow(const short sWidth, const short sHeight) noexcept { static const std::string resizeFormat = "\x1b[8;%d;%dt"; if (sWidth < 0 || sHeight < 0) @@ -327,8 +307,7 @@ HRESULT VtEngine::_ResizeWindow(const short sWidth, const short sHeight) noexcep // - // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT VtEngine::_RequestCursor() noexcept +[[nodiscard]] HRESULT VtEngine::_RequestCursor() noexcept { return _Write("\x1b[6n"); } @@ -339,8 +318,7 @@ HRESULT VtEngine::_RequestCursor() noexcept // - title: string to use as the new title of the window. // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT VtEngine::_ChangeTitle(_In_ const std::string& title) noexcept +[[nodiscard]] HRESULT VtEngine::_ChangeTitle(_In_ const std::string& title) noexcept { const std::string titleFormat = "\x1b]0;" + title + "\x7"; return _Write(titleFormat); @@ -352,8 +330,7 @@ HRESULT VtEngine::_ChangeTitle(_In_ const std::string& title) noexcept // - // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT VtEngine::_BeginUnderline() noexcept +[[nodiscard]] HRESULT VtEngine::_BeginUnderline() noexcept { return _Write("\x1b[4m"); } @@ -364,8 +341,7 @@ HRESULT VtEngine::_BeginUnderline() noexcept // - // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT VtEngine::_EndUnderline() noexcept +[[nodiscard]] HRESULT VtEngine::_EndUnderline() noexcept { return _Write("\x1b[24m"); } diff --git a/src/renderer/vt/WinTelnetEngine.cpp b/src/renderer/vt/WinTelnetEngine.cpp index 42fbed6b4..8278775da 100644 --- a/src/renderer/vt/WinTelnetEngine.cpp +++ b/src/renderer/vt/WinTelnetEngine.cpp @@ -18,7 +18,6 @@ WinTelnetEngine::WinTelnetEngine(_In_ wil::unique_hfile hPipe, _ColorTable(ColorTable), _cColorTable(cColorTable) { - } // Routine Description: @@ -33,12 +32,11 @@ WinTelnetEngine::WinTelnetEngine(_In_ wil::unique_hfile hPipe, // the window. Unused for VT // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT WinTelnetEngine::UpdateDrawingBrushes(const COLORREF colorForeground, - const COLORREF colorBackground, - const WORD /*legacyColorAttribute*/, - const bool isBold, - const bool /*isSettingDefaultBrushes*/) noexcept +[[nodiscard]] HRESULT WinTelnetEngine::UpdateDrawingBrushes(const COLORREF colorForeground, + const COLORREF colorBackground, + const WORD /*legacyColorAttribute*/, + const bool isBold, + const bool /*isSettingDefaultBrushes*/) noexcept { return VtEngine::_16ColorUpdateDrawingBrushes(colorForeground, colorBackground, isBold, _ColorTable, _cColorTable); } @@ -50,8 +48,7 @@ HRESULT WinTelnetEngine::UpdateDrawingBrushes(const COLORREF colorForeground, // - coord: location to move the cursor to. // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT WinTelnetEngine::_MoveCursor(COORD const coord) noexcept +[[nodiscard]] HRESULT WinTelnetEngine::_MoveCursor(COORD const coord) noexcept { HRESULT hr = S_OK; // don't try and be clever about moving the cursor. @@ -77,8 +74,7 @@ HRESULT WinTelnetEngine::_MoveCursor(COORD const coord) noexcept // - // Return Value: // - S_OK -[[nodiscard]] -HRESULT WinTelnetEngine::ScrollFrame() noexcept +[[nodiscard]] HRESULT WinTelnetEngine::ScrollFrame() noexcept { // win-telnet doesn't know anything about scroll vt sequences // every frame, we're repainitng everything, always. @@ -93,8 +89,7 @@ HRESULT WinTelnetEngine::ScrollFrame() noexcept // console would like us to move while scrolling. // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT WinTelnetEngine::InvalidateScroll(const COORD* const /*pcoordDelta*/) noexcept +[[nodiscard]] HRESULT WinTelnetEngine::InvalidateScroll(const COORD* const /*pcoordDelta*/) noexcept { // win-telnet assumes the client doesn't know anything about inserting or // deleting lines. @@ -109,8 +104,7 @@ HRESULT WinTelnetEngine::InvalidateScroll(const COORD* const /*pcoordDelta*/) no // - wstr - wstring of text to be written // Return Value: // - S_OK or suitable HRESULT error from either conversion or writing pipe. -[[nodiscard]] -HRESULT WinTelnetEngine::WriteTerminalW(_In_ const std::wstring& wstr) noexcept +[[nodiscard]] HRESULT WinTelnetEngine::WriteTerminalW(_In_ const std::wstring& wstr) noexcept { return VtEngine::_WriteTerminalAscii(wstr); } diff --git a/src/renderer/vt/WinTelnetEngine.hpp b/src/renderer/vt/WinTelnetEngine.hpp index 5329c3c59..e58841711 100644 --- a/src/renderer/vt/WinTelnetEngine.hpp +++ b/src/renderer/vt/WinTelnetEngine.hpp @@ -30,30 +30,26 @@ namespace Microsoft::Console::Render const WORD cColorTable); virtual ~WinTelnetEngine() override = default; - [[nodiscard]] - HRESULT UpdateDrawingBrushes(const COLORREF colorForeground, - const COLORREF colorBackground, - const WORD legacyColorAttribute, - const bool isBold, - const bool isSettingDefaultBrushes) noexcept override; - [[nodiscard]] - HRESULT ScrollFrame() noexcept override; + [[nodiscard]] HRESULT UpdateDrawingBrushes(const COLORREF colorForeground, + const COLORREF colorBackground, + const WORD legacyColorAttribute, + const bool isBold, + const bool isSettingDefaultBrushes) noexcept override; + [[nodiscard]] HRESULT ScrollFrame() noexcept override; - [[nodiscard]] - HRESULT InvalidateScroll(const COORD* const pcoordDelta) noexcept override; + [[nodiscard]] HRESULT InvalidateScroll(const COORD* const pcoordDelta) noexcept override; - [[nodiscard]] - HRESULT WriteTerminalW(const std::wstring& wstr) noexcept override; + [[nodiscard]] HRESULT WriteTerminalW(const std::wstring& wstr) noexcept override; + + protected: + [[nodiscard]] HRESULT _MoveCursor(const COORD coord) noexcept; -protected: - [[nodiscard]] - HRESULT _MoveCursor(const COORD coord) noexcept; private: const COLORREF* const _ColorTable; const WORD _cColorTable; - #ifdef UNIT_TESTING +#ifdef UNIT_TESTING friend class VtRendererTest; - #endif +#endif }; } diff --git a/src/renderer/vt/Xterm256Engine.cpp b/src/renderer/vt/Xterm256Engine.cpp index 6fab012dd..4ab94aacd 100644 --- a/src/renderer/vt/Xterm256Engine.cpp +++ b/src/renderer/vt/Xterm256Engine.cpp @@ -29,12 +29,11 @@ Xterm256Engine::Xterm256Engine(_In_ wil::unique_hfile hPipe, // the window. Unused for VT // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT Xterm256Engine::UpdateDrawingBrushes(const COLORREF colorForeground, - const COLORREF colorBackground, - const WORD legacyColorAttribute, - const bool isBold, - const bool /*isSettingDefaultBrushes*/) noexcept +[[nodiscard]] HRESULT Xterm256Engine::UpdateDrawingBrushes(const COLORREF colorForeground, + const COLORREF colorBackground, + const WORD legacyColorAttribute, + const bool isBold, + const bool /*isSettingDefaultBrushes*/) noexcept { //When we update the brushes, check the wAttrs to see if the LVB_UNDERSCORE // flag is there. If the state of that flag is different then our diff --git a/src/renderer/vt/Xterm256Engine.hpp b/src/renderer/vt/Xterm256Engine.hpp index 9e23ecd6c..12c959ac0 100644 --- a/src/renderer/vt/Xterm256Engine.hpp +++ b/src/renderer/vt/Xterm256Engine.hpp @@ -24,24 +24,22 @@ namespace Microsoft::Console::Render { public: Xterm256Engine(_In_ wil::unique_hfile hPipe, - const Microsoft::Console::IDefaultColorProvider& colorProvider, - const Microsoft::Console::Types::Viewport initialViewport, - _In_reads_(cColorTable) const COLORREF* const ColorTable, - const WORD cColorTable); + const Microsoft::Console::IDefaultColorProvider& colorProvider, + const Microsoft::Console::Types::Viewport initialViewport, + _In_reads_(cColorTable) const COLORREF* const ColorTable, + const WORD cColorTable); virtual ~Xterm256Engine() override = default; - [[nodiscard]] - HRESULT UpdateDrawingBrushes(const COLORREF colorForeground, - const COLORREF colorBackground, - const WORD legacyColorAttribute, - const bool isBold, - const bool isSettingDefaultBrushes) noexcept override; + [[nodiscard]] HRESULT UpdateDrawingBrushes(const COLORREF colorForeground, + const COLORREF colorBackground, + const WORD legacyColorAttribute, + const bool isBold, + const bool isSettingDefaultBrushes) noexcept override; private: - - #ifdef UNIT_TESTING +#ifdef UNIT_TESTING friend class VtRendererTest; - #endif +#endif }; } diff --git a/src/renderer/vt/XtermEngine.cpp b/src/renderer/vt/XtermEngine.cpp index 167bf570c..4c680f1b7 100644 --- a/src/renderer/vt/XtermEngine.cpp +++ b/src/renderer/vt/XtermEngine.cpp @@ -38,8 +38,7 @@ XtermEngine::XtermEngine(_In_ wil::unique_hfile hPipe, // - S_OK if we started to paint. S_FALSE if we didn't need to paint. HRESULT // error code if painting didn't start successfully, or we failed to write // the pipe. -[[nodiscard]] -HRESULT XtermEngine::StartPaint() noexcept +[[nodiscard]] HRESULT XtermEngine::StartPaint() noexcept { RETURN_IF_FAILED(VtEngine::StartPaint()); @@ -97,10 +96,8 @@ HRESULT XtermEngine::StartPaint() noexcept // - // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT XtermEngine::EndPaint() noexcept +[[nodiscard]] HRESULT XtermEngine::EndPaint() noexcept { - // MSFT:TODO:20331739 // Make sure to match the cursor visibility in the terminal to the console's // if (!_quickReturn) @@ -125,7 +122,6 @@ HRESULT XtermEngine::EndPaint() noexcept return S_OK; } - // Routine Description: // - Write a VT sequence to either start or stop underlining text. // Arguments: @@ -133,8 +129,7 @@ HRESULT XtermEngine::EndPaint() noexcept // about the underlining state of the text. // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT XtermEngine::_UpdateUnderline(const WORD legacyColorAttribute) noexcept +[[nodiscard]] HRESULT XtermEngine::_UpdateUnderline(const WORD legacyColorAttribute) noexcept { bool textUnderlined = WI_IsFlagSet(legacyColorAttribute, COMMON_LVB_UNDERSCORE); if (textUnderlined != _usingUnderLine) @@ -164,12 +159,11 @@ HRESULT XtermEngine::_UpdateUnderline(const WORD legacyColorAttribute) noexcept // the window. Unused for VT // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT XtermEngine::UpdateDrawingBrushes(const COLORREF colorForeground, - const COLORREF colorBackground, - const WORD legacyColorAttribute, - const bool isBold, - const bool /*isSettingDefaultBrushes*/) noexcept +[[nodiscard]] HRESULT XtermEngine::UpdateDrawingBrushes(const COLORREF colorForeground, + const COLORREF colorBackground, + const WORD legacyColorAttribute, + const bool isBold, + const bool /*isSettingDefaultBrushes*/) noexcept { //When we update the brushes, check the wAttrs to see if the LVB_UNDERSCORE // flag is there. If the state of that flag is different then our @@ -195,8 +189,7 @@ HRESULT XtermEngine::UpdateDrawingBrushes(const COLORREF colorForeground, // - coord: location to move the cursor to. // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT XtermEngine::_MoveCursor(COORD const coord) noexcept +[[nodiscard]] HRESULT XtermEngine::_MoveCursor(COORD const coord) noexcept { HRESULT hr = S_OK; @@ -207,7 +200,7 @@ HRESULT XtermEngine::_MoveCursor(COORD const coord) noexcept _needToDisableCursor = true; hr = _CursorHome(); } - else if (coord.X == 0 && coord.Y == (_lastText.Y+1)) + else if (coord.X == 0 && coord.Y == (_lastText.Y + 1)) { // Down one line, at the start of the line. @@ -229,13 +222,13 @@ HRESULT XtermEngine::_MoveCursor(COORD const coord) noexcept std::string seq = "\r"; hr = _Write(seq); } - else if (coord.X == _lastText.X && coord.Y == (_lastText.Y+1)) + else if (coord.X == _lastText.X && coord.Y == (_lastText.Y + 1)) { // Down one line, same X position std::string seq = "\n"; hr = _Write(seq); } - else if (coord.X == (_lastText.X-1) && coord.Y == (_lastText.Y)) + else if (coord.X == (_lastText.X - 1) && coord.Y == (_lastText.Y)) { // Back one char, same Y position std::string seq = "\b"; @@ -277,8 +270,7 @@ HRESULT XtermEngine::_MoveCursor(COORD const coord) noexcept // - // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT XtermEngine::ScrollFrame() noexcept +[[nodiscard]] HRESULT XtermEngine::ScrollFrame() noexcept { if (_scrollDelta.X != 0) { @@ -302,7 +294,7 @@ HRESULT XtermEngine::ScrollFrame() noexcept // That will cause everything to move up, by moving the viewport down. // This will let remote conhosts scroll up to see history like normal. const short bottom = _lastViewport.ToOrigin().BottomInclusive(); - hr = _MoveCursor({0, bottom}); + hr = _MoveCursor({ 0, bottom }); if (SUCCEEDED(hr)) { std::string seq = std::string(absDy, '\n'); @@ -318,7 +310,7 @@ HRESULT XtermEngine::ScrollFrame() noexcept { // Move to the top of the buffer, and insert some lines of text, to // cause the viewport contents to shift down. - hr = _MoveCursor({0, 0}); + hr = _MoveCursor({ 0, 0 }); if (SUCCEEDED(hr)) { hr = _InsertLine(absDy); @@ -337,8 +329,7 @@ HRESULT XtermEngine::ScrollFrame() noexcept // console would like us to move while scrolling. // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for safemath failure -[[nodiscard]] -HRESULT XtermEngine::InvalidateScroll(const COORD* const pcoordDelta) noexcept +[[nodiscard]] HRESULT XtermEngine::InvalidateScroll(const COORD* const pcoordDelta) noexcept { const short dx = pcoordDelta->X; const short dy = pcoordDelta->Y; @@ -367,7 +358,6 @@ HRESULT XtermEngine::InvalidateScroll(const COORD* const pcoordDelta) noexcept // Store if safemath succeeded _scrollDelta = invalidScrollNew; - } return S_OK; @@ -385,14 +375,13 @@ HRESULT XtermEngine::InvalidateScroll(const COORD* const pcoordDelta) noexcept // double-wide character. // Return Value: // - S_OK or suitable HRESULT error from writing pipe. -[[nodiscard]] -HRESULT XtermEngine::PaintBufferLine(std::basic_string_view const clusters, - const COORD coord, - const bool /*trimLeft*/) noexcept +[[nodiscard]] HRESULT XtermEngine::PaintBufferLine(std::basic_string_view const clusters, + const COORD coord, + const bool /*trimLeft*/) noexcept { return _fUseAsciiOnly ? - VtEngine::_PaintAsciiBufferLine(clusters, coord) : - VtEngine::_PaintUtf8BufferLine(clusters, coord); + VtEngine::_PaintAsciiBufferLine(clusters, coord) : + VtEngine::_PaintUtf8BufferLine(clusters, coord); } // Method Description: @@ -402,12 +391,11 @@ HRESULT XtermEngine::PaintBufferLine(std::basic_string_view const clust // - wstr - wstring of text to be written // Return Value: // - S_OK or suitable HRESULT error from either conversion or writing pipe. -[[nodiscard]] -HRESULT XtermEngine::WriteTerminalW(const std::wstring& wstr) noexcept +[[nodiscard]] HRESULT XtermEngine::WriteTerminalW(const std::wstring& wstr) noexcept { return _fUseAsciiOnly ? - VtEngine::_WriteTerminalAscii(wstr) : - VtEngine::_WriteTerminalUtf8(wstr); + VtEngine::_WriteTerminalAscii(wstr) : + VtEngine::_WriteTerminalUtf8(wstr); } // Method Description: @@ -416,8 +404,7 @@ HRESULT XtermEngine::WriteTerminalW(const std::wstring& wstr) noexcept // - newTitle: the new string to use for the title of the window // Return Value: // - S_OK -[[nodiscard]] -HRESULT XtermEngine::_DoUpdateTitle(const std::wstring& newTitle) noexcept +[[nodiscard]] HRESULT XtermEngine::_DoUpdateTitle(const std::wstring& newTitle) noexcept { // inbox telnet uses xterm-ascii as its mode. If we're in ascii mode, don't // do anything, to maintain compatibility. diff --git a/src/renderer/vt/XtermEngine.hpp b/src/renderer/vt/XtermEngine.hpp index 672d6202a..ca2f583c4 100644 --- a/src/renderer/vt/XtermEngine.hpp +++ b/src/renderer/vt/XtermEngine.hpp @@ -36,29 +36,22 @@ namespace Microsoft::Console::Render virtual ~XtermEngine() override = default; - [[nodiscard]] - HRESULT StartPaint() noexcept override; - [[nodiscard]] - HRESULT EndPaint() noexcept override; + [[nodiscard]] HRESULT StartPaint() noexcept override; + [[nodiscard]] HRESULT EndPaint() noexcept override; - [[nodiscard]] - virtual HRESULT UpdateDrawingBrushes(const COLORREF colorForeground, - const COLORREF colorBackground, - const WORD legacyColorAttribute, - const bool isBold, - const bool isSettingDefaultBrushes) noexcept override; - [[nodiscard]] - HRESULT PaintBufferLine(std::basic_string_view const clusters, - const COORD coord, - const bool trimLeft) noexcept override; - [[nodiscard]] - HRESULT ScrollFrame() noexcept override; + [[nodiscard]] virtual HRESULT UpdateDrawingBrushes(const COLORREF colorForeground, + const COLORREF colorBackground, + const WORD legacyColorAttribute, + const bool isBold, + const bool isSettingDefaultBrushes) noexcept override; + [[nodiscard]] HRESULT PaintBufferLine(std::basic_string_view const clusters, + const COORD coord, + const bool trimLeft) noexcept override; + [[nodiscard]] HRESULT ScrollFrame() noexcept override; - [[nodiscard]] - HRESULT InvalidateScroll(const COORD* const pcoordDelta) noexcept override; + [[nodiscard]] HRESULT InvalidateScroll(const COORD* const pcoordDelta) noexcept override; - [[nodiscard]] - HRESULT WriteTerminalW(_In_ const std::wstring& str) noexcept override; + [[nodiscard]] HRESULT WriteTerminalW(_In_ const std::wstring& str) noexcept override; protected: const COLORREF* const _ColorTable; @@ -68,17 +61,14 @@ namespace Microsoft::Console::Render bool _usingUnderLine; bool _needToDisableCursor; - [[nodiscard]] - HRESULT _MoveCursor(const COORD coord) noexcept override; + [[nodiscard]] HRESULT _MoveCursor(const COORD coord) noexcept override; - [[nodiscard]] - HRESULT _UpdateUnderline(const WORD wLegacyAttrs) noexcept; + [[nodiscard]] HRESULT _UpdateUnderline(const WORD wLegacyAttrs) noexcept; - [[nodiscard]] - HRESULT _DoUpdateTitle(const std::wstring& newTitle) noexcept override; + [[nodiscard]] HRESULT _DoUpdateTitle(const std::wstring& newTitle) noexcept override; - #ifdef UNIT_TESTING +#ifdef UNIT_TESTING friend class VtRendererTest; - #endif +#endif }; } diff --git a/src/renderer/vt/invalidate.cpp b/src/renderer/vt/invalidate.cpp index 100bb40cb..1272615ba 100644 --- a/src/renderer/vt/invalidate.cpp +++ b/src/renderer/vt/invalidate.cpp @@ -19,8 +19,7 @@ using namespace Microsoft::Console::Render; // believes is dirty // Return Value: // - S_OK -[[nodiscard]] -HRESULT VtEngine::InvalidateSystem(const RECT* const /*prcDirtyClient*/) noexcept +[[nodiscard]] HRESULT VtEngine::InvalidateSystem(const RECT* const /*prcDirtyClient*/) noexcept { return S_OK; } @@ -32,8 +31,7 @@ HRESULT VtEngine::InvalidateSystem(const RECT* const /*prcDirtyClient*/) noexcep // - rectangles - Vector of rectangles to draw, line by line // Return Value: // - S_OK -[[nodiscard]] -HRESULT VtEngine::InvalidateSelection(const std::vector& /*rectangles*/) noexcept +[[nodiscard]] HRESULT VtEngine::InvalidateSelection(const std::vector& /*rectangles*/) noexcept { // Selection shouldn't be handled bt the VT Renderer Host, it should be // handled by the client. @@ -48,8 +46,7 @@ HRESULT VtEngine::InvalidateSelection(const std::vector& /*rectangle // - psrRegion - Character region (SMALL_RECT) that has been changed // Return Value: // - S_OK, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT VtEngine::Invalidate(const SMALL_RECT* const psrRegion) noexcept +[[nodiscard]] HRESULT VtEngine::Invalidate(const SMALL_RECT* const psrRegion) noexcept { Viewport newInvalid = Viewport::FromExclusive(*psrRegion); _trace.TraceInvalidate(newInvalid); @@ -63,8 +60,7 @@ HRESULT VtEngine::Invalidate(const SMALL_RECT* const psrRegion) noexcept // - pcoordCursor - the new position of the cursor // Return Value: // - S_OK -[[nodiscard]] -HRESULT VtEngine::InvalidateCursor(const COORD* const pcoordCursor) noexcept +[[nodiscard]] HRESULT VtEngine::InvalidateCursor(const COORD* const pcoordCursor) noexcept { // If we just inherited the cursor, we're going to get an InvalidateCursor // for both where the old cursor was, and where the new cursor is @@ -90,8 +86,7 @@ HRESULT VtEngine::InvalidateCursor(const COORD* const pcoordCursor) noexcept // - // Return Value: // - S_OK, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT VtEngine::InvalidateAll() noexcept +[[nodiscard]] HRESULT VtEngine::InvalidateAll() noexcept { _trace.TraceInvalidateAll(_lastViewport.ToOrigin()); return this->_InvalidCombine(_lastViewport.ToOrigin()); @@ -105,8 +100,7 @@ HRESULT VtEngine::InvalidateAll() noexcept // - Recieves a bool indicating if we should force the repaint. // Return Value: // - S_OK -[[nodiscard]] -HRESULT VtEngine::InvalidateCircling(_Out_ bool* const pForcePaint) noexcept +[[nodiscard]] HRESULT VtEngine::InvalidateCircling(_Out_ bool* const pForcePaint) noexcept { *pForcePaint = true; @@ -125,8 +119,7 @@ HRESULT VtEngine::InvalidateCircling(_Out_ bool* const pForcePaint) noexcept // - Recieves a bool indicating if we should force the repaint. // Return Value: // - S_OK -[[nodiscard]] -HRESULT VtEngine::PrepareForTeardown(_Out_ bool* const pForcePaint) noexcept +[[nodiscard]] HRESULT VtEngine::PrepareForTeardown(_Out_ bool* const pForcePaint) noexcept { *pForcePaint = true; return S_OK; @@ -141,8 +134,7 @@ HRESULT VtEngine::PrepareForTeardown(_Out_ bool* const pForcePaint) noexcept // repainted on the next frame // Return Value: // - S_OK, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT VtEngine::_InvalidCombine(const Viewport invalid) noexcept +[[nodiscard]] HRESULT VtEngine::_InvalidCombine(const Viewport invalid) noexcept { if (!_fInvalidRectUsed) { @@ -167,8 +159,7 @@ HRESULT VtEngine::_InvalidCombine(const Viewport invalid) noexcept // - ppt - Distances by which we should move the invalid region in response to a scroll // Return Value: // - S_OK, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT VtEngine::_InvalidOffset(const COORD* const pCoord) noexcept +[[nodiscard]] HRESULT VtEngine::_InvalidOffset(const COORD* const pCoord) noexcept { if (_fInvalidRectUsed) { @@ -195,8 +186,7 @@ HRESULT VtEngine::_InvalidOffset(const COORD* const pCoord) noexcept // - // Return Value: // - S_OK, else an appropriate HRESULT for failing to allocate or safemath failure. -[[nodiscard]] -HRESULT VtEngine::_InvalidRestrict() noexcept +[[nodiscard]] HRESULT VtEngine::_InvalidRestrict() noexcept { SMALL_RECT oldInvalid = _invalidRect.ToExclusive(); diff --git a/src/renderer/vt/math.cpp b/src/renderer/vt/math.cpp index 342cdd4d2..27035bb60 100644 --- a/src/renderer/vt/math.cpp +++ b/src/renderer/vt/math.cpp @@ -35,8 +35,7 @@ SMALL_RECT VtEngine::GetDirtyRectInChars() // - pResult - recieves return value, True if it is full-width (2 wide). False if it is half-width (1 wide). // Return Value: // - S_FALSE: This is unsupported by the VT Renderer and should use another engine's value. -[[nodiscard]] -HRESULT VtEngine::IsGlyphWideByFont(const std::wstring_view /*glyph*/, _Out_ bool* const pResult) noexcept +[[nodiscard]] HRESULT VtEngine::IsGlyphWideByFont(const std::wstring_view /*glyph*/, _Out_ bool* const pResult) noexcept { *pResult = false; return S_FALSE; @@ -78,10 +77,8 @@ bool VtEngine::_WillWriteSingleChar() const // Either the next character to the right or the immediately previous // character should follow this code path // (The immediate previous character would suggest a backspace) - bool invalidIsNext = (_srcInvalid.Top == _lastText.Y) - && (_srcInvalid.Left == _lastText.X); - bool invalidIsLast = (_srcInvalid.Top == _lastText.Y) - && (_srcInvalid.Left == (_lastText.X-1)); + bool invalidIsNext = (_srcInvalid.Top == _lastText.Y) && (_srcInvalid.Left == _lastText.X); + bool invalidIsLast = (_srcInvalid.Top == _lastText.Y) && (_srcInvalid.Left == (_lastText.X - 1)); return noScrollDelta && invalidIsOneChar && (invalidIsNext || invalidIsLast); } diff --git a/src/renderer/vt/paint.cpp b/src/renderer/vt/paint.cpp index 13c64fc42..bc1a7f9fb 100644 --- a/src/renderer/vt/paint.cpp +++ b/src/renderer/vt/paint.cpp @@ -18,8 +18,7 @@ using namespace Microsoft::Console::Types; // Return Value: // - S_OK if we started to paint. S_FALSE if we didn't need to paint. // HRESULT error code if painting didn't start successfully. -[[nodiscard]] -HRESULT VtEngine::StartPaint() noexcept +[[nodiscard]] HRESULT VtEngine::StartPaint() noexcept { if (_pipeBroken) { @@ -28,9 +27,9 @@ HRESULT VtEngine::StartPaint() noexcept // If there's nothing to do, quick return bool somethingToDo = _fInvalidRectUsed || - (_scrollDelta.X != 0 || _scrollDelta.Y != 0) || - _cursorMoved || - _titleChanged; + (_scrollDelta.X != 0 || _scrollDelta.Y != 0) || + _cursorMoved || + _titleChanged; _quickReturn = !somethingToDo; _trace.TraceStartPaint(_quickReturn, _fInvalidRectUsed, _invalidRect, _lastViewport, _scrollDelta, _cursorMoved); @@ -47,14 +46,13 @@ HRESULT VtEngine::StartPaint() noexcept // - // Return Value: // - S_OK, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT VtEngine::EndPaint() noexcept +[[nodiscard]] HRESULT VtEngine::EndPaint() noexcept { _trace.TraceEndPaint(); _invalidRect = Viewport::Empty(); _fInvalidRectUsed = false; - _scrollDelta = {0}; + _scrollDelta = { 0 }; _clearedAllThisFrame = false; _cursorMoved = false; _firstPaint = false; @@ -92,8 +90,7 @@ HRESULT VtEngine::EndPaint() noexcept // - // Return Value: // - S_FALSE since we do nothing. -[[nodiscard]] -HRESULT VtEngine::Present() noexcept +[[nodiscard]] HRESULT VtEngine::Present() noexcept { return S_FALSE; } @@ -104,8 +101,7 @@ HRESULT VtEngine::Present() noexcept // - // Return Value: // - S_OK -[[nodiscard]] -HRESULT VtEngine::PaintBackground() noexcept +[[nodiscard]] HRESULT VtEngine::PaintBackground() noexcept { return S_OK; } @@ -121,10 +117,9 @@ HRESULT VtEngine::PaintBackground() noexcept // double-wide character. // Return Value: // - S_OK or suitable HRESULT error from writing pipe. -[[nodiscard]] -HRESULT VtEngine::PaintBufferLine(std::basic_string_view const clusters, - const COORD coord, - const bool /*trimLeft*/) noexcept +[[nodiscard]] HRESULT VtEngine::PaintBufferLine(std::basic_string_view const clusters, + const COORD coord, + const bool /*trimLeft*/) noexcept { return VtEngine::_PaintAsciiBufferLine(clusters, coord); } @@ -138,11 +133,10 @@ HRESULT VtEngine::PaintBufferLine(std::basic_string_view const clusters // - coordTarget - The starting X/Y position of the first character to draw on. // Return Value: // - S_OK -[[nodiscard]] -HRESULT VtEngine::PaintBufferGridLines(const GridLines /*lines*/, - const COLORREF /*color*/, - const size_t /*cchLine*/, - const COORD /*coordTarget*/) noexcept +[[nodiscard]] HRESULT VtEngine::PaintBufferGridLines(const GridLines /*lines*/, + const COLORREF /*color*/, + const size_t /*cchLine*/, + const COORD /*coordTarget*/) noexcept { return S_OK; } @@ -153,8 +147,7 @@ HRESULT VtEngine::PaintBufferGridLines(const GridLines /*lines*/, // - options - Options that affect the presentation of the cursor // Return Value: // - S_OK or suitable HRESULT error from writing pipe. -[[nodiscard]] -HRESULT VtEngine::PaintCursor(const IRenderEngine::CursorOptions& options) noexcept +[[nodiscard]] HRESULT VtEngine::PaintCursor(const IRenderEngine::CursorOptions& options) noexcept { // MSFT:15933349 - Send the terminal the updated cursor information, if it's changed. LOG_IF_FAILED(_MoveCursor(options.coordCursor)); @@ -172,8 +165,7 @@ HRESULT VtEngine::PaintCursor(const IRenderEngine::CursorOptions& options) noexc // - rect - Rectangle to invert or highlight to make the selection area // Return Value: // - S_OK -[[nodiscard]] -HRESULT VtEngine::PaintSelection(const SMALL_RECT /*rect*/) noexcept +[[nodiscard]] HRESULT VtEngine::PaintSelection(const SMALL_RECT /*rect*/) noexcept { return S_OK; } @@ -186,12 +178,11 @@ HRESULT VtEngine::PaintSelection(const SMALL_RECT /*rect*/) noexcept // - colorBackground: The RGB Color to use to paint the background of the text. // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT VtEngine::_RgbUpdateDrawingBrushes(const COLORREF colorForeground, - const COLORREF colorBackground, - const bool isBold, - _In_reads_(cColorTable) const COLORREF* const ColorTable, - const WORD cColorTable) noexcept +[[nodiscard]] HRESULT VtEngine::_RgbUpdateDrawingBrushes(const COLORREF colorForeground, + const COLORREF colorBackground, + const bool isBold, + _In_reads_(cColorTable) const COLORREF* const ColorTable, + const WORD cColorTable) noexcept { const bool fgChanged = colorForeground != _LastFG; const bool bgChanged = colorBackground != _LastBG; @@ -273,14 +264,12 @@ HRESULT VtEngine::_RgbUpdateDrawingBrushes(const COLORREF colorForeground, // - cColorTable: size of the color table. // Return Value: // - S_OK if we succeeded, else an appropriate HRESULT for failing to allocate or write. -[[nodiscard]] -HRESULT VtEngine::_16ColorUpdateDrawingBrushes(const COLORREF colorForeground, - const COLORREF colorBackground, - const bool isBold, - _In_reads_(cColorTable) const COLORREF* const ColorTable, - const WORD cColorTable) noexcept +[[nodiscard]] HRESULT VtEngine::_16ColorUpdateDrawingBrushes(const COLORREF colorForeground, + const COLORREF colorBackground, + const bool isBold, + _In_reads_(cColorTable) const COLORREF* const ColorTable, + const WORD cColorTable) noexcept { - const bool fgChanged = colorForeground != _LastFG; const bool bgChanged = colorBackground != _LastBG; const bool fgIsDefault = colorForeground == _colorProvider.GetDefaultForeground(); @@ -325,7 +314,6 @@ HRESULT VtEngine::_16ColorUpdateDrawingBrushes(const COLORREF colorForeground, _LastBG = colorBackground; } - } return S_OK; @@ -345,9 +333,8 @@ HRESULT VtEngine::_16ColorUpdateDrawingBrushes(const COLORREF colorForeground, // - coord - character coordinate target to render within viewport // Return Value: // - S_OK or suitable HRESULT error from writing pipe. -[[nodiscard]] -HRESULT VtEngine::_PaintAsciiBufferLine(std::basic_string_view const clusters, - const COORD coord) noexcept +[[nodiscard]] HRESULT VtEngine::_PaintAsciiBufferLine(std::basic_string_view const clusters, + const COORD coord) noexcept { try { @@ -381,9 +368,8 @@ HRESULT VtEngine::_PaintAsciiBufferLine(std::basic_string_view const cl // - coord - character coordinate target to render within viewport // Return Value: // - S_OK or suitable HRESULT error from writing pipe. -[[nodiscard]] -HRESULT VtEngine::_PaintUtf8BufferLine(std::basic_string_view const clusters, - const COORD coord) noexcept +[[nodiscard]] HRESULT VtEngine::_PaintUtf8BufferLine(std::basic_string_view const clusters, + const COORD coord) noexcept { if (coord.Y < _virtualTop) { @@ -452,12 +438,12 @@ HRESULT VtEngine::_PaintUtf8BufferLine(std::basic_string_view const clu // frame, don't add spaces at the end. const bool removeSpaces = (useEraseChar || (_clearedAllThisFrame) || (_newBottomLine)); const size_t cchActual = removeSpaces ? - (cchLine - numSpaces) : - cchLine; + (cchLine - numSpaces) : + cchLine; const size_t columnsActual = removeSpaces ? - (totalWidth - numSpaces) : - totalWidth; + (totalWidth - numSpaces) : + totalWidth; // Write the actual text string std::wstring wstr = std::wstring(unclusteredString.data(), cchActual); @@ -531,8 +517,7 @@ HRESULT VtEngine::_PaintUtf8BufferLine(std::basic_string_view const clu // - newTitle: the new string to use for the title of the window // Return Value: // - S_OK -[[nodiscard]] -HRESULT VtEngine::_DoUpdateTitle(const std::wstring& /*newTitle*/) noexcept +[[nodiscard]] HRESULT VtEngine::_DoUpdateTitle(const std::wstring& /*newTitle*/) noexcept { return S_OK; } diff --git a/src/renderer/vt/precomp.h b/src/renderer/vt/precomp.h index d315838c7..4e463adb2 100644 --- a/src/renderer/vt/precomp.h +++ b/src/renderer/vt/precomp.h @@ -24,12 +24,15 @@ Abstract: typedef _Return_type_success_(return >= 0) long NTSTATUS; #endif -#define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0) +#define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0) //#include -#define STATUS_SUCCESS ((NTSTATUS)0x00000000L) // ntsubauth -#define FACILITY_NTWIN32 0x7 -__inline int NTSTATUS_FROM_WIN32(long x) { return x <= 0 ? (NTSTATUS)x : (NTSTATUS)(((x) & 0x0000FFFF) | (FACILITY_NTWIN32 << 16) | ERROR_SEVERITY_ERROR); } +#define STATUS_SUCCESS ((NTSTATUS)0x00000000L) // ntsubauth +#define FACILITY_NTWIN32 0x7 +__inline int NTSTATUS_FROM_WIN32(long x) +{ + return x <= 0 ? (NTSTATUS)x : (NTSTATUS)(((x)&0x0000FFFF) | (FACILITY_NTWIN32 << 16) | ERROR_SEVERITY_ERROR); +} #define NT_TESTNULL(var) (((var) == nullptr) ? STATUS_NO_MEMORY : STATUS_SUCCESS) #define NT_TESTNULL_GLE(var) (((var) == nullptr) ? NTSTATUS_FROM_WIN32(GetLastError()) : STATUS_SUCCESS); @@ -42,8 +45,7 @@ __inline int NTSTATUS_FROM_WIN32(long x) { return x <= 0 ? (NTSTATUS)x : (NTSTAT // SafeMath #pragma prefast(push) -#pragma prefast(disable:26071, "Range violation in Intsafe. Not ours.") +#pragma prefast(disable : 26071, "Range violation in Intsafe. Not ours.") #define ENABLE_INTSAFE_SIGNED_FUNCTIONS // Only unsigned intsafe math/casts available without this def #include #pragma prefast(pop) - diff --git a/src/renderer/vt/state.cpp b/src/renderer/vt/state.cpp index 2fa50643d..d2b26bc2f 100644 --- a/src/renderer/vt/state.cpp +++ b/src/renderer/vt/state.cpp @@ -16,7 +16,7 @@ using namespace Microsoft::Console; using namespace Microsoft::Console::Render; using namespace Microsoft::Console::Types; -const COORD VtEngine::INVALID_COORDS = {-1, -1}; +const COORD VtEngine::INVALID_COORDS = { -1, -1 }; // Routine Description: // - Creates a new VT-based rendering engine @@ -37,9 +37,9 @@ VtEngine::VtEngine(_In_ wil::unique_hfile pipe, _lastViewport(initialViewport), _invalidRect(Viewport::Empty()), _fInvalidRectUsed(false), - _lastRealCursor({0}), - _lastText({0}), - _scrollDelta({0}), + _lastRealCursor({ 0 }), + _lastText({ 0 }), + _scrollDelta({ 0 }), _quickReturn(false), _clearedAllThisFrame(false), _cursorMoved(false), @@ -54,7 +54,7 @@ VtEngine::VtEngine(_In_ wil::unique_hfile pipe, _terminalOwner{ nullptr }, _newBottomLine{ false }, _deferredCursorPos{ INVALID_COORDS }, - _trace {} + _trace{} { #ifndef UNIT_TESTING // When unit testing, we can instantiate a VtEngine without a pipe. @@ -73,8 +73,7 @@ VtEngine::VtEngine(_In_ wil::unique_hfile pipe, // - str: The buffer to write to the pipe. Might have nulls in it. // Return Value: // - S_OK or suitable HRESULT error from writing pipe. -[[nodiscard]] -HRESULT VtEngine::_Write(std::string_view const str) noexcept +[[nodiscard]] HRESULT VtEngine::_Write(std::string_view const str) noexcept { _trace.TraceString(str); #ifdef UNIT_TESTING @@ -94,8 +93,7 @@ HRESULT VtEngine::_Write(std::string_view const str) noexcept CATCH_RETURN(); } -[[nodiscard]] -HRESULT VtEngine::_Flush() noexcept +[[nodiscard]] HRESULT VtEngine::_Flush() noexcept { #ifdef UNIT_TESTING if (_hFile.get() == INVALID_HANDLE_VALUE) @@ -126,8 +124,7 @@ HRESULT VtEngine::_Flush() noexcept // Method Description: // - Wrapper for ITerminalOutputConnection. See _Write. -[[nodiscard]] -HRESULT VtEngine::WriteTerminalUtf8(const std::string& str) noexcept +[[nodiscard]] HRESULT VtEngine::WriteTerminalUtf8(const std::string& str) noexcept { return _Write(str); } @@ -139,8 +136,7 @@ HRESULT VtEngine::WriteTerminalUtf8(const std::string& str) noexcept // - wstr - wstring of text to be written // Return Value: // - S_OK or suitable HRESULT error from either conversion or writing pipe. -[[nodiscard]] -HRESULT VtEngine::_WriteTerminalUtf8(const std::wstring& wstr) noexcept +[[nodiscard]] HRESULT VtEngine::_WriteTerminalUtf8(const std::wstring& wstr) noexcept { try { @@ -159,14 +155,13 @@ HRESULT VtEngine::_WriteTerminalUtf8(const std::wstring& wstr) noexcept // - wstr - wstring of text to be written // Return Value: // - S_OK or suitable HRESULT error from writing pipe. -[[nodiscard]] -HRESULT VtEngine::_WriteTerminalAscii(const std::wstring& wstr) noexcept +[[nodiscard]] HRESULT VtEngine::_WriteTerminalAscii(const std::wstring& wstr) noexcept { const size_t cchActual = wstr.length(); std::string needed; needed.reserve(wstr.size()); - + for (const auto& wch : wstr) { // We're explicitly replacing characters outside ASCII with a ? because @@ -186,10 +181,8 @@ HRESULT VtEngine::_WriteTerminalAscii(const std::wstring& wstr) noexcept // Return Value: // - S_OK, E_INVALIDARG for a invalid format string, or suitable HRESULT error // from writing pipe. -[[nodiscard]] -HRESULT VtEngine::_WriteFormattedString(const std::string* const pFormat, ...) noexcept +[[nodiscard]] HRESULT VtEngine::_WriteFormattedString(const std::string* const pFormat, ...) noexcept { - HRESULT hr = E_FAIL; va_list argList; va_start(argList, pFormat); @@ -221,9 +214,8 @@ HRESULT VtEngine::_WriteFormattedString(const std::string* const pFormat, ...) n // - Font - reference to font information where the chosen font information will be populated. // Return Value: // - HRESULT S_OK -[[nodiscard]] -HRESULT VtEngine::UpdateFont(const FontInfoDesired& /*pfiFontDesired*/, - _Out_ FontInfo& /*pfiFont*/) noexcept +[[nodiscard]] HRESULT VtEngine::UpdateFont(const FontInfoDesired& /*pfiFontDesired*/, + _Out_ FontInfo& /*pfiFont*/) noexcept { return S_OK; } @@ -236,8 +228,7 @@ HRESULT VtEngine::UpdateFont(const FontInfoDesired& /*pfiFontDesired*/, // the system default DPI defined in Windows headers as a constant. // Return Value: // - HRESULT S_OK -[[nodiscard]] -HRESULT VtEngine::UpdateDpi(const int /*iDpi*/) noexcept +[[nodiscard]] HRESULT VtEngine::UpdateDpi(const int /*iDpi*/) noexcept { return S_OK; } @@ -250,8 +241,7 @@ HRESULT VtEngine::UpdateDpi(const int /*iDpi*/) noexcept // - srNewViewport - The bounds of the new viewport. // Return Value: // - HRESULT S_OK -[[nodiscard]] -HRESULT VtEngine::UpdateViewport(const SMALL_RECT srNewViewport) noexcept +[[nodiscard]] HRESULT VtEngine::UpdateViewport(const SMALL_RECT srNewViewport) noexcept { HRESULT hr = S_OK; const Viewport oldView = _lastViewport; @@ -280,7 +270,7 @@ HRESULT VtEngine::UpdateViewport(const SMALL_RECT srNewViewport) noexcept if (SUCCEEDED(hr)) { // Viewport is smaller now - just update it all. - if ( oldView.Height() > newView.Height() || oldView.Width() > newView.Width() ) + if (oldView.Height() > newView.Height() || oldView.Width() > newView.Width()) { hr = InvalidateAll(); } @@ -295,7 +285,7 @@ HRESULT VtEngine::UpdateViewport(const SMALL_RECT srNewViewport) noexcept short top = 0; short right = newView.RightInclusive(); short bottom = oldView.BottomInclusive(); - Viewport rightOfOldViewport = Viewport::FromInclusive({left, top, right, bottom}); + Viewport rightOfOldViewport = Viewport::FromInclusive({ left, top, right, bottom }); hr = _InvalidCombine(rightOfOldViewport); } if (SUCCEEDED(hr) && oldView.Height() < newView.Height()) @@ -304,9 +294,8 @@ HRESULT VtEngine::UpdateViewport(const SMALL_RECT srNewViewport) noexcept short top = oldView.BottomExclusive(); short right = newView.RightInclusive(); short bottom = newView.BottomInclusive(); - Viewport belowOldViewport = Viewport::FromInclusive({left, top, right, bottom}); + Viewport belowOldViewport = Viewport::FromInclusive({ left, top, right, bottom }); hr = _InvalidCombine(belowOldViewport); - } } } @@ -326,10 +315,9 @@ HRESULT VtEngine::UpdateViewport(const SMALL_RECT srNewViewport) noexcept // - iDpi - The DPI we will have when rendering // Return Value: // - S_FALSE: This is unsupported by the VT Renderer and should use another engine's value. -[[nodiscard]] -HRESULT VtEngine::GetProposedFont(const FontInfoDesired& /*pfiFontDesired*/, - _Out_ FontInfo& /*pfiFont*/, - const int /*iDpi*/) noexcept +[[nodiscard]] HRESULT VtEngine::GetProposedFont(const FontInfoDesired& /*pfiFontDesired*/, + _Out_ FontInfo& /*pfiFont*/, + const int /*iDpi*/) noexcept { return S_FALSE; } @@ -340,10 +328,9 @@ HRESULT VtEngine::GetProposedFont(const FontInfoDesired& /*pfiFontDesired*/, // - pFontSize - recieves the current X by Y size of the font. // Return Value: // - S_FALSE: This is unsupported by the VT Renderer and should use another engine's value. -[[nodiscard]] -HRESULT VtEngine::GetFontSize(_Out_ COORD* const pFontSize) noexcept +[[nodiscard]] HRESULT VtEngine::GetFontSize(_Out_ COORD* const pFontSize) noexcept { - *pFontSize = COORD({1, 1}); + *pFontSize = COORD({ 1, 1 }); return S_FALSE; } @@ -356,7 +343,6 @@ HRESULT VtEngine::GetFontSize(_Out_ COORD* const pFontSize) noexcept // - void VtEngine::SetTestCallback(_In_ std::function pfn) { - #ifdef UNIT_TESTING _pfnTestCallback = pfn; @@ -365,7 +351,6 @@ void VtEngine::SetTestCallback(_In_ std::function // Return Value: // - S_OK -[[nodiscard]] -HRESULT VtEngine::SuppressResizeRepaint() noexcept +[[nodiscard]] HRESULT VtEngine::SuppressResizeRepaint() noexcept { _suppressResizeRepaint = true; return S_OK; @@ -404,8 +388,7 @@ HRESULT VtEngine::SuppressResizeRepaint() noexcept // - coordCursor: The cursor position to inherit from. // Return Value: // - S_OK -[[nodiscard]] -HRESULT VtEngine::InheritCursor(const COORD coordCursor) noexcept +[[nodiscard]] HRESULT VtEngine::InheritCursor(const COORD coordCursor) noexcept { _virtualTop = coordCursor.Y; _lastText = coordCursor; diff --git a/src/renderer/vt/tracing.cpp b/src/renderer/vt/tracing.cpp index c1d724960..3c5f4e0aa 100644 --- a/src/renderer/vt/tracing.cpp +++ b/src/renderer/vt/tracing.cpp @@ -6,26 +6,26 @@ #include TRACELOGGING_DEFINE_PROVIDER(g_hConsoleVtRendererTraceProvider, - "Microsoft.Windows.Console.Render.VtEngine", - // tl:{c9ba2a95-d3ca-5e19-2bd6-776a0910cb9d} - (0xc9ba2a95, 0xd3ca, 0x5e19, 0x2b, 0xd6, 0x77, 0x6a, 0x09, 0x10, 0xcb, 0x9d), - TraceLoggingOptionMicrosoftTelemetry()); + "Microsoft.Windows.Console.Render.VtEngine", + // tl:{c9ba2a95-d3ca-5e19-2bd6-776a0910cb9d} + (0xc9ba2a95, 0xd3ca, 0x5e19, 0x2b, 0xd6, 0x77, 0x6a, 0x09, 0x10, 0xcb, 0x9d), + TraceLoggingOptionMicrosoftTelemetry()); using namespace Microsoft::Console::VirtualTerminal; using namespace Microsoft::Console::Types; RenderTracing::RenderTracing() { - #ifndef UNIT_TESTING +#ifndef UNIT_TESTING TraceLoggingRegister(g_hConsoleVtRendererTraceProvider); - #endif UNIT_TESTING +#endif UNIT_TESTING } RenderTracing::~RenderTracing() { - #ifndef UNIT_TESTING +#ifndef UNIT_TESTING TraceLoggingUnregister(g_hConsoleVtRendererTraceProvider); - #endif UNIT_TESTING +#endif UNIT_TESTING } // Function Description: @@ -66,16 +66,16 @@ std::string toPrintableString(const std::string_view& inString) } void RenderTracing::TraceString(const std::string_view& instr) const { - #ifndef UNIT_TESTING +#ifndef UNIT_TESTING const std::string _seq = toPrintableString(instr); const char* const seq = _seq.c_str(); TraceLoggingWrite(g_hConsoleVtRendererTraceProvider, "VtEngine_TraceString", TraceLoggingString(seq), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE)); - #else +#else UNREFERENCED_PARAMETER(instr); - #endif UNIT_TESTING +#endif UNIT_TESTING } std::string _ViewportToString(const Viewport& view) @@ -116,42 +116,42 @@ std::string _CoordToString(const COORD& c) void RenderTracing::TraceInvalidate(const Viewport invalidRect) const { - #ifndef UNIT_TESTING +#ifndef UNIT_TESTING const auto invalidatedStr = _ViewportToString(invalidRect); const auto invalidated = invalidatedStr.c_str(); TraceLoggingWrite(g_hConsoleVtRendererTraceProvider, "VtEngine_TraceInvalidate", TraceLoggingString(invalidated), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE)); - #else +#else UNREFERENCED_PARAMETER(invalidRect); - #endif UNIT_TESTING +#endif UNIT_TESTING } void RenderTracing::TraceInvalidateAll(const Viewport viewport) const { - #ifndef UNIT_TESTING +#ifndef UNIT_TESTING const auto invalidatedStr = _ViewportToString(viewport); const auto invalidatedAll = invalidatedStr.c_str(); TraceLoggingWrite(g_hConsoleVtRendererTraceProvider, "VtEngine_TraceInvalidateAll", TraceLoggingString(invalidatedAll), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE)); - #else +#else UNREFERENCED_PARAMETER(viewport); - #endif UNIT_TESTING +#endif UNIT_TESTING } void RenderTracing::TraceTriggerCircling(const bool newFrame) const { - #ifndef UNIT_TESTING +#ifndef UNIT_TESTING TraceLoggingWrite(g_hConsoleVtRendererTraceProvider, "VtEngine_TraceTriggerCircling", TraceLoggingBool(newFrame), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE)); - #else +#else UNREFERENCED_PARAMETER(newFrame); - #endif UNIT_TESTING +#endif UNIT_TESTING } void RenderTracing::TraceStartPaint(const bool quickReturn, @@ -161,7 +161,7 @@ void RenderTracing::TraceStartPaint(const bool quickReturn, const COORD scrollDelt, const bool cursorMoved) const { - #ifndef UNIT_TESTING +#ifndef UNIT_TESTING const auto invalidatedStr = _ViewportToString(invalidRect); const auto invalidated = invalidatedStr.c_str(); const auto lastViewStr = _ViewportToString(lastViewport); @@ -177,37 +177,36 @@ void RenderTracing::TraceStartPaint(const bool quickReturn, TraceLoggingString(scrollDelta), TraceLoggingBool(cursorMoved), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE)); - #else +#else UNREFERENCED_PARAMETER(quickReturn); UNREFERENCED_PARAMETER(invalidRectUsed); UNREFERENCED_PARAMETER(invalidRect); UNREFERENCED_PARAMETER(lastViewport); UNREFERENCED_PARAMETER(scrollDelt); UNREFERENCED_PARAMETER(cursorMoved); - #endif UNIT_TESTING +#endif UNIT_TESTING } void RenderTracing::TraceEndPaint() const { - #ifndef UNIT_TESTING +#ifndef UNIT_TESTING TraceLoggingWrite(g_hConsoleVtRendererTraceProvider, "VtEngine_TraceEndPaint", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE)); - #else - #endif UNIT_TESTING +#else +#endif UNIT_TESTING } - void RenderTracing::TraceLastText(const COORD lastTextPos) const { - #ifndef UNIT_TESTING +#ifndef UNIT_TESTING const auto lastTextStr = _CoordToString(lastTextPos); const auto lastText = lastTextStr.c_str(); TraceLoggingWrite(g_hConsoleVtRendererTraceProvider, "VtEngine_TraceLastText", TraceLoggingString(lastText), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE)); - #else +#else UNREFERENCED_PARAMETER(lastTextPos); - #endif UNIT_TESTING +#endif UNIT_TESTING } diff --git a/src/renderer/vt/tracing.hpp b/src/renderer/vt/tracing.hpp index af1594d99..8d923adc8 100644 --- a/src/renderer/vt/tracing.hpp +++ b/src/renderer/vt/tracing.hpp @@ -24,7 +24,6 @@ namespace Microsoft::Console::VirtualTerminal class RenderTracing final { public: - RenderTracing(); ~RenderTracing(); void TraceString(const std::string_view& str) const; diff --git a/src/renderer/vt/vtrenderer.hpp b/src/renderer/vt/vtrenderer.hpp index 986905104..77a9c6349 100644 --- a/src/renderer/vt/vtrenderer.hpp +++ b/src/renderer/vt/vtrenderer.hpp @@ -39,88 +39,59 @@ namespace Microsoft::Console::Render virtual ~VtEngine() override = default; - [[nodiscard]] - HRESULT InvalidateSelection(const std::vector& rectangles) noexcept override; - [[nodiscard]] - virtual HRESULT InvalidateScroll(const COORD* const pcoordDelta) noexcept = 0; - [[nodiscard]] - HRESULT InvalidateSystem(const RECT* const prcDirtyClient) noexcept override; - [[nodiscard]] - HRESULT Invalidate(const SMALL_RECT* const psrRegion) noexcept override; - [[nodiscard]] - HRESULT InvalidateCursor(const COORD* const pcoordCursor) noexcept override; - [[nodiscard]] - HRESULT InvalidateAll() noexcept override; - [[nodiscard]] - HRESULT InvalidateCircling(_Out_ bool* const pForcePaint) noexcept override; - [[nodiscard]] - HRESULT PrepareForTeardown(_Out_ bool* const pForcePaint) noexcept override; + [[nodiscard]] HRESULT InvalidateSelection(const std::vector& rectangles) noexcept override; + [[nodiscard]] virtual HRESULT InvalidateScroll(const COORD* const pcoordDelta) noexcept = 0; + [[nodiscard]] HRESULT InvalidateSystem(const RECT* const prcDirtyClient) noexcept override; + [[nodiscard]] HRESULT Invalidate(const SMALL_RECT* const psrRegion) noexcept override; + [[nodiscard]] HRESULT InvalidateCursor(const COORD* const pcoordCursor) noexcept override; + [[nodiscard]] HRESULT InvalidateAll() noexcept override; + [[nodiscard]] HRESULT InvalidateCircling(_Out_ bool* const pForcePaint) noexcept override; + [[nodiscard]] HRESULT PrepareForTeardown(_Out_ bool* const pForcePaint) noexcept override; - [[nodiscard]] - virtual HRESULT StartPaint() noexcept override; - [[nodiscard]] - virtual HRESULT EndPaint() noexcept override; - [[nodiscard]] - virtual HRESULT Present() noexcept override; + [[nodiscard]] virtual HRESULT StartPaint() noexcept override; + [[nodiscard]] virtual HRESULT EndPaint() noexcept override; + [[nodiscard]] virtual HRESULT Present() noexcept override; - [[nodiscard]] - virtual HRESULT ScrollFrame() noexcept = 0; + [[nodiscard]] virtual HRESULT ScrollFrame() noexcept = 0; - [[nodiscard]] - HRESULT PaintBackground() noexcept override; - [[nodiscard]] - virtual HRESULT PaintBufferLine(std::basic_string_view const clusters, - const COORD coord, - const bool trimLeft) noexcept override; - [[nodiscard]] - HRESULT PaintBufferGridLines(const GridLines lines, - const COLORREF color, - const size_t cchLine, - const COORD coordTarget) noexcept override; - [[nodiscard]] - HRESULT PaintSelection(const SMALL_RECT rect) noexcept override; + [[nodiscard]] HRESULT PaintBackground() noexcept override; + [[nodiscard]] virtual HRESULT PaintBufferLine(std::basic_string_view const clusters, + const COORD coord, + const bool trimLeft) noexcept override; + [[nodiscard]] HRESULT PaintBufferGridLines(const GridLines lines, + const COLORREF color, + const size_t cchLine, + const COORD coordTarget) noexcept override; + [[nodiscard]] HRESULT PaintSelection(const SMALL_RECT rect) noexcept override; - [[nodiscard]] - HRESULT PaintCursor(const CursorOptions& options) noexcept override; + [[nodiscard]] HRESULT PaintCursor(const CursorOptions& options) noexcept override; - [[nodiscard]] - virtual HRESULT UpdateDrawingBrushes(const COLORREF colorForeground, - const COLORREF colorBackground, - const WORD legacyColorAttribute, - const bool isBold, - const bool isSettingDefaultBrushes) noexcept = 0; - [[nodiscard]] - HRESULT UpdateFont(const FontInfoDesired& pfiFontInfoDesired, - _Out_ FontInfo& pfiFontInfo) noexcept override; - [[nodiscard]] - HRESULT UpdateDpi(const int iDpi) noexcept override; - [[nodiscard]] - HRESULT UpdateViewport(const SMALL_RECT srNewViewport) noexcept override; + [[nodiscard]] virtual HRESULT UpdateDrawingBrushes(const COLORREF colorForeground, + const COLORREF colorBackground, + const WORD legacyColorAttribute, + const bool isBold, + const bool isSettingDefaultBrushes) noexcept = 0; + [[nodiscard]] HRESULT UpdateFont(const FontInfoDesired& pfiFontInfoDesired, + _Out_ FontInfo& pfiFontInfo) noexcept override; + [[nodiscard]] HRESULT UpdateDpi(const int iDpi) noexcept override; + [[nodiscard]] HRESULT UpdateViewport(const SMALL_RECT srNewViewport) noexcept override; - [[nodiscard]] - HRESULT GetProposedFont(const FontInfoDesired& FontDesired, - _Out_ FontInfo& Font, - const int iDpi) noexcept override; + [[nodiscard]] HRESULT GetProposedFont(const FontInfoDesired& FontDesired, + _Out_ FontInfo& Font, + const int iDpi) noexcept override; SMALL_RECT GetDirtyRectInChars() override; - [[nodiscard]] - HRESULT GetFontSize(_Out_ COORD* const pFontSize) noexcept override; - [[nodiscard]] - HRESULT IsGlyphWideByFont(const std::wstring_view glyph, _Out_ bool* const pResult) noexcept override; + [[nodiscard]] HRESULT GetFontSize(_Out_ COORD* const pFontSize) noexcept override; + [[nodiscard]] HRESULT IsGlyphWideByFont(const std::wstring_view glyph, _Out_ bool* const pResult) noexcept override; - [[nodiscard]] - HRESULT SuppressResizeRepaint() noexcept; + [[nodiscard]] HRESULT SuppressResizeRepaint() noexcept; - [[nodiscard]] - HRESULT RequestCursor() noexcept; - [[nodiscard]] - HRESULT InheritCursor(const COORD coordCursor) noexcept; + [[nodiscard]] HRESULT RequestCursor() noexcept; + [[nodiscard]] HRESULT InheritCursor(const COORD coordCursor) noexcept; - [[nodiscard]] - HRESULT WriteTerminalUtf8(const std::string& str) noexcept; + [[nodiscard]] HRESULT WriteTerminalUtf8(const std::string& str) noexcept; - [[nodiscard]] - virtual HRESULT WriteTerminalW(const std::wstring& str) noexcept = 0; + [[nodiscard]] virtual HRESULT WriteTerminalW(const std::wstring& str) noexcept = 0; void SetTerminalOwner(Microsoft::Console::ITerminalOwner* const terminalOwner); @@ -162,119 +133,81 @@ namespace Microsoft::Console::Render Microsoft::Console::VirtualTerminal::RenderTracing _trace; - [[nodiscard]] - HRESULT _Write(std::string_view const str) noexcept; - [[nodiscard]] - HRESULT _WriteFormattedString(const std::string* const pFormat, ...) noexcept; - [[nodiscard]] - HRESULT _Flush() noexcept; + [[nodiscard]] HRESULT _Write(std::string_view const str) noexcept; + [[nodiscard]] HRESULT _WriteFormattedString(const std::string* const pFormat, ...) noexcept; + [[nodiscard]] HRESULT _Flush() noexcept; void _OrRect(_Inout_ SMALL_RECT* const pRectExisting, const SMALL_RECT* const pRectToOr) const; - [[nodiscard]] - HRESULT _InvalidCombine(const Microsoft::Console::Types::Viewport invalid) noexcept; - [[nodiscard]] - HRESULT _InvalidOffset(const COORD* const ppt) noexcept; - [[nodiscard]] - HRESULT _InvalidRestrict() noexcept; + [[nodiscard]] HRESULT _InvalidCombine(const Microsoft::Console::Types::Viewport invalid) noexcept; + [[nodiscard]] HRESULT _InvalidOffset(const COORD* const ppt) noexcept; + [[nodiscard]] HRESULT _InvalidRestrict() noexcept; bool _AllIsInvalid() const; - [[nodiscard]] - HRESULT _StopCursorBlinking() noexcept; - [[nodiscard]] - HRESULT _StartCursorBlinking() noexcept; - [[nodiscard]] - HRESULT _HideCursor() noexcept; - [[nodiscard]] - HRESULT _ShowCursor() noexcept; - [[nodiscard]] - HRESULT _EraseLine() noexcept; - [[nodiscard]] - HRESULT _InsertDeleteLine(const short sLines, const bool fInsertLine) noexcept; - [[nodiscard]] - HRESULT _DeleteLine(const short sLines) noexcept; - [[nodiscard]] - HRESULT _InsertLine(const short sLines) noexcept; - [[nodiscard]] - HRESULT _CursorForward(const short chars) noexcept; - [[nodiscard]] - HRESULT _EraseCharacter(const short chars) noexcept; - [[nodiscard]] - HRESULT _CursorPosition(const COORD coord) noexcept; - [[nodiscard]] - HRESULT _CursorHome() noexcept; - [[nodiscard]] - HRESULT _ClearScreen() noexcept; - [[nodiscard]] - HRESULT _ChangeTitle(const std::string& title) noexcept; - [[nodiscard]] - HRESULT _SetGraphicsRendition16Color(const WORD wAttr, - const bool fIsForeground) noexcept; - [[nodiscard]] - HRESULT _SetGraphicsRenditionRGBColor(const COLORREF color, - const bool fIsForeground) noexcept; - [[nodiscard]] - HRESULT _SetGraphicsRenditionDefaultColor(const bool fIsForeground) noexcept; + [[nodiscard]] HRESULT _StopCursorBlinking() noexcept; + [[nodiscard]] HRESULT _StartCursorBlinking() noexcept; + [[nodiscard]] HRESULT _HideCursor() noexcept; + [[nodiscard]] HRESULT _ShowCursor() noexcept; + [[nodiscard]] HRESULT _EraseLine() noexcept; + [[nodiscard]] HRESULT _InsertDeleteLine(const short sLines, const bool fInsertLine) noexcept; + [[nodiscard]] HRESULT _DeleteLine(const short sLines) noexcept; + [[nodiscard]] HRESULT _InsertLine(const short sLines) noexcept; + [[nodiscard]] HRESULT _CursorForward(const short chars) noexcept; + [[nodiscard]] HRESULT _EraseCharacter(const short chars) noexcept; + [[nodiscard]] HRESULT _CursorPosition(const COORD coord) noexcept; + [[nodiscard]] HRESULT _CursorHome() noexcept; + [[nodiscard]] HRESULT _ClearScreen() noexcept; + [[nodiscard]] HRESULT _ChangeTitle(const std::string& title) noexcept; + [[nodiscard]] HRESULT _SetGraphicsRendition16Color(const WORD wAttr, + const bool fIsForeground) noexcept; + [[nodiscard]] HRESULT _SetGraphicsRenditionRGBColor(const COLORREF color, + const bool fIsForeground) noexcept; + [[nodiscard]] HRESULT _SetGraphicsRenditionDefaultColor(const bool fIsForeground) noexcept; - [[nodiscard]] - HRESULT _SetGraphicsBoldness(const bool isBold) noexcept; + [[nodiscard]] HRESULT _SetGraphicsBoldness(const bool isBold) noexcept; - [[nodiscard]] - HRESULT _SetGraphicsDefault() noexcept; + [[nodiscard]] HRESULT _SetGraphicsDefault() noexcept; - [[nodiscard]] - HRESULT _ResizeWindow(const short sWidth, const short sHeight) noexcept; + [[nodiscard]] HRESULT _ResizeWindow(const short sWidth, const short sHeight) noexcept; - [[nodiscard]] - HRESULT _BeginUnderline() noexcept; + [[nodiscard]] HRESULT _BeginUnderline() noexcept; - [[nodiscard]] - HRESULT _EndUnderline() noexcept; + [[nodiscard]] HRESULT _EndUnderline() noexcept; - [[nodiscard]] - HRESULT _RequestCursor() noexcept; + [[nodiscard]] HRESULT _RequestCursor() noexcept; - [[nodiscard]] - virtual HRESULT _MoveCursor(const COORD coord) noexcept = 0; - [[nodiscard]] - HRESULT _RgbUpdateDrawingBrushes(const COLORREF colorForeground, - const COLORREF colorBackground, - const bool isBold, - _In_reads_(cColorTable) const COLORREF* const ColorTable, - const WORD cColorTable) noexcept; - [[nodiscard]] - HRESULT _16ColorUpdateDrawingBrushes(const COLORREF colorForeground, - const COLORREF colorBackground, - const bool isBold, - _In_reads_(cColorTable) const COLORREF* const ColorTable, - const WORD cColorTable) noexcept; + [[nodiscard]] virtual HRESULT _MoveCursor(const COORD coord) noexcept = 0; + [[nodiscard]] HRESULT _RgbUpdateDrawingBrushes(const COLORREF colorForeground, + const COLORREF colorBackground, + const bool isBold, + _In_reads_(cColorTable) const COLORREF* const ColorTable, + const WORD cColorTable) noexcept; + [[nodiscard]] HRESULT _16ColorUpdateDrawingBrushes(const COLORREF colorForeground, + const COLORREF colorBackground, + const bool isBold, + _In_reads_(cColorTable) const COLORREF* const ColorTable, + const WORD cColorTable) noexcept; bool _WillWriteSingleChar() const; - [[nodiscard]] - HRESULT _PaintUtf8BufferLine(std::basic_string_view const clusters, - const COORD coord) noexcept; + [[nodiscard]] HRESULT _PaintUtf8BufferLine(std::basic_string_view const clusters, + const COORD coord) noexcept; - [[nodiscard]] - HRESULT _PaintAsciiBufferLine(std::basic_string_view const clusters, - const COORD coord) noexcept; + [[nodiscard]] HRESULT _PaintAsciiBufferLine(std::basic_string_view const clusters, + const COORD coord) noexcept; - [[nodiscard]] - HRESULT _WriteTerminalUtf8(const std::wstring& str) noexcept; - [[nodiscard]] - HRESULT _WriteTerminalAscii(const std::wstring& str) noexcept; + [[nodiscard]] HRESULT _WriteTerminalUtf8(const std::wstring& str) noexcept; + [[nodiscard]] HRESULT _WriteTerminalAscii(const std::wstring& str) noexcept; - [[nodiscard]] - virtual HRESULT _DoUpdateTitle(const std::wstring& newTitle) noexcept override; + [[nodiscard]] virtual HRESULT _DoUpdateTitle(const std::wstring& newTitle) noexcept override; /////////////////////////// Unit Testing Helpers /////////////////////////// - #ifdef UNIT_TESTING +#ifdef UNIT_TESTING std::function _pfnTestCallback; bool _usingTestCallback; friend class VtRendererTest; - #endif +#endif void SetTestCallback(_In_ std::function pfn); - }; } diff --git a/src/renderer/wddmcon/WddmConRenderer.cpp b/src/renderer/wddmcon/WddmConRenderer.cpp index d70110338..150d4a1e6 100644 --- a/src/renderer/wddmcon/WddmConRenderer.cpp +++ b/src/renderer/wddmcon/WddmConRenderer.cpp @@ -13,10 +13,10 @@ // Default non-bright white. // -#define DEFAULT_COLOR_ATTRIBUTE (0xC) +#define DEFAULT_COLOR_ATTRIBUTE (0xC) -#define DEFAULT_FONT_WIDTH (8) -#define DEFAULT_FONT_HEIGHT (12) +#define DEFAULT_FONT_WIDTH (8) +#define DEFAULT_FONT_HEIGHT (12) using namespace Microsoft::Console::Render; @@ -28,7 +28,6 @@ WddmConEngine::WddmConEngine() : _displayState(nullptr), _currentLegacyColorAttribute(DEFAULT_COLOR_ATTRIBUTE) { - } void WddmConEngine::FreeResources(ULONG displayHeight) @@ -67,8 +66,7 @@ WddmConEngine::~WddmConEngine() FreeResources(_displayHeight); } -[[nodiscard]] -HRESULT WddmConEngine::Initialize() noexcept +[[nodiscard]] HRESULT WddmConEngine::Initialize() noexcept { HRESULT hr; RECT DisplaySize; @@ -89,7 +87,7 @@ HRESULT WddmConEngine::Initialize() noexcept DisplaySize.bottom = (LONG)DisplaySizeIoctl.Height; DisplaySize.right = (LONG)DisplaySizeIoctl.Width; - _displayState = (PCD_IO_ROW_INFORMATION *)calloc(DisplaySize.bottom, sizeof(PCD_IO_ROW_INFORMATION)); + _displayState = (PCD_IO_ROW_INFORMATION*)calloc(DisplaySize.bottom, sizeof(PCD_IO_ROW_INFORMATION)); if (_displayState != nullptr) { @@ -151,79 +149,67 @@ bool WddmConEngine::IsInitialized() return _hWddmConCtx != INVALID_HANDLE_VALUE; } -[[nodiscard]] -HRESULT WddmConEngine::Enable() noexcept +[[nodiscard]] HRESULT WddmConEngine::Enable() noexcept { RETURN_IF_HANDLE_INVALID(_hWddmConCtx); return WDDMConEnableDisplayAccess((PHANDLE)_hWddmConCtx, TRUE); } -[[nodiscard]] -HRESULT WddmConEngine::Disable() noexcept +[[nodiscard]] HRESULT WddmConEngine::Disable() noexcept { RETURN_IF_HANDLE_INVALID(_hWddmConCtx); return WDDMConEnableDisplayAccess((PHANDLE)_hWddmConCtx, FALSE); } -[[nodiscard]] -HRESULT WddmConEngine::Invalidate(const SMALL_RECT* const /*psrRegion*/) noexcept +[[nodiscard]] HRESULT WddmConEngine::Invalidate(const SMALL_RECT* const /*psrRegion*/) noexcept { return S_OK; } -[[nodiscard]] -HRESULT WddmConEngine::InvalidateCursor(const COORD* const /*pcoordCursor*/) noexcept +[[nodiscard]] HRESULT WddmConEngine::InvalidateCursor(const COORD* const /*pcoordCursor*/) noexcept { return S_OK; } -[[nodiscard]] -HRESULT WddmConEngine::InvalidateSystem(const RECT* const /*prcDirtyClient*/) noexcept +[[nodiscard]] HRESULT WddmConEngine::InvalidateSystem(const RECT* const /*prcDirtyClient*/) noexcept { return S_OK; } -[[nodiscard]] -HRESULT WddmConEngine::InvalidateSelection(const std::vector& /*rectangles*/) noexcept +[[nodiscard]] HRESULT WddmConEngine::InvalidateSelection(const std::vector& /*rectangles*/) noexcept { return S_OK; } -[[nodiscard]] -HRESULT WddmConEngine::InvalidateScroll(const COORD* const /*pcoordDelta*/) noexcept +[[nodiscard]] HRESULT WddmConEngine::InvalidateScroll(const COORD* const /*pcoordDelta*/) noexcept { return S_OK; } -[[nodiscard]] -HRESULT WddmConEngine::InvalidateAll() noexcept +[[nodiscard]] HRESULT WddmConEngine::InvalidateAll() noexcept { return S_OK; } -[[nodiscard]] -HRESULT WddmConEngine::InvalidateCircling(_Out_ bool* const pForcePaint) noexcept +[[nodiscard]] HRESULT WddmConEngine::InvalidateCircling(_Out_ bool* const pForcePaint) noexcept { *pForcePaint = false; return S_FALSE; } -[[nodiscard]] -HRESULT WddmConEngine::PrepareForTeardown(_Out_ bool* const pForcePaint) noexcept +[[nodiscard]] HRESULT WddmConEngine::PrepareForTeardown(_Out_ bool* const pForcePaint) noexcept { *pForcePaint = false; return S_FALSE; } -[[nodiscard]] -HRESULT WddmConEngine::StartPaint() noexcept +[[nodiscard]] HRESULT WddmConEngine::StartPaint() noexcept { RETURN_IF_HANDLE_INVALID(_hWddmConCtx); return WDDMConBeginUpdateDisplayBatch(_hWddmConCtx); } -[[nodiscard]] -HRESULT WddmConEngine::EndPaint() noexcept +[[nodiscard]] HRESULT WddmConEngine::EndPaint() noexcept { RETURN_IF_HANDLE_INVALID(_hWddmConCtx); return WDDMConEndUpdateDisplayBatch(_hWddmConCtx); @@ -237,20 +223,17 @@ HRESULT WddmConEngine::EndPaint() noexcept // Return Value: // - S_FALSE since we do nothing. -[[nodiscard]] -HRESULT WddmConEngine::Present() noexcept +[[nodiscard]] HRESULT WddmConEngine::Present() noexcept { return S_FALSE; } -[[nodiscard]] -HRESULT WddmConEngine::ScrollFrame() noexcept +[[nodiscard]] HRESULT WddmConEngine::ScrollFrame() noexcept { return S_OK; } -[[nodiscard]] -HRESULT WddmConEngine::PaintBackground() noexcept +[[nodiscard]] HRESULT WddmConEngine::PaintBackground() noexcept { RETURN_IF_HANDLE_INVALID(_hWddmConCtx); @@ -272,14 +255,12 @@ HRESULT WddmConEngine::PaintBackground() noexcept } } - return S_OK; } -[[nodiscard]] -HRESULT WddmConEngine::PaintBufferLine(std::basic_string_view const clusters, - const COORD coord, - const bool /*trimLeft*/) noexcept +[[nodiscard]] HRESULT WddmConEngine::PaintBufferLine(std::basic_string_view const clusters, + const COORD coord, + const bool /*trimLeft*/) noexcept { try { @@ -305,47 +286,41 @@ HRESULT WddmConEngine::PaintBufferLine(std::basic_string_view const clu CATCH_RETURN(); } -[[nodiscard]] -HRESULT WddmConEngine::PaintBufferGridLines(GridLines const /*lines*/, - COLORREF const /*color*/, - size_t const /*cchLine*/, - COORD const /*coordTarget*/) noexcept +[[nodiscard]] HRESULT WddmConEngine::PaintBufferGridLines(GridLines const /*lines*/, + COLORREF const /*color*/, + size_t const /*cchLine*/, + COORD const /*coordTarget*/) noexcept { return S_OK; } -[[nodiscard]] -HRESULT WddmConEngine::PaintSelection(const SMALL_RECT /*rect*/) noexcept +[[nodiscard]] HRESULT WddmConEngine::PaintSelection(const SMALL_RECT /*rect*/) noexcept { return S_OK; } -[[nodiscard]] -HRESULT WddmConEngine::PaintCursor(const IRenderEngine::CursorOptions& /*options*/) noexcept +[[nodiscard]] HRESULT WddmConEngine::PaintCursor(const IRenderEngine::CursorOptions& /*options*/) noexcept { return S_OK; } -[[nodiscard]] -HRESULT WddmConEngine::UpdateDrawingBrushes(COLORREF const /*colorForeground*/, - COLORREF const /*colorBackground*/, - const WORD legacyColorAttribute, - const bool /*isBold*/, - bool const /*isSettingDefaultBrushes*/) noexcept +[[nodiscard]] HRESULT WddmConEngine::UpdateDrawingBrushes(COLORREF const /*colorForeground*/, + COLORREF const /*colorBackground*/, + const WORD legacyColorAttribute, + const bool /*isBold*/, + bool const /*isSettingDefaultBrushes*/) noexcept { _currentLegacyColorAttribute = legacyColorAttribute; return S_OK; } -[[nodiscard]] -HRESULT WddmConEngine::UpdateFont(const FontInfoDesired& fiFontInfoDesired, FontInfo& fiFontInfo) noexcept +[[nodiscard]] HRESULT WddmConEngine::UpdateFont(const FontInfoDesired& fiFontInfoDesired, FontInfo& fiFontInfo) noexcept { return GetProposedFont(fiFontInfoDesired, fiFontInfo, USER_DEFAULT_SCREEN_DPI); } -[[nodiscard]] -HRESULT WddmConEngine::UpdateDpi(int const /*iDpi*/) noexcept +[[nodiscard]] HRESULT WddmConEngine::UpdateDpi(int const /*iDpi*/) noexcept { return S_OK; } @@ -357,26 +332,24 @@ HRESULT WddmConEngine::UpdateDpi(int const /*iDpi*/) noexcept // - srNewViewport - The bounds of the new viewport. // Return Value: // - HRESULT S_OK -[[nodiscard]] -HRESULT WddmConEngine::UpdateViewport(const SMALL_RECT /*srNewViewport*/) noexcept +[[nodiscard]] HRESULT WddmConEngine::UpdateViewport(const SMALL_RECT /*srNewViewport*/) noexcept { return S_OK; } -[[nodiscard]] -HRESULT WddmConEngine::GetProposedFont(const FontInfoDesired& /*fiFontInfoDesired*/, - FontInfo& fiFontInfo, - int const /*iDpi*/) noexcept +[[nodiscard]] HRESULT WddmConEngine::GetProposedFont(const FontInfoDesired& /*fiFontInfoDesired*/, + FontInfo& fiFontInfo, + int const /*iDpi*/) noexcept { COORD coordSize = { 0 }; LOG_IF_FAILED(GetFontSize(&coordSize)); fiFontInfo.SetFromEngine(fiFontInfo.GetFaceName(), - fiFontInfo.GetFamily(), - fiFontInfo.GetWeight(), - fiFontInfo.IsTrueTypeFont(), - coordSize, - coordSize); + fiFontInfo.GetFamily(), + fiFontInfo.GetWeight(), + fiFontInfo.IsTrueTypeFont(), + coordSize, + coordSize); return S_OK; } @@ -403,8 +376,7 @@ RECT WddmConEngine::GetDisplaySize() return r; } -[[nodiscard]] -HRESULT WddmConEngine::GetFontSize(_Out_ COORD* const pFontSize) noexcept +[[nodiscard]] HRESULT WddmConEngine::GetFontSize(_Out_ COORD* const pFontSize) noexcept { // In order to retrieve the font size being used by DirectX, it is necessary // to modify the API set that defines the contract for WddmCon. However, the @@ -425,8 +397,7 @@ HRESULT WddmConEngine::GetFontSize(_Out_ COORD* const pFontSize) noexcept return S_OK; } -[[nodiscard]] -HRESULT WddmConEngine::IsGlyphWideByFont(const std::wstring_view /*glyph*/, _Out_ bool* const pResult) noexcept +[[nodiscard]] HRESULT WddmConEngine::IsGlyphWideByFont(const std::wstring_view /*glyph*/, _Out_ bool* const pResult) noexcept { *pResult = false; return S_OK; @@ -439,8 +410,7 @@ HRESULT WddmConEngine::IsGlyphWideByFont(const std::wstring_view /*glyph*/, _Out // - newTitle: the new string to use for the title of the window // Return Value: // - S_OK -[[nodiscard]] -HRESULT WddmConEngine::_DoUpdateTitle(_In_ const std::wstring& /*newTitle*/) noexcept +[[nodiscard]] HRESULT WddmConEngine::_DoUpdateTitle(_In_ const std::wstring& /*newTitle*/) noexcept { return S_OK; } diff --git a/src/renderer/wddmcon/WddmConRenderer.hpp b/src/renderer/wddmcon/WddmConRenderer.hpp index eecdfdea1..714e977e3 100644 --- a/src/renderer/wddmcon/WddmConRenderer.hpp +++ b/src/renderer/wddmcon/WddmConRenderer.hpp @@ -13,88 +13,59 @@ namespace Microsoft::Console::Render WddmConEngine(); ~WddmConEngine() override; - [[nodiscard]] - HRESULT Initialize() noexcept; + [[nodiscard]] HRESULT Initialize() noexcept; bool IsInitialized(); // Used to release device resources so that another instance of // conhost can render to the screen (i.e. only one DirectX // application may control the screen at a time.) - [[nodiscard]] - HRESULT Enable() noexcept; - [[nodiscard]] - HRESULT Disable() noexcept; + [[nodiscard]] HRESULT Enable() noexcept; + [[nodiscard]] HRESULT Disable() noexcept; RECT GetDisplaySize(); // IRenderEngine Members - [[nodiscard]] - HRESULT Invalidate(const SMALL_RECT* const psrRegion) noexcept override; - [[nodiscard]] - HRESULT InvalidateCursor(const COORD* const pcoordCursor) noexcept override; - [[nodiscard]] - HRESULT InvalidateSystem(const RECT* const prcDirtyClient) noexcept override; - [[nodiscard]] - HRESULT InvalidateSelection(const std::vector& rectangles) noexcept override; - [[nodiscard]] - HRESULT InvalidateScroll(const COORD* const pcoordDelta) noexcept override; - [[nodiscard]] - HRESULT InvalidateAll() noexcept override; - [[nodiscard]] - HRESULT InvalidateCircling(_Out_ bool* const pForcePaint) noexcept override; - [[nodiscard]] - HRESULT PrepareForTeardown(_Out_ bool* const pForcePaint) noexcept override; + [[nodiscard]] HRESULT Invalidate(const SMALL_RECT* const psrRegion) noexcept override; + [[nodiscard]] HRESULT InvalidateCursor(const COORD* const pcoordCursor) noexcept override; + [[nodiscard]] HRESULT InvalidateSystem(const RECT* const prcDirtyClient) noexcept override; + [[nodiscard]] HRESULT InvalidateSelection(const std::vector& rectangles) noexcept override; + [[nodiscard]] HRESULT InvalidateScroll(const COORD* const pcoordDelta) noexcept override; + [[nodiscard]] HRESULT InvalidateAll() noexcept override; + [[nodiscard]] HRESULT InvalidateCircling(_Out_ bool* const pForcePaint) noexcept override; + [[nodiscard]] HRESULT PrepareForTeardown(_Out_ bool* const pForcePaint) noexcept override; - [[nodiscard]] - HRESULT StartPaint() noexcept override; - [[nodiscard]] - HRESULT EndPaint() noexcept override; - [[nodiscard]] - HRESULT Present() noexcept override; - - - [[nodiscard]] - HRESULT ScrollFrame() noexcept override; + [[nodiscard]] HRESULT StartPaint() noexcept override; + [[nodiscard]] HRESULT EndPaint() noexcept override; + [[nodiscard]] HRESULT Present() noexcept override; - [[nodiscard]] - HRESULT PaintBackground() noexcept override; - [[nodiscard]] - HRESULT PaintBufferLine(std::basic_string_view const clusters, - const COORD coord, - const bool trimLeft) noexcept override; - [[nodiscard]] - HRESULT PaintBufferGridLines(GridLines const lines, COLORREF const color, size_t const cchLine, COORD const coordTarget) noexcept override; - [[nodiscard]] - HRESULT PaintSelection(const SMALL_RECT rect) noexcept override; + [[nodiscard]] HRESULT ScrollFrame() noexcept override; - [[nodiscard]] - HRESULT PaintCursor(const CursorOptions& options) noexcept override; + [[nodiscard]] HRESULT PaintBackground() noexcept override; + [[nodiscard]] HRESULT PaintBufferLine(std::basic_string_view const clusters, + const COORD coord, + const bool trimLeft) noexcept override; + [[nodiscard]] HRESULT PaintBufferGridLines(GridLines const lines, COLORREF const color, size_t const cchLine, COORD const coordTarget) noexcept override; + [[nodiscard]] HRESULT PaintSelection(const SMALL_RECT rect) noexcept override; - [[nodiscard]] - HRESULT UpdateDrawingBrushes(COLORREF const colorForeground, - COLORREF const colorBackground, - const WORD legacyColorAttribute, - const bool isBold, - bool const isSettingDefaultBrushes) noexcept override; - [[nodiscard]] - HRESULT UpdateFont(const FontInfoDesired& fiFontInfoDesired, FontInfo& fiFontInfo) noexcept override; - [[nodiscard]] - HRESULT UpdateDpi(int const iDpi) noexcept override; - [[nodiscard]] - HRESULT UpdateViewport(const SMALL_RECT srNewViewport) noexcept override; + [[nodiscard]] HRESULT PaintCursor(const CursorOptions& options) noexcept override; - [[nodiscard]] - HRESULT GetProposedFont(const FontInfoDesired& fiFontInfoDesired, FontInfo& fiFontInfo, int const iDpi) noexcept override; + [[nodiscard]] HRESULT UpdateDrawingBrushes(COLORREF const colorForeground, + COLORREF const colorBackground, + const WORD legacyColorAttribute, + const bool isBold, + bool const isSettingDefaultBrushes) noexcept override; + [[nodiscard]] HRESULT UpdateFont(const FontInfoDesired& fiFontInfoDesired, FontInfo& fiFontInfo) noexcept override; + [[nodiscard]] HRESULT UpdateDpi(int const iDpi) noexcept override; + [[nodiscard]] HRESULT UpdateViewport(const SMALL_RECT srNewViewport) noexcept override; + + [[nodiscard]] HRESULT GetProposedFont(const FontInfoDesired& fiFontInfoDesired, FontInfo& fiFontInfo, int const iDpi) noexcept override; SMALL_RECT GetDirtyRectInChars() override; - [[nodiscard]] - HRESULT GetFontSize(_Out_ COORD* const pFontSize) noexcept override; - [[nodiscard]] - HRESULT IsGlyphWideByFont(const std::wstring_view glyph, _Out_ bool* const pResult) noexcept override; + [[nodiscard]] HRESULT GetFontSize(_Out_ COORD* const pFontSize) noexcept override; + [[nodiscard]] HRESULT IsGlyphWideByFont(const std::wstring_view glyph, _Out_ bool* const pResult) noexcept override; protected: - [[nodiscard]] - HRESULT _DoUpdateTitle(_In_ const std::wstring& newTitle) noexcept override; + [[nodiscard]] HRESULT _DoUpdateTitle(_In_ const std::wstring& newTitle) noexcept override; private: HANDLE _hWddmConCtx; @@ -106,7 +77,7 @@ namespace Microsoft::Console::Render LONG _displayHeight; LONG _displayWidth; - PCD_IO_ROW_INFORMATION *_displayState; + PCD_IO_ROW_INFORMATION* _displayState; WORD _currentLegacyColorAttribute; }; diff --git a/src/renderer/wddmcon/main.h b/src/renderer/wddmcon/main.h index 4a2078e2e..a3a46bf28 100644 --- a/src/renderer/wddmcon/main.h +++ b/src/renderer/wddmcon/main.h @@ -5,45 +5,38 @@ HRESULT WINAPI WDDMConBeginUpdateDisplayBatch( - _In_ HANDLE hDisplay - ); + _In_ HANDLE hDisplay); HRESULT WINAPI WDDMConCreate( - _In_ HANDLE* phDisplay - ); + _In_ HANDLE* phDisplay); VOID -WINAPI -WDDMConDestroy( - _In_ HANDLE hDisplay - ); + WINAPI + WDDMConDestroy( + _In_ HANDLE hDisplay); HRESULT WINAPI WDDMConEnableDisplayAccess( _In_ HANDLE phDisplay, - _In_ BOOLEAN fEnabled - ); + _In_ BOOLEAN fEnabled); HRESULT WINAPI WDDMConEndUpdateDisplayBatch( - _In_ HANDLE hDisplay - ); + _In_ HANDLE hDisplay); HRESULT WINAPI WDDMConGetDisplaySize( _In_ HANDLE hDisplay, - _In_ CD_IO_DISPLAY_SIZE* pDisplaySize - ); + _In_ CD_IO_DISPLAY_SIZE* pDisplaySize); HRESULT WINAPI WDDMConUpdateDisplay( _In_ HANDLE hDisplay, _In_ CD_IO_ROW_INFORMATION* pRowInformation, - _In_ BOOLEAN fInvalidate - ); + _In_ BOOLEAN fInvalidate); diff --git a/src/server/ApiDispatchers.cpp b/src/server/ApiDispatchers.cpp index 58f4aced5..b574809b0 100644 --- a/src/server/ApiDispatchers.cpp +++ b/src/server/ApiDispatchers.cpp @@ -12,8 +12,8 @@ #include "../host/telemetry.hpp" #include "../host/cmdline.h" -[[nodiscard]] -HRESULT ApiDispatchers::ServerGetConsoleCP(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleCP(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { CONSOLE_GETCP_MSG* const a = &m->u.consoleMsgL1.GetConsoleCP; @@ -30,25 +30,24 @@ HRESULT ApiDispatchers::ServerGetConsoleCP(_Inout_ CONSOLE_API_MSG * const m, _I return S_OK; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerGetConsoleMode(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleMode(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetConsoleMode); CONSOLE_MODE_MSG* const a = &m->u.consoleMsgL1.GetConsoleMode; std::wstring handleType = L"unknown"; - TraceLoggingWrite(g_hConhostV2EventTraceProvider, "API_GetConsoleMode", + TraceLoggingWrite(g_hConhostV2EventTraceProvider, + "API_GetConsoleMode", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingOpcode(WINEVENT_OPCODE_START) - ); + TraceLoggingOpcode(WINEVENT_OPCODE_START)); - auto tracing = wil::scope_exit([&]() - { + auto tracing = wil::scope_exit([&]() { Tracing::s_TraceApi(a, handleType); - TraceLoggingWrite(g_hConhostV2EventTraceProvider, "API_GetConsoleMode", + TraceLoggingWrite(g_hConhostV2EventTraceProvider, + "API_GetConsoleMode", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE), - TraceLoggingOpcode(WINEVENT_OPCODE_STOP) - ); + TraceLoggingOpcode(WINEVENT_OPCODE_STOP)); }); ConsoleHandleData* const pObjectHandle = m->GetObjectHandle(); @@ -70,8 +69,8 @@ HRESULT ApiDispatchers::ServerGetConsoleMode(_Inout_ CONSOLE_API_MSG * const m, return S_OK; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerSetConsoleMode(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleMode(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { Telemetry::Instance().LogApiCall(Telemetry::ApiCall::SetConsoleMode); CONSOLE_MODE_MSG* const a = &m->u.consoleMsgL1.SetConsoleMode; @@ -92,8 +91,8 @@ HRESULT ApiDispatchers::ServerSetConsoleMode(_Inout_ CONSOLE_API_MSG * const m, } } -[[nodiscard]] -HRESULT ApiDispatchers::ServerGetNumberOfInputEvents(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerGetNumberOfInputEvents(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetNumberOfConsoleInputEvents); CONSOLE_GETNUMBEROFINPUTEVENTS_MSG* const a = &m->u.consoleMsgL1.GetNumberOfConsoleInputEvents; @@ -107,8 +106,8 @@ HRESULT ApiDispatchers::ServerGetNumberOfInputEvents(_Inout_ CONSOLE_API_MSG * c return m->_pApiRoutines->GetNumberOfConsoleInputEventsImpl(*pObj, a->ReadyEvents); } -[[nodiscard]] -HRESULT ApiDispatchers::ServerGetConsoleInput(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const pbReplyPending) +[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleInput(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const pbReplyPending) { *pbReplyPending = FALSE; @@ -157,22 +156,38 @@ HRESULT ApiDispatchers::ServerGetConsoleInput(_Inout_ CONSOLE_API_MSG * const m, { if (fIsPeek) { - hr = m->_pApiRoutines->PeekConsoleInputWImpl(*pInputBuffer, outEvents, eventsToRead, *pInputReadHandleData, waiter); + hr = m->_pApiRoutines->PeekConsoleInputWImpl(*pInputBuffer, + outEvents, + eventsToRead, + *pInputReadHandleData, + waiter); } else { - hr = m->_pApiRoutines->ReadConsoleInputWImpl(*pInputBuffer, outEvents, eventsToRead, *pInputReadHandleData, waiter); + hr = m->_pApiRoutines->ReadConsoleInputWImpl(*pInputBuffer, + outEvents, + eventsToRead, + *pInputReadHandleData, + waiter); } } else { if (fIsPeek) { - hr = m->_pApiRoutines->PeekConsoleInputAImpl(*pInputBuffer, outEvents, eventsToRead, *pInputReadHandleData, waiter); + hr = m->_pApiRoutines->PeekConsoleInputAImpl(*pInputBuffer, + outEvents, + eventsToRead, + *pInputReadHandleData, + waiter); } else { - hr = m->_pApiRoutines->ReadConsoleInputAImpl(*pInputBuffer, outEvents, eventsToRead, *pInputReadHandleData, waiter); + hr = m->_pApiRoutines->ReadConsoleInputAImpl(*pInputBuffer, + outEvents, + eventsToRead, + *pInputReadHandleData, + waiter); } } @@ -234,8 +249,8 @@ HRESULT ApiDispatchers::ServerGetConsoleInput(_Inout_ CONSOLE_API_MSG * const m, return hr; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerReadConsole(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const pbReplyPending) +[[nodiscard]] HRESULT ApiDispatchers::ServerReadConsole(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const pbReplyPending) { *pbReplyPending = FALSE; @@ -320,8 +335,6 @@ HRESULT ApiDispatchers::ServerReadConsole(_Inout_ CONSOLE_API_MSG * const m, _In hConsoleClient, a->CtrlWakeupMask, a->ControlKeyState); - - } else { @@ -337,7 +350,6 @@ HRESULT ApiDispatchers::ServerReadConsole(_Inout_ CONSOLE_API_MSG * const m, _In hConsoleClient, a->CtrlWakeupMask, a->ControlKeyState); - } LOG_IF_FAILED(SizeTToULong(cbWritten, &a->NumBytes)); @@ -371,8 +383,8 @@ HRESULT ApiDispatchers::ServerReadConsole(_Inout_ CONSOLE_API_MSG * const m, _In return hr; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerWriteConsole(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const pbReplyPending) +[[nodiscard]] HRESULT ApiDispatchers::ServerWriteConsole(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const pbReplyPending) { *pbReplyPending = FALSE; @@ -388,8 +400,7 @@ HRESULT ApiDispatchers::ServerWriteConsole(_Inout_ CONSOLE_API_MSG * const m, _I // Get input parameter buffer PVOID pvBuffer; ULONG cbBufferSize; - auto tracing = wil::scope_exit([&]() - { + auto tracing = wil::scope_exit([&]() { Tracing::s_TraceApi(pvBuffer, a); }); RETURN_IF_FAILED(m->GetInputBuffer(&pvBuffer, &cbBufferSize)); @@ -444,8 +455,8 @@ HRESULT ApiDispatchers::ServerWriteConsole(_Inout_ CONSOLE_API_MSG * const m, _I return hr; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerFillConsoleOutput(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerFillConsoleOutput(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { PCONSOLE_FILLCONSOLEOUTPUT_MSG const a = &m->u.consoleMsgL2.FillConsoleOutput; @@ -475,7 +486,6 @@ HRESULT ApiDispatchers::ServerFillConsoleOutput(_Inout_ CONSOLE_API_MSG * const SCREEN_INFORMATION* pScreenInfo; RETURN_IF_FAILED(HandleData->GetScreenBuffer(GENERIC_WRITE, &pScreenInfo)); - HRESULT hr; size_t amountWritten; switch (a->ElementType) @@ -517,8 +527,8 @@ HRESULT ApiDispatchers::ServerFillConsoleOutput(_Inout_ CONSOLE_API_MSG * const return hr; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerSetConsoleActiveScreenBuffer(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleActiveScreenBuffer(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { Telemetry::Instance().LogApiCall(Telemetry::ApiCall::SetConsoleActiveScreenBuffer); ConsoleHandleData* const pObjectHandle = m->GetObjectHandle(); @@ -531,8 +541,8 @@ HRESULT ApiDispatchers::ServerSetConsoleActiveScreenBuffer(_Inout_ CONSOLE_API_M return S_OK; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerFlushConsoleInputBuffer(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerFlushConsoleInputBuffer(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { Telemetry::Instance().LogApiCall(Telemetry::ApiCall::FlushConsoleInputBuffer); ConsoleHandleData* const pObjectHandle = m->GetObjectHandle(); @@ -545,8 +555,8 @@ HRESULT ApiDispatchers::ServerFlushConsoleInputBuffer(_Inout_ CONSOLE_API_MSG * return S_OK; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerSetConsoleCP(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleCP(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { CONSOLE_SETCP_MSG* const a = &m->u.consoleMsgL2.SetConsoleCP; @@ -562,8 +572,8 @@ HRESULT ApiDispatchers::ServerSetConsoleCP(_Inout_ CONSOLE_API_MSG * const m, _I } } -[[nodiscard]] -HRESULT ApiDispatchers::ServerGetConsoleCursorInfo(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleCursorInfo(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetConsoleCursorInfo); CONSOLE_GETCURSORINFO_MSG* const a = &m->u.consoleMsgL2.GetConsoleCursorInfo; @@ -580,8 +590,8 @@ HRESULT ApiDispatchers::ServerGetConsoleCursorInfo(_Inout_ CONSOLE_API_MSG * con return S_OK; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerSetConsoleCursorInfo(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleCursorInfo(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { Telemetry::Instance().LogApiCall(Telemetry::ApiCall::SetConsoleCursorInfo); CONSOLE_SETCURSORINFO_MSG* const a = &m->u.consoleMsgL2.SetConsoleCursorInfo; @@ -595,14 +605,13 @@ HRESULT ApiDispatchers::ServerSetConsoleCursorInfo(_Inout_ CONSOLE_API_MSG * con return m->_pApiRoutines->SetConsoleCursorInfoImpl(*pObj, a->CursorSize, a->Visible); } -[[nodiscard]] -HRESULT ApiDispatchers::ServerGetConsoleScreenBufferInfo(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleScreenBufferInfo(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetConsoleScreenBufferInfoEx); CONSOLE_SCREENBUFFERINFO_MSG* const a = &m->u.consoleMsgL2.GetConsoleScreenBufferInfo; - auto tracing = wil::scope_exit([&]() - { + auto tracing = wil::scope_exit([&]() { Tracing::s_TraceApi(a); }); @@ -633,8 +642,8 @@ HRESULT ApiDispatchers::ServerGetConsoleScreenBufferInfo(_Inout_ CONSOLE_API_MSG return S_OK; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerSetConsoleScreenBufferInfo(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleScreenBufferInfo(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { Telemetry::Instance().LogApiCall(Telemetry::ApiCall::SetConsoleScreenBufferInfoEx); CONSOLE_SCREENBUFFERINFO_MSG* const a = &m->u.consoleMsgL2.SetConsoleScreenBufferInfo; @@ -664,8 +673,8 @@ HRESULT ApiDispatchers::ServerSetConsoleScreenBufferInfo(_Inout_ CONSOLE_API_MSG return m->_pApiRoutines->SetConsoleScreenBufferInfoExImpl(*pObj, ex); } -[[nodiscard]] -HRESULT ApiDispatchers::ServerSetConsoleScreenBufferSize(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleScreenBufferSize(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { Telemetry::Instance().LogApiCall(Telemetry::ApiCall::SetConsoleScreenBufferSize); CONSOLE_SETSCREENBUFFERSIZE_MSG* const a = &m->u.consoleMsgL2.SetConsoleScreenBufferSize; @@ -679,8 +688,8 @@ HRESULT ApiDispatchers::ServerSetConsoleScreenBufferSize(_Inout_ CONSOLE_API_MSG return m->_pApiRoutines->SetConsoleScreenBufferSizeImpl(*pObj, a->Size); } -[[nodiscard]] -HRESULT ApiDispatchers::ServerSetConsoleCursorPosition(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleCursorPosition(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { Telemetry::Instance().LogApiCall(Telemetry::ApiCall::SetConsoleCursorPosition); CONSOLE_SETCURSORPOSITION_MSG* const a = &m->u.consoleMsgL2.SetConsoleCursorPosition; @@ -694,8 +703,8 @@ HRESULT ApiDispatchers::ServerSetConsoleCursorPosition(_Inout_ CONSOLE_API_MSG * return m->_pApiRoutines->SetConsoleCursorPositionImpl(*pObj, a->CursorPosition); } -[[nodiscard]] -HRESULT ApiDispatchers::ServerGetLargestConsoleWindowSize(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerGetLargestConsoleWindowSize(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetLargestConsoleWindowSize); CONSOLE_GETLARGESTWINDOWSIZE_MSG* const a = &m->u.consoleMsgL2.GetLargestConsoleWindowSize; @@ -710,8 +719,8 @@ HRESULT ApiDispatchers::ServerGetLargestConsoleWindowSize(_Inout_ CONSOLE_API_MS return S_OK; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerScrollConsoleScreenBuffer(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerScrollConsoleScreenBuffer(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { CONSOLE_SCROLLSCREENBUFFER_MSG* const a = &m->u.consoleMsgL2.ScrollConsoleScreenBuffer; Telemetry::Instance().LogApiCall(Telemetry::ApiCall::ScrollConsoleScreenBuffer, a->Unicode); @@ -742,14 +751,13 @@ HRESULT ApiDispatchers::ServerScrollConsoleScreenBuffer(_Inout_ CONSOLE_API_MSG } } -[[nodiscard]] -HRESULT ApiDispatchers::ServerSetConsoleTextAttribute(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleTextAttribute(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { Telemetry::Instance().LogApiCall(Telemetry::ApiCall::SetConsoleTextAttribute); CONSOLE_SETTEXTATTRIBUTE_MSG* const a = &m->u.consoleMsgL2.SetConsoleTextAttribute; - auto tracing = wil::scope_exit([&]() - { + auto tracing = wil::scope_exit([&]() { Tracing::s_TraceApi(a); }); @@ -761,8 +769,8 @@ HRESULT ApiDispatchers::ServerSetConsoleTextAttribute(_Inout_ CONSOLE_API_MSG * RETURN_HR(m->_pApiRoutines->SetConsoleTextAttributeImpl(*pObj, a->Attributes)); } -[[nodiscard]] -HRESULT ApiDispatchers::ServerSetConsoleWindowInfo(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleWindowInfo(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { Telemetry::Instance().LogApiCall(Telemetry::ApiCall::SetConsoleWindowInfo); CONSOLE_SETWINDOWINFO_MSG* const a = &m->u.consoleMsgL2.SetConsoleWindowInfo; @@ -776,8 +784,8 @@ HRESULT ApiDispatchers::ServerSetConsoleWindowInfo(_Inout_ CONSOLE_API_MSG * con return m->_pApiRoutines->SetConsoleWindowInfoImpl(*pObj, a->Absolute, a->Window); } -[[nodiscard]] -HRESULT ApiDispatchers::ServerReadConsoleOutputString(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerReadConsoleOutputString(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { RETURN_HR_IF(E_ACCESSDENIED, !m->GetProcessHandle()->GetPolicy().CanReadOutputBuffer()); @@ -843,8 +851,8 @@ HRESULT ApiDispatchers::ServerReadConsoleOutputString(_Inout_ CONSOLE_API_MSG * return S_OK; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerWriteConsoleInput(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerWriteConsoleInput(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { PCONSOLE_WRITECONSOLEINPUT_MSG const a = &m->u.consoleMsgL2.WriteConsoleInput; @@ -880,8 +888,8 @@ HRESULT ApiDispatchers::ServerWriteConsoleInput(_Inout_ CONSOLE_API_MSG * const return S_OK; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerWriteConsoleOutput(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerWriteConsoleOutput(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { PCONSOLE_WRITECONSOLEOUTPUT_MSG const a = &m->u.consoleMsgL2.WriteConsoleOutput; @@ -926,13 +934,12 @@ HRESULT ApiDispatchers::ServerWriteConsoleOutput(_Inout_ CONSOLE_API_MSG * const return S_OK; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerWriteConsoleOutputString(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerWriteConsoleOutputString(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { PCONSOLE_WRITECONSOLEOUTPUTSTRING_MSG const a = &m->u.consoleMsgL2.WriteConsoleOutputString; - auto tracing = wil::scope_exit([&]() - { + auto tracing = wil::scope_exit([&]() { Tracing::s_TraceApi(a); }); @@ -1012,8 +1019,8 @@ HRESULT ApiDispatchers::ServerWriteConsoleOutputString(_Inout_ CONSOLE_API_MSG * return hr; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerReadConsoleOutput(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerReadConsoleOutput(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { RETURN_HR_IF(E_ACCESSDENIED, !m->GetProcessHandle()->GetPolicy().CanReadOutputBuffer()); @@ -1042,7 +1049,7 @@ HRESULT ApiDispatchers::ServerReadConsoleOutput(_Inout_ CONSOLE_API_MSG * const size_t regionBytes; RETURN_IF_FAILED(SizeTMult(regionArea, sizeof(CHAR_INFO), ®ionBytes)); RETURN_HR_IF(E_INVALIDARG, regionArea > 0 && ((regionArea > ULONG_MAX / sizeof(CHAR_INFO)) || (cbBuffer < regionBytes))); - + gsl::span buffer(reinterpret_cast(pvBuffer), cbBuffer / sizeof(CHAR_INFO)); auto finalRegion = Microsoft::Console::Types::Viewport::Empty(); // the actual region read out of the buffer if (!a->Unicode) @@ -1069,8 +1076,8 @@ HRESULT ApiDispatchers::ServerReadConsoleOutput(_Inout_ CONSOLE_API_MSG * const return S_OK; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerGetConsoleTitle(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleTitle(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { PCONSOLE_GETTITLE_MSG const a = &m->u.consoleMsgL2.GetConsoleTitle; Telemetry::Instance().LogApiCall(a->Original ? Telemetry::ApiCall::GetConsoleOriginalTitle : Telemetry::ApiCall::GetConsoleTitle, a->Unicode); @@ -1126,8 +1133,8 @@ HRESULT ApiDispatchers::ServerGetConsoleTitle(_Inout_ CONSOLE_API_MSG * const m, return hr; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerSetConsoleTitle(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleTitle(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { CONSOLE_SETTITLE_MSG* const a = &m->u.consoleMsgL2.SetConsoleTitle; Telemetry::Instance().LogApiCall(Telemetry::ApiCall::SetConsoleTitle, a->Unicode); @@ -1149,8 +1156,8 @@ HRESULT ApiDispatchers::ServerSetConsoleTitle(_Inout_ CONSOLE_API_MSG * const m, } } -[[nodiscard]] -HRESULT ApiDispatchers::ServerGetConsoleMouseInfo(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleMouseInfo(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetNumberOfConsoleMouseButtons); CONSOLE_GETMOUSEINFO_MSG* const a = &m->u.consoleMsgL3.GetConsoleMouseInfo; @@ -1159,8 +1166,8 @@ HRESULT ApiDispatchers::ServerGetConsoleMouseInfo(_Inout_ CONSOLE_API_MSG * cons return S_OK; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerGetConsoleFontSize(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleFontSize(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetConsoleFontSize); CONSOLE_GETFONTSIZE_MSG* const a = &m->u.consoleMsgL3.GetConsoleFontSize; @@ -1174,8 +1181,8 @@ HRESULT ApiDispatchers::ServerGetConsoleFontSize(_Inout_ CONSOLE_API_MSG * const return m->_pApiRoutines->GetConsoleFontSizeImpl(*pObj, a->FontIndex, a->FontSize); } -[[nodiscard]] -HRESULT ApiDispatchers::ServerGetConsoleCurrentFont(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleCurrentFont(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetCurrentConsoleFontEx); CONSOLE_CURRENTFONT_MSG* const a = &m->u.consoleMsgL3.GetCurrentConsoleFont; @@ -1200,8 +1207,8 @@ HRESULT ApiDispatchers::ServerGetConsoleCurrentFont(_Inout_ CONSOLE_API_MSG * co return S_OK; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerSetConsoleDisplayMode(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleDisplayMode(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { Telemetry::Instance().LogApiCall(Telemetry::ApiCall::SetConsoleDisplayMode); CONSOLE_SETDISPLAYMODE_MSG* const a = &m->u.consoleMsgL3.SetConsoleDisplayMode; @@ -1215,8 +1222,8 @@ HRESULT ApiDispatchers::ServerSetConsoleDisplayMode(_Inout_ CONSOLE_API_MSG * co return m->_pApiRoutines->SetConsoleDisplayModeImpl(*pObj, a->dwFlags, a->ScreenBufferDimensions); } -[[nodiscard]] -HRESULT ApiDispatchers::ServerGetConsoleDisplayMode(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleDisplayMode(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetConsoleDisplayMode); CONSOLE_GETDISPLAYMODE_MSG* const a = &m->u.consoleMsgL3.GetConsoleDisplayMode; @@ -1227,8 +1234,8 @@ HRESULT ApiDispatchers::ServerGetConsoleDisplayMode(_Inout_ CONSOLE_API_MSG * co return S_OK; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerAddConsoleAlias(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerAddConsoleAlias(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { CONSOLE_ADDALIAS_MSG* const a = &m->u.consoleMsgL3.AddConsoleAliasW; Telemetry::Instance().LogApiCall(Telemetry::ApiCall::AddConsoleAlias, a->Unicode); @@ -1244,6 +1251,7 @@ HRESULT ApiDispatchers::ServerAddConsoleAlias(_Inout_ CONSOLE_API_MSG * const m, ULONG const cbInputExeName = a->ExeLength; PVOID pvInputSource; ULONG const cbInputSource = a->SourceLength; + // clang-format off RETURN_HR_IF(E_INVALIDARG, !IsValidStringBuffer(a->Unicode, pvBuffer, cbBufferSize, @@ -1254,6 +1262,7 @@ HRESULT ApiDispatchers::ServerAddConsoleAlias(_Inout_ CONSOLE_API_MSG * const m, &pvInputSource, cbInputTarget, &pvInputTarget)); + // clang-format on if (a->Unicode) { @@ -1273,8 +1282,8 @@ HRESULT ApiDispatchers::ServerAddConsoleAlias(_Inout_ CONSOLE_API_MSG * const m, } } -[[nodiscard]] -HRESULT ApiDispatchers::ServerGetConsoleAlias(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleAlias(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { CONSOLE_GETALIAS_MSG* const a = &m->u.consoleMsgL3.GetConsoleAliasW; Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetConsoleAlias, a->Unicode); @@ -1287,6 +1296,7 @@ HRESULT ApiDispatchers::ServerGetConsoleAlias(_Inout_ CONSOLE_API_MSG * const m, ULONG const cbInputExe = a->ExeLength; PVOID pvInputSource; ULONG const cbInputSource = a->SourceLength; + // clang-format off RETURN_HR_IF(E_INVALIDARG, !IsValidStringBuffer(a->Unicode, pvInputBuffer, cbInputBufferSize, @@ -1295,6 +1305,7 @@ HRESULT ApiDispatchers::ServerGetConsoleAlias(_Inout_ CONSOLE_API_MSG * const m, &pvInputExe, cbInputSource, &pvInputSource)); + // clang-format on PVOID pvOutputBuffer; ULONG cbOutputBufferSize; @@ -1343,8 +1354,8 @@ HRESULT ApiDispatchers::ServerGetConsoleAlias(_Inout_ CONSOLE_API_MSG * const m, return hr; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerGetConsoleAliasesLength(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleAliasesLength(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { PCONSOLE_GETALIASESLENGTH_MSG const a = &m->u.consoleMsgL3.GetConsoleAliasesLengthW; Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetConsoleAliasesLength, a->Unicode); @@ -1376,8 +1387,8 @@ HRESULT ApiDispatchers::ServerGetConsoleAliasesLength(_Inout_ CONSOLE_API_MSG * return S_OK; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerGetConsoleAliasExesLength(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleAliasExesLength(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { PCONSOLE_GETALIASEXESLENGTH_MSG const a = &m->u.consoleMsgL3.GetConsoleAliasExesLengthW; Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetConsoleAliasExesLength, a->Unicode); @@ -1401,8 +1412,8 @@ HRESULT ApiDispatchers::ServerGetConsoleAliasExesLength(_Inout_ CONSOLE_API_MSG return S_OK; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerGetConsoleAliases(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleAliases(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { CONSOLE_GETALIASES_MSG* const a = &m->u.consoleMsgL3.GetConsoleAliasesW; Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetConsoleAliases, a->Unicode); @@ -1445,8 +1456,8 @@ HRESULT ApiDispatchers::ServerGetConsoleAliases(_Inout_ CONSOLE_API_MSG * const return S_OK; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerGetConsoleAliasExes(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleAliasExes(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { CONSOLE_GETALIASEXES_MSG* const a = &m->u.consoleMsgL3.GetConsoleAliasExesW; Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetConsoleAliasExes, a->Unicode); @@ -1481,8 +1492,8 @@ HRESULT ApiDispatchers::ServerGetConsoleAliasExes(_Inout_ CONSOLE_API_MSG * cons return S_OK; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerExpungeConsoleCommandHistory(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerExpungeConsoleCommandHistory(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { CONSOLE_EXPUNGECOMMANDHISTORY_MSG* const a = &m->u.consoleMsgL3.ExpungeConsoleCommandHistoryW; @@ -1504,8 +1515,8 @@ HRESULT ApiDispatchers::ServerExpungeConsoleCommandHistory(_Inout_ CONSOLE_API_M } } -[[nodiscard]] -HRESULT ApiDispatchers::ServerSetConsoleNumberOfCommands(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleNumberOfCommands(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { CONSOLE_SETNUMBEROFCOMMANDS_MSG* const a = &m->u.consoleMsgL3.SetConsoleNumberOfCommandsW; PVOID pvExeName; @@ -1527,8 +1538,8 @@ HRESULT ApiDispatchers::ServerSetConsoleNumberOfCommands(_Inout_ CONSOLE_API_MSG } } -[[nodiscard]] -HRESULT ApiDispatchers::ServerGetConsoleCommandHistoryLength(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleCommandHistoryLength(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { PCONSOLE_GETCOMMANDHISTORYLENGTH_MSG const a = &m->u.consoleMsgL3.GetConsoleCommandHistoryLengthW; @@ -1563,8 +1574,8 @@ HRESULT ApiDispatchers::ServerGetConsoleCommandHistoryLength(_Inout_ CONSOLE_API return S_OK; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerGetConsoleCommandHistory(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleCommandHistory(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { PCONSOLE_GETCOMMANDHISTORY_MSG const a = &m->u.consoleMsgL3.GetConsoleCommandHistoryW; @@ -1605,8 +1616,8 @@ HRESULT ApiDispatchers::ServerGetConsoleCommandHistory(_Inout_ CONSOLE_API_MSG * return S_OK; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerGetConsoleWindow(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleWindow(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetConsoleWindow); CONSOLE_GETCONSOLEWINDOW_MSG* const a = &m->u.consoleMsgL3.GetConsoleWindow; @@ -1615,8 +1626,8 @@ HRESULT ApiDispatchers::ServerGetConsoleWindow(_Inout_ CONSOLE_API_MSG * const m return S_OK; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerGetConsoleSelectionInfo(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleSelectionInfo(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetConsoleSelectionInfo); CONSOLE_GETSELECTIONINFO_MSG* const a = &m->u.consoleMsgL3.GetConsoleSelectionInfo; @@ -1625,8 +1636,8 @@ HRESULT ApiDispatchers::ServerGetConsoleSelectionInfo(_Inout_ CONSOLE_API_MSG * return S_OK; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerGetConsoleHistory(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleHistory(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { CONSOLE_HISTORY_MSG* const a = &m->u.consoleMsgL3.GetConsoleHistory; Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetConsoleHistoryInfo); @@ -1643,8 +1654,8 @@ HRESULT ApiDispatchers::ServerGetConsoleHistory(_Inout_ CONSOLE_API_MSG * const return S_OK; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerSetConsoleHistory(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleHistory(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { CONSOLE_HISTORY_MSG* const a = &m->u.consoleMsgL3.SetConsoleHistory; Telemetry::Instance().LogApiCall(Telemetry::ApiCall::SetConsoleHistoryInfo); @@ -1658,8 +1669,8 @@ HRESULT ApiDispatchers::ServerSetConsoleHistory(_Inout_ CONSOLE_API_MSG * const return m->_pApiRoutines->SetConsoleHistoryInfoImpl(info); } -[[nodiscard]] -HRESULT ApiDispatchers::ServerSetConsoleCurrentFont(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleCurrentFont(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { Telemetry::Instance().LogApiCall(Telemetry::ApiCall::SetCurrentConsoleFontEx); CONSOLE_CURRENTFONT_MSG* const a = &m->u.consoleMsgL3.SetCurrentConsoleFont; diff --git a/src/server/ApiDispatchersInternal.cpp b/src/server/ApiDispatchersInternal.cpp index 988780e75..1b25804a2 100644 --- a/src/server/ApiDispatchersInternal.cpp +++ b/src/server/ApiDispatchersInternal.cpp @@ -16,15 +16,14 @@ using Microsoft::Console::Interactivity::ServiceLocator; -[[nodiscard]] -HRESULT ApiDispatchers::ServerDeprecatedApi(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerDeprecatedApi(_Inout_ CONSOLE_API_MSG* const m, _Inout_ BOOL* const /*pbReplyPending*/) { // log if we hit a deprecated API. RETURN_HR_MSG(E_NOTIMPL, "Deprecated API attempted: 0x%08x", m->Descriptor.Function); } -[[nodiscard]] -HRESULT ApiDispatchers::ServerGetConsoleProcessList(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleProcessList(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); PCONSOLE_GETCONSOLEPROCESSLIST_MSG const a = &m->u.consoleMsgL3.GetConsoleProcessList; @@ -57,8 +56,8 @@ HRESULT ApiDispatchers::ServerGetConsoleProcessList(_Inout_ CONSOLE_API_MSG * co return S_OK; } -[[nodiscard]] -HRESULT ApiDispatchers::ServerGetConsoleLangId(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleLangId(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { CONSOLE_LANGID_MSG* const a = &m->u.consoleMsgL1.GetConsoleLangId; Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetConsoleLangId); @@ -67,8 +66,8 @@ HRESULT ApiDispatchers::ServerGetConsoleLangId(_Inout_ CONSOLE_API_MSG * const m return m->_pApiRoutines->GetConsoleLangIdImpl(a->LangId); } -[[nodiscard]] -HRESULT ApiDispatchers::ServerGenerateConsoleCtrlEvent(_Inout_ CONSOLE_API_MSG * const m, _Inout_ BOOL* const /*pbReplyPending*/) +[[nodiscard]] HRESULT ApiDispatchers::ServerGenerateConsoleCtrlEvent(_Inout_ CONSOLE_API_MSG* const m, + _Inout_ BOOL* const /*pbReplyPending*/) { CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); CONSOLE_CTRLEVENT_MSG* const a = &m->u.consoleMsgL2.GenerateConsoleCtrlEvent; diff --git a/src/server/ApiMessage.cpp b/src/server/ApiMessage.cpp index bd76d71bf..3b99ce93e 100644 --- a/src/server/ApiMessage.cpp +++ b/src/server/ApiMessage.cpp @@ -8,7 +8,7 @@ #include "ApiMessage.h" #include "DeviceComm.h" -_CONSOLE_API_MSG::_CONSOLE_API_MSG() : +_CONSOLE_API_MSG::_CONSOLE_API_MSG() : _pDeviceComm(nullptr), _pApiRoutines(nullptr) { @@ -33,10 +33,9 @@ ConsoleHandleData* _CONSOLE_API_MSG::GetObjectHandle() const // - cbSize - Supplies the number of bytes to be read into the buffer. // Return Value: // - HRESULT indicating if the payload was successfully read. -[[nodiscard]] -HRESULT _CONSOLE_API_MSG::ReadMessageInput(const ULONG cbOffset, - _Out_writes_bytes_(cbSize) PVOID pvBuffer, - const ULONG cbSize) +[[nodiscard]] HRESULT _CONSOLE_API_MSG::ReadMessageInput(const ULONG cbOffset, + _Out_writes_bytes_(cbSize) PVOID pvBuffer, + const ULONG cbSize) { CD_IO_OPERATION IoOperation; IoOperation.Identifier = Descriptor.Identifier; @@ -56,9 +55,8 @@ HRESULT _CONSOLE_API_MSG::ReadMessageInput(const ULONG cbOffset, // - Size - Receives the size, in bytes, of the input buffer. // Return Value: // - HRESULT indicating if the input buffer was successfully retrieved. -[[nodiscard]] -HRESULT _CONSOLE_API_MSG::GetInputBuffer(_Outptr_result_bytebuffer_(*pcbSize) void** const ppvBuffer, - _Out_ ULONG* const pcbSize) +[[nodiscard]] HRESULT _CONSOLE_API_MSG::GetInputBuffer(_Outptr_result_bytebuffer_(*pcbSize) void** const ppvBuffer, + _Out_ ULONG* const pcbSize) { // Initialize the buffer if it hasn't been initialized yet. if (State.InputBuffer == nullptr) @@ -93,10 +91,9 @@ HRESULT _CONSOLE_API_MSG::GetInputBuffer(_Outptr_result_bytebuffer_(*pcbSize) vo // - Size - Receives the size, in bytes, of the output buffer. // Return Value: // - HRESULT indicating if the output buffer was successfully retrieved. -[[nodiscard]] -HRESULT _CONSOLE_API_MSG::GetAugmentedOutputBuffer(const ULONG cbFactor, - _Outptr_result_bytebuffer_(*pcbSize) PVOID * const ppvBuffer, - _Out_ PULONG pcbSize) +[[nodiscard]] HRESULT _CONSOLE_API_MSG::GetAugmentedOutputBuffer(const ULONG cbFactor, + _Outptr_result_bytebuffer_(*pcbSize) PVOID* const ppvBuffer, + _Out_ PULONG pcbSize) { // Initialize the buffer if it hasn't been initialized yet. if (State.OutputBuffer == nullptr) @@ -106,7 +103,7 @@ HRESULT _CONSOLE_API_MSG::GetAugmentedOutputBuffer(const ULONG cbFactor, ULONG cbWriteSize = Descriptor.OutputSize - State.WriteOffset; RETURN_IF_FAILED(ULongMult(cbWriteSize, cbFactor, &cbWriteSize)); - BYTE* pPayload = new(std::nothrow) BYTE[cbWriteSize]; + BYTE* pPayload = new (std::nothrow) BYTE[cbWriteSize]; RETURN_IF_NULL_ALLOC(pPayload); ZeroMemory(pPayload, sizeof(BYTE) * cbWriteSize); @@ -130,9 +127,8 @@ HRESULT _CONSOLE_API_MSG::GetAugmentedOutputBuffer(const ULONG cbFactor, // - Size - Receives the size, in bytes, of the output buffer. // Return Value: // - HRESULT indicating if the output buffer was successfully retrieved. -[[nodiscard]] -HRESULT _CONSOLE_API_MSG::GetOutputBuffer(_Outptr_result_bytebuffer_(*pcbSize) void** const ppvBuffer, - _Out_ ULONG * const pcbSize) +[[nodiscard]] HRESULT _CONSOLE_API_MSG::GetOutputBuffer(_Outptr_result_bytebuffer_(*pcbSize) void** const ppvBuffer, + _Out_ ULONG* const pcbSize) { return GetAugmentedOutputBuffer(1, ppvBuffer, pcbSize); } @@ -146,8 +142,7 @@ HRESULT _CONSOLE_API_MSG::GetOutputBuffer(_Outptr_result_bytebuffer_(*pcbSize) v // - // Return Value: // - HRESULT indicating if the payload was successfully written if applicable. -[[nodiscard]] -HRESULT _CONSOLE_API_MSG::ReleaseMessageBuffers() +[[nodiscard]] HRESULT _CONSOLE_API_MSG::ReleaseMessageBuffers() { HRESULT hr = S_OK; diff --git a/src/server/ApiMessage.h b/src/server/ApiMessage.h index e86b3a189..8e76ccff8 100644 --- a/src/server/ApiMessage.h +++ b/src/server/ApiMessage.h @@ -61,21 +61,16 @@ public: ConsoleProcessHandle* GetProcessHandle() const; ConsoleHandleData* GetObjectHandle() const; - [[nodiscard]] - HRESULT ReadMessageInput(const ULONG cbOffset, _Out_writes_bytes_(cbSize) PVOID pvBuffer, const ULONG cbSize); - [[nodiscard]] - HRESULT GetAugmentedOutputBuffer(const ULONG cbFactor, - _Outptr_result_bytebuffer_(*pcbSize) PVOID * ppvBuffer, - _Out_ PULONG pcbSize); - [[nodiscard]] - HRESULT GetOutputBuffer(_Outptr_result_bytebuffer_(*pcbSize) void** const ppvBuffer, _Out_ ULONG* const pcbSize); - [[nodiscard]] - HRESULT GetInputBuffer(_Outptr_result_bytebuffer_(*pcbSize) void** const ppvBuffer, _Out_ ULONG* const pcbSize); + [[nodiscard]] HRESULT ReadMessageInput(const ULONG cbOffset, _Out_writes_bytes_(cbSize) PVOID pvBuffer, const ULONG cbSize); + [[nodiscard]] HRESULT GetAugmentedOutputBuffer(const ULONG cbFactor, + _Outptr_result_bytebuffer_(*pcbSize) PVOID* ppvBuffer, + _Out_ PULONG pcbSize); + [[nodiscard]] HRESULT GetOutputBuffer(_Outptr_result_bytebuffer_(*pcbSize) void** const ppvBuffer, _Out_ ULONG* const pcbSize); + [[nodiscard]] HRESULT GetInputBuffer(_Outptr_result_bytebuffer_(*pcbSize) void** const ppvBuffer, _Out_ ULONG* const pcbSize); - [[nodiscard]] - HRESULT ReleaseMessageBuffers(); + [[nodiscard]] HRESULT ReleaseMessageBuffers(); void SetReplyStatus(const NTSTATUS Status); void SetReplyInformation(const ULONG_PTR pInformation); -} CONSOLE_API_MSG, *PCONSOLE_API_MSG, *const PCCONSOLE_API_MSG; +} CONSOLE_API_MSG, *PCONSOLE_API_MSG, * const PCCONSOLE_API_MSG; diff --git a/src/server/ApiMessageState.cpp b/src/server/ApiMessageState.cpp index 13a5dbb1a..685bd5def 100644 --- a/src/server/ApiMessageState.cpp +++ b/src/server/ApiMessageState.cpp @@ -4,4 +4,3 @@ #include "precomp.h" #include "ApiMessageState.h" - diff --git a/src/server/ApiMessageState.h b/src/server/ApiMessageState.h index 0259ce0ae..bd5cf8183 100644 --- a/src/server/ApiMessageState.h +++ b/src/server/ApiMessageState.h @@ -25,4 +25,4 @@ typedef struct _CONSOLE_API_STATE ULONG OutputBufferSize; PVOID InputBuffer; PVOID OutputBuffer; -} CONSOLE_API_STATE, *PCONSOLE_API_STATE, *const PCCONSOLE_API_STATE; +} CONSOLE_API_STATE, *PCONSOLE_API_STATE, * const PCCONSOLE_API_STATE; diff --git a/src/server/ApiSorter.cpp b/src/server/ApiSorter.cpp index 6adf0f804..84cc81f96 100644 --- a/src/server/ApiSorter.cpp +++ b/src/server/ApiSorter.cpp @@ -9,11 +9,23 @@ #include "../host/tracing.hpp" -#define CONSOLE_API_STRUCT(Routine, Struct, TraceName) { Routine, sizeof(Struct), TraceName } -#define CONSOLE_API_NO_PARAMETER(Routine, TraceName) { Routine, 0, TraceName } +#define CONSOLE_API_STRUCT(Routine, Struct, TraceName) \ + { \ + Routine, sizeof(Struct), TraceName \ + } +#define CONSOLE_API_NO_PARAMETER(Routine, TraceName) \ + { \ + Routine, 0, TraceName \ + } -#define CONSOLE_API_DEPRECATED(Struct) { ApiDispatchers::ServerDeprecatedApi, sizeof(Struct), "Deprecated"} -#define CONSOLE_API_DEPRECATED_NO_PARAM() {ApiDispatchers::ServerDeprecatedApi, 0, "Deprecated"} +#define CONSOLE_API_DEPRECATED(Struct) \ + { \ + ApiDispatchers::ServerDeprecatedApi, sizeof(Struct), "Deprecated" \ + } +#define CONSOLE_API_DEPRECATED_NO_PARAM() \ + { \ + ApiDispatchers::ServerDeprecatedApi, 0, "Deprecated" \ + } typedef struct _CONSOLE_API_DESCRIPTOR { @@ -24,7 +36,7 @@ typedef struct _CONSOLE_API_DESCRIPTOR typedef struct _CONSOLE_API_LAYER_DESCRIPTOR { - const CONSOLE_API_DESCRIPTOR *Descriptor; + const CONSOLE_API_DESCRIPTOR* Descriptor; ULONG Count; } CONSOLE_API_LAYER_DESCRIPTOR, *PCONSOLE_API_LAYER_DESCRIPTOR; @@ -139,7 +151,7 @@ PCONSOLE_API_MSG ApiSorter::ConsoleDispatchRequest(_Inout_ PCONSOLE_API_MSG Mess goto Complete; } - CONSOLE_API_DESCRIPTOR const *Descriptor = &ConsoleApiLayerTable[LayerNumber].Descriptor[ApiNumber]; + CONSOLE_API_DESCRIPTOR const* Descriptor = &ConsoleApiLayerTable[LayerNumber].Descriptor[ApiNumber]; // Validate the argument size and call the API. if ((Message->Descriptor.InputSize < sizeof(CONSOLE_MSG_HEADER)) || diff --git a/src/server/ApiSorter.h b/src/server/ApiSorter.h index fe7ab947a..6366b2854 100644 --- a/src/server/ApiSorter.h +++ b/src/server/ApiSorter.h @@ -12,23 +12,24 @@ Author: - Michael Niksa (miniksa) 12-Oct-2016 Revision History: -- Adapted from original items in srvinit.cpp +- Adapted from original items in srvinit.cpp --*/ #pragma once #include "ApiMessage.h" -typedef HRESULT(*PCONSOLE_API_ROUTINE) (_Inout_ PCONSOLE_API_MSG m, _Inout_ PBOOL ReplyPending); +typedef HRESULT (*PCONSOLE_API_ROUTINE)(_Inout_ PCONSOLE_API_MSG m, _Inout_ PBOOL ReplyPending); // These are required for wait routines to accurately identify which function is waited on and needs to be dispatched later. // It's stored here so it can be easily aligned with the layer descriptions below. // 0x01 stands for level 1 API (layers are 1-based) // 0x000004 stands for the 5th one down in the layer structure (call IDs are 0-based) -#define API_NUMBER_GETCONSOLEINPUT 0x01000004 -#define API_NUMBER_READCONSOLE 0x01000005 -#define API_NUMBER_WRITECONSOLE 0x01000006 - +// clang-format off +#define API_NUMBER_GETCONSOLEINPUT 0x01000004 +#define API_NUMBER_READCONSOLE 0x01000005 +#define API_NUMBER_WRITECONSOLE 0x01000006 +// clang-format on class ApiSorter { diff --git a/src/server/DeviceComm.cpp b/src/server/DeviceComm.cpp index ce4572795..10cee37f2 100644 --- a/src/server/DeviceComm.cpp +++ b/src/server/DeviceComm.cpp @@ -10,7 +10,6 @@ DeviceComm::DeviceComm(_In_ HANDLE Server) : THROW_HR_IF(E_HANDLE, Server == INVALID_HANDLE_VALUE); } - DeviceComm::~DeviceComm() { } @@ -23,8 +22,7 @@ DeviceComm::~DeviceComm() // - pServerInfo - Structure containing information required to initialize driver state for this console connection. // Return Value: // - HRESULT S_OK or suitable error. -[[nodiscard]] -HRESULT DeviceComm::SetServerInformation(_In_ CD_IO_SERVER_INFORMATION* const pServerInfo) const +[[nodiscard]] HRESULT DeviceComm::SetServerInformation(_In_ CD_IO_SERVER_INFORMATION* const pServerInfo) const { return _CallIoctl(IOCTL_CONDRV_SET_SERVER_INFORMATION, pServerInfo, @@ -40,9 +38,8 @@ HRESULT DeviceComm::SetServerInformation(_In_ CD_IO_SERVER_INFORMATION* const pS // - pMessage - A structure to hold the message data retrieved from the driver. // Return Value: // - HRESULT S_OK or suitable error. -[[nodiscard]] -HRESULT DeviceComm::ReadIo(_In_opt_ PCONSOLE_API_MSG const pReplyMsg, - _Out_ CONSOLE_API_MSG* const pMessage) const +[[nodiscard]] HRESULT DeviceComm::ReadIo(_In_opt_ PCONSOLE_API_MSG const pReplyMsg, + _Out_ CONSOLE_API_MSG* const pMessage) const { HRESULT hr = _CallIoctl(IOCTL_CONDRV_READ_IO, pReplyMsg == nullptr ? nullptr : &pReplyMsg->Complete, @@ -65,8 +62,7 @@ HRESULT DeviceComm::ReadIo(_In_opt_ PCONSOLE_API_MSG const pReplyMsg, // - pCompletion - Completion structure from the previous activity (can be used in lieu of calling CompleteIo seperately.) // Return Value: // - HRESULT S_OK or suitable error. -[[nodiscard]] -HRESULT DeviceComm::CompleteIo(_In_ CD_IO_COMPLETE* const pCompletion) const +[[nodiscard]] HRESULT DeviceComm::CompleteIo(_In_ CD_IO_COMPLETE* const pCompletion) const { return _CallIoctl(IOCTL_CONDRV_COMPLETE_IO, pCompletion, @@ -82,8 +78,7 @@ HRESULT DeviceComm::CompleteIo(_In_ CD_IO_COMPLETE* const pCompletion) const // to hold retrieved buffered input data from the client application. // Return Value: // - HRESULT S_OK or suitable error. -[[nodiscard]] -HRESULT DeviceComm::ReadInput(_In_ CD_IO_OPERATION* const pIoOperation) const +[[nodiscard]] HRESULT DeviceComm::ReadInput(_In_ CD_IO_OPERATION* const pIoOperation) const { return _CallIoctl(IOCTL_CONDRV_READ_INPUT, pIoOperation, @@ -99,8 +94,7 @@ HRESULT DeviceComm::ReadInput(_In_ CD_IO_OPERATION* const pIoOperation) const // to hold buffered output data to be sent to the client application. // Return Value: // - HRESULT S_OK or suitable error. -[[nodiscard]] -HRESULT DeviceComm::WriteOutput(_In_ CD_IO_OPERATION* const pIoOperation) const +[[nodiscard]] HRESULT DeviceComm::WriteOutput(_In_ CD_IO_OPERATION* const pIoOperation) const { return _CallIoctl(IOCTL_CONDRV_WRITE_OUTPUT, pIoOperation, @@ -116,8 +110,7 @@ HRESULT DeviceComm::WriteOutput(_In_ CD_IO_OPERATION* const pIoOperation) const // - // Return Value: // - HRESULT S_OK or suitable error. -[[nodiscard]] -HRESULT DeviceComm::AllowUIAccess() const +[[nodiscard]] HRESULT DeviceComm::AllowUIAccess() const { return _CallIoctl(IOCTL_CONDRV_ALLOW_VIA_UIACCESS, nullptr, @@ -137,12 +130,11 @@ HRESULT DeviceComm::AllowUIAccess() const // - cbOutBufferSize - The length in bytes of the optional output buffer. // Return Value: // - HRESULT S_OK or suitable error. -[[nodiscard]] -HRESULT DeviceComm::_CallIoctl(_In_ DWORD dwIoControlCode, - _In_reads_bytes_opt_(cbInBufferSize) PVOID pInBuffer, - _In_ DWORD cbInBufferSize, - _Out_writes_bytes_opt_(cbOutBufferSize) PVOID pOutBuffer, - _In_ DWORD cbOutBufferSize) const +[[nodiscard]] HRESULT DeviceComm::_CallIoctl(_In_ DWORD dwIoControlCode, + _In_reads_bytes_opt_(cbInBufferSize) PVOID pInBuffer, + _In_ DWORD cbInBufferSize, + _Out_writes_bytes_opt_(cbOutBufferSize) PVOID pOutBuffer, + _In_ DWORD cbOutBufferSize) const { // See: https://msdn.microsoft.com/en-us/library/windows/desktop/aa363216(v=vs.85).aspx // Written is unused but cannot be nullptr because we aren't using overlapped. diff --git a/src/server/DeviceComm.h b/src/server/DeviceComm.h index 1864199eb..ec78caca5 100644 --- a/src/server/DeviceComm.h +++ b/src/server/DeviceComm.h @@ -26,31 +26,22 @@ public: DeviceComm(_In_ HANDLE Server); ~DeviceComm(); - [[nodiscard]] - HRESULT SetServerInformation(_In_ CD_IO_SERVER_INFORMATION* const pServerInfo) const; - [[nodiscard]] - HRESULT ReadIo(_In_opt_ PCONSOLE_API_MSG const pReplyMsg, - _Out_ CONSOLE_API_MSG* const pMessage) const; - [[nodiscard]] - HRESULT CompleteIo(_In_ CD_IO_COMPLETE* const pCompletion) const; + [[nodiscard]] HRESULT SetServerInformation(_In_ CD_IO_SERVER_INFORMATION* const pServerInfo) const; + [[nodiscard]] HRESULT ReadIo(_In_opt_ PCONSOLE_API_MSG const pReplyMsg, + _Out_ CONSOLE_API_MSG* const pMessage) const; + [[nodiscard]] HRESULT CompleteIo(_In_ CD_IO_COMPLETE* const pCompletion) const; - [[nodiscard]] - HRESULT ReadInput(_In_ CD_IO_OPERATION* const pIoOperation) const; - [[nodiscard]] - HRESULT WriteOutput(_In_ CD_IO_OPERATION* const pIoOperation) const; + [[nodiscard]] HRESULT ReadInput(_In_ CD_IO_OPERATION* const pIoOperation) const; + [[nodiscard]] HRESULT WriteOutput(_In_ CD_IO_OPERATION* const pIoOperation) const; - [[nodiscard]] - HRESULT AllowUIAccess() const; + [[nodiscard]] HRESULT AllowUIAccess() const; private: - - [[nodiscard]] - HRESULT _CallIoctl(_In_ DWORD dwIoControlCode, - _In_reads_bytes_opt_(cbInBufferSize) PVOID pInBuffer, - _In_ DWORD cbInBufferSize, - _Out_writes_bytes_opt_(cbOutBufferSize) PVOID pOutBuffer, - _In_ DWORD cbOutBufferSize) const; + [[nodiscard]] HRESULT _CallIoctl(_In_ DWORD dwIoControlCode, + _In_reads_bytes_opt_(cbInBufferSize) PVOID pInBuffer, + _In_ DWORD cbInBufferSize, + _Out_writes_bytes_opt_(cbOutBufferSize) PVOID pOutBuffer, + _In_ DWORD cbOutBufferSize) const; wil::unique_handle _Server; - }; diff --git a/src/server/DeviceHandle.cpp b/src/server/DeviceHandle.cpp index c4a11fc03..35f898684 100644 --- a/src/server/DeviceHandle.cpp +++ b/src/server/DeviceHandle.cpp @@ -6,7 +6,7 @@ #include "WinNTControl.h" -#define FILE_SYNCHRONOUS_IO_NONALERT 0x00000020 +#define FILE_SYNCHRONOUS_IO_NONALERT 0x00000020 /*++ Routine Description: @@ -24,8 +24,7 @@ Arguments: Return Value: - NTSTATUS indicating if the client was successfully created. --*/ -[[nodiscard]] -NTSTATUS +[[nodiscard]] NTSTATUS DeviceHandle::CreateClientHandle( _Out_ PHANDLE Handle, _In_ HANDLE ServerHandle, @@ -51,8 +50,7 @@ Arguments: Return Value: - NTSTATUS indicating if the console was successfully created. --*/ -[[nodiscard]] -NTSTATUS +[[nodiscard]] NTSTATUS DeviceHandle::CreateServerHandle( _Out_ PHANDLE Handle, _In_ BOOLEAN Inheritable) @@ -82,8 +80,7 @@ Arguments: Return Value: - NTSTATUS indicating if the handle was successfully created. --*/ -[[nodiscard]] -NTSTATUS +[[nodiscard]] NTSTATUS DeviceHandle::_CreateHandle( _Out_ PHANDLE Handle, _In_ PCWSTR DeviceName, diff --git a/src/server/DeviceHandle.h b/src/server/DeviceHandle.h index 51054a576..16c90f545 100644 --- a/src/server/DeviceHandle.h +++ b/src/server/DeviceHandle.h @@ -17,30 +17,24 @@ Revision History: #pragma once namespace DeviceHandle { - [[nodiscard]] - NTSTATUS - CreateServerHandle( - _Out_ PHANDLE Handle, - _In_ BOOLEAN Inheritable - ); + [[nodiscard]] NTSTATUS + CreateServerHandle( + _Out_ PHANDLE Handle, + _In_ BOOLEAN Inheritable); - [[nodiscard]] - NTSTATUS - CreateClientHandle( - _Out_ PHANDLE Handle, - _In_ HANDLE ServerHandle, - _In_ PCWSTR Name, - _In_ BOOLEAN Inheritable - ); + [[nodiscard]] NTSTATUS + CreateClientHandle( + _Out_ PHANDLE Handle, + _In_ HANDLE ServerHandle, + _In_ PCWSTR Name, + _In_ BOOLEAN Inheritable); - [[nodiscard]] - NTSTATUS - _CreateHandle( - _Out_ PHANDLE Handle, - _In_ PCWSTR DeviceName, - _In_ ACCESS_MASK DesiredAccess, - _In_opt_ HANDLE Parent, - _In_ BOOLEAN Inheritable, - _In_ ULONG OpenOptions - ); + [[nodiscard]] NTSTATUS + _CreateHandle( + _Out_ PHANDLE Handle, + _In_ PCWSTR DeviceName, + _In_ ACCESS_MASK DesiredAccess, + _In_opt_ HANDLE Parent, + _In_ BOOLEAN Inheritable, + _In_ ULONG OpenOptions); }; diff --git a/src/server/Entrypoints.cpp b/src/server/Entrypoints.cpp index 8a7a951b3..cc77e2f3e 100644 --- a/src/server/Entrypoints.cpp +++ b/src/server/Entrypoints.cpp @@ -9,8 +9,8 @@ #include "winbasep.h" -[[nodiscard]] -HRESULT Entrypoints::StartConsoleForServerHandle(const HANDLE ServerHandle, const ConsoleArguments* const args) +[[nodiscard]] HRESULT Entrypoints::StartConsoleForServerHandle(const HANDLE ServerHandle, + const ConsoleArguments* const args) { return ConsoleCreateIoThreadLegacy(ServerHandle, args); } @@ -18,10 +18,10 @@ HRESULT Entrypoints::StartConsoleForServerHandle(const HANDLE ServerHandle, cons // this function has unreachable code due to its unusual lifetime. We // disable the warning about it here. #pragma warning(push) -#pragma warning(disable:4702) +#pragma warning(disable : 4702) -[[nodiscard]] -HRESULT Entrypoints::StartConsoleForCmdLine(_In_ PCWSTR pwszCmdLine, const ConsoleArguments* const args) +[[nodiscard]] HRESULT Entrypoints::StartConsoleForCmdLine(_In_ PCWSTR pwszCmdLine, + const ConsoleArguments* const args) { // Create a scope because we're going to exit thread if everything goes well. // This scope will ensure all C++ objects and smart pointers get a chance to destruct before ExitThread is called. @@ -115,8 +115,7 @@ HRESULT Entrypoints::StartConsoleForCmdLine(_In_ PCWSTR pwszCmdLine, const Conso 0, &AttributeListSize)); // Set cleanup data for ProcThreadAttributeList when successful. - auto CleanupProcThreadAttribute = wil::scope_exit([&] - { + auto CleanupProcThreadAttribute = wil::scope_exit([&] { DeleteProcThreadAttributeList(StartupInformation.lpAttributeList); }); @@ -136,12 +135,12 @@ HRESULT Entrypoints::StartConsoleForCmdLine(_In_ PCWSTR pwszCmdLine, const Conso HandleList[2] = StartupInformation.StartupInfo.hStdError; RETURN_IF_WIN32_BOOL_FALSE(UpdateProcThreadAttribute(StartupInformation.lpAttributeList, - 0, - PROC_THREAD_ATTRIBUTE_HANDLE_LIST, - &HandleList[0], - sizeof HandleList, - NULL, - NULL)); + 0, + PROC_THREAD_ATTRIBUTE_HANDLE_LIST, + &HandleList[0], + sizeof HandleList, + NULL, + NULL)); // We have to copy the command line string we're given because CreateProcessW has to be called with mutable data. if (wcslen(pwszCmdLine) == 0) diff --git a/src/server/Entrypoints.h b/src/server/Entrypoints.h index a9c5b4e7d..e12c05afd 100644 --- a/src/server/Entrypoints.h +++ b/src/server/Entrypoints.h @@ -20,8 +20,6 @@ class ConsoleArguments; namespace Entrypoints { - [[nodiscard]] - HRESULT StartConsoleForServerHandle(const HANDLE ServerHandle, const ConsoleArguments* const args); - [[nodiscard]] - HRESULT StartConsoleForCmdLine(_In_ PCWSTR pwszCmdLine, const ConsoleArguments* const args); + [[nodiscard]] HRESULT StartConsoleForServerHandle(const HANDLE ServerHandle, const ConsoleArguments* const args); + [[nodiscard]] HRESULT StartConsoleForCmdLine(_In_ PCWSTR pwszCmdLine, const ConsoleArguments* const args); }; diff --git a/src/server/IApiRoutines.h b/src/server/IApiRoutines.h index 7fe612860..df2e4a7d4 100644 --- a/src/server/IApiRoutines.h +++ b/src/server/IApiRoutines.h @@ -36,7 +36,6 @@ class INPUT_READ_HANDLE_DATA; class IApiRoutines { public: - #pragma region ObjectManagement // TODO: 9115192 - We will need to make the objects via an interface eventually. This represents that idea. /*virtual HRESULT CreateInitialObjects(_Out_ IConsoleInputObject** const ppInputObject, @@ -56,383 +55,317 @@ public: virtual void GetConsoleOutputModeImpl(SCREEN_INFORMATION& context, ULONG& mode) noexcept = 0; - [[nodiscard]] - virtual HRESULT SetConsoleInputModeImpl(IConsoleInputObject& context, - const ULONG mode) noexcept = 0; + [[nodiscard]] virtual HRESULT SetConsoleInputModeImpl(IConsoleInputObject& context, + const ULONG mode) noexcept = 0; - [[nodiscard]] - virtual HRESULT SetConsoleOutputModeImpl(IConsoleOutputObject& context, - const ULONG mode) noexcept = 0; + [[nodiscard]] virtual HRESULT SetConsoleOutputModeImpl(IConsoleOutputObject& context, + const ULONG mode) noexcept = 0; - [[nodiscard]] - virtual HRESULT GetNumberOfConsoleInputEventsImpl(const IConsoleInputObject& context, - ULONG& events) noexcept = 0; + [[nodiscard]] virtual HRESULT GetNumberOfConsoleInputEventsImpl(const IConsoleInputObject& context, + ULONG& events) noexcept = 0; - [[nodiscard]] - virtual HRESULT PeekConsoleInputAImpl(IConsoleInputObject& context, - std::deque>& outEvents, - const size_t eventsToRead, - INPUT_READ_HANDLE_DATA& readHandleState, - std::unique_ptr& waiter) noexcept = 0; + [[nodiscard]] virtual HRESULT PeekConsoleInputAImpl(IConsoleInputObject& context, + std::deque>& outEvents, + const size_t eventsToRead, + INPUT_READ_HANDLE_DATA& readHandleState, + std::unique_ptr& waiter) noexcept = 0; - [[nodiscard]] - virtual HRESULT PeekConsoleInputWImpl(IConsoleInputObject& context, - std::deque>& outEvents, - const size_t eventsToRead, - INPUT_READ_HANDLE_DATA& readHandleState, - std::unique_ptr& waiter) noexcept = 0; + [[nodiscard]] virtual HRESULT PeekConsoleInputWImpl(IConsoleInputObject& context, + std::deque>& outEvents, + const size_t eventsToRead, + INPUT_READ_HANDLE_DATA& readHandleState, + std::unique_ptr& waiter) noexcept = 0; - [[nodiscard]] - virtual HRESULT ReadConsoleInputAImpl(IConsoleInputObject& context, - std::deque>& outEvents, - const size_t eventsToRead, - INPUT_READ_HANDLE_DATA& readHandleState, - std::unique_ptr& waiter) noexcept = 0; + [[nodiscard]] virtual HRESULT ReadConsoleInputAImpl(IConsoleInputObject& context, + std::deque>& outEvents, + const size_t eventsToRead, + INPUT_READ_HANDLE_DATA& readHandleState, + std::unique_ptr& waiter) noexcept = 0; - [[nodiscard]] - virtual HRESULT ReadConsoleInputWImpl(IConsoleInputObject& context, - std::deque>& outEvents, - const size_t eventsToRead, - INPUT_READ_HANDLE_DATA& readHandleState, - std::unique_ptr& waiter) noexcept = 0; + [[nodiscard]] virtual HRESULT ReadConsoleInputWImpl(IConsoleInputObject& context, + std::deque>& outEvents, + const size_t eventsToRead, + INPUT_READ_HANDLE_DATA& readHandleState, + std::unique_ptr& waiter) noexcept = 0; - [[nodiscard]] - virtual HRESULT ReadConsoleAImpl(IConsoleInputObject& context, - gsl::span buffer, - size_t& written, - std::unique_ptr& waiter, - const std::string_view initialData, - const std::wstring_view exeName, - INPUT_READ_HANDLE_DATA& readHandleState, - const HANDLE clientHandle, - const DWORD controlWakeupMask, - DWORD& controlKeyState) noexcept = 0; + [[nodiscard]] virtual HRESULT ReadConsoleAImpl(IConsoleInputObject& context, + gsl::span buffer, + size_t& written, + std::unique_ptr& waiter, + const std::string_view initialData, + const std::wstring_view exeName, + INPUT_READ_HANDLE_DATA& readHandleState, + const HANDLE clientHandle, + const DWORD controlWakeupMask, + DWORD& controlKeyState) noexcept = 0; - [[nodiscard]] - virtual HRESULT ReadConsoleWImpl(IConsoleInputObject& context, - gsl::span buffer, - size_t& written, - std::unique_ptr& waiter, - const std::string_view initialData, - const std::wstring_view exeName, - INPUT_READ_HANDLE_DATA& readHandleState, - const HANDLE clientHandle, - const DWORD controlWakeupMask, - DWORD& controlKeyState) noexcept = 0; + [[nodiscard]] virtual HRESULT ReadConsoleWImpl(IConsoleInputObject& context, + gsl::span buffer, + size_t& written, + std::unique_ptr& waiter, + const std::string_view initialData, + const std::wstring_view exeName, + INPUT_READ_HANDLE_DATA& readHandleState, + const HANDLE clientHandle, + const DWORD controlWakeupMask, + DWORD& controlKeyState) noexcept = 0; - [[nodiscard]] - virtual HRESULT WriteConsoleAImpl(IConsoleOutputObject& context, - const std::string_view buffer, - size_t& read, - std::unique_ptr& waiter) noexcept = 0; + [[nodiscard]] virtual HRESULT WriteConsoleAImpl(IConsoleOutputObject& context, + const std::string_view buffer, + size_t& read, + std::unique_ptr& waiter) noexcept = 0; - [[nodiscard]] - virtual HRESULT WriteConsoleWImpl(IConsoleOutputObject& context, - const std::wstring_view buffer, - size_t& read, - std::unique_ptr& waiter) noexcept = 0; + [[nodiscard]] virtual HRESULT WriteConsoleWImpl(IConsoleOutputObject& context, + const std::wstring_view buffer, + size_t& read, + std::unique_ptr& waiter) noexcept = 0; #pragma region Thread Creation Info - [[nodiscard]] - virtual HRESULT GetConsoleLangIdImpl(LANGID& langId) noexcept = 0; + [[nodiscard]] virtual HRESULT GetConsoleLangIdImpl(LANGID& langId) noexcept = 0; #pragma endregion #pragma endregion #pragma region L2 - [[nodiscard]] - virtual HRESULT FillConsoleOutputAttributeImpl(IConsoleOutputObject& OutContext, - const WORD attribute, - const size_t lengthToWrite, - const COORD startingCoordinate, - size_t& cellsModified) noexcept = 0; + [[nodiscard]] virtual HRESULT FillConsoleOutputAttributeImpl(IConsoleOutputObject& OutContext, + const WORD attribute, + const size_t lengthToWrite, + const COORD startingCoordinate, + size_t& cellsModified) noexcept = 0; - [[nodiscard]] - virtual HRESULT FillConsoleOutputCharacterAImpl(IConsoleOutputObject& OutContext, - const char character, - const size_t lengthToWrite, - const COORD startingCoordinate, - size_t& cellsModified) noexcept = 0; + [[nodiscard]] virtual HRESULT FillConsoleOutputCharacterAImpl(IConsoleOutputObject& OutContext, + const char character, + const size_t lengthToWrite, + const COORD startingCoordinate, + size_t& cellsModified) noexcept = 0; - [[nodiscard]] - virtual HRESULT FillConsoleOutputCharacterWImpl(IConsoleOutputObject& OutContext, - const wchar_t character, - const size_t lengthToWrite, - const COORD startingCoordinate, - size_t& cellsModified) noexcept = 0; + [[nodiscard]] virtual HRESULT FillConsoleOutputCharacterWImpl(IConsoleOutputObject& OutContext, + const wchar_t character, + const size_t lengthToWrite, + const COORD startingCoordinate, + size_t& cellsModified) noexcept = 0; virtual void SetConsoleActiveScreenBufferImpl(IConsoleOutputObject& newContext) noexcept = 0; virtual void FlushConsoleInputBuffer(IConsoleInputObject& context) noexcept = 0; - [[nodiscard]] - virtual HRESULT SetConsoleInputCodePageImpl(const ULONG codepage) noexcept = 0; + [[nodiscard]] virtual HRESULT SetConsoleInputCodePageImpl(const ULONG codepage) noexcept = 0; - [[nodiscard]] - virtual HRESULT SetConsoleOutputCodePageImpl(const ULONG codepage) noexcept = 0; + [[nodiscard]] virtual HRESULT SetConsoleOutputCodePageImpl(const ULONG codepage) noexcept = 0; virtual void GetConsoleCursorInfoImpl(const SCREEN_INFORMATION& context, ULONG& size, bool& isVisible) noexcept = 0; - [[nodiscard]] - virtual HRESULT SetConsoleCursorInfoImpl(IConsoleOutputObject& context, - const ULONG size, - const bool isVisible) noexcept = 0; + [[nodiscard]] virtual HRESULT SetConsoleCursorInfoImpl(IConsoleOutputObject& context, + const ULONG size, + const bool isVisible) noexcept = 0; // driver will pare down for non-Ex method virtual void GetConsoleScreenBufferInfoExImpl(const IConsoleOutputObject& context, CONSOLE_SCREEN_BUFFER_INFOEX& data) noexcept = 0; - [[nodiscard]] - virtual HRESULT SetConsoleScreenBufferInfoExImpl(IConsoleOutputObject& OutContext, - const CONSOLE_SCREEN_BUFFER_INFOEX& data) noexcept = 0; + [[nodiscard]] virtual HRESULT SetConsoleScreenBufferInfoExImpl(IConsoleOutputObject& OutContext, + const CONSOLE_SCREEN_BUFFER_INFOEX& data) noexcept = 0; - [[nodiscard]] - virtual HRESULT SetConsoleScreenBufferSizeImpl(IConsoleOutputObject& context, - const COORD size) noexcept = 0; + [[nodiscard]] virtual HRESULT SetConsoleScreenBufferSizeImpl(IConsoleOutputObject& context, + const COORD size) noexcept = 0; - [[nodiscard]] - virtual HRESULT SetConsoleCursorPositionImpl(IConsoleOutputObject& context, - const COORD position) noexcept = 0; + [[nodiscard]] virtual HRESULT SetConsoleCursorPositionImpl(IConsoleOutputObject& context, + const COORD position) noexcept = 0; virtual void GetLargestConsoleWindowSizeImpl(const IConsoleOutputObject& context, COORD& size) noexcept = 0; - [[nodiscard]] - virtual HRESULT ScrollConsoleScreenBufferAImpl(IConsoleOutputObject& context, - const SMALL_RECT& source, - const COORD target, - std::optional clip, - const char fillCharacter, - const WORD fillAttribute) noexcept = 0; + [[nodiscard]] virtual HRESULT ScrollConsoleScreenBufferAImpl(IConsoleOutputObject& context, + const SMALL_RECT& source, + const COORD target, + std::optional clip, + const char fillCharacter, + const WORD fillAttribute) noexcept = 0; - [[nodiscard]] - virtual HRESULT ScrollConsoleScreenBufferWImpl(IConsoleOutputObject& context, - const SMALL_RECT& source, - const COORD target, - std::optional clip, - const wchar_t fillCharacter, - const WORD fillAttribute) noexcept = 0; + [[nodiscard]] virtual HRESULT ScrollConsoleScreenBufferWImpl(IConsoleOutputObject& context, + const SMALL_RECT& source, + const COORD target, + std::optional clip, + const wchar_t fillCharacter, + const WORD fillAttribute) noexcept = 0; - [[nodiscard]] - virtual HRESULT SetConsoleTextAttributeImpl(IConsoleOutputObject& context, - const WORD attribute) noexcept = 0; + [[nodiscard]] virtual HRESULT SetConsoleTextAttributeImpl(IConsoleOutputObject& context, + const WORD attribute) noexcept = 0; - [[nodiscard]] - virtual HRESULT SetConsoleWindowInfoImpl(IConsoleOutputObject& context, - const bool isAbsolute, - const SMALL_RECT& windowRect) noexcept = 0; + [[nodiscard]] virtual HRESULT SetConsoleWindowInfoImpl(IConsoleOutputObject& context, + const bool isAbsolute, + const SMALL_RECT& windowRect) noexcept = 0; - [[nodiscard]] - virtual HRESULT ReadConsoleOutputAttributeImpl(const IConsoleOutputObject& context, - const COORD origin, - gsl::span buffer, - size_t& written) noexcept = 0; + [[nodiscard]] virtual HRESULT ReadConsoleOutputAttributeImpl(const IConsoleOutputObject& context, + const COORD origin, + gsl::span buffer, + size_t& written) noexcept = 0; - [[nodiscard]] - virtual HRESULT ReadConsoleOutputCharacterAImpl(const IConsoleOutputObject& context, - const COORD origin, - gsl::span buffer, - size_t& written) noexcept = 0; + [[nodiscard]] virtual HRESULT ReadConsoleOutputCharacterAImpl(const IConsoleOutputObject& context, + const COORD origin, + gsl::span buffer, + size_t& written) noexcept = 0; - [[nodiscard]] - virtual HRESULT ReadConsoleOutputCharacterWImpl(const IConsoleOutputObject& context, - const COORD origin, - gsl::span buffer, - size_t& written) noexcept = 0; + [[nodiscard]] virtual HRESULT ReadConsoleOutputCharacterWImpl(const IConsoleOutputObject& context, + const COORD origin, + gsl::span buffer, + size_t& written) noexcept = 0; - [[nodiscard]] - virtual HRESULT WriteConsoleInputAImpl(IConsoleInputObject& context, - const std::basic_string_view buffer, - size_t& written, - const bool append) noexcept = 0; + [[nodiscard]] virtual HRESULT WriteConsoleInputAImpl(IConsoleInputObject& context, + const std::basic_string_view buffer, + size_t& written, + const bool append) noexcept = 0; - [[nodiscard]] - virtual HRESULT WriteConsoleInputWImpl(IConsoleInputObject& context, - const std::basic_string_view buffer, - size_t& written, - const bool append) noexcept = 0; + [[nodiscard]] virtual HRESULT WriteConsoleInputWImpl(IConsoleInputObject& context, + const std::basic_string_view buffer, + size_t& written, + const bool append) noexcept = 0; - [[nodiscard]] - virtual HRESULT WriteConsoleOutputAImpl(IConsoleOutputObject& context, - gsl::span buffer, - const Microsoft::Console::Types::Viewport& requestRectangle, - Microsoft::Console::Types::Viewport& writtenRectangle) noexcept = 0; + [[nodiscard]] virtual HRESULT WriteConsoleOutputAImpl(IConsoleOutputObject& context, + gsl::span buffer, + const Microsoft::Console::Types::Viewport& requestRectangle, + Microsoft::Console::Types::Viewport& writtenRectangle) noexcept = 0; - [[nodiscard]] - virtual HRESULT WriteConsoleOutputWImpl(IConsoleOutputObject& context, - gsl::span buffer, - const Microsoft::Console::Types::Viewport& requestRectangle, - Microsoft::Console::Types::Viewport& writtenRectangle) noexcept = 0; + [[nodiscard]] virtual HRESULT WriteConsoleOutputWImpl(IConsoleOutputObject& context, + gsl::span buffer, + const Microsoft::Console::Types::Viewport& requestRectangle, + Microsoft::Console::Types::Viewport& writtenRectangle) noexcept = 0; - [[nodiscard]] - virtual HRESULT WriteConsoleOutputAttributeImpl(IConsoleOutputObject& OutContext, - const std::basic_string_view attrs, - const COORD target, - size_t& used) noexcept = 0; + [[nodiscard]] virtual HRESULT WriteConsoleOutputAttributeImpl(IConsoleOutputObject& OutContext, + const std::basic_string_view attrs, + const COORD target, + size_t& used) noexcept = 0; - [[nodiscard]] - virtual HRESULT WriteConsoleOutputCharacterAImpl(IConsoleOutputObject& OutContext, - const std::string_view text, - const COORD target, - size_t& used) noexcept = 0; + [[nodiscard]] virtual HRESULT WriteConsoleOutputCharacterAImpl(IConsoleOutputObject& OutContext, + const std::string_view text, + const COORD target, + size_t& used) noexcept = 0; - [[nodiscard]] - virtual HRESULT WriteConsoleOutputCharacterWImpl(IConsoleOutputObject& OutContext, - const std::wstring_view text, - const COORD target, - size_t& used) noexcept = 0; + [[nodiscard]] virtual HRESULT WriteConsoleOutputCharacterWImpl(IConsoleOutputObject& OutContext, + const std::wstring_view text, + const COORD target, + size_t& used) noexcept = 0; - [[nodiscard]] - virtual HRESULT ReadConsoleOutputAImpl(const IConsoleOutputObject& context, - gsl::span buffer, - const Microsoft::Console::Types::Viewport& sourceRectangle, - Microsoft::Console::Types::Viewport& readRectangle) noexcept = 0; + [[nodiscard]] virtual HRESULT ReadConsoleOutputAImpl(const IConsoleOutputObject& context, + gsl::span buffer, + const Microsoft::Console::Types::Viewport& sourceRectangle, + Microsoft::Console::Types::Viewport& readRectangle) noexcept = 0; - [[nodiscard]] - virtual HRESULT ReadConsoleOutputWImpl(const IConsoleOutputObject& context, - gsl::span buffer, - const Microsoft::Console::Types::Viewport& sourceRectangle, - Microsoft::Console::Types::Viewport& readRectangle) noexcept = 0; + [[nodiscard]] virtual HRESULT ReadConsoleOutputWImpl(const IConsoleOutputObject& context, + gsl::span buffer, + const Microsoft::Console::Types::Viewport& sourceRectangle, + Microsoft::Console::Types::Viewport& readRectangle) noexcept = 0; - [[nodiscard]] - virtual HRESULT GetConsoleTitleAImpl(gsl::span title, - size_t& written, - size_t& needed) noexcept = 0; + [[nodiscard]] virtual HRESULT GetConsoleTitleAImpl(gsl::span title, + size_t& written, + size_t& needed) noexcept = 0; - [[nodiscard]] - virtual HRESULT GetConsoleTitleWImpl(gsl::span title, - size_t& written, - size_t& needed) noexcept = 0; + [[nodiscard]] virtual HRESULT GetConsoleTitleWImpl(gsl::span title, + size_t& written, + size_t& needed) noexcept = 0; - [[nodiscard]] - virtual HRESULT GetConsoleOriginalTitleAImpl(gsl::span title, - size_t& written, - size_t& needed) noexcept = 0; + [[nodiscard]] virtual HRESULT GetConsoleOriginalTitleAImpl(gsl::span title, + size_t& written, + size_t& needed) noexcept = 0; - [[nodiscard]] - virtual HRESULT GetConsoleOriginalTitleWImpl(gsl::span title, - size_t& written, - size_t& needed) noexcept = 0; + [[nodiscard]] virtual HRESULT GetConsoleOriginalTitleWImpl(gsl::span title, + size_t& written, + size_t& needed) noexcept = 0; - [[nodiscard]] - virtual HRESULT SetConsoleTitleAImpl(const std::string_view title) noexcept = 0; + [[nodiscard]] virtual HRESULT SetConsoleTitleAImpl(const std::string_view title) noexcept = 0; - [[nodiscard]] - virtual HRESULT SetConsoleTitleWImpl(const std::wstring_view title) noexcept = 0; + [[nodiscard]] virtual HRESULT SetConsoleTitleWImpl(const std::wstring_view title) noexcept = 0; #pragma endregion #pragma region L3 virtual void GetNumberOfConsoleMouseButtonsImpl(ULONG& buttons) noexcept = 0; - [[nodiscard]] - virtual HRESULT GetConsoleFontSizeImpl(const SCREEN_INFORMATION& context, - const DWORD index, - COORD& size) noexcept = 0; + [[nodiscard]] virtual HRESULT GetConsoleFontSizeImpl(const SCREEN_INFORMATION& context, + const DWORD index, + COORD& size) noexcept = 0; // driver will pare down for non-Ex method - [[nodiscard]] - virtual HRESULT GetCurrentConsoleFontExImpl(const SCREEN_INFORMATION& context, - const bool isForMaximumWindowSize, - CONSOLE_FONT_INFOEX& consoleFontInfoEx) noexcept = 0; + [[nodiscard]] virtual HRESULT GetCurrentConsoleFontExImpl(const SCREEN_INFORMATION& context, + const bool isForMaximumWindowSize, + CONSOLE_FONT_INFOEX& consoleFontInfoEx) noexcept = 0; - [[nodiscard]] - virtual HRESULT SetConsoleDisplayModeImpl(SCREEN_INFORMATION& context, - const ULONG flags, - COORD& newSize) noexcept = 0; + [[nodiscard]] virtual HRESULT SetConsoleDisplayModeImpl(SCREEN_INFORMATION& context, + const ULONG flags, + COORD& newSize) noexcept = 0; virtual void GetConsoleDisplayModeImpl(ULONG& flags) noexcept = 0; - [[nodiscard]] - virtual HRESULT AddConsoleAliasAImpl(const std::string_view source, - const std::string_view target, - const std::string_view exeName) noexcept = 0; + [[nodiscard]] virtual HRESULT AddConsoleAliasAImpl(const std::string_view source, + const std::string_view target, + const std::string_view exeName) noexcept = 0; - [[nodiscard]] - virtual HRESULT AddConsoleAliasWImpl(const std::wstring_view source, - const std::wstring_view target, - const std::wstring_view exeName) noexcept = 0; + [[nodiscard]] virtual HRESULT AddConsoleAliasWImpl(const std::wstring_view source, + const std::wstring_view target, + const std::wstring_view exeName) noexcept = 0; - [[nodiscard]] - virtual HRESULT GetConsoleAliasAImpl(const std::string_view source, - gsl::span target, - size_t& written, - const std::string_view exeName) noexcept = 0; + [[nodiscard]] virtual HRESULT GetConsoleAliasAImpl(const std::string_view source, + gsl::span target, + size_t& written, + const std::string_view exeName) noexcept = 0; - [[nodiscard]] - virtual HRESULT GetConsoleAliasWImpl(const std::wstring_view source, - gsl::span target, - size_t& written, - const std::wstring_view exeName) noexcept = 0; + [[nodiscard]] virtual HRESULT GetConsoleAliasWImpl(const std::wstring_view source, + gsl::span target, + size_t& written, + const std::wstring_view exeName) noexcept = 0; - [[nodiscard]] - virtual HRESULT GetConsoleAliasesLengthAImpl(const std::string_view exeName, - size_t& bufferRequired) noexcept = 0; + [[nodiscard]] virtual HRESULT GetConsoleAliasesLengthAImpl(const std::string_view exeName, + size_t& bufferRequired) noexcept = 0; - [[nodiscard]] - virtual HRESULT GetConsoleAliasesLengthWImpl(const std::wstring_view exeName, - size_t& bufferRequired) noexcept = 0; + [[nodiscard]] virtual HRESULT GetConsoleAliasesLengthWImpl(const std::wstring_view exeName, + size_t& bufferRequired) noexcept = 0; - [[nodiscard]] - virtual HRESULT GetConsoleAliasExesLengthAImpl(size_t& bufferRequired) noexcept = 0; + [[nodiscard]] virtual HRESULT GetConsoleAliasExesLengthAImpl(size_t& bufferRequired) noexcept = 0; - [[nodiscard]] - virtual HRESULT GetConsoleAliasExesLengthWImpl(size_t& bufferRequired) noexcept = 0; + [[nodiscard]] virtual HRESULT GetConsoleAliasExesLengthWImpl(size_t& bufferRequired) noexcept = 0; - [[nodiscard]] - virtual HRESULT GetConsoleAliasesAImpl(const std::string_view exeName, - gsl::span alias, - size_t& written) noexcept = 0; + [[nodiscard]] virtual HRESULT GetConsoleAliasesAImpl(const std::string_view exeName, + gsl::span alias, + size_t& written) noexcept = 0; - [[nodiscard]] - virtual HRESULT GetConsoleAliasesWImpl(const std::wstring_view exeName, - gsl::span alias, - size_t& written) noexcept = 0; + [[nodiscard]] virtual HRESULT GetConsoleAliasesWImpl(const std::wstring_view exeName, + gsl::span alias, + size_t& written) noexcept = 0; - [[nodiscard]] - virtual HRESULT GetConsoleAliasExesAImpl(gsl::span aliasExes, - size_t& written) noexcept = 0; + [[nodiscard]] virtual HRESULT GetConsoleAliasExesAImpl(gsl::span aliasExes, + size_t& written) noexcept = 0; - [[nodiscard]] - virtual HRESULT GetConsoleAliasExesWImpl(gsl::span aliasExes, - size_t& written) noexcept = 0; + [[nodiscard]] virtual HRESULT GetConsoleAliasExesWImpl(gsl::span aliasExes, + size_t& written) noexcept = 0; #pragma region CMDext Private API - [[nodiscard]] - virtual HRESULT ExpungeConsoleCommandHistoryAImpl(const std::string_view exeName) noexcept = 0; + [[nodiscard]] virtual HRESULT ExpungeConsoleCommandHistoryAImpl(const std::string_view exeName) noexcept = 0; - [[nodiscard]] - virtual HRESULT ExpungeConsoleCommandHistoryWImpl(const std::wstring_view exeName) noexcept = 0; + [[nodiscard]] virtual HRESULT ExpungeConsoleCommandHistoryWImpl(const std::wstring_view exeName) noexcept = 0; - [[nodiscard]] - virtual HRESULT SetConsoleNumberOfCommandsAImpl(const std::string_view exeName, - const size_t numberOfCommands) noexcept = 0; + [[nodiscard]] virtual HRESULT SetConsoleNumberOfCommandsAImpl(const std::string_view exeName, + const size_t numberOfCommands) noexcept = 0; - [[nodiscard]] - virtual HRESULT SetConsoleNumberOfCommandsWImpl(const std::wstring_view exeName, - const size_t numberOfCommands) noexcept = 0; + [[nodiscard]] virtual HRESULT SetConsoleNumberOfCommandsWImpl(const std::wstring_view exeName, + const size_t numberOfCommands) noexcept = 0; - [[nodiscard]] - virtual HRESULT GetConsoleCommandHistoryLengthAImpl(const std::string_view exeName, - size_t& length) noexcept = 0; + [[nodiscard]] virtual HRESULT GetConsoleCommandHistoryLengthAImpl(const std::string_view exeName, + size_t& length) noexcept = 0; - [[nodiscard]] - virtual HRESULT GetConsoleCommandHistoryLengthWImpl(const std::wstring_view exeName, - size_t& length) noexcept = 0; + [[nodiscard]] virtual HRESULT GetConsoleCommandHistoryLengthWImpl(const std::wstring_view exeName, + size_t& length) noexcept = 0; - [[nodiscard]] - virtual HRESULT GetConsoleCommandHistoryAImpl(const std::string_view exeName, - gsl::span commandHistory, - size_t& written) noexcept = 0; + [[nodiscard]] virtual HRESULT GetConsoleCommandHistoryAImpl(const std::string_view exeName, + gsl::span commandHistory, + size_t& written) noexcept = 0; - [[nodiscard]] - virtual HRESULT GetConsoleCommandHistoryWImpl(const std::wstring_view exeName, - gsl::span commandHistory, - size_t& written) noexcept = 0; + [[nodiscard]] virtual HRESULT GetConsoleCommandHistoryWImpl(const std::wstring_view exeName, + gsl::span commandHistory, + size_t& written) noexcept = 0; #pragma endregion @@ -442,13 +375,11 @@ public: virtual void GetConsoleHistoryInfoImpl(CONSOLE_HISTORY_INFO& consoleHistoryInfo) noexcept = 0; - [[nodiscard]] - virtual HRESULT SetConsoleHistoryInfoImpl(const CONSOLE_HISTORY_INFO& consoleHistoryInfo) noexcept = 0; + [[nodiscard]] virtual HRESULT SetConsoleHistoryInfoImpl(const CONSOLE_HISTORY_INFO& consoleHistoryInfo) noexcept = 0; - [[nodiscard]] - virtual HRESULT SetCurrentConsoleFontExImpl(IConsoleOutputObject& context, - const bool isForMaximumWindowSize, - const CONSOLE_FONT_INFOEX& consoleFontInfoEx) noexcept = 0; + [[nodiscard]] virtual HRESULT SetCurrentConsoleFontExImpl(IConsoleOutputObject& context, + const bool isForMaximumWindowSize, + const CONSOLE_FONT_INFOEX& consoleFontInfoEx) noexcept = 0; #pragma endregion }; diff --git a/src/server/IWaitRoutine.h b/src/server/IWaitRoutine.h index 708733548..bc308f2e4 100644 --- a/src/server/IWaitRoutine.h +++ b/src/server/IWaitRoutine.h @@ -29,8 +29,8 @@ enum class ReplyDataType class IWaitRoutine { public: - IWaitRoutine(ReplyDataType type) - : _ReplyType(type) + IWaitRoutine(ReplyDataType type) : + _ReplyType(type) { } diff --git a/src/server/IoDispatchers.cpp b/src/server/IoDispatchers.cpp index c34fc61af..31f5f240b 100644 --- a/src/server/IoDispatchers.cpp +++ b/src/server/IoDispatchers.cpp @@ -26,7 +26,7 @@ using namespace Microsoft::Console::Interactivity; // // Object Name not found. // -#define STATUS_OBJECT_NAME_NOT_FOUND ((NTSTATUS)0xC0000034L) +#define STATUS_OBJECT_NAME_NOT_FOUND ((NTSTATUS)0xC0000034L) // Routine Description: // - This routine handles IO requests to create new objects. It validates the request, creates the object and a "handle" to it. @@ -49,7 +49,6 @@ PCONSOLE_API_MSG IoDispatchers::ConsoleCreateObject(_In_ PCONSOLE_API_MSG pMessa if ((CreateInformation->DesiredAccess & (GENERIC_READ | GENERIC_WRITE)) == GENERIC_READ) { CreateInformation->ObjectType = CD_IO_OBJECT_TYPE_CURRENT_INPUT; - } else if ((CreateInformation->DesiredAccess & (GENERIC_READ | GENERIC_WRITE)) == GENERIC_WRITE) { @@ -214,7 +213,6 @@ PCONSOLE_API_MSG IoDispatchers::ConsoleHandleConnectionRequest(_In_ PCONSOLE_API goto Error; } - auto& screenInfo = gci.GetActiveOutputBuffer().GetMainBuffer(); Status = NTSTATUS_FROM_HRESULT(screenInfo.AllocateIoHandle(ConsoleHandleData::HandleType::Output, GENERIC_READ | GENERIC_WRITE, diff --git a/src/server/IoSorter.cpp b/src/server/IoSorter.cpp index c21917cbf..9cbdf5a50 100644 --- a/src/server/IoSorter.cpp +++ b/src/server/IoSorter.cpp @@ -58,7 +58,6 @@ void IoSorter::ServiceIoOperation(_In_ CONSOLE_API_MSG* const pMsg, if (ReplyPending) { *ReplyMsg = nullptr; - } else { @@ -77,7 +76,6 @@ void IoSorter::ServiceIoOperation(_In_ CONSOLE_API_MSG* const pMsg, if (ReplyPending) { *ReplyMsg = nullptr; - } else { @@ -88,7 +86,7 @@ void IoSorter::ServiceIoOperation(_In_ CONSOLE_API_MSG* const pMsg, case CONSOLE_IO_RAW_FLUSH: ReplyPending = FALSE; - + Status = NTSTATUS_FROM_HRESULT(ApiDispatchers::ServerFlushConsoleInputBuffer(pMsg, &ReplyPending)); FAIL_FAST_IF(!(!ReplyPending)); pMsg->SetReplyStatus(Status); diff --git a/src/server/IoThread.h b/src/server/IoThread.h index f170ec598..28915450d 100644 --- a/src/server/IoThread.h +++ b/src/server/IoThread.h @@ -5,5 +5,4 @@ class ConsoleArguments; -[[nodiscard]] -HRESULT ConsoleCreateIoThreadLegacy(_In_ HANDLE Server, const ConsoleArguments* const args); +[[nodiscard]] HRESULT ConsoleCreateIoThreadLegacy(_In_ HANDLE Server, const ConsoleArguments* const args); diff --git a/src/server/ObjectHandle.cpp b/src/server/ObjectHandle.cpp index bb4ba3bdd..eaef19caa 100644 --- a/src/server/ObjectHandle.cpp +++ b/src/server/ObjectHandle.cpp @@ -120,9 +120,8 @@ bool ConsoleHandleData::IsWriteShared() const // - ppInputBuffer - On success, filled with the referenced Input Buffer object // Return Value: // - HRESULT S_OK or suitable error. -[[nodiscard]] -HRESULT ConsoleHandleData::GetInputBuffer(const ACCESS_MASK amRequested, - _Outptr_ InputBuffer** const ppInputBuffer) const +[[nodiscard]] HRESULT ConsoleHandleData::GetInputBuffer(const ACCESS_MASK amRequested, + _Outptr_ InputBuffer** const ppInputBuffer) const { *ppInputBuffer = nullptr; @@ -141,9 +140,8 @@ HRESULT ConsoleHandleData::GetInputBuffer(const ACCESS_MASK amRequested, // - ppInputBuffer - On success, filled with the referenced Screen Buffer object // Return Value: // - HRESULT S_OK or suitable error. -[[nodiscard]] -HRESULT ConsoleHandleData::GetScreenBuffer(const ACCESS_MASK amRequested, - _Outptr_ SCREEN_INFORMATION** const ppScreenInfo) const +[[nodiscard]] HRESULT ConsoleHandleData::GetScreenBuffer(const ACCESS_MASK amRequested, + _Outptr_ SCREEN_INFORMATION** const ppScreenInfo) const { *ppScreenInfo = nullptr; @@ -161,8 +159,7 @@ HRESULT ConsoleHandleData::GetScreenBuffer(const ACCESS_MASK amRequested, // - ppWaitQueue - On success, filled with a pointer to the desired queue // Return Value: // - HRESULT S_OK or E_UNEXPECTED if the handle data structure is in an invalid state. -[[nodiscard]] -HRESULT ConsoleHandleData::GetWaitQueue(_Outptr_ ConsoleWaitQueue** const ppWaitQueue) const +[[nodiscard]] HRESULT ConsoleHandleData::GetWaitQueue(_Outptr_ ConsoleWaitQueue** const ppWaitQueue) const { CONSOLE_INFORMATION& gci = Microsoft::Console::Interactivity::ServiceLocator::LocateGlobals().getConsoleInformation(); if (_IsInput()) @@ -205,8 +202,7 @@ INPUT_READ_HANDLE_DATA* ConsoleHandleData::GetClientInput() const // - HRESULT S_OK or suitable error code. // Note: // - The console lock must be held when calling this routine. -[[nodiscard]] -HRESULT ConsoleHandleData::_CloseInputHandle() +[[nodiscard]] HRESULT ConsoleHandleData::_CloseInputHandle() { FAIL_FAST_IF(!(_IsInput())); InputBuffer* pInputBuffer = static_cast(_pvClientPointer); @@ -245,8 +241,7 @@ HRESULT ConsoleHandleData::_CloseInputHandle() // - HRESULT S_OK or suitable error code. // Note: // - The console lock must be held when calling this routine. -[[nodiscard]] -HRESULT ConsoleHandleData::_CloseOutputHandle() +[[nodiscard]] HRESULT ConsoleHandleData::_CloseOutputHandle() { FAIL_FAST_IF(!(_IsOutput())); SCREEN_INFORMATION* pScreenInfo = static_cast(_pvClientPointer); diff --git a/src/server/ObjectHandle.h b/src/server/ObjectHandle.h index 21eb55168..37b40a260 100644 --- a/src/server/ObjectHandle.h +++ b/src/server/ObjectHandle.h @@ -40,15 +40,12 @@ public: ConsoleHandleData& operator=(const ConsoleHandleData&) & = delete; ConsoleHandleData& operator=(ConsoleHandleData&&) & = delete; - [[nodiscard]] - HRESULT GetInputBuffer(const ACCESS_MASK amRequested, - _Outptr_ InputBuffer** const ppInputBuffer) const; - [[nodiscard]] - HRESULT GetScreenBuffer(const ACCESS_MASK amRequested, - _Outptr_ SCREEN_INFORMATION** const ppScreenInfo) const; + [[nodiscard]] HRESULT GetInputBuffer(const ACCESS_MASK amRequested, + _Outptr_ InputBuffer** const ppInputBuffer) const; + [[nodiscard]] HRESULT GetScreenBuffer(const ACCESS_MASK amRequested, + _Outptr_ SCREEN_INFORMATION** const ppScreenInfo) const; - [[nodiscard]] - HRESULT GetWaitQueue(_Outptr_ ConsoleWaitQueue** const ppWaitQueue) const; + [[nodiscard]] HRESULT GetWaitQueue(_Outptr_ ConsoleWaitQueue** const ppWaitQueue) const; INPUT_READ_HANDLE_DATA* GetClientInput() const; @@ -73,10 +70,8 @@ private: bool _IsInput() const; bool _IsOutput() const; - [[nodiscard]] - HRESULT _CloseInputHandle(); - [[nodiscard]] - HRESULT _CloseOutputHandle(); + [[nodiscard]] HRESULT _CloseInputHandle(); + [[nodiscard]] HRESULT _CloseOutputHandle(); ULONG const _ulHandleType; ACCESS_MASK const _amAccess; diff --git a/src/server/ObjectHeader.cpp b/src/server/ObjectHeader.cpp index 78786db61..83f9319d0 100644 --- a/src/server/ObjectHeader.cpp +++ b/src/server/ObjectHeader.cpp @@ -15,7 +15,6 @@ ConsoleObjectHeader::ConsoleObjectHeader() : _ulReadShareCount(0), _ulWriteShareCount(0) { - } // Routine Description: @@ -32,11 +31,10 @@ ConsoleObjectHeader::ConsoleObjectHeader() : // TODO: MSFT 614400 - Add concurrency SAL to enforce the lock http://osgvsowi/614400 // - The console lock must be held when calling this routine. The handle is allocated from the per-process handle table. Holding the console // lock serializes both threads within the calling process and any other process that shares the console. -[[nodiscard]] -HRESULT ConsoleObjectHeader::AllocateIoHandle(const ConsoleHandleData::HandleType ulHandleType, - const ACCESS_MASK amDesired, - const ULONG ulShareMode, - std::unique_ptr& out) +[[nodiscard]] HRESULT ConsoleObjectHeader::AllocateIoHandle(const ConsoleHandleData::HandleType ulHandleType, + const ACCESS_MASK amDesired, + const ULONG ulShareMode, + std::unique_ptr& out) { try { @@ -91,8 +89,7 @@ HRESULT ConsoleObjectHeader::AllocateIoHandle(const ConsoleHandleData::HandleTyp // - pFree - Pointer to the handle data to be freed // Return Value: // - HRESULT S_OK or appropriate error. -[[nodiscard]] -HRESULT ConsoleObjectHeader::FreeIoHandle(_In_ ConsoleHandleData* const pFree) +[[nodiscard]] HRESULT ConsoleObjectHeader::FreeIoHandle(_In_ ConsoleHandleData* const pFree) { // This absolutely should not happen and our state is corrupt/bad if we try to release past 0. THROW_HR_IF(E_NOT_VALID_STATE, !(_ulOpenCount > 0)); diff --git a/src/server/ObjectHeader.h b/src/server/ObjectHeader.h index c40a0fc68..842e4c294 100644 --- a/src/server/ObjectHeader.h +++ b/src/server/ObjectHeader.h @@ -26,16 +26,14 @@ public: // NOTE: This class must have a virtual method for the stored "this" pointers to match what we're actually looking for. // If there is no virtual method, we may have the "this" pointer be offset by 8 from the actual object that inherits ConsoleObjectHeader. - virtual ~ConsoleObjectHeader() {}; + virtual ~ConsoleObjectHeader(){}; - [[nodiscard]] - HRESULT AllocateIoHandle(const ConsoleHandleData::HandleType ulHandleType, - const ACCESS_MASK amDesired, - const ULONG ulShareMode, - std::unique_ptr& out); + [[nodiscard]] HRESULT AllocateIoHandle(const ConsoleHandleData::HandleType ulHandleType, + const ACCESS_MASK amDesired, + const ULONG ulShareMode, + std::unique_ptr& out); - [[nodiscard]] - HRESULT FreeIoHandle(_In_ ConsoleHandleData* const pFree); + [[nodiscard]] HRESULT FreeIoHandle(_In_ ConsoleHandleData* const pFree); bool HasAnyOpenHandles() const; diff --git a/src/server/ProcessHandle.h b/src/server/ProcessHandle.h index 384765067..bc8c16d98 100644 --- a/src/server/ProcessHandle.h +++ b/src/server/ProcessHandle.h @@ -36,9 +36,9 @@ public: DWORD const dwProcessId; DWORD const dwThreadId; - const ConsoleProcessPolicy GetPolicy() const; + const ConsoleProcessPolicy GetPolicy() const; - CD_CONNECTION_INFORMATION GetConnectionInformation() const; + CD_CONNECTION_INFORMATION GetConnectionInformation() const; private: ConsoleProcessHandle(const DWORD dwProcessId, diff --git a/src/server/ProcessList.cpp b/src/server/ProcessList.cpp index cc31da0e2..f488b35e7 100644 --- a/src/server/ProcessList.cpp +++ b/src/server/ProcessList.cpp @@ -27,12 +27,11 @@ using namespace Microsoft::Console::Interactivity; // - S_OK if the process was recorded in the list successfully or already existed. // - E_FAIL if we're running into an LPC port conflict by nature of the process chain. // - E_OUTOFMEMORY if there wasn't space to allocate a handle or push it into the list. -[[nodiscard]] -HRESULT ConsoleProcessList::AllocProcessData(const DWORD dwProcessId, - const DWORD dwThreadId, - const ULONG ulProcessGroupId, - _In_opt_ ConsoleProcessHandle* const pParentProcessData, - _Outptr_opt_ ConsoleProcessHandle** const ppProcessData) +[[nodiscard]] HRESULT ConsoleProcessList::AllocProcessData(const DWORD dwProcessId, + const DWORD dwThreadId, + const ULONG ulProcessGroupId, + _In_opt_ ConsoleProcessHandle* const pParentProcessData, + _Outptr_opt_ ConsoleProcessHandle** const ppProcessData) { FAIL_FAST_IF(!(ServiceLocator::LocateGlobals().getConsoleInformation().IsConsoleLocked())); @@ -166,9 +165,8 @@ ConsoleProcessHandle* ConsoleProcessList::FindProcessByGroupId(_In_ ULONG ulProc // Return Value: // - S_OK if buffer was filled successfully and resulting count of items is in pcProcessList. // - E_NOT_SUFFICIENT_BUFFER if the buffer given was too small. Refer to pcProcessList for size requirement. -[[nodiscard]] -HRESULT ConsoleProcessList::GetProcessList(_Inout_updates_(*pcProcessList) DWORD* const pProcessList, - _Inout_ size_t* const pcProcessList) const +[[nodiscard]] HRESULT ConsoleProcessList::GetProcessList(_Inout_updates_(*pcProcessList) DWORD* const pProcessList, + _Inout_ size_t* const pcProcessList) const { HRESULT hr = S_OK; @@ -210,11 +208,10 @@ HRESULT ConsoleProcessList::GetProcessList(_Inout_updates_(*pcProcessList) DWORD // Return Value: // - S_OK if prgRecords was filled successfully or if no records were found that matched. // - E_OUTOFMEMORY in a low memory situation. -[[nodiscard]] -HRESULT ConsoleProcessList::GetTerminationRecordsByGroupId(const DWORD dwLimitingProcessId, - const bool fCtrlClose, - _Outptr_result_buffer_all_(*pcRecords) ConsoleProcessTerminationRecord** prgRecords, - _Out_ size_t* const pcRecords) const +[[nodiscard]] HRESULT ConsoleProcessList::GetTerminationRecordsByGroupId(const DWORD dwLimitingProcessId, + const bool fCtrlClose, + _Outptr_result_buffer_all_(*pcRecords) ConsoleProcessTerminationRecord** prgRecords, + _Out_ size_t* const pcRecords) const { *pcRecords = 0; diff --git a/src/server/ProcessList.h b/src/server/ProcessList.h index e8766da34..2b3e2af69 100644 --- a/src/server/ProcessList.h +++ b/src/server/ProcessList.h @@ -31,33 +31,28 @@ struct ConsoleProcessTerminationRecord class ConsoleProcessList { public: - static const DWORD ROOT_PROCESS_ID = 0; - [[nodiscard]] - HRESULT AllocProcessData(const DWORD dwProcessId, - const DWORD dwThreadId, - const ULONG ulProcessGroupId, - _In_opt_ ConsoleProcessHandle* const pParentProcessData, - _Outptr_opt_ ConsoleProcessHandle** const ppProcessData); + [[nodiscard]] HRESULT AllocProcessData(const DWORD dwProcessId, + const DWORD dwThreadId, + const ULONG ulProcessGroupId, + _In_opt_ ConsoleProcessHandle* const pParentProcessData, + _Outptr_opt_ ConsoleProcessHandle** const ppProcessData); void FreeProcessData(_In_ ConsoleProcessHandle* const ProcessData); - ConsoleProcessHandle* FindProcessInList(const DWORD dwProcessId) const; ConsoleProcessHandle* FindProcessByGroupId(_In_ ULONG ulProcessGroupId) const; - [[nodiscard]] - HRESULT GetTerminationRecordsByGroupId(const DWORD dwLimitingProcessId, - const bool fCtrlClose, - _Outptr_result_buffer_all_(*pcRecords) ConsoleProcessTerminationRecord** prgRecords, - _Out_ size_t* const pcRecords) const; + [[nodiscard]] HRESULT GetTerminationRecordsByGroupId(const DWORD dwLimitingProcessId, + const bool fCtrlClose, + _Outptr_result_buffer_all_(*pcRecords) ConsoleProcessTerminationRecord** prgRecords, + _Out_ size_t* const pcRecords) const; ConsoleProcessHandle* GetFirstProcess() const; - [[nodiscard]] - HRESULT GetProcessList(_Inout_updates_(*pcProcessList) DWORD* const pProcessList, - _Inout_ size_t* const pcProcessList) const; + [[nodiscard]] HRESULT GetProcessList(_Inout_updates_(*pcProcessList) DWORD* const pProcessList, + _Inout_ size_t* const pcProcessList) const; void ModifyConsoleProcessFocus(const bool fForeground); diff --git a/src/server/WaitBlock.cpp b/src/server/WaitBlock.cpp index 924c8a95d..fd1b19e59 100644 --- a/src/server/WaitBlock.cpp +++ b/src/server/WaitBlock.cpp @@ -65,9 +65,8 @@ ConsoleWaitBlock::~ConsoleWaitBlock() // - pWaiter - The context/callback information to restore and dispatch the call later. // Return Value: // - S_OK if queued and ready to go. Appropriate HRESULT value if it failed. -[[nodiscard]] -HRESULT ConsoleWaitBlock::s_CreateWait(_Inout_ CONSOLE_API_MSG* const pWaitReplyMessage, - _In_ IWaitRoutine* const pWaiter) +[[nodiscard]] HRESULT ConsoleWaitBlock::s_CreateWait(_Inout_ CONSOLE_API_MSG* const pWaitReplyMessage, + _In_ IWaitRoutine* const pWaiter) { ConsoleProcessHandle* const ProcessData = pWaitReplyMessage->GetProcessHandle(); FAIL_FAST_IF_NULL(ProcessData); @@ -181,7 +180,6 @@ bool ConsoleWaitBlock::Notify(const WaitTerminationReason TerminationReason) pRecordBuffer[i] = outEvents.front()->ToInputRecord(); outEvents.pop_front(); } - } else if (API_NUMBER_READCONSOLE == _WaitReplyMessage.msgHeader.ApiNumber) { diff --git a/src/server/WaitBlock.h b/src/server/WaitBlock.h index f7d6d1c4e..b757b004b 100644 --- a/src/server/WaitBlock.h +++ b/src/server/WaitBlock.h @@ -28,15 +28,12 @@ class ConsoleWaitQueue; class ConsoleWaitBlock { public: - ~ConsoleWaitBlock(); bool Notify(const WaitTerminationReason TerminationReason); - [[nodiscard]] - static HRESULT s_CreateWait(_Inout_ CONSOLE_API_MSG* const pWaitReplymessage, - _In_ IWaitRoutine* const pWaiter); - + [[nodiscard]] static HRESULT s_CreateWait(_Inout_ CONSOLE_API_MSG* const pWaitReplymessage, + _In_ IWaitRoutine* const pWaiter); private: ConsoleWaitBlock(_In_ ConsoleWaitQueue* const pProcessQueue, diff --git a/src/server/WaitQueue.cpp b/src/server/WaitQueue.cpp index 94244603c..33775cc62 100644 --- a/src/server/WaitQueue.cpp +++ b/src/server/WaitQueue.cpp @@ -14,7 +14,6 @@ ConsoleWaitQueue::ConsoleWaitQueue() : _blocks() { - } // Routine Description: @@ -33,9 +32,8 @@ ConsoleWaitQueue::~ConsoleWaitQueue() // - pWaiter - The context/callback information to restore and dispatch the call later. // Return Value: // - S_OK if enqueued appropriately and everything is alright. Or suitable HRESULT failure otherwise. -[[nodiscard]] -HRESULT ConsoleWaitQueue::s_CreateWait(_Inout_ CONSOLE_API_MSG* const pWaitReplyMessage, - _In_ IWaitRoutine* const pWaiter) +[[nodiscard]] HRESULT ConsoleWaitQueue::s_CreateWait(_Inout_ CONSOLE_API_MSG* const pWaitReplyMessage, + _In_ IWaitRoutine* const pWaiter) { // Normally we'd have the Wait Queue handle the insertion of the block into the queue, but // the console does queues in a somewhat special way. diff --git a/src/server/WaitQueue.h b/src/server/WaitQueue.h index d525abeef..316dd3853 100644 --- a/src/server/WaitQueue.h +++ b/src/server/WaitQueue.h @@ -37,9 +37,8 @@ public: bool NotifyWaiters(const bool fNotifyAll, const WaitTerminationReason TerminationReason); - [[nodiscard]] - static HRESULT s_CreateWait(_Inout_ CONSOLE_API_MSG* const pWaitReplyMessage, - _In_ IWaitRoutine* const pWaiter); + [[nodiscard]] static HRESULT s_CreateWait(_Inout_ CONSOLE_API_MSG* const pWaitReplyMessage, + _In_ IWaitRoutine* const pWaiter); private: bool _NotifyBlock(_In_ ConsoleWaitBlock* pWaitBlock, diff --git a/src/server/WinNTControl.cpp b/src/server/WinNTControl.cpp index 9762258bb..66eadb5f8 100644 --- a/src/server/WinNTControl.cpp +++ b/src/server/WinNTControl.cpp @@ -19,7 +19,6 @@ WinNTControl::WinNTControl() : // - Destructs an instance of the NTDLL method-invoking class. WinNTControl::~WinNTControl() { - } // Routine Description: @@ -41,13 +40,12 @@ WinNTControl& WinNTControl::GetInstance() // - See definitions at MSDN // Return Value: // - See definitions at MSDN -[[nodiscard]] -NTSTATUS WinNTControl::NtOpenFile(_Out_ PHANDLE FileHandle, - _In_ ACCESS_MASK DesiredAccess, - _In_ POBJECT_ATTRIBUTES ObjectAttributes, - _Out_ PIO_STATUS_BLOCK IoStatusBlock, - _In_ ULONG ShareAccess, - _In_ ULONG OpenOptions) +[[nodiscard]] NTSTATUS WinNTControl::NtOpenFile(_Out_ PHANDLE FileHandle, + _In_ ACCESS_MASK DesiredAccess, + _In_ POBJECT_ATTRIBUTES ObjectAttributes, + _Out_ PIO_STATUS_BLOCK IoStatusBlock, + _In_ ULONG ShareAccess, + _In_ ULONG OpenOptions) { try { diff --git a/src/server/WinNTControl.h b/src/server/WinNTControl.h index dc99b9e37..bcdf62a25 100644 --- a/src/server/WinNTControl.h +++ b/src/server/WinNTControl.h @@ -19,13 +19,12 @@ Revision History: class WinNTControl { public: - [[nodiscard]] - static NTSTATUS NtOpenFile(_Out_ PHANDLE FileHandle, - _In_ ACCESS_MASK DesiredAccess, - _In_ POBJECT_ATTRIBUTES ObjectAttributes, - _Out_ PIO_STATUS_BLOCK IoStatusBlock, - _In_ ULONG ShareAccess, - _In_ ULONG OpenOptions); + [[nodiscard]] static NTSTATUS NtOpenFile(_Out_ PHANDLE FileHandle, + _In_ ACCESS_MASK DesiredAccess, + _In_ POBJECT_ATTRIBUTES ObjectAttributes, + _Out_ PIO_STATUS_BLOCK IoStatusBlock, + _In_ ULONG ShareAccess, + _In_ ULONG OpenOptions); ~WinNTControl(); @@ -41,5 +40,4 @@ private: typedef NTSTATUS(NTAPI* PfnNtOpenFile)(PHANDLE, ACCESS_MASK, POBJECT_ATTRIBUTES, PIO_STATUS_BLOCK, ULONG, ULONG); PfnNtOpenFile const _NtOpenFile; - }; diff --git a/src/server/precomp.h b/src/server/precomp.h index a728cd060..c05192ea0 100644 --- a/src/server/precomp.h +++ b/src/server/precomp.h @@ -18,17 +18,17 @@ Abstract: #pragma once #ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers +#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers #endif // Windows Header Files: #include typedef long NTSTATUS; -#define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0) +#define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0) #define STATUS_SUCCESS ((DWORD)0x0) #define STATUS_UNSUCCESSFUL ((DWORD)0xC0000001L) -#define STATUS_SHARING_VIOLATION ((NTSTATUS)0xC0000043L) +#define STATUS_SHARING_VIOLATION ((NTSTATUS)0xC0000043L) #define STATUS_INSUFFICIENT_RESOURCES ((DWORD)0xC000009AL) #define STATUS_ILLEGAL_FUNCTION ((DWORD)0xC00000AFL) #define STATUS_PIPE_DISCONNECTED ((DWORD)0xC00000B0L) @@ -40,13 +40,16 @@ typedef long NTSTATUS; // Note: This assumes that WIN32 errors fall in the range -32k to 32k. // -#define FACILITY_NTWIN32 0x7 +#define FACILITY_NTWIN32 0x7 -#define __NTSTATUS_FROM_WIN32(x) ((NTSTATUS)(x) <= 0 ? ((NTSTATUS)(x)) : ((NTSTATUS) (((x) & 0x0000FFFF) | (FACILITY_NTWIN32 << 16) | ERROR_SEVERITY_ERROR))) +#define __NTSTATUS_FROM_WIN32(x) ((NTSTATUS)(x) <= 0 ? ((NTSTATUS)(x)) : ((NTSTATUS)(((x)&0x0000FFFF) | (FACILITY_NTWIN32 << 16) | ERROR_SEVERITY_ERROR))) #ifdef INLINE_NTSTATUS_FROM_WIN32 #ifndef __midl -__inline NTSTATUS_FROM_WIN32(long x) { return x <= 0 ? (NTSTATUS)x : (NTSTATUS)(((x) & 0x0000FFFF) | (FACILITY_NTWIN32 << 16) | ERROR_SEVERITY_ERROR); } +__inline NTSTATUS_FROM_WIN32(long x) +{ + return x <= 0 ? (NTSTATUS)x : (NTSTATUS)(((x)&0x0000FFFF) | (FACILITY_NTWIN32 << 16) | ERROR_SEVERITY_ERROR); +} #else #define NTSTATUS_FROM_WIN32(x) __NTSTATUS_FROM_WIN32(x) #endif @@ -72,8 +75,7 @@ __inline NTSTATUS_FROM_WIN32(long x) { return x <= 0 ? (NTSTATUS)x : (NTSTATUS)( #include // TODO: MSFT 9355094 Find a better way of doing this. http://osgvsowi/9355094 -[[nodiscard]] -inline NTSTATUS NTSTATUS_FROM_HRESULT(HRESULT hr) +[[nodiscard]] inline NTSTATUS NTSTATUS_FROM_HRESULT(HRESULT hr) { return NTSTATUS_FROM_WIN32(HRESULT_CODE(hr)); } diff --git a/src/server/winbasep.h b/src/server/winbasep.h index 03f50e5a9..86aaebed6 100644 --- a/src/server/winbasep.h +++ b/src/server/winbasep.h @@ -6,4 +6,4 @@ #define ProcThreadAttributeConsoleReference 10 #define PROC_THREAD_ATTRIBUTE_CONSOLE_REFERENCE \ - ProcThreadAttributeValue (10, FALSE, TRUE, FALSE) + ProcThreadAttributeValue(10, FALSE, TRUE, FALSE) diff --git a/src/terminal/adapter/DispatchCommon.cpp b/src/terminal/adapter/DispatchCommon.cpp index 24b4bb88a..6d022299d 100644 --- a/src/terminal/adapter/DispatchCommon.cpp +++ b/src/terminal/adapter/DispatchCommon.cpp @@ -45,7 +45,7 @@ bool DispatchCommon::s_ResizeWindow(ConGetSet& conApi, csbiex.dwSize.X = sColumns; // Only set the screen buffer's height if it's currently less than // what we're requesting. - if(sRows > csbiex.dwSize.Y) + if (sRows > csbiex.dwSize.Y) { csbiex.dwSize.Y = sRows; } diff --git a/src/terminal/adapter/DispatchCommon.hpp b/src/terminal/adapter/DispatchCommon.hpp index e9385bdc6..5f06a6559 100644 --- a/src/terminal/adapter/DispatchCommon.hpp +++ b/src/terminal/adapter/DispatchCommon.hpp @@ -22,7 +22,6 @@ namespace Microsoft::Console::VirtualTerminal class DispatchCommon final { public: - static bool s_ResizeWindow(ConGetSet& conApi, const unsigned short usWidth, const unsigned short usHeight); @@ -30,6 +29,5 @@ namespace Microsoft::Console::VirtualTerminal static bool s_RefreshWindow(ConGetSet& conApi); static bool s_SuppressResizeRepaint(ConGetSet& conApi); - }; } diff --git a/src/terminal/adapter/DispatchTypes.hpp b/src/terminal/adapter/DispatchTypes.hpp index dd159bf88..5a2365077 100644 --- a/src/terminal/adapter/DispatchTypes.hpp +++ b/src/terminal/adapter/DispatchTypes.hpp @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. #pragma once diff --git a/src/terminal/adapter/IInteractDispatch.hpp b/src/terminal/adapter/IInteractDispatch.hpp index 94c5d8670..954f75094 100644 --- a/src/terminal/adapter/IInteractDispatch.hpp +++ b/src/terminal/adapter/IInteractDispatch.hpp @@ -37,6 +37,5 @@ namespace Microsoft::Console::VirtualTerminal virtual bool MoveCursor(const unsigned int row, const unsigned int col) = 0; - }; } diff --git a/src/terminal/adapter/ITermDispatch.hpp b/src/terminal/adapter/ITermDispatch.hpp index fec42544b..ea42a4f8d 100644 --- a/src/terminal/adapter/ITermDispatch.hpp +++ b/src/terminal/adapter/ITermDispatch.hpp @@ -46,9 +46,9 @@ public: virtual bool InsertLine(const unsigned int uiDistance) = 0; // IL virtual bool DeleteLine(const unsigned int uiDistance) = 0; // DL virtual bool SetColumns(const unsigned int uiColumns) = 0; // DECSCPP, DECCOLM - virtual bool SetCursorKeysMode(const bool fApplicationMode) = 0; // DECCKM - virtual bool SetKeypadMode(const bool fApplicationMode) = 0; // DECKPAM, DECKPNM - virtual bool EnableCursorBlinking(const bool fEnable) = 0; // ATT610 + virtual bool SetCursorKeysMode(const bool fApplicationMode) = 0; // DECCKM + virtual bool SetKeypadMode(const bool fApplicationMode) = 0; // DECKPAM, DECKPNM + virtual bool EnableCursorBlinking(const bool fEnable) = 0; // ATT610 virtual bool SetTopBottomScrollingMargins(const SHORT sTopMargin, const SHORT sBottomMargin) = 0; // DECSTBM virtual bool ReverseLineFeed() = 0; // RI virtual bool SetWindowTitle(std::wstring_view title) = 0; // OscWindowTitle @@ -68,8 +68,8 @@ public: virtual bool SetDefaultForeground(const DWORD dwColor) = 0; // OSCDefaultForeground virtual bool SetDefaultBackground(const DWORD dwColor) = 0; // OSCDefaultBackground - virtual bool EraseInDisplay(const DispatchTypes::EraseType eraseType) = 0; // ED - virtual bool EraseInLine(const DispatchTypes::EraseType eraseType) = 0; // EL + virtual bool EraseInDisplay(const DispatchTypes::EraseType eraseType) = 0; // ED + virtual bool EraseInLine(const DispatchTypes::EraseType eraseType) = 0; // EL virtual bool EraseCharacters(const unsigned int uiNumChars) = 0; // ECH virtual bool SetGraphicsRendition(_In_reads_(cOptions) const DispatchTypes::GraphicsOptions* const rgOptions, @@ -96,6 +96,5 @@ public: virtual bool WindowManipulation(const DispatchTypes::WindowManipulationType uiFunction, _In_reads_(cParams) const unsigned short* const rgusParams, const size_t cParams) = 0; - }; -inline Microsoft::Console::VirtualTerminal::ITermDispatch::~ITermDispatch() { } +inline Microsoft::Console::VirtualTerminal::ITermDispatch::~ITermDispatch() {} diff --git a/src/terminal/adapter/InteractDispatch.cpp b/src/terminal/adapter/InteractDispatch.cpp index 6572b655d..afbddc0fd 100644 --- a/src/terminal/adapter/InteractDispatch.cpp +++ b/src/terminal/adapter/InteractDispatch.cpp @@ -14,10 +14,9 @@ using namespace Microsoft::Console::Types; using namespace Microsoft::Console::VirtualTerminal; // takes ownership of pConApi -InteractDispatch::InteractDispatch(ConGetSet* const pConApi) - : _pConApi(THROW_IF_NULL_ALLOC(pConApi)) +InteractDispatch::InteractDispatch(ConGetSet* const pConApi) : + _pConApi(THROW_IF_NULL_ALLOC(pConApi)) { - } // Method Description: @@ -108,25 +107,25 @@ bool InteractDispatch::WindowManipulation(const DispatchTypes::WindowManipulatio // MSFT:13271146 - QueryScreenSize switch (uiFunction) { - case DispatchTypes::WindowManipulationType::RefreshWindow: - if (cParams == 0) + case DispatchTypes::WindowManipulationType::RefreshWindow: + if (cParams == 0) + { + fSuccess = DispatchCommon::s_RefreshWindow(*_pConApi); + } + break; + case DispatchTypes::WindowManipulationType::ResizeWindowInCharacters: + if (cParams == 2) + { + fSuccess = DispatchCommon::s_ResizeWindow(*_pConApi, rgusParams[1], rgusParams[0]); + if (fSuccess) { - fSuccess = DispatchCommon::s_RefreshWindow(*_pConApi); + DispatchCommon::s_SuppressResizeRepaint(*_pConApi); } - break; - case DispatchTypes::WindowManipulationType::ResizeWindowInCharacters: - if (cParams == 2) - { - fSuccess = DispatchCommon::s_ResizeWindow(*_pConApi, rgusParams[1], rgusParams[0]); - if (fSuccess) - { - DispatchCommon::s_SuppressResizeRepaint(*_pConApi); - } - } - break; - default: - fSuccess = false; - break; + } + break; + default: + fSuccess = false; + break; } return fSuccess; @@ -182,13 +181,13 @@ bool InteractDispatch::MoveCursor(const unsigned int row, const unsigned int col // Safely convert the UINT positions we were given into shorts (which is the size the console deals with) fSuccess = SUCCEEDED(UIntToShort(uiRow, &coordCursor.Y)) && - SUCCEEDED(UIntToShort(uiCol, &coordCursor.X)); + SUCCEEDED(UIntToShort(uiCol, &coordCursor.X)); if (fSuccess) { // Set the line and column values as offsets from the viewport edge. Use safe math to prevent overflow. fSuccess = SUCCEEDED(ShortAdd(coordCursor.Y, csbiex.srWindow.Top, &coordCursor.Y)) && - SUCCEEDED(ShortAdd(coordCursor.X, csbiex.srWindow.Left, &coordCursor.X)); + SUCCEEDED(ShortAdd(coordCursor.X, csbiex.srWindow.Left, &coordCursor.X)); if (fSuccess) { diff --git a/src/terminal/adapter/InteractDispatch.hpp b/src/terminal/adapter/InteractDispatch.hpp index 413bb4753..6914194c8 100644 --- a/src/terminal/adapter/InteractDispatch.hpp +++ b/src/terminal/adapter/InteractDispatch.hpp @@ -23,7 +23,6 @@ namespace Microsoft::Console::VirtualTerminal class InteractDispatch : public IInteractDispatch { public: - InteractDispatch(ConGetSet* const pConApi); ~InteractDispatch() = default; @@ -36,9 +35,8 @@ namespace Microsoft::Console::VirtualTerminal const size_t cParams) override; // DTTERM_WindowManipulation bool MoveCursor(const unsigned int row, const unsigned int col) override; + private: - std::unique_ptr _pConApi; - }; } diff --git a/src/terminal/adapter/MouseInput.cpp b/src/terminal/adapter/MouseInput.cpp index 76c8b818f..a9dffd299 100644 --- a/src/terminal/adapter/MouseInput.cpp +++ b/src/terminal/adapter/MouseInput.cpp @@ -31,12 +31,10 @@ MouseInput::MouseInput(const WriteInputEvents pfnWriteEvents) : _coordLastPos{ -1, -1 }, _lastButton{ 0 } { - } MouseInput::~MouseInput() { - } // Routine Description: @@ -52,19 +50,19 @@ bool MouseInput::s_IsButtonMsg(const unsigned int uiButton) bool fIsButton = false; switch (uiButton) { - case WM_LBUTTONDBLCLK: - case WM_LBUTTONDOWN: - case WM_LBUTTONUP: - case WM_MBUTTONUP: - case WM_RBUTTONUP: - case WM_RBUTTONDOWN: - case WM_RBUTTONDBLCLK: - case WM_MBUTTONDOWN: - case WM_MBUTTONDBLCLK: - case WM_MOUSEWHEEL: - case WM_MOUSEHWHEEL: - fIsButton = true; - break; + case WM_LBUTTONDBLCLK: + case WM_LBUTTONDOWN: + case WM_LBUTTONUP: + case WM_MBUTTONUP: + case WM_RBUTTONUP: + case WM_RBUTTONDOWN: + case WM_RBUTTONDBLCLK: + case WM_MBUTTONDOWN: + case WM_MBUTTONDBLCLK: + case WM_MOUSEWHEEL: + case WM_MOUSEHWHEEL: + fIsButton = true; + break; } return fIsButton; } @@ -92,16 +90,16 @@ bool MouseInput::s_IsButtonDown(const unsigned int uiButton) bool fIsButtonDown = false; switch (uiButton) { - case WM_LBUTTONDBLCLK: - case WM_LBUTTONDOWN: - case WM_RBUTTONDOWN: - case WM_RBUTTONDBLCLK: - case WM_MBUTTONDOWN: - case WM_MBUTTONDBLCLK: - case WM_MOUSEWHEEL: - case WM_MOUSEHWHEEL: - fIsButtonDown = true; - break; + case WM_LBUTTONDBLCLK: + case WM_LBUTTONDOWN: + case WM_RBUTTONDOWN: + case WM_RBUTTONDBLCLK: + case WM_MBUTTONDOWN: + case WM_MBUTTONDBLCLK: + case WM_MOUSEWHEEL: + case WM_MOUSEHWHEEL: + fIsButtonDown = true; + break; } return fIsButtonDown; } @@ -140,26 +138,26 @@ int MouseInput::s_WindowsButtonToXEncoding(const unsigned int uiButton, int iXValue = 0; switch (uiButton) { - case WM_LBUTTONDBLCLK: - case WM_LBUTTONDOWN: - iXValue = 0; - break; - case WM_LBUTTONUP: - case WM_MBUTTONUP: - case WM_RBUTTONUP: - iXValue = 3; - break; - case WM_RBUTTONDOWN: - case WM_RBUTTONDBLCLK: - iXValue = 2; - break; - case WM_MBUTTONDOWN: - case WM_MBUTTONDBLCLK: - iXValue = 1; - break; - case WM_MOUSEWHEEL: - case WM_MOUSEHWHEEL: - iXValue = sWheelDelta > 0 ? 0x40 : 0x41; + case WM_LBUTTONDBLCLK: + case WM_LBUTTONDOWN: + iXValue = 0; + break; + case WM_LBUTTONUP: + case WM_MBUTTONUP: + case WM_RBUTTONUP: + iXValue = 3; + break; + case WM_RBUTTONDOWN: + case WM_RBUTTONDBLCLK: + iXValue = 2; + break; + case WM_MBUTTONDOWN: + case WM_MBUTTONDBLCLK: + iXValue = 1; + break; + case WM_MOUSEWHEEL: + case WM_MOUSEHWHEEL: + iXValue = sWheelDelta > 0 ? 0x40 : 0x41; } if (fIsHover) { @@ -176,7 +174,6 @@ int MouseInput::s_WindowsButtonToXEncoding(const unsigned int uiButton, return iXValue; } - // Routine Description: // - translates the input windows mouse message into its equivalent SGR encoding. // This is nearly identical to the X encoding, with an important difference. @@ -195,27 +192,27 @@ int MouseInput::s_WindowsButtonToSGREncoding(const unsigned int uiButton, int iXValue = 0; switch (uiButton) { - case WM_LBUTTONDBLCLK: - case WM_LBUTTONDOWN: - case WM_LBUTTONUP: - iXValue = 0; - break; - case WM_RBUTTONUP: - case WM_RBUTTONDOWN: - case WM_RBUTTONDBLCLK: - iXValue = 2; - break; - case WM_MBUTTONUP: - case WM_MBUTTONDOWN: - case WM_MBUTTONDBLCLK: - iXValue = 1; - break; - case WM_MOUSEMOVE: - iXValue = 3; - break; - case WM_MOUSEWHEEL: - case WM_MOUSEHWHEEL: - iXValue = sWheelDelta > 0 ? 0x40 : 0x41; + case WM_LBUTTONDBLCLK: + case WM_LBUTTONDOWN: + case WM_LBUTTONUP: + iXValue = 0; + break; + case WM_RBUTTONUP: + case WM_RBUTTONDOWN: + case WM_RBUTTONDBLCLK: + iXValue = 2; + break; + case WM_MBUTTONUP: + case WM_MBUTTONDOWN: + case WM_MBUTTONDBLCLK: + iXValue = 1; + break; + case WM_MOUSEMOVE: + iXValue = 3; + break; + case WM_MOUSEWHEEL: + case WM_MOUSEHWHEEL: + iXValue = sWheelDelta > 0 ? 0x40 : 0x41; } if (fIsHover) { @@ -288,42 +285,42 @@ bool MouseInput::HandleMouse(const COORD coordMousePosition, size_t cchSequenceLength = 0; switch (_ExtendedMode) { - case ExtendedMode::None: - fSuccess = _GenerateDefaultSequence(coordMousePosition, - uiRealButton, - fIsHover, - sModifierKeystate, - sWheelDelta, - &pwchSequence, - &cchSequenceLength); - break; - case ExtendedMode::Utf8: - fSuccess = _GenerateUtf8Sequence(coordMousePosition, - uiRealButton, - fIsHover, - sModifierKeystate, - sWheelDelta, - &pwchSequence, - &cchSequenceLength); - break; - case ExtendedMode::Sgr: - // For SGR encoding, if no physical buttons were pressed, - // then we want to handle hovers with WM_MOUSEMOVE. - // However, if we're dragging (WM_MOUSEMOVE with a button pressed), - // then use that pressed button instead. - fSuccess = _GenerateSGRSequence(coordMousePosition, - physicalButtonPressed ? uiRealButton : uiButton, - s_IsButtonDown(uiRealButton), // Use uiRealButton here, to properly get the up/down state + case ExtendedMode::None: + fSuccess = _GenerateDefaultSequence(coordMousePosition, + uiRealButton, fIsHover, sModifierKeystate, sWheelDelta, &pwchSequence, &cchSequenceLength); - break; - case ExtendedMode::Urxvt: - default: - fSuccess = false; - break; + break; + case ExtendedMode::Utf8: + fSuccess = _GenerateUtf8Sequence(coordMousePosition, + uiRealButton, + fIsHover, + sModifierKeystate, + sWheelDelta, + &pwchSequence, + &cchSequenceLength); + break; + case ExtendedMode::Sgr: + // For SGR encoding, if no physical buttons were pressed, + // then we want to handle hovers with WM_MOUSEMOVE. + // However, if we're dragging (WM_MOUSEMOVE with a button pressed), + // then use that pressed button instead. + fSuccess = _GenerateSGRSequence(coordMousePosition, + physicalButtonPressed ? uiRealButton : uiButton, + s_IsButtonDown(uiRealButton), // Use uiRealButton here, to properly get the up/down state + fIsHover, + sModifierKeystate, + sWheelDelta, + &pwchSequence, + &cchSequenceLength); + break; + case ExtendedMode::Urxvt: + default: + fSuccess = false; + break; } if (fSuccess) { @@ -376,7 +373,7 @@ bool MouseInput::_GenerateDefaultSequence(const COORD coordMousePosition, const COORD coordVTCoords = s_WinToVTCoord(coordMousePosition); const short sEncodedX = s_EncodeDefaultCoordinate(coordVTCoords.X); const short sEncodedY = s_EncodeDefaultCoordinate(coordVTCoords.Y); - wchar_t* pwchFormat = new(std::nothrow) wchar_t[7]{ L"\x1b[Mbxy" }; + wchar_t* pwchFormat = new (std::nothrow) wchar_t[7]{ L"\x1b[Mbxy" }; if (pwchFormat != nullptr) { pwchFormat[3] = ' ' + (short)s_WindowsButtonToXEncoding(uiButton, fIsHover, sModifierKeystate, sWheelDelta); @@ -430,12 +427,12 @@ bool MouseInput::_GenerateUtf8Sequence(const COORD coordMousePosition, // So bash would also need to change, but how could it tell the difference between them? no real good way. // I'm going to emit a utf16 encoded value for now. Besides, if a windows program really wants it, just use the SGR mode, which is unambiguous. // TODO: Followup once the UTF-8 input stack is ready, MSFT:8509613 - if (coordMousePosition.X <= (SHORT_MAX - 33) && coordMousePosition.Y <= (SHORT_MAX - 33)) + if (coordMousePosition.X <= (SHORT_MAX - 33) && coordMousePosition.Y <= (SHORT_MAX - 33)) { const COORD coordVTCoords = s_WinToVTCoord(coordMousePosition); const short sEncodedX = s_EncodeDefaultCoordinate(coordVTCoords.X); const short sEncodedY = s_EncodeDefaultCoordinate(coordVTCoords.Y); - wchar_t* pwchFormat = new(std::nothrow) wchar_t[7]{ L"\x1b[Mbxy" }; + wchar_t* pwchFormat = new (std::nothrow) wchar_t[7]{ L"\x1b[Mbxy" }; if (pwchFormat != nullptr) { // The short cast is safe because we know s_WindowsButtonToXEncoding never returns more than xff @@ -481,18 +478,17 @@ bool MouseInput::_GenerateSGRSequence(const COORD coordMousePosition, bool fSuccess = false; const int iXButton = s_WindowsButtonToSGREncoding(uiButton, fIsHover, sModifierKeystate, sWheelDelta); - #pragma warning( push ) - #pragma warning( disable: 4996 ) - // Disable 4996 - The _s version of _snprintf doesn't return the cch if the buffer is null, and we need the cch - #pragma prefast(suppress:28719, "Using the output of _snwprintf to determine cch. _snwprintf_s used below.") - int iNeededChars = _snwprintf(nullptr, 0, L"\x1b[<%d;%d;%d%c", - iXButton, coordMousePosition.X+1, coordMousePosition.Y+1, isDown ? L'M' : L'm'); +#pragma warning(push) +#pragma warning(disable : 4996) +// Disable 4996 - The _s version of _snprintf doesn't return the cch if the buffer is null, and we need the cch +#pragma prefast(suppress : 28719, "Using the output of _snwprintf to determine cch. _snwprintf_s used below.") + int iNeededChars = _snwprintf(nullptr, 0, L"\x1b[<%d;%d;%d%c", iXButton, coordMousePosition.X + 1, coordMousePosition.Y + 1, isDown ? L'M' : L'm'); - #pragma warning( pop ) +#pragma warning(pop) iNeededChars += 1; // for null - wchar_t* pwchFormat = new(std::nothrow) wchar_t[iNeededChars]; + wchar_t* pwchFormat = new (std::nothrow) wchar_t[iNeededChars]; if (pwchFormat != nullptr) { int iTakenChars = _snwprintf_s(pwchFormat, @@ -500,10 +496,10 @@ bool MouseInput::_GenerateSGRSequence(const COORD coordMousePosition, iNeededChars, L"\x1b[<%d;%d;%d%c", iXButton, - coordMousePosition.X+1, - coordMousePosition.Y+1, + coordMousePosition.X + 1, + coordMousePosition.Y + 1, isDown ? L'M' : L'm'); - if (iTakenChars == iNeededChars-1) // again, adjust for null + if (iTakenChars == iNeededChars - 1) // again, adjust for null { *ppwchSequence = pwchFormat; *pcchLength = iTakenChars; @@ -555,7 +551,7 @@ void MouseInput::SetSGRExtendedMode(const bool fEnable) void MouseInput::EnableDefaultTracking(const bool fEnable) { _TrackingMode = fEnable ? TrackingMode::Default : TrackingMode::None; - _coordLastPos = {-1,-1}; // Clear out the last saved mouse position & button. + _coordLastPos = { -1, -1 }; // Clear out the last saved mouse position & button. _lastButton = 0; } @@ -571,7 +567,7 @@ void MouseInput::EnableDefaultTracking(const bool fEnable) void MouseInput::EnableButtonEventTracking(const bool fEnable) { _TrackingMode = fEnable ? TrackingMode::ButtonEvent : TrackingMode::None; - _coordLastPos = {-1,-1}; // Clear out the last saved mouse position & button. + _coordLastPos = { -1, -1 }; // Clear out the last saved mouse position & button. _lastButton = 0; } @@ -587,7 +583,7 @@ void MouseInput::EnableButtonEventTracking(const bool fEnable) void MouseInput::EnableAnyEventTracking(const bool fEnable) { _TrackingMode = fEnable ? TrackingMode::AnyEvent : TrackingMode::None; - _coordLastPos = {-1,-1}; // Clear out the last saved mouse position & button. + _coordLastPos = { -1, -1 }; // Clear out the last saved mouse position & button. _lastButton = 0; } @@ -631,7 +627,7 @@ void MouseInput::_SendInputSequence(_In_reads_(cchLength) const wchar_t* const p // - the translated coordinate. COORD MouseInput::s_WinToVTCoord(const COORD coordWinCoordinate) { - return {coordWinCoordinate.X + 1, coordWinCoordinate.Y + 1}; + return { coordWinCoordinate.X + 1, coordWinCoordinate.Y + 1 }; } // Routine Description: @@ -671,7 +667,6 @@ unsigned int MouseInput::s_GetPressedButton() return uiButton; } - // Routine Description: // - Enables alternate scroll mode. This sends Cursor Up/down sequences when in the alternate buffer // Parameters: @@ -718,8 +713,7 @@ bool MouseInput::_ShouldSendAlternateScroll(_In_ unsigned int uiButton, _In_ sho { return _fInAlternateBuffer && _fAlternateScroll && - (uiButton == WM_MOUSEWHEEL || uiButton == WM_MOUSEHWHEEL) - && sScrollDelta != 0; + (uiButton == WM_MOUSEWHEEL || uiButton == WM_MOUSEHWHEEL) && sScrollDelta != 0; } // Routine Description: @@ -730,7 +724,7 @@ bool MouseInput::_ShouldSendAlternateScroll(_In_ unsigned int uiButton, _In_ sho // True iff the input sequence was sent successfully. bool MouseInput::_SendAlternateScroll(_In_ short sScrollDelta) const { - const wchar_t* const pwchSequence = sScrollDelta > 0? CURSOR_UP_SEQUENCE : CURSOR_DOWN_SEQUENCE; + const wchar_t* const pwchSequence = sScrollDelta > 0 ? CURSOR_UP_SEQUENCE : CURSOR_DOWN_SEQUENCE; _SendInputSequence(pwchSequence, CCH_CURSOR_SEQUENCES); return true; diff --git a/src/terminal/adapter/MouseInput.hpp b/src/terminal/adapter/MouseInput.hpp index 3b9df609e..adb1f8675 100644 --- a/src/terminal/adapter/MouseInput.hpp +++ b/src/terminal/adapter/MouseInput.hpp @@ -21,7 +21,7 @@ Author(s): namespace Microsoft::Console::VirtualTerminal { - typedef void(*WriteInputEvents)(_Inout_ std::deque>& events); + typedef void (*WriteInputEvents)(_Inout_ std::deque>& events); class MouseInput sealed { @@ -30,9 +30,9 @@ namespace Microsoft::Console::VirtualTerminal ~MouseInput(); bool HandleMouse(const COORD coordMousePosition, - const unsigned int uiButton, - const short sModifierKeystate, - const short sWheelDelta); + const unsigned int uiButton, + const short sModifierKeystate, + const short sWheelDelta); void SetUtf8ExtendedMode(const bool fEnable); void SetSGRExtendedMode(const bool fEnable); diff --git a/src/terminal/adapter/adaptDispatch.cpp b/src/terminal/adapter/adaptDispatch.cpp index 8e1da0e32..e4ccf61e8 100644 --- a/src/terminal/adapter/adaptDispatch.cpp +++ b/src/terminal/adapter/adaptDispatch.cpp @@ -10,7 +10,15 @@ // Inspired from RETURN_IF_WIN32_BOOL_FALSE // WIL doesn't include a RETURN_IF_FALSE, and RETURN_IF_WIN32_BOOL_FALSE // will actually return the value of GLE. -#define RETURN_IF_FALSE(b) do { BOOL __boolRet = wil::verify_bool(b); if (!__boolRet) { return b; }} while (0, 0) +#define RETURN_IF_FALSE(b) \ + do \ + { \ + BOOL __boolRet = wil::verify_bool(b); \ + if (!__boolRet) \ + { \ + return b; \ + } \ + } while (0, 0) using namespace Microsoft::Console::Types; using namespace Microsoft::Console::VirtualTerminal; @@ -21,25 +29,27 @@ using namespace Microsoft::Console::VirtualTerminal; // - // Return Value: // - Always false to signify we didn't handle it. -bool NoOp() { return false; } +bool NoOp() +{ + return false; +} // Note: AdaptDispatch will take ownership of pConApi and pDefaults AdaptDispatch::AdaptDispatch(ConGetSet* const pConApi, - AdaptDefaults* const pDefaults) - : _conApi{ THROW_IF_NULL_ALLOC(pConApi) }, - _pDefaults{ THROW_IF_NULL_ALLOC(pDefaults) }, - _fChangedBackground(false), - _fChangedForeground(false), - _fChangedMetaAttrs(false), - _TermOutput() + AdaptDefaults* const pDefaults) : + _conApi{ THROW_IF_NULL_ALLOC(pConApi) }, + _pDefaults{ THROW_IF_NULL_ALLOC(pDefaults) }, + _fChangedBackground(false), + _fChangedForeground(false), + _fChangedMetaAttrs(false), + _TermOutput() { // The top-left corner in VT-speak is 1,1. Our internal array uses 0 indexes, but VT uses 1,1 for top left corner. _coordSavedCursor.X = 1; _coordSavedCursor.Y = 1; - _srScrollMargins = {0}; // initially, there are no scroll margins. + _srScrollMargins = { 0 }; // initially, there are no scroll margins. _fIsSetColumnsEnabled = false; // by default, DECSCPP is disabled. // TODO:10086990 - Create a setting to re-enable this. - } void AdaptDispatch::Print(const wchar_t wchPrintable) @@ -64,7 +74,6 @@ void AdaptDispatch::PrintString(const wchar_t* const rgwch, const size_t cch) { _pDefaults->PrintString(rgwch, cch); } - } CATCH_LOG(); } @@ -356,7 +365,7 @@ bool AdaptDispatch::_CursorMovePosition(_In_opt_ const unsigned int* const puiRo { // Set the line and column values as offsets from the viewport edge. Use safe math to prevent overflow. fSuccess = SUCCEEDED(ShortAdd(coordCursor.Y, csbiex.srWindow.Top, &coordCursor.Y)) && - SUCCEEDED(ShortAdd(coordCursor.X, csbiex.srWindow.Left, &coordCursor.X)); + SUCCEEDED(ShortAdd(coordCursor.X, csbiex.srWindow.Left, &coordCursor.X)); if (fSuccess) { @@ -597,7 +606,6 @@ bool AdaptDispatch::_InsertDeleteHelper(_In_ unsigned int const uiCount, const b } } - return fSuccess; } @@ -658,7 +666,7 @@ bool AdaptDispatch::_EraseAreaHelper(const COORD coordStartPosition, const COORD bool fSuccess = false; for (short y = coordStartPosition.Y; y < coordLastPosition.Y; y++) { - const COORD coordLine = {coordStartPosition.X, y}; + const COORD coordLine = { coordStartPosition.X, y }; fSuccess = !!_conApi->FillConsoleOutputCharacterW(wchSpace, coordLastPosition.X - coordStartPosition.X, coordLine, written); if (fSuccess) { @@ -718,7 +726,6 @@ bool AdaptDispatch::_EraseSingleLineHelper(const CONSOLE_SCREEN_BUFFER_INFOEX* c } return _EraseSingleLineDistanceHelper(coordStartPosition, nLength, wFillColor); - } // Routine Description: @@ -741,9 +748,9 @@ bool AdaptDispatch::EraseCharacters(_In_ unsigned int const uiNumChars) const COORD coordStartPosition = csbiex.dwCursorPosition; const SHORT sRemainingSpaces = csbiex.srWindow.Right - coordStartPosition.X; - const unsigned short usActualRemaining = (sRemainingSpaces < 0)? 0 : sRemainingSpaces; + const unsigned short usActualRemaining = (sRemainingSpaces < 0) ? 0 : sRemainingSpaces; // erase at max the number of characters remaining in the line from the current position. - const DWORD dwEraseLength = (uiNumChars <= usActualRemaining)? uiNumChars : usActualRemaining; + const DWORD dwEraseLength = (uiNumChars <= usActualRemaining) ? uiNumChars : usActualRemaining; fSuccess = _EraseSingleLineDistanceHelper(coordStartPosition, dwEraseLength, csbiex.wAttributes); } @@ -857,7 +864,6 @@ bool AdaptDispatch::EraseInLine(const DispatchTypes::EraseType eraseType) return fSuccess; } - // Routine Description: // - DSR - Reports status of a console property back to the STDIN based on the type of status requested. // - This particular routine responds to ANSI status patterns only (CSI # n), not the DEC format (CSI ? # n) @@ -1003,7 +1009,7 @@ bool AdaptDispatch::_ScrollMovement(const ScrollDirection sdDirection, _In_ unsi COORD coordDestination; coordDestination.X = srScreen.Left; // Scroll starting from the top of the scroll margins. - coordDestination.Y = (_srScrollMargins.Top + srScreen.Top) + sDistance * (sdDirection == ScrollDirection::Up? -1 : 1); + coordDestination.Y = (_srScrollMargins.Top + srScreen.Top) + sDistance * (sdDirection == ScrollDirection::Up ? -1 : 1); // We don't need to worry about clipping the margins at all, ScrollRegion inside conhost will do that correctly for us // Fill character for remaining space left behind by "cut" operation (or for fill if we "cut" the entire line) @@ -1099,14 +1105,14 @@ bool AdaptDispatch::_DoDECCOLMHelper(_In_ unsigned int const uiColumns) bool AdaptDispatch::_PrivateModeParamsHelper(_In_ DispatchTypes::PrivateModeParams const param, const bool fEnable) { bool fSuccess = false; - switch(param) + switch (param) { case DispatchTypes::PrivateModeParams::DECCKM_CursorKeysMode: // set - Enable Application Mode, reset - Normal mode fSuccess = SetCursorKeysMode(fEnable); break; case DispatchTypes::PrivateModeParams::DECCOLM_SetNumberOfColumns: - fSuccess = _DoDECCOLMHelper(fEnable? DispatchTypes::s_sDECCOLMSetColumns : DispatchTypes::s_sDECCOLMResetColumns); + fSuccess = _DoDECCOLMHelper(fEnable ? DispatchTypes::s_sDECCOLMSetColumns : DispatchTypes::s_sDECCOLMResetColumns); break; case DispatchTypes::PrivateModeParams::ATT610_StartCursorBlink: fSuccess = EnableCursorBlinking(fEnable); @@ -1133,7 +1139,7 @@ bool AdaptDispatch::_PrivateModeParamsHelper(_In_ DispatchTypes::PrivateModePara fSuccess = EnableAlternateScroll(fEnable); break; case DispatchTypes::PrivateModeParams::ASB_AlternateScreenBuffer: - fSuccess = fEnable? UseAlternateScreenBuffer() : UseMainScreenBuffer(); + fSuccess = fEnable ? UseAlternateScreenBuffer() : UseMainScreenBuffer(); break; default: // If no functions to call, overall dispatch was a failure. @@ -1160,7 +1166,7 @@ bool AdaptDispatch::_SetResetPrivateModes(_In_reads_(cParams) const DispatchType size_t cFailures = 0; for (size_t i = 0; i < cParams; i++) { - cFailures += _PrivateModeParamsHelper(rgParams[i], fEnable)? 0 : 1; // increment the number of failures if we fail. + cFailures += _PrivateModeParamsHelper(rgParams[i], fEnable) ? 0 : 1; // increment the number of failures if we fail. } return cFailures == 0; } @@ -1278,7 +1284,7 @@ bool AdaptDispatch::_DoSetTopBottomScrollingMargins(const SHORT sTopMargin, SHORT sActualTop = sTopMargin; SHORT sActualBottom = sBottomMargin; SHORT sScreenHeight = csbiex.srWindow.Bottom - csbiex.srWindow.Top; - if ( sActualTop == 0 && sActualBottom == 0) + if (sActualTop == 0 && sActualBottom == 0) { // Disable Margins // This case is valid, and nothing changes. @@ -1518,7 +1524,7 @@ bool AdaptDispatch::SoftReset() if (fSuccess) { // Save cursor state: Home position. - _coordSavedCursor = {1, 1}; + _coordSavedCursor = { 1, 1 }; } return fSuccess; @@ -1617,15 +1623,15 @@ bool AdaptDispatch::_EraseScrollback() // First clear section A const DWORD dwTotalAreaBelow = csbiex.dwSize.X * (csbiex.dwSize.Y - sHeight); - const COORD coordBelowStartPosition = {0, sHeight}; + const COORD coordBelowStartPosition = { 0, sHeight }; // We don't use the _EraseAreaHelper here because _EraseSingleLineDistanceHelper does it all in one operation fSuccess = _EraseSingleLineDistanceHelper(coordBelowStartPosition, dwTotalAreaBelow, csbiex.wAttributes); if (fSuccess) { // If there is a section B, clear it. - const COORD coordBottomRight = {csbiex.dwSize.X, coordBelowStartPosition.Y}; - const COORD coordRightStartPosition = {sWidth, 0}; + const COORD coordBottomRight = { csbiex.dwSize.X, coordBelowStartPosition.Y }; + const COORD coordRightStartPosition = { sWidth, 0 }; if (coordBottomRight.X > coordRightStartPosition.X) { // We use the Area helper here because the Line helper would @@ -1647,7 +1653,7 @@ bool AdaptDispatch::_EraseScrollback() if (fSuccess) { // Move the cursor to the same relative location. - const COORD newCursor = {Cursor.X-Screen.Left, Cursor.Y-Screen.Top}; + const COORD newCursor = { Cursor.X - Screen.Left, Cursor.Y - Screen.Top }; fSuccess = !!_conApi->SetConsoleCursorPosition(newCursor); } } @@ -1762,7 +1768,7 @@ bool AdaptDispatch::SetCursorStyle(const DispatchTypes::CursorStyle cursorStyle) CursorType actualType = CursorType::Legacy; bool fEnableBlinking = false; - switch(cursorStyle) + switch (cursorStyle) { case DispatchTypes::CursorStyle::BlinkingBlock: case DispatchTypes::CursorStyle::BlinkingBlockDefault: @@ -1830,12 +1836,11 @@ bool AdaptDispatch::SetCursorColor(const COLORREF cursorColor) // True if handled successfully. False otherwise. bool AdaptDispatch::SetColorTableEntry(const size_t tableIndex, const DWORD dwColor) { - bool fSuccess = tableIndex < 256; if (fSuccess) { const auto realIndex = ::Xterm256ToWindowsIndex(tableIndex); - fSuccess = !! _conApi->PrivateSetColorTableEntry(realIndex, dwColor); + fSuccess = !!_conApi->PrivateSetColorTableEntry(realIndex, dwColor); } // If we're a conpty, always return false, so that we send the updated color @@ -1924,20 +1929,20 @@ bool AdaptDispatch::WindowManipulation(const DispatchTypes::WindowManipulationTy // MSFT:13271146 - QueryScreenSize switch (uiFunction) { - case DispatchTypes::WindowManipulationType::RefreshWindow: - if (cParams == 0) - { - fSuccess = DispatchCommon::s_RefreshWindow(*_conApi); - } - break; - case DispatchTypes::WindowManipulationType::ResizeWindowInCharacters: - if (cParams == 2) - { - fSuccess = DispatchCommon::s_ResizeWindow(*_conApi, rgusParams[1], rgusParams[0]); - } - break; - default: - fSuccess = false; + case DispatchTypes::WindowManipulationType::RefreshWindow: + if (cParams == 0) + { + fSuccess = DispatchCommon::s_RefreshWindow(*_conApi); + } + break; + case DispatchTypes::WindowManipulationType::ResizeWindowInCharacters: + if (cParams == 2) + { + fSuccess = DispatchCommon::s_ResizeWindow(*_conApi, rgusParams[1], rgusParams[0]); + } + break; + default: + fSuccess = false; } return fSuccess; diff --git a/src/terminal/adapter/adaptDispatch.hpp b/src/terminal/adapter/adaptDispatch.hpp index 39d05d986..4c7879b52 100644 --- a/src/terminal/adapter/adaptDispatch.hpp +++ b/src/terminal/adapter/adaptDispatch.hpp @@ -23,13 +23,11 @@ Author(s): #define XTERM_COLOR_TABLE_SIZE (256) - namespace Microsoft::Console::VirtualTerminal { class AdaptDispatch : public ITermDispatch { public: - AdaptDispatch(ConGetSet* const pConApi, AdaptDefaults* const pDefaults); @@ -71,8 +69,8 @@ namespace Microsoft::Console::VirtualTerminal const size_t cParams) override; // DECSET bool ResetPrivateModes(_In_reads_(cParams) const DispatchTypes::PrivateModeParams* const rParams, const size_t cParams) override; // DECRST - bool SetCursorKeysMode(const bool fApplicationMode) override; // DECCKM - bool SetKeypadMode(const bool fApplicationMode) override; // DECKPAM, DECKPNM + bool SetCursorKeysMode(const bool fApplicationMode) override; // DECCKM + bool SetKeypadMode(const bool fApplicationMode) override; // DECKPAM, DECKPNM bool EnableCursorBlinking(const bool bEnable) override; // ATT610 bool SetTopBottomScrollingMargins(const SHORT sTopMargin, const SHORT sBottomMargin) override; // DECSTBM @@ -100,13 +98,12 @@ namespace Microsoft::Console::VirtualTerminal const DWORD dwColor) override; // OscColorTable bool SetDefaultForeground(const DWORD dwColor) override; // OSCDefaultForeground bool SetDefaultBackground(const DWORD dwColor) override; // OSCDefaultBackground - + bool WindowManipulation(const DispatchTypes::WindowManipulationType uiFunction, _In_reads_(cParams) const unsigned short* const rgusParams, const size_t cParams) override; // DTTERM_WindowManipulation private: - enum class CursorDirection { Up, diff --git a/src/terminal/adapter/adaptDispatchGraphics.cpp b/src/terminal/adapter/adaptDispatchGraphics.cpp index 6950ca775..f676e08ad 100644 --- a/src/terminal/adapter/adaptDispatchGraphics.cpp +++ b/src/terminal/adapter/adaptDispatchGraphics.cpp @@ -316,10 +316,10 @@ bool AdaptDispatch::s_IsDefaultColorOption(const DispatchTypes::GraphicsOptions // 3 - true, parsed an xterm index to a color // 5 - true, parsed an RGB color. bool AdaptDispatch::_SetRgbColorsHelper(_In_reads_(cOptions) const DispatchTypes::GraphicsOptions* const rgOptions, - const size_t cOptions, - _Out_ COLORREF* const prgbColor, - _Out_ bool* const pfIsForeground, - _Out_ size_t* const pcOptionsConsumed) + const size_t cOptions, + _Out_ COLORREF* const prgbColor, + _Out_ bool* const pfIsForeground, + _Out_ size_t* const pcOptionsConsumed) { bool fSuccess = false; *pcOptionsConsumed = 1; @@ -342,9 +342,9 @@ bool AdaptDispatch::_SetRgbColorsHelper(_In_reads_(cOptions) const DispatchTypes { *pcOptionsConsumed = 5; // ensure that each value fits in a byte - unsigned int red = rgOptions[2] > 255? 255 : rgOptions[2]; - unsigned int green = rgOptions[3] > 255? 255 : rgOptions[3]; - unsigned int blue = rgOptions[4] > 255? 255 : rgOptions[4]; + unsigned int red = rgOptions[2] > 255 ? 255 : rgOptions[2]; + unsigned int green = rgOptions[3] > 255 ? 255 : rgOptions[3]; + unsigned int blue = rgOptions[4] > 255 ? 255 : rgOptions[4]; *prgbColor = RGB(red, green, blue); @@ -424,7 +424,7 @@ bool AdaptDispatch::SetGraphicsRendition(_In_reads_(cOptions) const DispatchType size_t cOptionsConsumed = 0; // _SetRgbColorsHelper will call the appropriate ConApi function - fSuccess = _SetRgbColorsHelper(&(rgOptions[i]), cOptions-i, &rgbColor, &fIsForeground, &cOptionsConsumed); + fSuccess = _SetRgbColorsHelper(&(rgOptions[i]), cOptions - i, &rgbColor, &fIsForeground, &cOptionsConsumed); i += (cOptionsConsumed - 1); // cOptionsConsumed includes the opt we're currently on. } @@ -444,7 +444,6 @@ bool AdaptDispatch::SetGraphicsRendition(_In_reads_(cOptions) const DispatchType _fChangedMetaAttrs = false; } } - } return fSuccess; diff --git a/src/terminal/adapter/conGetSet.hpp b/src/terminal/adapter/conGetSet.hpp index ecf7e215e..37b85596c 100644 --- a/src/terminal/adapter/conGetSet.hpp +++ b/src/terminal/adapter/conGetSet.hpp @@ -15,7 +15,6 @@ Author(s): #pragma once - #include "..\..\types\inc\IInputEvent.hpp" #include "..\..\inc\conattrs.hpp" @@ -109,6 +108,5 @@ namespace Microsoft::Console::VirtualTerminal virtual BOOL PrivateSetColorTableEntry(const short index, const COLORREF value) const = 0; virtual BOOL PrivateSetDefaultForeground(const COLORREF value) const = 0; virtual BOOL PrivateSetDefaultBackground(const COLORREF value) const = 0; - }; } diff --git a/src/terminal/adapter/termDispatch.hpp b/src/terminal/adapter/termDispatch.hpp index acc3e3147..66330821b 100644 --- a/src/terminal/adapter/termDispatch.hpp +++ b/src/terminal/adapter/termDispatch.hpp @@ -43,9 +43,9 @@ public: bool InsertLine(const unsigned int /*uiDistance*/) override { return false; } // IL bool DeleteLine(const unsigned int /*uiDistance*/) override { return false; } // DL bool SetColumns(const unsigned int /*uiColumns*/) override { return false; } // DECSCPP, DECCOLM - bool SetCursorKeysMode(const bool /*fApplicationMode*/) override { return false; } // DECCKM - bool SetKeypadMode(const bool /*fApplicationMode*/) override { return false; } // DECKPAM, DECKPNM - bool EnableCursorBlinking(const bool /*fEnable*/) override { return false; } // ATT610 + bool SetCursorKeysMode(const bool /*fApplicationMode*/) override { return false; } // DECCKM + bool SetKeypadMode(const bool /*fApplicationMode*/) override { return false; } // DECKPAM, DECKPNM + bool EnableCursorBlinking(const bool /*fEnable*/) override { return false; } // ATT610 bool SetTopBottomScrollingMargins(const SHORT /*sTopMargin*/, const SHORT /*sBottomMargin*/) override { return false; } // DECSTBM bool ReverseLineFeed() override { return false; } // RI bool SetWindowTitle(std::wstring_view /*title*/) override { return false; } // OscWindowTitle @@ -58,7 +58,7 @@ public: bool EnableVT200MouseMode(const bool /*fEnabled*/) override { return false; } // ?1000 bool EnableUTF8ExtendedMouseMode(const bool /*fEnabled*/) override { return false; } // ?1005 bool EnableSGRExtendedMouseMode(const bool /*fEnabled*/) override { return false; } // ?1006 - bool EnableButtonEventMouseMode(const bool /*fEnabled*/)override { return false; } // ?1002 + bool EnableButtonEventMouseMode(const bool /*fEnabled*/) override { return false; } // ?1002 bool EnableAnyEventMouseMode(const bool /*fEnabled*/) override { return false; } // ?1003 bool EnableAlternateScroll(const bool /*fEnabled*/) override { return false; } // ?1007 bool SetColorTableEntry(const size_t /*tableIndex*/, const DWORD /*dwColor*/) override { return false; } // OSCColorTable @@ -88,11 +88,9 @@ public: bool SetCursorStyle(const DispatchTypes::CursorStyle /*cursorStyle*/) override { return false; } // DECSCUSR bool SetCursorColor(const COLORREF /*Color*/) override { return false; } // OSCSetCursorColor, OSCResetCursorColor - + // DTTERM_WindowManipulation bool WindowManipulation(const DispatchTypes::WindowManipulationType /*uiFunction*/, _In_reads_(_Param_(3)) const unsigned short* const /*rgusParams*/, const size_t /*cParams*/) override { return false; } - }; - diff --git a/src/terminal/adapter/terminalOutput.cpp b/src/terminal/adapter/terminalOutput.cpp index 259565003..3becfdbdf 100644 --- a/src/terminal/adapter/terminalOutput.cpp +++ b/src/terminal/adapter/terminalOutput.cpp @@ -10,55 +10,112 @@ using namespace Microsoft::Console::VirtualTerminal; TerminalOutput::TerminalOutput() { - } TerminalOutput::~TerminalOutput() { - } // We include a full table so all we have to do is the lookup. // The tables only ever change the values x20 - x7f, hence why the table starts at \x20 // From http://vt100.net/docs/vt220-rm/table2-4.html -const wchar_t TerminalOutput::s_rgDECSpecialGraphicsTranslations[s_uiNumDisplayCharacters] -{ - L'\x20', L'\x21', L'\x22', L'\x23', L'\x24', L'\x25', L'\x26', L'\x27', L'\x28', L'\x29', L'\x2a', L'\x2b', L'\x2c', L'\x2d', L'\x2e', L'\x2f', - L'\x30', L'\x31', L'\x32', L'\x33', L'\x34', L'\x35', L'\x36', L'\x37', L'\x38', L'\x39', L'\x3a', L'\x3b', L'\x3c', L'\x3d', L'\x3e', L'\x3f', - L'\x40', L'\x41', L'\x42', L'\x43', L'\x44', L'\x45', L'\x46', L'\x47', L'\x48', L'\x49', L'\x4a', L'\x4b', L'\x4c', L'\x4d', L'\x4e', L'\x4f', - L'\x50', L'\x51', L'\x52', L'\x53', L'\x54', L'\x55', L'\x56', L'\x57', L'\x58', L'\x59', L'\x5a', L'\x5b', L'\x5c', L'\x5d', L'\x5e', L'\x5f', - L'\u25C6', // L'\x60', -> Diamond - L'\u2592', // L'\x61', -> Checkerboard - L'\u2409', // L'\x62', -> HT, SYMBOL FOR HORIZONTAL TABULATION - L'\u240c', // L'\x63', -> FF, SYMBOL FOR FORM FEED - L'\u240d', // L'\x64', -> CR, SYMBOL FOR CARRIAGE RETURN - L'\u240a', // L'\x65', -> LF, SYMBOL FOR LINE FEED - L'\u00B0', // L'\x66', -> Degree symbol - L'\u00B1', // L'\x67', -> Plus/minus - L'\u2424', // L'\x68', -> NL, SYMBOL FOR NEWLINE - L'\u240b', // L'\x69', -> VT, SYMBOL FOR VERTICAL TABULATION - L'\u2518', // L'\x6a', -> Lower-right corner - L'\u2510', // L'\x6b', -> Upper-right corner - L'\u250c', // L'\x6c', -> Upper-left corner - L'\u2514', // L'\x6d', -> Lower-left corner - L'\u253C', // L'\x6e', -> crossing lines - L'\u23ba', // L'\x6f', -> HORIZONTAL SCAN LINE-3 - L'\u23bb', // L'\x70', -> HORIZONTAL SCAN LINE-3 - L'\u2500', // L'\x71', -> HORIZONTAL SCAN LINE-5 - L'\u23bc', // L'\x72', -> HORIZONTAL SCAN LINE-7 - L'\u23bd', // L'\x73', -> HORIZONTAL SCAN LINE-7 - L'\u251c', // L'\x74', -> Left "T" - L'\u2524', // L'\x75', -> Right "T" - L'\u2534', // L'\x76', -> Bottom "T" - L'\u252c', // L'\x77', -> Top "T" - L'\u2502', // L'\x78', -> | Vertical bar - L'\u2264', // L'\x79', -> Less than or equal to - L'\u2265', // L'\x7a', -> Greater than or equal to - L'\u03C0', // L'\x7b', -> Pi - L'\u2260', // L'\x7c', -> Not equal to - L'\u00A3', // L'\x7d', -> UK pound sign - L'\u00B7', // L'\x7e', -> Centered dot - L'\x7f' // L'\x7f', -> DEL +const wchar_t TerminalOutput::s_rgDECSpecialGraphicsTranslations[s_uiNumDisplayCharacters]{ + L'\x20', + L'\x21', + L'\x22', + L'\x23', + L'\x24', + L'\x25', + L'\x26', + L'\x27', + L'\x28', + L'\x29', + L'\x2a', + L'\x2b', + L'\x2c', + L'\x2d', + L'\x2e', + L'\x2f', + L'\x30', + L'\x31', + L'\x32', + L'\x33', + L'\x34', + L'\x35', + L'\x36', + L'\x37', + L'\x38', + L'\x39', + L'\x3a', + L'\x3b', + L'\x3c', + L'\x3d', + L'\x3e', + L'\x3f', + L'\x40', + L'\x41', + L'\x42', + L'\x43', + L'\x44', + L'\x45', + L'\x46', + L'\x47', + L'\x48', + L'\x49', + L'\x4a', + L'\x4b', + L'\x4c', + L'\x4d', + L'\x4e', + L'\x4f', + L'\x50', + L'\x51', + L'\x52', + L'\x53', + L'\x54', + L'\x55', + L'\x56', + L'\x57', + L'\x58', + L'\x59', + L'\x5a', + L'\x5b', + L'\x5c', + L'\x5d', + L'\x5e', + L'\x5f', + L'\u25C6', // L'\x60', -> Diamond + L'\u2592', // L'\x61', -> Checkerboard + L'\u2409', // L'\x62', -> HT, SYMBOL FOR HORIZONTAL TABULATION + L'\u240c', // L'\x63', -> FF, SYMBOL FOR FORM FEED + L'\u240d', // L'\x64', -> CR, SYMBOL FOR CARRIAGE RETURN + L'\u240a', // L'\x65', -> LF, SYMBOL FOR LINE FEED + L'\u00B0', // L'\x66', -> Degree symbol + L'\u00B1', // L'\x67', -> Plus/minus + L'\u2424', // L'\x68', -> NL, SYMBOL FOR NEWLINE + L'\u240b', // L'\x69', -> VT, SYMBOL FOR VERTICAL TABULATION + L'\u2518', // L'\x6a', -> Lower-right corner + L'\u2510', // L'\x6b', -> Upper-right corner + L'\u250c', // L'\x6c', -> Upper-left corner + L'\u2514', // L'\x6d', -> Lower-left corner + L'\u253C', // L'\x6e', -> crossing lines + L'\u23ba', // L'\x6f', -> HORIZONTAL SCAN LINE-3 + L'\u23bb', // L'\x70', -> HORIZONTAL SCAN LINE-3 + L'\u2500', // L'\x71', -> HORIZONTAL SCAN LINE-5 + L'\u23bc', // L'\x72', -> HORIZONTAL SCAN LINE-7 + L'\u23bd', // L'\x73', -> HORIZONTAL SCAN LINE-7 + L'\u251c', // L'\x74', -> Left "T" + L'\u2524', // L'\x75', -> Right "T" + L'\u2534', // L'\x76', -> Bottom "T" + L'\u252c', // L'\x77', -> Top "T" + L'\u2502', // L'\x78', -> | Vertical bar + L'\u2264', // L'\x79', -> Less than or equal to + L'\u2265', // L'\x7a', -> Greater than or equal to + L'\u03C0', // L'\x7b', -> Pi + L'\u2260', // L'\x7c', -> Not equal to + L'\u00A3', // L'\x7d', -> UK pound sign + L'\u00B7', // L'\x7e', -> Centered dot + L'\x7f' // L'\x7f', -> DEL }; bool TerminalOutput::DesignateCharset(const wchar_t wchNewCharset) @@ -100,7 +157,7 @@ wchar_t TerminalOutput::TranslateKey(const wchar_t wch) const { wchar_t wchFound = wch; if (_wchCurrentCharset == DispatchTypes::VTCharacterSets::USASCII || - wch < '\x60' || wch > '\x7f') // filter out the region we know is unchanged + wch < '\x60' || wch > '\x7f') // filter out the region we know is unchanged { ; // do nothing, these are the same as default. } @@ -113,5 +170,4 @@ wchar_t TerminalOutput::TranslateKey(const wchar_t wch) const } } return wchFound; - } diff --git a/src/terminal/adapter/terminalOutput.hpp b/src/terminal/adapter/terminalOutput.hpp index 365c99386..33d8deb79 100644 --- a/src/terminal/adapter/terminalOutput.hpp +++ b/src/terminal/adapter/terminalOutput.hpp @@ -23,7 +23,6 @@ namespace Microsoft::Console::VirtualTerminal class TerminalOutput sealed { public: - TerminalOutput(); ~TerminalOutput(); @@ -39,6 +38,5 @@ namespace Microsoft::Console::VirtualTerminal static const wchar_t s_rgDECSpecialGraphicsTranslations[s_uiNumDisplayCharacters]; const wchar_t* _GetTranslationTable() const; - }; } diff --git a/src/terminal/adapter/ut_adapter/MouseInputTest.cpp b/src/terminal/adapter/ut_adapter/MouseInputTest.cpp index bf4b4510d..b54f9ee48 100644 --- a/src/terminal/adapter/ut_adapter/MouseInputTest.cpp +++ b/src/terminal/adapter/ut_adapter/MouseInputTest.cpp @@ -29,24 +29,24 @@ static wchar_t* s_pwszInputExpected; static wchar_t s_pwszExpectedBuffer[BYTE_MAX]; // big enough for anything -static COORD s_rgTestCoords [] = { - {0, 0}, - {0, 1}, - {1, 1}, - {2, 2}, - {94, 94}, // 94+1+32 = 127 - {95, 95}, // 95+1+32 = 128, this is the ascii boundary - {96, 96}, - {127,127}, - {128,128}, - {SHORT_MAX-33,SHORT_MAX-33}, - {SHORT_MAX-32,SHORT_MAX-32}, +static COORD s_rgTestCoords[] = { + { 0, 0 }, + { 0, 1 }, + { 1, 1 }, + { 2, 2 }, + { 94, 94 }, // 94+1+32 = 127 + { 95, 95 }, // 95+1+32 = 128, this is the ascii boundary + { 96, 96 }, + { 127, 127 }, + { 128, 128 }, + { SHORT_MAX - 33, SHORT_MAX - 33 }, + { SHORT_MAX - 32, SHORT_MAX - 32 }, }; // Note: We're going to be changing the value of the third char (the space) of // these strings as we test things with this array, to alter the expected button value. // The default value is the button=WM_LBUTTONDOWN case, which is element[3]=' ' -static wchar_t* s_rgDefaultTestOutput [] = { +static wchar_t* s_rgDefaultTestOutput[] = { L"\x1b[M !!", L"\x1b[M !\"", L"\x1b[M \"\"", @@ -64,7 +64,7 @@ static wchar_t* s_rgDefaultTestOutput [] = { // these strings as we test things with this array, to alter the expected button value. // The default value is the button=WM_LBUTTONDOWN case, which is element[3]='0' // We're also going to change the last element, for button-down (M) vs button-up (m) -static wchar_t* s_rgSgrTestOutput [] = { +static wchar_t* s_rgSgrTestOutput[] = { L"\x1b[<%d;1;1M", L"\x1b[<%d;1;2M", L"\x1b[<%d;2;2M", @@ -83,7 +83,6 @@ static int s_iTestCoordsLength = ARRAYSIZE(s_rgTestCoords); class MouseInputTest { public: - TEST_CLASS(MouseInputTest); static void s_MouseInputTestCallback(_Inout_ std::deque>& events) @@ -101,10 +100,7 @@ public: { KeyEvent expectedKeyEvent(TRUE, 1, 0, 0, s_pwszInputExpected[i], 0); KeyEvent testKeyEvent = *static_cast(events[i].get()); - VERIFY_ARE_EQUAL(expectedKeyEvent, testKeyEvent, - NoThrowString().Format(L"Chars='%c','%c'", - s_pwszInputExpected[i], - testKeyEvent.GetCharData())); + VERIFY_ARE_EQUAL(expectedKeyEvent, testKeyEvent, NoThrowString().Format(L"Chars='%c','%c'", s_pwszInputExpected[i], testKeyEvent.GetCharData())); } } } @@ -142,7 +138,6 @@ public: // correctly filled in to match uiButton. wchar_t* BuildSGRTestOutput(wchar_t* pwchTestOutput, unsigned int uiButton, short sModifierKeystate, short sScrollDelta) { - ClearTestBuffer(); // Copy the expected output into the buffer @@ -151,7 +146,7 @@ public: size_t cchInputExpected = 0; VERIFY_SUCCEEDED(StringCchLengthW(s_pwszExpectedBuffer, STRSAFE_MAX_CCH, &cchInputExpected)); - s_pwszExpectedBuffer[cchInputExpected-1] = IsButtonDown(uiButton)? L'M' : L'm'; + s_pwszExpectedBuffer[cchInputExpected - 1] = IsButtonDown(uiButton) ? L'M' : L'm'; Log::Comment(NoThrowString().Format(L"Expected Input:\'%s\'", s_pwszExpectedBuffer)); return s_pwszExpectedBuffer; @@ -163,33 +158,33 @@ public: Log::Comment(NoThrowString().Format(L"uiButton '%d'", uiButton)); switch (uiButton) { - case WM_LBUTTONDBLCLK: - case WM_LBUTTONDOWN: - wch = L' '; - break; - case WM_LBUTTONUP: - case WM_MBUTTONUP: - case WM_RBUTTONUP: - wch = L'#'; - break; - case WM_RBUTTONDOWN: - case WM_RBUTTONDBLCLK: - wch = L'\"'; - break; - case WM_MBUTTONDOWN: - case WM_MBUTTONDBLCLK: - wch = L'!'; - break; - case WM_MOUSEWHEEL: - case WM_MOUSEHWHEEL: - Log::Comment(NoThrowString().Format(L"MOUSEWHEEL")); - wch = L'`' + (sScrollDelta > 0? 0 : 1); - break; - case WM_MOUSEMOVE: - default: - Log::Comment(NoThrowString().Format(L"DEFAULT")); - wch = L'\x0'; - break; + case WM_LBUTTONDBLCLK: + case WM_LBUTTONDOWN: + wch = L' '; + break; + case WM_LBUTTONUP: + case WM_MBUTTONUP: + case WM_RBUTTONUP: + wch = L'#'; + break; + case WM_RBUTTONDOWN: + case WM_RBUTTONDBLCLK: + wch = L'\"'; + break; + case WM_MBUTTONDOWN: + case WM_MBUTTONDBLCLK: + wch = L'!'; + break; + case WM_MOUSEWHEEL: + case WM_MOUSEHWHEEL: + Log::Comment(NoThrowString().Format(L"MOUSEWHEEL")); + wch = L'`' + (sScrollDelta > 0 ? 0 : 1); + break; + case WM_MOUSEMOVE: + default: + Log::Comment(NoThrowString().Format(L"DEFAULT")); + wch = L'\x0'; + break; } // MK_SHIFT is ignored by the translator wch += (sModifierKeystate & MK_CONTROL) ? 0x08 : 0x00; @@ -201,31 +196,31 @@ public: int result = 0; switch (uiButton) { - case WM_LBUTTONDBLCLK: - case WM_LBUTTONDOWN: - case WM_LBUTTONUP: - result = 0; - break; - case WM_MBUTTONUP: - case WM_MBUTTONDOWN: - case WM_MBUTTONDBLCLK: - result = 1; - break; - case WM_RBUTTONUP: - case WM_RBUTTONDOWN: - case WM_RBUTTONDBLCLK: - result = 2; - break; - case WM_MOUSEMOVE: - result = 3 + 0x20; // we add 0x20 to hover events, which are all encoded as WM_MOUSEMOVE events - break; - case WM_MOUSEWHEEL: - case WM_MOUSEHWHEEL: - result = (sScrollDelta > 0? 64 : 65); - break; - default: - result = 0; - break; + case WM_LBUTTONDBLCLK: + case WM_LBUTTONDOWN: + case WM_LBUTTONUP: + result = 0; + break; + case WM_MBUTTONUP: + case WM_MBUTTONDOWN: + case WM_MBUTTONDBLCLK: + result = 1; + break; + case WM_RBUTTONUP: + case WM_RBUTTONDOWN: + case WM_RBUTTONDBLCLK: + result = 2; + break; + case WM_MOUSEMOVE: + result = 3 + 0x20; // we add 0x20 to hover events, which are all encoded as WM_MOUSEMOVE events + break; + case WM_MOUSEWHEEL: + case WM_MOUSEHWHEEL: + result = (sScrollDelta > 0 ? 64 : 65); + break; + default: + result = 0; + break; } // MK_SHIFT and MK_ALT is ignored by the translator result += (sModifierKeystate & MK_CONTROL) ? 0x08 : 0x00; @@ -237,16 +232,16 @@ public: bool fIsDown = false; switch (uiButton) { - case WM_LBUTTONDBLCLK: - case WM_LBUTTONDOWN: - case WM_RBUTTONDOWN: - case WM_RBUTTONDBLCLK: - case WM_MBUTTONDOWN: - case WM_MBUTTONDBLCLK: - case WM_MOUSEWHEEL: - case WM_MOUSEHWHEEL: - fIsDown = true; - break; + case WM_LBUTTONDBLCLK: + case WM_LBUTTONDOWN: + case WM_RBUTTONDOWN: + case WM_RBUTTONDBLCLK: + case WM_MBUTTONDOWN: + case WM_MBUTTONDBLCLK: + case WM_MOUSEWHEEL: + case WM_MOUSEHWHEEL: + fIsDown = true; + break; } return fIsDown; } @@ -297,7 +292,7 @@ public: bool fExpectedKeyHandled = false; s_pwszInputExpected = L"\x0"; - VERIFY_ARE_EQUAL(fExpectedKeyHandled, mouseInput->HandleMouse({0,0}, uiButton, sModifierKeystate, sScrollDelta)); + VERIFY_ARE_EQUAL(fExpectedKeyHandled, mouseInput->HandleMouse({ 0, 0 }, uiButton, sModifierKeystate, sScrollDelta)); mouseInput->EnableDefaultTracking(true); @@ -310,7 +305,11 @@ public: s_pwszInputExpected = BuildDefaultTestOutput(s_rgDefaultTestOutput[i], uiButton, sModifierKeystate, sScrollDelta); // validate translation - VERIFY_ARE_EQUAL(fExpectedKeyHandled, mouseInput->HandleMouse(Coord, uiButton, sModifierKeystate, sScrollDelta), + VERIFY_ARE_EQUAL(fExpectedKeyHandled, + mouseInput->HandleMouse(Coord, + uiButton, + sModifierKeystate, + sScrollDelta), NoThrowString().Format(L"(x,y)=(%d,%d)", Coord.X, Coord.Y)); } @@ -324,7 +323,11 @@ public: s_pwszInputExpected = BuildDefaultTestOutput(s_rgDefaultTestOutput[i], uiButton, sModifierKeystate, sScrollDelta); // validate translation - VERIFY_ARE_EQUAL(fExpectedKeyHandled, mouseInput->HandleMouse(Coord, uiButton, sModifierKeystate, sScrollDelta), + VERIFY_ARE_EQUAL(fExpectedKeyHandled, + mouseInput->HandleMouse(Coord, + uiButton, + sModifierKeystate, + sScrollDelta), NoThrowString().Format(L"(x,y)=(%d,%d)", Coord.X, Coord.Y)); } @@ -338,10 +341,13 @@ public: s_pwszInputExpected = BuildDefaultTestOutput(s_rgDefaultTestOutput[i], uiButton, sModifierKeystate, sScrollDelta); // validate translation - VERIFY_ARE_EQUAL(fExpectedKeyHandled, mouseInput->HandleMouse(Coord, uiButton, sModifierKeystate, sScrollDelta), + VERIFY_ARE_EQUAL(fExpectedKeyHandled, + mouseInput->HandleMouse(Coord, + uiButton, + sModifierKeystate, + sScrollDelta), NoThrowString().Format(L"(x,y)=(%d,%d)", Coord.X, Coord.Y)); } - } TEST_METHOD(Utf8ModeTests) { @@ -365,7 +371,7 @@ public: bool fExpectedKeyHandled = false; s_pwszInputExpected = L"\x0"; - VERIFY_ARE_EQUAL(fExpectedKeyHandled, mouseInput->HandleMouse({0,0}, uiButton, sModifierKeystate, sScrollDelta)); + VERIFY_ARE_EQUAL(fExpectedKeyHandled, mouseInput->HandleMouse({ 0, 0 }, uiButton, sModifierKeystate, sScrollDelta)); mouseInput->SetUtf8ExtendedMode(true); @@ -381,9 +387,12 @@ public: s_pwszInputExpected = BuildDefaultTestOutput(s_rgDefaultTestOutput[i], uiButton, sModifierKeystate, sScrollDelta); // validate translation - VERIFY_ARE_EQUAL(fExpectedKeyHandled, mouseInput->HandleMouse(Coord, uiButton, sModifierKeystate, sScrollDelta), + VERIFY_ARE_EQUAL(fExpectedKeyHandled, + mouseInput->HandleMouse(Coord, + uiButton, + sModifierKeystate, + sScrollDelta), NoThrowString().Format(L"(x,y)=(%d,%d)", Coord.X, Coord.Y)); - } mouseInput->EnableButtonEventTracking(true); @@ -396,9 +405,12 @@ public: s_pwszInputExpected = BuildDefaultTestOutput(s_rgDefaultTestOutput[i], uiButton, sModifierKeystate, sScrollDelta); // validate translation - VERIFY_ARE_EQUAL(fExpectedKeyHandled, mouseInput->HandleMouse(Coord, uiButton, sModifierKeystate, sScrollDelta), + VERIFY_ARE_EQUAL(fExpectedKeyHandled, + mouseInput->HandleMouse(Coord, + uiButton, + sModifierKeystate, + sScrollDelta), NoThrowString().Format(L"(x,y)=(%d,%d)", Coord.X, Coord.Y)); - } mouseInput->EnableAnyEventTracking(true); @@ -411,9 +423,12 @@ public: s_pwszInputExpected = BuildDefaultTestOutput(s_rgDefaultTestOutput[i], uiButton, sModifierKeystate, sScrollDelta); // validate translation - VERIFY_ARE_EQUAL(fExpectedKeyHandled, mouseInput->HandleMouse(Coord, uiButton, sModifierKeystate, sScrollDelta), + VERIFY_ARE_EQUAL(fExpectedKeyHandled, + mouseInput->HandleMouse(Coord, + uiButton, + sModifierKeystate, + sScrollDelta), NoThrowString().Format(L"(x,y)=(%d,%d)", Coord.X, Coord.Y)); - } } @@ -438,7 +453,7 @@ public: bool fExpectedKeyHandled = false; s_pwszInputExpected = L"\x0"; - VERIFY_ARE_EQUAL(fExpectedKeyHandled, mouseInput->HandleMouse({0,0}, uiButton, sModifierKeystate, sScrollDelta)); + VERIFY_ARE_EQUAL(fExpectedKeyHandled, mouseInput->HandleMouse({ 0, 0 }, uiButton, sModifierKeystate, sScrollDelta)); mouseInput->SetSGRExtendedMode(true); @@ -458,7 +473,6 @@ public: VERIFY_ARE_EQUAL(fExpectedKeyHandled, mouseInput->HandleMouse(Coord, uiButton, sModifierKeystate, sScrollDelta), NoThrowString().Format(L"(x,y)=(%d,%d)", Coord.X, Coord.Y)); - } mouseInput->EnableButtonEventTracking(true); @@ -470,9 +484,12 @@ public: s_pwszInputExpected = BuildSGRTestOutput(s_rgSgrTestOutput[i], uiButton, sModifierKeystate, sScrollDelta); // validate translation - VERIFY_ARE_EQUAL(fExpectedKeyHandled, mouseInput->HandleMouse(Coord, uiButton, sModifierKeystate, sScrollDelta), + VERIFY_ARE_EQUAL(fExpectedKeyHandled, + mouseInput->HandleMouse(Coord, + uiButton, + sModifierKeystate, + sScrollDelta), NoThrowString().Format(L"(x,y)=(%d,%d)", Coord.X, Coord.Y)); - } fExpectedKeyHandled = true; @@ -485,9 +502,12 @@ public: s_pwszInputExpected = BuildSGRTestOutput(s_rgSgrTestOutput[i], uiButton, sModifierKeystate, sScrollDelta); // validate translation - VERIFY_ARE_EQUAL(fExpectedKeyHandled, mouseInput->HandleMouse(Coord, uiButton, sModifierKeystate, sScrollDelta), + VERIFY_ARE_EQUAL(fExpectedKeyHandled, + mouseInput->HandleMouse(Coord, + uiButton, + sModifierKeystate, + sScrollDelta), NoThrowString().Format(L"(x,y)=(%d,%d)", Coord.X, Coord.Y)); - } } @@ -512,7 +532,7 @@ public: bool fExpectedKeyHandled = false; s_pwszInputExpected = L"\x0"; - VERIFY_ARE_EQUAL(fExpectedKeyHandled, mouseInput->HandleMouse({0,0}, uiButton, sModifierKeystate, sScrollDelta)); + VERIFY_ARE_EQUAL(fExpectedKeyHandled, mouseInput->HandleMouse({ 0, 0 }, uiButton, sModifierKeystate, sScrollDelta)); // Default Tracking, Default Encoding mouseInput->EnableDefaultTracking(true); @@ -526,9 +546,12 @@ public: s_pwszInputExpected = BuildDefaultTestOutput(s_rgDefaultTestOutput[i], uiButton, sModifierKeystate, sScrollDelta); // validate translation - VERIFY_ARE_EQUAL(fExpectedKeyHandled, mouseInput->HandleMouse(Coord, uiButton, sModifierKeystate, sScrollDelta), + VERIFY_ARE_EQUAL(fExpectedKeyHandled, + mouseInput->HandleMouse(Coord, + uiButton, + sModifierKeystate, + sScrollDelta), NoThrowString().Format(L"(x,y)=(%d,%d)", Coord.X, Coord.Y)); - } // Default Tracking, UTF8 Encoding @@ -543,12 +566,14 @@ public: s_pwszInputExpected = BuildDefaultTestOutput(s_rgDefaultTestOutput[i], uiButton, sModifierKeystate, sScrollDelta); // validate translation - VERIFY_ARE_EQUAL(fExpectedKeyHandled, mouseInput->HandleMouse(Coord, uiButton, sModifierKeystate, sScrollDelta), + VERIFY_ARE_EQUAL(fExpectedKeyHandled, + mouseInput->HandleMouse(Coord, + uiButton, + sModifierKeystate, + sScrollDelta), NoThrowString().Format(L"(x,y)=(%d,%d)", Coord.X, Coord.Y)); - } - // Default Tracking, SGR Encoding mouseInput->SetSGRExtendedMode(true); fExpectedKeyHandled = true; // SGR Mode should be able to handle any arbitrary coords. @@ -560,9 +585,12 @@ public: s_pwszInputExpected = BuildSGRTestOutput(s_rgSgrTestOutput[i], uiButton, sModifierKeystate, sScrollDelta); // validate translation - VERIFY_ARE_EQUAL(fExpectedKeyHandled, mouseInput->HandleMouse(Coord, uiButton, sModifierKeystate, sScrollDelta), + VERIFY_ARE_EQUAL(fExpectedKeyHandled, + mouseInput->HandleMouse(Coord, + uiButton, + sModifierKeystate, + sScrollDelta), NoThrowString().Format(L"(x,y)=(%d,%d)", Coord.X, Coord.Y)); - } } }; diff --git a/src/terminal/adapter/ut_adapter/WexHelpers.hpp b/src/terminal/adapter/ut_adapter/WexHelpers.hpp index 5bc14ddc3..a0dc274b3 100644 --- a/src/terminal/adapter/ut_adapter/WexHelpers.hpp +++ b/src/terminal/adapter/ut_adapter/WexHelpers.hpp @@ -1,10 +1,12 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -namespace WEX { - namespace TestExecution { +namespace WEX +{ + namespace TestExecution + { template<> - class VerifyOutputTraits < SMALL_RECT > + class VerifyOutputTraits { public: static WEX::Common::NoThrowString ToString(const SMALL_RECT& sr) @@ -14,15 +16,15 @@ namespace WEX { }; template<> - class VerifyCompareTraits < SMALL_RECT, SMALL_RECT > + class VerifyCompareTraits { public: static bool AreEqual(const SMALL_RECT& expected, const SMALL_RECT& actual) { return expected.Left == actual.Left && - expected.Right == actual.Right && - expected.Top == actual.Top && - expected.Bottom == actual.Bottom; + expected.Right == actual.Right && + expected.Top == actual.Top && + expected.Bottom == actual.Bottom; } static bool AreSame(const SMALL_RECT& expected, const SMALL_RECT& actual) @@ -49,7 +51,7 @@ namespace WEX { }; template<> - class VerifyOutputTraits < COORD > + class VerifyOutputTraits { public: static WEX::Common::NoThrowString ToString(const COORD& coord) @@ -59,13 +61,13 @@ namespace WEX { }; template<> - class VerifyCompareTraits < COORD, COORD> + class VerifyCompareTraits { public: static bool AreEqual(const COORD& expected, const COORD& actual) { return expected.X == actual.X && - expected.Y == actual.Y; + expected.Y == actual.Y; } static bool AreSame(const COORD& expected, const COORD& actual) @@ -77,16 +79,16 @@ namespace WEX { { // less is on a line above greater (Y values less than) return (expectedLess.Y < expectedGreater.Y) || - // or on the same lines and less is left of greater (X values less than) - ((expectedLess.Y == expectedGreater.Y) && (expectedLess.X < expectedGreater.X)); + // or on the same lines and less is left of greater (X values less than) + ((expectedLess.Y == expectedGreater.Y) && (expectedLess.X < expectedGreater.X)); } static bool IsGreaterThan(const COORD& expectedGreater, const COORD& expectedLess) { // greater is on a line below less (Y value greater than) return (expectedGreater.Y > expectedLess.Y) || - // or on the same lines and greater is right of less (X values greater than) - ((expectedGreater.Y == expectedLess.Y) && (expectedGreater.X > expectedLess.X)); + // or on the same lines and greater is right of less (X values greater than) + ((expectedGreater.Y == expectedLess.Y) && (expectedGreater.X > expectedLess.X)); } static bool IsNull(const COORD& object) @@ -96,7 +98,7 @@ namespace WEX { }; template<> - class VerifyOutputTraits < CONSOLE_CURSOR_INFO > + class VerifyOutputTraits { public: static WEX::Common::NoThrowString ToString(const CONSOLE_CURSOR_INFO& cci) @@ -106,13 +108,13 @@ namespace WEX { }; template<> - class VerifyCompareTraits < CONSOLE_CURSOR_INFO, CONSOLE_CURSOR_INFO > + class VerifyCompareTraits { public: static bool AreEqual(const CONSOLE_CURSOR_INFO& expected, const CONSOLE_CURSOR_INFO& actual) { return expected.bVisible == actual.bVisible && - expected.dwSize == actual.dwSize; + expected.dwSize == actual.dwSize; } static bool AreSame(const CONSOLE_CURSOR_INFO& expected, const CONSOLE_CURSOR_INFO& actual) @@ -140,68 +142,67 @@ namespace WEX { }; template<> - class VerifyOutputTraits < CONSOLE_SCREEN_BUFFER_INFOEX > + class VerifyOutputTraits { public: static WEX::Common::NoThrowString ToString(const CONSOLE_SCREEN_BUFFER_INFOEX& sbiex) { return WEX::Common::NoThrowString().Format(L"(Full:%s Attrs:0x%x PopupAttrs:0x%x CursorPos:%s Size:%s MaxSize:%s Viewport:%s)\r\nColors:\r\n(0:0x%x)\r\n(1:0x%x)\r\n(2:0x%x)\r\n(3:0x%x)\r\n(4:0x%x)\r\n(5:0x%x)\r\n(6:0x%x)\r\n(7:0x%x)\r\n(8:0x%x)\r\n(9:0x%x)\r\n(A:0x%x)\r\n(B:0x%x)\r\n(C:0x%x)\r\n(D:0x%x)\r\n(E:0x%x)\r\n(F:0x%x)\r\n", - sbiex.bFullscreenSupported ? L"True" : L"False", - sbiex.wAttributes, - sbiex.wPopupAttributes, - VerifyOutputTraits::ToString(sbiex.dwCursorPosition).ToCStrWithFallbackTo(L"Fail"), - VerifyOutputTraits::ToString(sbiex.dwSize).ToCStrWithFallbackTo(L"Fail"), - VerifyOutputTraits::ToString(sbiex.dwMaximumWindowSize).ToCStrWithFallbackTo(L"Fail"), - VerifyOutputTraits::ToString(sbiex.srWindow).ToCStrWithFallbackTo(L"Fail"), - sbiex.ColorTable[0], - sbiex.ColorTable[1], - sbiex.ColorTable[2], - sbiex.ColorTable[3], - sbiex.ColorTable[4], - sbiex.ColorTable[5], - sbiex.ColorTable[6], - sbiex.ColorTable[7], - sbiex.ColorTable[8], - sbiex.ColorTable[9], - sbiex.ColorTable[10], - sbiex.ColorTable[11], - sbiex.ColorTable[12], - sbiex.ColorTable[13], - sbiex.ColorTable[14], - sbiex.ColorTable[15]); - + sbiex.bFullscreenSupported ? L"True" : L"False", + sbiex.wAttributes, + sbiex.wPopupAttributes, + VerifyOutputTraits::ToString(sbiex.dwCursorPosition).ToCStrWithFallbackTo(L"Fail"), + VerifyOutputTraits::ToString(sbiex.dwSize).ToCStrWithFallbackTo(L"Fail"), + VerifyOutputTraits::ToString(sbiex.dwMaximumWindowSize).ToCStrWithFallbackTo(L"Fail"), + VerifyOutputTraits::ToString(sbiex.srWindow).ToCStrWithFallbackTo(L"Fail"), + sbiex.ColorTable[0], + sbiex.ColorTable[1], + sbiex.ColorTable[2], + sbiex.ColorTable[3], + sbiex.ColorTable[4], + sbiex.ColorTable[5], + sbiex.ColorTable[6], + sbiex.ColorTable[7], + sbiex.ColorTable[8], + sbiex.ColorTable[9], + sbiex.ColorTable[10], + sbiex.ColorTable[11], + sbiex.ColorTable[12], + sbiex.ColorTable[13], + sbiex.ColorTable[14], + sbiex.ColorTable[15]); } }; template<> - class VerifyCompareTraits < CONSOLE_SCREEN_BUFFER_INFOEX, CONSOLE_SCREEN_BUFFER_INFOEX > + class VerifyCompareTraits { public: static bool AreEqual(const CONSOLE_SCREEN_BUFFER_INFOEX& expected, const CONSOLE_SCREEN_BUFFER_INFOEX& actual) { return expected.bFullscreenSupported == actual.bFullscreenSupported && - expected.wAttributes == actual.wAttributes && - expected.wPopupAttributes == actual.wPopupAttributes && - VerifyCompareTraits::AreEqual(expected.dwCursorPosition, actual.dwCursorPosition) && - VerifyCompareTraits::AreEqual(expected.dwSize, actual.dwSize) && - VerifyCompareTraits::AreEqual(expected.dwMaximumWindowSize, actual.dwMaximumWindowSize) && - VerifyCompareTraits::AreEqual(expected.srWindow, actual.srWindow) && - expected.ColorTable[0] == actual.ColorTable[0] && - expected.ColorTable[1] == actual.ColorTable[1] && - expected.ColorTable[2] == actual.ColorTable[2] && - expected.ColorTable[3] == actual.ColorTable[3] && - expected.ColorTable[4] == actual.ColorTable[4] && - expected.ColorTable[5] == actual.ColorTable[5] && - expected.ColorTable[6] == actual.ColorTable[6] && - expected.ColorTable[7] == actual.ColorTable[7] && - expected.ColorTable[8] == actual.ColorTable[8] && - expected.ColorTable[9] == actual.ColorTable[9] && - expected.ColorTable[10] == actual.ColorTable[10] && - expected.ColorTable[11] == actual.ColorTable[11] && - expected.ColorTable[12] == actual.ColorTable[12] && - expected.ColorTable[13] == actual.ColorTable[13] && - expected.ColorTable[14] == actual.ColorTable[14] && - expected.ColorTable[15] == actual.ColorTable[15]; + expected.wAttributes == actual.wAttributes && + expected.wPopupAttributes == actual.wPopupAttributes && + VerifyCompareTraits::AreEqual(expected.dwCursorPosition, actual.dwCursorPosition) && + VerifyCompareTraits::AreEqual(expected.dwSize, actual.dwSize) && + VerifyCompareTraits::AreEqual(expected.dwMaximumWindowSize, actual.dwMaximumWindowSize) && + VerifyCompareTraits::AreEqual(expected.srWindow, actual.srWindow) && + expected.ColorTable[0] == actual.ColorTable[0] && + expected.ColorTable[1] == actual.ColorTable[1] && + expected.ColorTable[2] == actual.ColorTable[2] && + expected.ColorTable[3] == actual.ColorTable[3] && + expected.ColorTable[4] == actual.ColorTable[4] && + expected.ColorTable[5] == actual.ColorTable[5] && + expected.ColorTable[6] == actual.ColorTable[6] && + expected.ColorTable[7] == actual.ColorTable[7] && + expected.ColorTable[8] == actual.ColorTable[8] && + expected.ColorTable[9] == actual.ColorTable[9] && + expected.ColorTable[10] == actual.ColorTable[10] && + expected.ColorTable[11] == actual.ColorTable[11] && + expected.ColorTable[12] == actual.ColorTable[12] && + expected.ColorTable[13] == actual.ColorTable[13] && + expected.ColorTable[14] == actual.ColorTable[14] && + expected.ColorTable[15] == actual.ColorTable[15]; } static bool AreSame(const CONSOLE_SCREEN_BUFFER_INFOEX& expected, const CONSOLE_SCREEN_BUFFER_INFOEX& actual) @@ -226,33 +227,33 @@ namespace WEX { static bool IsNull(const CONSOLE_SCREEN_BUFFER_INFOEX& object) { return object.bFullscreenSupported == 0 && - object.wAttributes == 0 && - object.wPopupAttributes == 0 && - VerifyCompareTraits::IsNull(object.dwCursorPosition) && - VerifyCompareTraits::IsNull(object.dwSize) && - VerifyCompareTraits::IsNull(object.dwMaximumWindowSize) && - VerifyCompareTraits::IsNull(object.srWindow) && - object.ColorTable[0] == 0x0 && - object.ColorTable[1] == 0x0 && - object.ColorTable[2] == 0x0 && - object.ColorTable[3] == 0x0 && - object.ColorTable[4] == 0x0 && - object.ColorTable[5] == 0x0 && - object.ColorTable[6] == 0x0 && - object.ColorTable[7] == 0x0 && - object.ColorTable[8] == 0x0 && - object.ColorTable[9] == 0x0 && - object.ColorTable[10] == 0x0 && - object.ColorTable[11] == 0x0 && - object.ColorTable[12] == 0x0 && - object.ColorTable[13] == 0x0 && - object.ColorTable[14] == 0x0 && - object.ColorTable[15] == 0x0; + object.wAttributes == 0 && + object.wPopupAttributes == 0 && + VerifyCompareTraits::IsNull(object.dwCursorPosition) && + VerifyCompareTraits::IsNull(object.dwSize) && + VerifyCompareTraits::IsNull(object.dwMaximumWindowSize) && + VerifyCompareTraits::IsNull(object.srWindow) && + object.ColorTable[0] == 0x0 && + object.ColorTable[1] == 0x0 && + object.ColorTable[2] == 0x0 && + object.ColorTable[3] == 0x0 && + object.ColorTable[4] == 0x0 && + object.ColorTable[5] == 0x0 && + object.ColorTable[6] == 0x0 && + object.ColorTable[7] == 0x0 && + object.ColorTable[8] == 0x0 && + object.ColorTable[9] == 0x0 && + object.ColorTable[10] == 0x0 && + object.ColorTable[11] == 0x0 && + object.ColorTable[12] == 0x0 && + object.ColorTable[13] == 0x0 && + object.ColorTable[14] == 0x0 && + object.ColorTable[15] == 0x0; } }; template<> - class VerifyOutputTraits + class VerifyOutputTraits { public: static WEX::Common::NoThrowString ToString(const INPUT_RECORD& ir) @@ -260,76 +261,76 @@ namespace WEX { SetVerifyOutput verifySettings(VerifyOutputSettings::LogOnlyFailures); WCHAR szBuf[1024]; VERIFY_SUCCEEDED(StringCchCopy(szBuf, ARRAYSIZE(szBuf), L"(ev: ")); - switch(ir.EventType) + switch (ir.EventType) { - case FOCUS_EVENT: - { - WCHAR szFocus[512]; - VERIFY_SUCCEEDED(StringCchPrintf(szFocus, - ARRAYSIZE(szFocus), - L"FOCUS set: %s)", - ir.Event.FocusEvent.bSetFocus ? L"T" : L"F")); - VERIFY_SUCCEEDED(StringCchCat(szBuf, ARRAYSIZE(szBuf), szFocus)); - break; - } + case FOCUS_EVENT: + { + WCHAR szFocus[512]; + VERIFY_SUCCEEDED(StringCchPrintf(szFocus, + ARRAYSIZE(szFocus), + L"FOCUS set: %s)", + ir.Event.FocusEvent.bSetFocus ? L"T" : L"F")); + VERIFY_SUCCEEDED(StringCchCat(szBuf, ARRAYSIZE(szBuf), szFocus)); + break; + } - case KEY_EVENT: - { - WCHAR szKey[512]; - VERIFY_SUCCEEDED(StringCchPrintf(szKey, - ARRAYSIZE(szKey), - L"KEY down: %s reps: %d kc: 0x%x sc: 0x%x uc: %d ctl: 0x%x)", - ir.Event.KeyEvent.bKeyDown ? L"T" : L"F", - ir.Event.KeyEvent.wRepeatCount, - ir.Event.KeyEvent.wVirtualKeyCode, - ir.Event.KeyEvent.wVirtualScanCode, - ir.Event.KeyEvent.uChar.UnicodeChar, - ir.Event.KeyEvent.dwControlKeyState)); - VERIFY_SUCCEEDED(StringCchCat(szBuf, ARRAYSIZE(szBuf), szKey)); - break; - } + case KEY_EVENT: + { + WCHAR szKey[512]; + VERIFY_SUCCEEDED(StringCchPrintf(szKey, + ARRAYSIZE(szKey), + L"KEY down: %s reps: %d kc: 0x%x sc: 0x%x uc: %d ctl: 0x%x)", + ir.Event.KeyEvent.bKeyDown ? L"T" : L"F", + ir.Event.KeyEvent.wRepeatCount, + ir.Event.KeyEvent.wVirtualKeyCode, + ir.Event.KeyEvent.wVirtualScanCode, + ir.Event.KeyEvent.uChar.UnicodeChar, + ir.Event.KeyEvent.dwControlKeyState)); + VERIFY_SUCCEEDED(StringCchCat(szBuf, ARRAYSIZE(szBuf), szKey)); + break; + } - case MENU_EVENT: - { - WCHAR szMenu[512]; - VERIFY_SUCCEEDED(StringCchPrintf(szMenu, - ARRAYSIZE(szMenu), - L"MENU cmd: %d (0x%x))", - ir.Event.MenuEvent.dwCommandId, - ir.Event.MenuEvent.dwCommandId)); - VERIFY_SUCCEEDED(StringCchCat(szBuf, ARRAYSIZE(szBuf), szMenu)); - break; - } + case MENU_EVENT: + { + WCHAR szMenu[512]; + VERIFY_SUCCEEDED(StringCchPrintf(szMenu, + ARRAYSIZE(szMenu), + L"MENU cmd: %d (0x%x))", + ir.Event.MenuEvent.dwCommandId, + ir.Event.MenuEvent.dwCommandId)); + VERIFY_SUCCEEDED(StringCchCat(szBuf, ARRAYSIZE(szBuf), szMenu)); + break; + } - case MOUSE_EVENT: - { - WCHAR szMouse[512]; - VERIFY_SUCCEEDED(StringCchPrintf(szMouse, - ARRAYSIZE(szMouse), - L"MOUSE pos: (%d, %d) buttons: 0x%x ctl: 0x%x evflags: 0x%x)", - ir.Event.MouseEvent.dwMousePosition.X, - ir.Event.MouseEvent.dwMousePosition.Y, - ir.Event.MouseEvent.dwButtonState, - ir.Event.MouseEvent.dwControlKeyState, - ir.Event.MouseEvent.dwEventFlags)); - VERIFY_SUCCEEDED(StringCchCat(szBuf, ARRAYSIZE(szBuf), szMouse)); - break; - } + case MOUSE_EVENT: + { + WCHAR szMouse[512]; + VERIFY_SUCCEEDED(StringCchPrintf(szMouse, + ARRAYSIZE(szMouse), + L"MOUSE pos: (%d, %d) buttons: 0x%x ctl: 0x%x evflags: 0x%x)", + ir.Event.MouseEvent.dwMousePosition.X, + ir.Event.MouseEvent.dwMousePosition.Y, + ir.Event.MouseEvent.dwButtonState, + ir.Event.MouseEvent.dwControlKeyState, + ir.Event.MouseEvent.dwEventFlags)); + VERIFY_SUCCEEDED(StringCchCat(szBuf, ARRAYSIZE(szBuf), szMouse)); + break; + } - case WINDOW_BUFFER_SIZE_EVENT: - { - WCHAR szBufferSize[512]; - VERIFY_SUCCEEDED(StringCchPrintf(szBufferSize, - ARRAYSIZE(szBufferSize), - L"WINDOW_BUFFER_SIZE (%d, %d)", - ir.Event.WindowBufferSizeEvent.dwSize.X, - ir.Event.WindowBufferSizeEvent.dwSize.Y)); - VERIFY_SUCCEEDED(StringCchCat(szBuf, ARRAYSIZE(szBuf), szBufferSize)); - break; - } + case WINDOW_BUFFER_SIZE_EVENT: + { + WCHAR szBufferSize[512]; + VERIFY_SUCCEEDED(StringCchPrintf(szBufferSize, + ARRAYSIZE(szBufferSize), + L"WINDOW_BUFFER_SIZE (%d, %d)", + ir.Event.WindowBufferSizeEvent.dwSize.X, + ir.Event.WindowBufferSizeEvent.dwSize.Y)); + VERIFY_SUCCEEDED(StringCchCat(szBuf, ARRAYSIZE(szBuf), szBufferSize)); + break; + } - default: - VERIFY_FAIL(L"ERROR: unknown input event type encountered"); + default: + VERIFY_FAIL(L"ERROR: unknown input event type encountered"); } return WEX::Common::NoThrowString(szBuf); @@ -337,7 +338,7 @@ namespace WEX { }; template<> - class VerifyCompareTraits < INPUT_RECORD, INPUT_RECORD > + class VerifyCompareTraits { public: static bool AreEqual(const INPUT_RECORD& expected, const INPUT_RECORD& actual) diff --git a/src/terminal/adapter/ut_adapter/adapterTest.cpp b/src/terminal/adapter/ut_adapter/adapterTest.cpp index 7289d6bed..7b079f248 100644 --- a/src/terminal/adapter/ut_adapter/adapterTest.cpp +++ b/src/terminal/adapter/ut_adapter/adapterTest.cpp @@ -23,7 +23,6 @@ namespace Microsoft }; }; - enum class CursorY { TOP, @@ -312,8 +311,7 @@ public: bool fBlue = (iXtermTableEntry & 0x04) > 0; bool fBright = (iXtermTableEntry & 0x08) > 0; WORD iWinEntry = (fRed ? 0x4 : 0x0) | (fGreen ? 0x2 : 0x0) | (fBlue ? 0x1 : 0x0) | (fBright ? 0x8 : 0x0); - _wAttribute = fIsForeground ? ((_wAttribute & 0xF0) | iWinEntry) - : ((iWinEntry << 4) | (_wAttribute & 0x0F)); + _wAttribute = fIsForeground ? ((_wAttribute & 0xF0) | iWinEntry) : ((iWinEntry << 4) | (_wAttribute & 0x0F)); } } @@ -421,17 +419,32 @@ public: L"\tScrolling Rectangle (T: %d, B: %d, L: %d, R: %d) " L"into new top-left coordinate (X: %d, Y:%d) with Fill ('%c', 0x%x) " L"clipping to (T: %d, B: %d, L: %d, R: %d)...", - pScrollRectangle->Top, pScrollRectangle->Bottom, pScrollRectangle->Left, pScrollRectangle->Right, - dwDestinationOrigin.X, dwDestinationOrigin.Y, pFill->Char.UnicodeChar, pFill->Attributes, - pClipRectangle->Top, pClipRectangle->Bottom, pClipRectangle->Left, pClipRectangle->Right)); + pScrollRectangle->Top, + pScrollRectangle->Bottom, + pScrollRectangle->Left, + pScrollRectangle->Right, + dwDestinationOrigin.X, + dwDestinationOrigin.Y, + pFill->Char.UnicodeChar, + pFill->Attributes, + pClipRectangle->Top, + pClipRectangle->Bottom, + pClipRectangle->Left, + pClipRectangle->Right)); } else { Log::Comment(NoThrowString().Format( L"\tScrolling Rectangle (T: %d, B: %d, L: %d, R: %d) " L"into new top-left coordinate (X: %d, Y:%d) with Fill ('%c', 0x%x) ", - pScrollRectangle->Top, pScrollRectangle->Bottom, pScrollRectangle->Left, pScrollRectangle->Right, - dwDestinationOrigin.X, dwDestinationOrigin.Y, pFill->Char.UnicodeChar, pFill->Attributes)); + pScrollRectangle->Top, + pScrollRectangle->Bottom, + pScrollRectangle->Left, + pScrollRectangle->Right, + dwDestinationOrigin.X, + dwDestinationOrigin.Y, + pFill->Char.UnicodeChar, + pFill->Attributes)); } // allocate buffer space to hold scrolling rectangle @@ -448,7 +461,6 @@ public: // back up space and fill it with the fill. for (SHORT iCharX = pScrollRectangle->Left; iCharX < pScrollRectangle->Right; iCharX++) { - COORD coordTarget; coordTarget.X = (SHORT)iCharX; coordTarget.Y = iCharY; @@ -465,7 +477,6 @@ public: *pciStored = *pFill; } } - } Log::Comment(NoThrowString().Format(L"\tCopied a total %zu chars", cciFilled)); Log::Comment(L"\tCopying chars back"); @@ -1027,7 +1038,6 @@ public: { wchar_t const wch = pwszExpectedResponse[iInput / 2]; // the same portion of the string will be used twice. 0/2 = 0. 1/2 = 0. 2/2 = 1. 3/2 = 1. and so on. - VERIFY_ARE_EQUAL(InputEventType::KeyEvent, _events[iInput]->EventType()); const KeyEvent* const keyEvent = static_cast(_events[iInput].get()); @@ -1242,10 +1252,9 @@ public: bool _IsInRegionInclusive(SMALL_RECT srRegion, short sRow, short sCol) { return srRegion.Left <= sCol && - srRegion.Right >= sCol && - srRegion.Top <= sRow && - srRegion.Bottom >= sRow; - + srRegion.Right >= sCol && + srRegion.Top <= sRow && + srRegion.Bottom >= sRow; } CHAR_INFO* _GetCharAt(size_t const iRow, size_t const iCol) @@ -1355,7 +1364,7 @@ public: COORD _coordExpectedScreenBufferSize = { 0, 0 }; SMALL_RECT _srExpectedScreenBufferViewport{ 0, 0, 0, 0 }; - WORD _wExpectedAttributes = 0; + WORD _wExpectedAttributes = 0; BOOL _fPrivateSetCursorKeysModeResult = false; BOOL _fPrivateSetKeypadModeResult = false; bool _fCursorKeysApplicationMode = false; @@ -1428,7 +1437,6 @@ class DummyAdapter : public AdaptDefaults class AdapterTest { public: - TEST_CLASS(AdapterTest); TEST_METHOD_SETUP(SetupMethods) @@ -1457,12 +1465,12 @@ public: { BEGIN_TEST_METHOD_PROPERTIES() TEST_METHOD_PROPERTY(L"Data:uiDirection", L"{0, 1, 2, 3, 4, 5}") // These values align with the CursorDirection enum class to try all the directions. - END_TEST_METHOD_PROPERTIES() + END_TEST_METHOD_PROPERTIES() - Log::Comment(L"Starting test..."); + Log::Comment(L"Starting test..."); // Used to switch between the various function options. - typedef bool(AdaptDispatch::*CursorMoveFunc)(unsigned int); + typedef bool (AdaptDispatch::*CursorMoveFunc)(unsigned int); CursorMoveFunc moveFunc = nullptr; // Modify variables based on directionality of this test @@ -1676,8 +1684,7 @@ public: _testGetSet->_fGetConsoleScreenBufferInfoExResult = FALSE; _testGetSet->_fMoveCursorVerticallyResult = true; Log::Comment(NoThrowString().Format( - L"Cursor Up and Down don't need GetConsoleScreenBufferInfoEx, so they will succeed" - )); + L"Cursor Up and Down don't need GetConsoleScreenBufferInfoEx, so they will succeed")); if (direction == CursorDirection::UP || direction == CursorDirection::DOWN) { VERIFY_IS_TRUE((_pDispatch->*(moveFunc))(0)); @@ -1693,7 +1700,6 @@ public: { Log::Comment(L"Starting test..."); - Log::Comment(L"Test 1: Place cursor within the viewport. Start from top left, move to middle."); _testGetSet->PrepData(CursorX::LEFT, CursorY::TOP); @@ -1755,20 +1761,18 @@ public: _testGetSet->PrepData(CursorX::LEFT, CursorY::TOP); VERIFY_IS_FALSE(_pDispatch->CursorPosition(0, 0)); - } TEST_METHOD(CursorSingleDimensionMoveTest) { BEGIN_TEST_METHOD_PROPERTIES() TEST_METHOD_PROPERTY(L"Data:uiDirection", L"{0, 1}") // These values align with the CursorDirection enum class to try all the directions. - END_TEST_METHOD_PROPERTIES() - - Log::Comment(L"Starting test..."); + END_TEST_METHOD_PROPERTIES() + Log::Comment(L"Starting test..."); //// Used to switch between the various function options. - typedef bool(AdaptDispatch::*CursorMoveFunc)(unsigned int); + typedef bool (AdaptDispatch::*CursorMoveFunc)(unsigned int); CursorMoveFunc moveFunc = nullptr; SHORT* psViewportEnd = nullptr; SHORT* psViewportStart = nullptr; @@ -1876,7 +1880,6 @@ public: { Log::Comment(L"Starting test..."); - COORD coordExpected = { 0 }; Log::Comment(L"Test 1: Restore with no saved data should move to top-left corner, the null/default position."); @@ -2140,7 +2143,6 @@ public: srTestText.Left -= cchDeleteSize; srTestText.Right -= cchDeleteSize; - // delete out 5 spots. this should shift the ABCDE text left by 5 and insert 5 spaces at the end of the line VERIFY_IS_TRUE(_pDispatch->DeleteCharacter(cchDeleteSize), L"Verify delete call was sucessful."); @@ -2315,10 +2317,10 @@ public: BEGIN_TEST_METHOD_PROPERTIES() TEST_METHOD_PROPERTY(L"Data:uiEraseType", L"{0, 1, 2}") // corresponds to options in DispatchTypes::EraseType TEST_METHOD_PROPERTY(L"Data:fEraseScreen", L"{FALSE, TRUE}") // corresponds to Line (FALSE) or Screen (TRUE) - END_TEST_METHOD_PROPERTIES() + END_TEST_METHOD_PROPERTIES() - // Modify variables based on type of this test - DispatchTypes::EraseType eraseType; + // Modify variables based on type of this test + DispatchTypes::EraseType eraseType; unsigned int uiEraseType; VERIFY_SUCCEEDED_RETURN(TestData::TryGetValue(L"uiEraseType", uiEraseType)); eraseType = (DispatchTypes::EraseType)uiEraseType; @@ -2491,7 +2493,6 @@ public: { Log::Comment(L"Starting test..."); - Log::Comment(L"Test 1: Send no options."); _testGetSet->PrepData(); @@ -2513,7 +2514,7 @@ public: _testGetSet->PrepData(); _testGetSet->_fSetConsoleTextAttributeResult = FALSE; // Need at least one option in order for the call to be able to fail. - rgOptions[0] = (DispatchTypes::GraphicsOptions) 0; + rgOptions[0] = (DispatchTypes::GraphicsOptions)0; cOptions = 1; VERIFY_IS_FALSE(_pDispatch->SetGraphicsRendition(rgOptions, cOptions)); } @@ -2522,9 +2523,9 @@ public: { BEGIN_TEST_METHOD_PROPERTIES() TEST_METHOD_PROPERTY(L"Data:uiGraphicsOptions", L"{0, 1, 4, 7, 24, 27, 30, 31, 32, 33, 34, 35, 36, 37, 39, 40, 41, 42, 43, 44, 45, 46, 47, 49, 90, 91, 92, 93, 94, 95, 96, 97, 100, 101, 102, 103, 104, 105, 106, 107}") // corresponds to options in DispatchTypes::GraphicsOptions - END_TEST_METHOD_PROPERTIES() + END_TEST_METHOD_PROPERTIES() - Log::Comment(L"Starting test..."); + Log::Comment(L"Starting test..."); _testGetSet->PrepData(); // Modify variables based on type of this test @@ -2934,7 +2935,7 @@ public: Log::Comment(L"Test 1: Verify failure when using bad status."); _testGetSet->PrepData(); - VERIFY_IS_FALSE(_pDispatch->DeviceStatusReport((DispatchTypes::AnsiStatusType) - 1)); + VERIFY_IS_FALSE(_pDispatch->DeviceStatusReport((DispatchTypes::AnsiStatusType)-1)); } TEST_METHOD(DeviceStatus_CursorPositionReportTests) @@ -2986,12 +2987,12 @@ public: BEGIN_TEST_METHOD_PROPERTIES() TEST_METHOD_PROPERTY(L"Data:uiDirection", L"{0, 1}") // These values align with the ScrollDirection enum class to try all the directions. TEST_METHOD_PROPERTY(L"Data:uiMagnitude", L"{1, 2, 5}") // These values align with the ScrollDirection enum class to try all the directions. - END_TEST_METHOD_PROPERTIES() + END_TEST_METHOD_PROPERTIES() - Log::Comment(L"Starting test..."); + Log::Comment(L"Starting test..."); // Used to switch between the various function options. - typedef bool(AdaptDispatch::*ScrollFunc)(const unsigned int); + typedef bool (AdaptDispatch::*ScrollFunc)(const unsigned int); ScrollFunc scrollFunc = nullptr; // Modify variables based on directionality of this test @@ -3102,12 +3103,10 @@ public: coordTestText.X = srTestText.Left; coordTestText.Y = (fScrollUp) ? (srTestText.Top - sMagnitude) : (srTestText.Top + sMagnitude); VERIFY_IS_TRUE(_testGetSet->ValidateString(coordTestText, pwszTestText, wAttrTestText), L"String should have moved up/down by given magnitude."); - } TEST_METHOD(CursorKeysModeTest) { - Log::Comment(L"Starting test..."); // success cases @@ -3124,12 +3123,10 @@ public: _testGetSet->_fCursorKeysApplicationMode = true; VERIFY_IS_TRUE(_pDispatch->SetCursorKeysMode(true)); - } TEST_METHOD(KeypadModeTest) { - Log::Comment(L"Starting test..."); // success cases @@ -3146,12 +3143,10 @@ public: _testGetSet->_fKeypadApplicationMode = true; VERIFY_IS_TRUE(_pDispatch->SetKeypadMode(true)); - } TEST_METHOD(AllowBlinkingTest) { - Log::Comment(L"Starting test..."); // success cases @@ -3168,7 +3163,6 @@ public: _testGetSet->_fEnable = false; VERIFY_IS_TRUE(_pDispatch->EnableCursorBlinking(false)); - } TEST_METHOD(ScrollMarginsTest) @@ -3212,7 +3206,6 @@ public: _testGetSet->_fPrivateSetScrollingRegionResult = TRUE; VERIFY_IS_FALSE(_pDispatch->SetTopBottomScrollingMargins(srTestMargins.Top, srTestMargins.Bottom)); - Log::Comment(L"Test 6: Verify Setting margins to (0, height) clears them"); // First set, _testGetSet->_fPrivateSetScrollingRegionResult = TRUE; @@ -3224,7 +3217,6 @@ public: _testGetSet->_SetMarginsHelper(&srTestMargins, 0, 7); VERIFY_IS_TRUE(_pDispatch->SetTopBottomScrollingMargins(srTestMargins.Top, srTestMargins.Bottom)); - Log::Comment(L"Test 7: Verify Setting margins to (1, height) clears them"); // First set, _testGetSet->_fPrivateSetScrollingRegionResult = TRUE; @@ -3235,10 +3227,8 @@ public: _testGetSet->_srExpectedScrollRegion.Bottom = 0; _testGetSet->_SetMarginsHelper(&srTestMargins, 0, 7); VERIFY_IS_TRUE(_pDispatch->SetTopBottomScrollingMargins(srTestMargins.Top, srTestMargins.Bottom)); - } - TEST_METHOD(TabSetClearTests) { Log::Comment(L"Starting test..."); @@ -3260,12 +3250,10 @@ public: _testGetSet->_fExpectedClearAll = false; VERIFY_IS_TRUE(_pDispatch->TabClear(DispatchTypes::TabClearType::ClearCurrentColumn)); - } TEST_METHOD(SetConsoleTitleTest) { - Log::Comment(L"Starting test..."); Log::Comment(L"Test 1: set title to be non-null"); @@ -3281,7 +3269,6 @@ public: _testGetSet->_pwchExpectedWindowTitle = nullptr; VERIFY_IS_TRUE(_pDispatch->SetWindowTitle({})); - } TEST_METHOD(TestMouseModes) @@ -3337,7 +3324,6 @@ public: _testGetSet->PrepData(); // default color from here is gray on black, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED - DispatchTypes::GraphicsOptions rgOptions[16]; size_t cOptions = 3; @@ -3363,8 +3349,6 @@ public: _testGetSet->_fUsingRgbColor = false; VERIFY_IS_TRUE(_pDispatch->SetGraphicsRendition(rgOptions, cOptions)); - - Log::Comment(L"Test 3: Change Foreground to RGB color"); rgOptions[0] = DispatchTypes::GraphicsOptions::ForegroundExtended; rgOptions[1] = DispatchTypes::GraphicsOptions::Xterm256Index; @@ -3374,7 +3358,6 @@ public: _testGetSet->_fUsingRgbColor = true; VERIFY_IS_TRUE(_pDispatch->SetGraphicsRendition(rgOptions, cOptions)); - Log::Comment(L"Test 4: Change Background to RGB color"); rgOptions[0] = DispatchTypes::GraphicsOptions::BackgroundExtended; rgOptions[1] = DispatchTypes::GraphicsOptions::Xterm256Index; @@ -3396,10 +3379,8 @@ public: _testGetSet->_fExpectedIsForeground = true; _testGetSet->_fUsingRgbColor = false; VERIFY_IS_TRUE(_pDispatch->SetGraphicsRendition(rgOptions, cOptions)); - } - TEST_METHOD(HardReset) { Log::Comment(L"Starting test..."); @@ -3531,7 +3512,6 @@ public: _testGetSet->_expectedColorTableIndex = 15; // Windows BRIGHT_WHITE VERIFY_IS_FALSE(_pDispatch->SetColorTableEntry(15, testColor)); - } private: diff --git a/src/terminal/adapter/ut_adapter/inputTest.cpp b/src/terminal/adapter/ut_adapter/inputTest.cpp index 21392161b..f245ea9f4 100644 --- a/src/terminal/adapter/ut_adapter/inputTest.cpp +++ b/src/terminal/adapter/ut_adapter/inputTest.cpp @@ -36,7 +36,6 @@ static wchar_t s_pwsInputBuffer[256]; class Microsoft::Console::VirtualTerminal::InputTest { public: - TEST_CLASS(InputTest); static void s_TerminalInputTestCallback(_In_ std::deque>& inEvents); @@ -49,13 +48,12 @@ public: wchar_t GetModifierChar(const bool fShift, const bool fAlt, const bool fCtrl) { - return L'1' + (fShift? 1 : 0) + (fAlt? 2 : 0) + (fCtrl? 4 : 0); + return L'1' + (fShift ? 1 : 0) + (fAlt ? 2 : 0) + (fCtrl ? 4 : 0); } bool ControlAndAltPressed(unsigned int uiKeystate) { - return WI_IsAnyFlagSet(uiKeystate, LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED) - && WI_IsAnyFlagSet(uiKeystate, LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED); + return WI_IsAnyFlagSet(uiKeystate, LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED) && WI_IsAnyFlagSet(uiKeystate, LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED); } bool ControlOrAltPressed(unsigned int uiKeystate) @@ -127,7 +125,6 @@ void InputTest::s_TerminalInputTestNullCallback(_In_ std::dequeHandleKey(inputEvent.get()), L"Verify key was handled if it should have been."); - } } @@ -592,7 +587,6 @@ void InputTest::TerminalInputNullKeyTests() irTest.Event.KeyEvent.dwControlKeyState = uiKeystate; inputEvent = IInputEvent::Create(irTest); VERIFY_ARE_EQUAL(false, pInput->HandleKey(inputEvent.get()), L"Verify key was handled if it should have been."); - } void TestKey(const TerminalInput* const pInput, const unsigned int uiKeystate, const BYTE vkey, const wchar_t wch) @@ -621,7 +615,6 @@ void InputTest::DifferentModifiersTest() { Log::Comment(L"Starting test..."); - const TerminalInput* const pInput = new TerminalInput(s_TerminalInputTestCallback); Log::Comment(L"Sending a bunch of keystrokes that are a little weird."); diff --git a/src/terminal/input/terminalInput.cpp b/src/terminal/input/terminalInput.cpp index 3936731e9..73072ec36 100644 --- a/src/terminal/input/terminalInput.cpp +++ b/src/terminal/input/terminalInput.cpp @@ -29,8 +29,7 @@ TerminalInput::TerminalInput(_In_ std::functionpwszSequence, _TermKeyMap::s_cchMaxSequenceLength + 1, &cch)) && cch > 0) { - wchar_t* rwchModifiedSequence = new(std::nothrow) wchar_t[cch + 1]; + wchar_t* rwchModifiedSequence = new (std::nothrow) wchar_t[cch + 1]; if (rwchModifiedSequence != nullptr) { memcpy(rwchModifiedSequence, pMatchingMapping->pwszSequence, cch * sizeof(wchar_t)); @@ -261,7 +254,7 @@ bool TerminalInput::_SearchWithModifier(const KeyEvent& keyEvent) const rwchModifiedSequence[cch] = 0; _SendInputSequence(rwchModifiedSequence); fSuccess = true; - delete [] rwchModifiedSequence; + delete[] rwchModifiedSequence; } } } @@ -291,7 +284,6 @@ bool TerminalInput::_SearchWithModifier(const KeyEvent& keyEvent) const // This mapping doesn't need to be changed at all. _SendInputSequence(CTRL_SLASH_SEQUENCE); fSuccess = true; - } } } @@ -407,7 +399,7 @@ bool TerminalInput::HandleKey(const IInputEvent* const pInEvent) const keyEvent.IsCtrlPressed() && (keyEvent.GetCharData() == 0 || keyEvent.GetCharData() == 0x20) && ((keyEvent.GetVirtualKeyCode() > 0x40 && keyEvent.GetVirtualKeyCode() <= 0x5A) || - keyEvent.GetVirtualKeyCode() == VK_SPACE) ) + keyEvent.GetVirtualKeyCode() == VK_SPACE)) { // For Alt+Ctrl+Key messages, the UnicodeChar is NOT the Ctrl+key char, it's null. // So we need to get the char from the vKey. @@ -438,7 +430,7 @@ bool TerminalInput::HandleKey(const IInputEvent* const pInEvent) const } if (!fKeyHandled && keyEvent.IsCtrlPressed()) { - if ((keyEvent.GetCharData() == UNICODE_SPACE ) || // Ctrl+Space + if ((keyEvent.GetCharData() == UNICODE_SPACE) || // Ctrl+Space // when Ctrl+@ comes through, the unicodechar // will be '\x0' (UNICODE_NULL), and the vkey will be // VkKeyScanW(0), the vkey for null diff --git a/src/terminal/input/terminalInput.hpp b/src/terminal/input/terminalInput.hpp index 47f34d8ff..fba8f391c 100644 --- a/src/terminal/input/terminalInput.hpp +++ b/src/terminal/input/terminalInput.hpp @@ -21,7 +21,6 @@ namespace Microsoft::Console::VirtualTerminal { class TerminalInput final { - public: TerminalInput(_In_ std::function>&)> pfn); @@ -58,12 +57,12 @@ namespace Microsoft::Console::VirtualTerminal _TermKeyMap(const WORD wVirtualKey, _In_ PCWSTR const pwszSequence) : wVirtualKey(wVirtualKey), pwszSequence(pwszSequence), - dwModifiers(0) {}; + dwModifiers(0){}; _TermKeyMap(const WORD wVirtualKey, const DWORD dwModifiers, _In_ PCWSTR const pwszSequence) : wVirtualKey(wVirtualKey), pwszSequence(pwszSequence), - dwModifiers(dwModifiers) {}; + dwModifiers(dwModifiers){}; // C++11 syntax for prohibiting assignment // We can't assign, everything here is const. @@ -93,18 +92,17 @@ namespace Microsoft::Console::VirtualTerminal static const size_t s_cSimpleModifedKeyMapping; bool _SearchKeyMapping(const KeyEvent& keyEvent, - _In_reads_(cKeyMapping) const TerminalInput::_TermKeyMap* keyMapping, - const size_t cKeyMapping, - _Out_ const TerminalInput::_TermKeyMap** pMatchingMapping) const; + _In_reads_(cKeyMapping) const TerminalInput::_TermKeyMap* keyMapping, + const size_t cKeyMapping, + _Out_ const TerminalInput::_TermKeyMap** pMatchingMapping) const; bool _TranslateDefaultMapping(const KeyEvent& keyEvent, - _In_reads_(cKeyMapping) const TerminalInput::_TermKeyMap* keyMapping, - const size_t cKeyMapping) const; + _In_reads_(cKeyMapping) const TerminalInput::_TermKeyMap* keyMapping, + const size_t cKeyMapping) const; bool _SearchWithModifier(const KeyEvent& keyEvent) const; const size_t GetKeyMappingLength(const KeyEvent& keyEvent) const; const _TermKeyMap* GetKeyMapping(const KeyEvent& keyEvent) const; - }; } diff --git a/src/terminal/parser/IStateMachineEngine.hpp b/src/terminal/parser/IStateMachineEngine.hpp index 1db380f66..54a3c2958 100644 --- a/src/terminal/parser/IStateMachineEngine.hpp +++ b/src/terminal/parser/IStateMachineEngine.hpp @@ -17,7 +17,6 @@ namespace Microsoft::Console::VirtualTerminal class IStateMachineEngine { public: - virtual ~IStateMachineEngine() = 0; virtual bool ActionExecute(const wchar_t wch) = 0; @@ -43,17 +42,16 @@ namespace Microsoft::Console::VirtualTerminal virtual bool ActionIgnore() = 0; virtual bool ActionOscDispatch(const wchar_t wch, - const unsigned short sOscParam, - _Inout_updates_(cchOscString) wchar_t* const pwchOscStringBuffer, - const unsigned short cchOscString) = 0; + const unsigned short sOscParam, + _Inout_updates_(cchOscString) wchar_t* const pwchOscStringBuffer, + const unsigned short cchOscString) = 0; virtual bool ActionSs3Dispatch(const wchar_t wch, - _In_reads_(cParams) const unsigned short* const rgusParams, - const unsigned short cParams) = 0; + _In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams) = 0; virtual bool FlushAtEndOfString() const = 0; virtual bool DispatchControlCharsFromEscape() const = 0; - }; inline IStateMachineEngine::~IStateMachineEngine() {} diff --git a/src/terminal/parser/InputStateMachineEngine.cpp b/src/terminal/parser/InputStateMachineEngine.cpp index 5a27d5638..8ef0049dc 100644 --- a/src/terminal/parser/InputStateMachineEngine.cpp +++ b/src/terminal/parser/InputStateMachineEngine.cpp @@ -38,8 +38,7 @@ const size_t WRAPPED_SEQUENCE_MAX_LENGTH = 8; // CAPSLOCK_ON 0x0080 // ENHANCED_KEY 0x0100 -const InputStateMachineEngine::CSI_TO_VKEY InputStateMachineEngine::s_rgCsiMap[] -{ +const InputStateMachineEngine::CSI_TO_VKEY InputStateMachineEngine::s_rgCsiMap[]{ { CsiActionCodes::ArrowUp, VK_UP }, { CsiActionCodes::ArrowDown, VK_DOWN }, { CsiActionCodes::ArrowRight, VK_RIGHT }, @@ -52,8 +51,7 @@ const InputStateMachineEngine::CSI_TO_VKEY InputStateMachineEngine::s_rgCsiMap[] { CsiActionCodes::CSI_F4, VK_F4 }, }; -const InputStateMachineEngine::GENERIC_TO_VKEY InputStateMachineEngine::s_rgGenericMap[] -{ +const InputStateMachineEngine::GENERIC_TO_VKEY InputStateMachineEngine::s_rgGenericMap[]{ { GenericKeyIdentifiers::GenericHome, VK_HOME }, { GenericKeyIdentifiers::Insert, VK_INSERT }, { GenericKeyIdentifiers::Delete, VK_DELETE }, @@ -70,8 +68,7 @@ const InputStateMachineEngine::GENERIC_TO_VKEY InputStateMachineEngine::s_rgGene { GenericKeyIdentifiers::F12, VK_F12 }, }; -const InputStateMachineEngine::SS3_TO_VKEY InputStateMachineEngine::s_rgSs3Map[] -{ +const InputStateMachineEngine::SS3_TO_VKEY InputStateMachineEngine::s_rgSs3Map[]{ { Ss3ActionCodes::SS3_F1, VK_F1 }, { Ss3ActionCodes::SS3_F2, VK_F2 }, { Ss3ActionCodes::SS3_F3, VK_F3 }, @@ -80,7 +77,8 @@ const InputStateMachineEngine::SS3_TO_VKEY InputStateMachineEngine::s_rgSs3Map[] InputStateMachineEngine::InputStateMachineEngine(IInteractDispatch* const pDispatch) : InputStateMachineEngine(pDispatch, false) -{} +{ +} InputStateMachineEngine::InputStateMachineEngine(IInteractDispatch* const pDispatch, const bool lookingForDSR) : _pDispatch(THROW_IF_NULL_ALLOC(pDispatch)), @@ -118,10 +116,10 @@ bool InputStateMachineEngine::_DoControlCharacter(const wchar_t wch, const bool short vkey = 0; DWORD dwModifierState = 0; - switch(wch) + switch (wch) { case L'\b': - fSuccess = _GenerateKeyFromChar(wch+0x40, &vkey, nullptr); + fSuccess = _GenerateKeyFromChar(wch + 0x40, &vkey, nullptr); break; case L'\r': writeCtrl = false; @@ -176,7 +174,6 @@ bool InputStateMachineEngine::_DoControlCharacter(const wchar_t wch, const bool return fSuccess; } - // Routine Description: // - Triggers the Execute action to indicate that the listener should // immediately respond to a C0 control character. @@ -204,7 +201,7 @@ bool InputStateMachineEngine::ActionPrint(const wchar_t wch) { short vkey = 0; DWORD dwModifierState = 0; - bool fSuccess = _GenerateKeyFromChar(wch, &vkey, &dwModifierState); + bool fSuccess = _GenerateKeyFromChar(wch, &vkey, &dwModifierState); if (fSuccess) { fSuccess = _WriteSingleKey(wch, vkey, dwModifierState); @@ -311,12 +308,54 @@ bool InputStateMachineEngine::ActionCsiDispatch(const wchar_t wch, const unsigned short cRemainingArgs = (cParams >= 1) ? cParams - 1 : 0; bool fSuccess = false; - switch(wch) + switch (wch) { - case CsiActionCodes::Generic: - dwModifierState = _GetGenericKeysModifierState(rgusParams, cParams); - fSuccess = _GetGenericVkey(rgusParams, cParams, &vkey); + case CsiActionCodes::Generic: + dwModifierState = _GetGenericKeysModifierState(rgusParams, cParams); + fSuccess = _GetGenericVkey(rgusParams, cParams, &vkey); + break; + // case CsiActionCodes::DSR_DeviceStatusReportResponse: + case CsiActionCodes::CSI_F3: + // The F3 case is special - it shares a code with the DeviceStatusResponse. + // If we're looking for that response, then do that, and break out. + // Else, fall though to the _GetCursorKeysModifierState handler. + if (_lookingForDSR) + { + fSuccess = true; + fSuccess = _GetXYPosition(rgusParams, cParams, &row, &col); break; + } + case CsiActionCodes::ArrowUp: + case CsiActionCodes::ArrowDown: + case CsiActionCodes::ArrowRight: + case CsiActionCodes::ArrowLeft: + case CsiActionCodes::Home: + case CsiActionCodes::End: + case CsiActionCodes::CSI_F1: + case CsiActionCodes::CSI_F2: + case CsiActionCodes::CSI_F4: + dwModifierState = _GetCursorKeysModifierState(rgusParams, cParams); + fSuccess = _GetCursorKeysVkey(wch, &vkey); + break; + case CsiActionCodes::CursorBackTab: + dwModifierState = SHIFT_PRESSED; + vkey = VK_TAB; + fSuccess = true; + break; + case CsiActionCodes::DTTERM_WindowManipulation: + fSuccess = _GetWindowManipulationType(rgusParams, + cParams, + &uiFunction); + break; + default: + fSuccess = false; + break; + } + + if (fSuccess) + { + switch (wch) + { // case CsiActionCodes::DSR_DeviceStatusReportResponse: case CsiActionCodes::CSI_F3: // The F3 case is special - it shares a code with the DeviceStatusResponse. @@ -324,10 +363,14 @@ bool InputStateMachineEngine::ActionCsiDispatch(const wchar_t wch, // Else, fall though to the _GetCursorKeysModifierState handler. if (_lookingForDSR) { - fSuccess = true; - fSuccess = _GetXYPosition(rgusParams, cParams, &row, &col); + fSuccess = _pDispatch->MoveCursor(row, col); + // Right now we're only looking for on initial cursor + // position response. After that, only look for F3. + _lookingForDSR = false; break; } + __fallthrough; + case CsiActionCodes::Generic: case CsiActionCodes::ArrowUp: case CsiActionCodes::ArrowDown: case CsiActionCodes::ArrowRight: @@ -337,67 +380,18 @@ bool InputStateMachineEngine::ActionCsiDispatch(const wchar_t wch, case CsiActionCodes::CSI_F1: case CsiActionCodes::CSI_F2: case CsiActionCodes::CSI_F4: - dwModifierState = _GetCursorKeysModifierState(rgusParams, cParams); - fSuccess = _GetCursorKeysVkey(wch, &vkey); - break; case CsiActionCodes::CursorBackTab: - dwModifierState = SHIFT_PRESSED; - vkey = VK_TAB; - fSuccess = true; + fSuccess = _WriteSingleKey(vkey, dwModifierState); break; case CsiActionCodes::DTTERM_WindowManipulation: - fSuccess = _GetWindowManipulationType(rgusParams, - cParams, - &uiFunction); + fSuccess = _pDispatch->WindowManipulation(static_cast(uiFunction), + rgusRemainingArgs, + cRemainingArgs); break; default: fSuccess = false; break; - - } - - if (fSuccess) - { - switch(wch) - { - // case CsiActionCodes::DSR_DeviceStatusReportResponse: - case CsiActionCodes::CSI_F3: - // The F3 case is special - it shares a code with the DeviceStatusResponse. - // If we're looking for that response, then do that, and break out. - // Else, fall though to the _GetCursorKeysModifierState handler. - if (_lookingForDSR) - { - fSuccess = _pDispatch->MoveCursor(row, col); - // Right now we're only looking for on initial cursor - // position response. After that, only look for F3. - _lookingForDSR = false; - break; - } - __fallthrough; - case CsiActionCodes::Generic: - case CsiActionCodes::ArrowUp: - case CsiActionCodes::ArrowDown: - case CsiActionCodes::ArrowRight: - case CsiActionCodes::ArrowLeft: - case CsiActionCodes::Home: - case CsiActionCodes::End: - case CsiActionCodes::CSI_F1: - case CsiActionCodes::CSI_F2: - case CsiActionCodes::CSI_F4: - case CsiActionCodes::CursorBackTab: - fSuccess = _WriteSingleKey(vkey, dwModifierState); - break; - case CsiActionCodes::DTTERM_WindowManipulation: - fSuccess = _pDispatch->WindowManipulation(static_cast(uiFunction), - rgusRemainingArgs, - cRemainingArgs); - break; - default: - fSuccess = false; - break; - } - } return fSuccess; @@ -604,7 +598,6 @@ size_t InputStateMachineEngine::_GenerateWrappedSequence(const wchar_t wch, } return index; - } // Method Description: @@ -706,7 +699,7 @@ DWORD InputStateMachineEngine::_GetCursorKeysModifierState(_In_reads_(cParams) c DWORD InputStateMachineEngine::_GetGenericKeysModifierState(_In_reads_(cParams) const unsigned short* const rgusParams, const unsigned short cParams) { DWORD dwModifiers = 0; - if (_IsModified(cParams) && cParams >=2) + if (_IsModified(cParams) && cParams >= 2) { dwModifiers = _GetModifier(rgusParams[1]); } @@ -736,13 +729,13 @@ bool InputStateMachineEngine::_IsModified(const unsigned short cParams) DWORD InputStateMachineEngine::_GetModifier(const unsigned short modifierParam) { // VT Modifiers are 1+(modifier flags) - unsigned short vtParam = modifierParam-1; + unsigned short vtParam = modifierParam - 1; DWORD modifierState = modifierParam > 0 ? ENHANCED_KEY : 0; bool fShift = WI_IsFlagSet(vtParam, VT_SHIFT); bool fAlt = WI_IsFlagSet(vtParam, VT_ALT); bool fCtrl = WI_IsFlagSet(vtParam, VT_CTRL); - return modifierState | (fShift? SHIFT_PRESSED : 0) | (fAlt? LEFT_ALT_PRESSED : 0) | (fCtrl? LEFT_CTRL_PRESSED : 0); + return modifierState | (fShift ? SHIFT_PRESSED : 0) | (fAlt ? LEFT_ALT_PRESSED : 0) | (fCtrl ? LEFT_CTRL_PRESSED : 0); } // Method Description: @@ -764,7 +757,7 @@ bool InputStateMachineEngine::_GetGenericVkey(_In_reads_(cParams) const unsigned } const unsigned short identifier = rgusParams[0]; - for(int i = 0; i < ARRAYSIZE(s_rgGenericMap); i++) + for (int i = 0; i < ARRAYSIZE(s_rgGenericMap); i++) { GENERIC_TO_VKEY mapping = s_rgGenericMap[i]; if (mapping.Identifier == identifier) @@ -786,7 +779,7 @@ bool InputStateMachineEngine::_GetGenericVkey(_In_reads_(cParams) const unsigned bool InputStateMachineEngine::_GetCursorKeysVkey(const wchar_t wch, _Out_ short* const pVkey) const { *pVkey = 0; - for(int i = 0; i < ARRAYSIZE(s_rgCsiMap); i++) + for (int i = 0; i < ARRAYSIZE(s_rgCsiMap); i++) { CSI_TO_VKEY mapping = s_rgCsiMap[i]; if (mapping.Action == wch) @@ -809,7 +802,7 @@ bool InputStateMachineEngine::_GetCursorKeysVkey(const wchar_t wch, _Out_ short* bool InputStateMachineEngine::_GetSs3KeysVkey(const wchar_t wch, _Out_ short* const pVkey) const { *pVkey = 0; - for(int i = 0; i < ARRAYSIZE(s_rgSs3Map); i++) + for (int i = 0; i < ARRAYSIZE(s_rgSs3Map); i++) { SS3_TO_VKEY mapping = s_rgSs3Map[i]; if (mapping.Action == wch) @@ -848,9 +841,9 @@ bool InputStateMachineEngine::_GenerateKeyFromChar(const wchar_t wch, // Because of course, these are not the same flags. short dwModifierState = 0 | - (WI_IsFlagSet(keyscanModifiers, KEYSCAN_SHIFT) ? SHIFT_PRESSED : 0) | - (WI_IsFlagSet(keyscanModifiers, KEYSCAN_CTRL) ? LEFT_CTRL_PRESSED : 0) | - (WI_IsFlagSet(keyscanModifiers, KEYSCAN_ALT) ? LEFT_ALT_PRESSED : 0); + (WI_IsFlagSet(keyscanModifiers, KEYSCAN_SHIFT) ? SHIFT_PRESSED : 0) | + (WI_IsFlagSet(keyscanModifiers, KEYSCAN_CTRL) ? LEFT_CTRL_PRESSED : 0) | + (WI_IsFlagSet(keyscanModifiers, KEYSCAN_ALT) ? LEFT_ALT_PRESSED : 0); if (pVkey != nullptr) { @@ -910,18 +903,18 @@ bool InputStateMachineEngine::_GetWindowManipulationType(_In_reads_(cParams) con if (cParams > 0) { - switch(rgusParams[0]) + switch (rgusParams[0]) { - case DispatchTypes::WindowManipulationType::RefreshWindow: - *puiFunction = DispatchTypes::WindowManipulationType::RefreshWindow; - fSuccess = true; - break; - case DispatchTypes::WindowManipulationType::ResizeWindowInCharacters: - *puiFunction = DispatchTypes::WindowManipulationType::ResizeWindowInCharacters; - fSuccess = true; - break; - default: - fSuccess = false; + case DispatchTypes::WindowManipulationType::RefreshWindow: + *puiFunction = DispatchTypes::WindowManipulationType::RefreshWindow; + fSuccess = true; + break; + case DispatchTypes::WindowManipulationType::ResizeWindowInCharacters: + *puiFunction = DispatchTypes::WindowManipulationType::ResizeWindowInCharacters; + fSuccess = true; + break; + default: + fSuccess = false; } } @@ -935,11 +928,10 @@ bool InputStateMachineEngine::_GetWindowManipulationType(_In_reads_(cParams) con // - puiColumn - Memory location to receive the X/Column position // Return Value: // - True if we successfully pulled the cursor coordinates from the parameters we've stored. False otherwise. -_Success_(return) -bool InputStateMachineEngine::_GetXYPosition(_In_reads_(cParams) const unsigned short* const rgusParams, - const unsigned short cParams, - _Out_ unsigned int* const puiLine, - _Out_ unsigned int* const puiColumn) const +_Success_(return ) bool InputStateMachineEngine::_GetXYPosition(_In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams, + _Out_ unsigned int* const puiLine, + _Out_ unsigned int* const puiColumn) const { bool fSuccess = true; *puiLine = s_uiDefaultLine; @@ -974,7 +966,6 @@ bool InputStateMachineEngine::_GetXYPosition(_In_reads_(cParams) const unsigned if (*puiColumn == 0) { *puiColumn = s_uiDefaultColumn; - } return fSuccess; diff --git a/src/terminal/parser/InputStateMachineEngine.hpp b/src/terminal/parser/InputStateMachineEngine.hpp index 1cf661e34..0e1a33407 100644 --- a/src/terminal/parser/InputStateMachineEngine.hpp +++ b/src/terminal/parser/InputStateMachineEngine.hpp @@ -42,33 +42,32 @@ namespace Microsoft::Console::VirtualTerminal size_t const cch) override; bool ActionEscDispatch(const wchar_t wch, - const unsigned short cIntermediate, - const wchar_t wchIntermediate) override; + const unsigned short cIntermediate, + const wchar_t wchIntermediate) override; bool ActionCsiDispatch(const wchar_t wch, - const unsigned short cIntermediate, - const wchar_t wchIntermediate, - _In_reads_(cParams) const unsigned short* const rgusParams, - const unsigned short cParams); + const unsigned short cIntermediate, + const wchar_t wchIntermediate, + _In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams); bool ActionClear() override; bool ActionIgnore() override; bool ActionOscDispatch(const wchar_t wch, - const unsigned short sOscParam, - _Inout_updates_(cchOscString) wchar_t* const pwchOscStringBuffer, - const unsigned short cchOscString) override; + const unsigned short sOscParam, + _Inout_updates_(cchOscString) wchar_t* const pwchOscStringBuffer, + const unsigned short cchOscString) override; bool ActionSs3Dispatch(const wchar_t wch, - _In_reads_(cParams) const unsigned short* const rgusParams, - const unsigned short cParams) override; + _In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams) override; bool FlushAtEndOfString() const override; bool DispatchControlCharsFromEscape() const override; private: - const std::unique_ptr _pDispatch; bool _lookingForDSR; @@ -125,17 +124,20 @@ namespace Microsoft::Console::VirtualTerminal F12 = 24, }; - struct CSI_TO_VKEY { + struct CSI_TO_VKEY + { CsiActionCodes Action; short vkey; }; - struct GENERIC_TO_VKEY { + struct GENERIC_TO_VKEY + { GenericKeyIdentifiers Identifier; short vkey; }; - struct SS3_TO_VKEY { + struct SS3_TO_VKEY + { Ss3ActionCodes Action; short vkey; }; @@ -144,20 +146,18 @@ namespace Microsoft::Console::VirtualTerminal static const GENERIC_TO_VKEY s_rgGenericMap[]; static const SS3_TO_VKEY s_rgSs3Map[]; - DWORD _GetCursorKeysModifierState(_In_reads_(cParams) const unsigned short* const rgusParams, - const unsigned short cParams); + const unsigned short cParams); DWORD _GetGenericKeysModifierState(_In_reads_(cParams) const unsigned short* const rgusParams, - const unsigned short cParams); - bool _GenerateKeyFromChar(const wchar_t wch, _Out_ short* const pVkey, - _Out_ DWORD* const pdwModifierState); + const unsigned short cParams); + bool _GenerateKeyFromChar(const wchar_t wch, _Out_ short* const pVkey, _Out_ DWORD* const pdwModifierState); bool _IsModified(const unsigned short cParams); DWORD _GetModifier(const unsigned short modifierParam); bool _GetGenericVkey(_In_reads_(cParams) const unsigned short* const rgusParams, - const unsigned short cParams, - _Out_ short* const pVkey) const; + const unsigned short cParams, + _Out_ short* const pVkey) const; bool _GetCursorKeysVkey(const wchar_t wch, _Out_ short* const pVkey) const; bool _GetSs3KeysVkey(const wchar_t wch, _Out_ short* const pVkey) const; @@ -171,10 +171,10 @@ namespace Microsoft::Console::VirtualTerminal const size_t cInput); size_t _GetSingleKeypress(const wchar_t wch, - const short vkey, - const DWORD dwModifierState, - _Inout_updates_(cRecords) INPUT_RECORD* const rgInput, - const size_t cRecords); + const short vkey, + const DWORD dwModifierState, + _Inout_updates_(cRecords) INPUT_RECORD* const rgInput, + const size_t cRecords); bool _GetWindowManipulationType(_In_reads_(cParams) const unsigned short* const rgusParams, const unsigned short cParams, diff --git a/src/terminal/parser/OutputStateMachineEngine.cpp b/src/terminal/parser/OutputStateMachineEngine.cpp index 7037975cc..9b20caa38 100644 --- a/src/terminal/parser/OutputStateMachineEngine.cpp +++ b/src/terminal/parser/OutputStateMachineEngine.cpp @@ -21,7 +21,6 @@ OutputStateMachineEngine::OutputStateMachineEngine(ITermDispatch* const pDispatc OutputStateMachineEngine::~OutputStateMachineEngine() { - } const ITermDispatch& OutputStateMachineEngine::Dispatch() const noexcept @@ -523,14 +522,15 @@ bool OutputStateMachineEngine::ActionCsiDispatch(const wchar_t wch, return fSuccess; } - // Routine Description: // - Handles actions that have postfix params on an intermediate '?', such as DECTCEM, DECCOLM, ATT610 // Arguments: // - wch - Character to dispatch. // Return Value: // - True if handled successfully. False otherwise. -bool OutputStateMachineEngine::_IntermediateQuestionMarkDispatch(const wchar_t wchAction, _In_reads_(cParams) const unsigned short* const rgusParams, const unsigned short cParams) +bool OutputStateMachineEngine::_IntermediateQuestionMarkDispatch(const wchar_t wchAction, + _In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams) { bool fSuccess = false; @@ -539,19 +539,19 @@ bool OutputStateMachineEngine::_IntermediateQuestionMarkDispatch(const wchar_t w // Ensure that there was the right number of params switch (wchAction) { - case VTActionCodes::DECSET_PrivateModeSet: - case VTActionCodes::DECRST_PrivateModeReset: - fSuccess = _GetPrivateModeParams(rgusParams, cParams, rgPrivateModeParams, &cOptions); - break; + case VTActionCodes::DECSET_PrivateModeSet: + case VTActionCodes::DECRST_PrivateModeReset: + fSuccess = _GetPrivateModeParams(rgusParams, cParams, rgPrivateModeParams, &cOptions); + break; - default: - // If no params to fill, param filling was successful. - fSuccess = true; - break; + default: + // If no params to fill, param filling was successful. + fSuccess = true; + break; } if (fSuccess) { - switch(wchAction) + switch (wchAction) { case VTActionCodes::DECSET_PrivateModeSet: fSuccess = _dispatch->SetPrivateModes(rgPrivateModeParams, cOptions); @@ -571,7 +571,6 @@ bool OutputStateMachineEngine::_IntermediateQuestionMarkDispatch(const wchar_t w return fSuccess; } - // Routine Description: // - Handles actions that have an intermediate '!', such as DECSTR // Arguments: @@ -582,7 +581,7 @@ bool OutputStateMachineEngine::_IntermediateExclamationDispatch(const wchar_t wc { bool fSuccess = false; - switch(wchAction) + switch (wchAction) { case VTActionCodes::DECSTR_SoftReset: fSuccess = _dispatch->SoftReset(); @@ -610,7 +609,7 @@ bool OutputStateMachineEngine::_IntermediateSpaceDispatch(const wchar_t wchActio DispatchTypes::CursorStyle cursorStyle = s_defaultCursorStyle; // Parse params - switch(wchAction) + switch (wchAction) { case VTActionCodes::DECSCUSR_SetCursorStyle: fSuccess = _GetCursorStyle(rgusParams, cParams, &cursorStyle); @@ -624,7 +623,7 @@ bool OutputStateMachineEngine::_IntermediateSpaceDispatch(const wchar_t wchActio // if param filling successful, try to dispatch if (fSuccess) { - switch(wchAction) + switch (wchAction) { case VTActionCodes::DECSCUSR_SetCursorStyle: fSuccess = _dispatch->SetCursorStyle(cursorStyle); @@ -787,11 +786,10 @@ bool OutputStateMachineEngine::ActionSs3Dispatch(const wchar_t /*wch*/, // - pcOptions - Pointer to the length of rgGraphicsOptions on the way in, and the count of the array used on the way out. // Return Value: // - True if we successfully retrieved an array of valid graphics options from the parameters we've stored. False otherwise. -_Success_(return) -bool OutputStateMachineEngine::_GetGraphicsOptions(_In_reads_(cParams) const unsigned short* const rgusParams, - const unsigned short cParams, - _Out_writes_(*pcOptions) DispatchTypes::GraphicsOptions* const rgGraphicsOptions, - _Inout_ size_t* const pcOptions) const +_Success_(return ) bool OutputStateMachineEngine::_GetGraphicsOptions(_In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams, + _Out_writes_(*pcOptions) DispatchTypes::GraphicsOptions* const rgGraphicsOptions, + _Inout_ size_t* const pcOptions) const { bool fSuccess = false; @@ -843,8 +841,9 @@ bool OutputStateMachineEngine::_GetGraphicsOptions(_In_reads_(cParams) const uns // - pEraseType - Memory location to receive the erase type parameter // Return Value: // - True if we successfully pulled an erase type from the parameters we've stored. False otherwise. -_Success_(return) -bool OutputStateMachineEngine::_GetEraseOperation(_In_reads_(cParams) const unsigned short* const rgusParams, const unsigned short cParams, _Out_ DispatchTypes::EraseType* const pEraseType) const +_Success_(return ) bool OutputStateMachineEngine::_GetEraseOperation(_In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams, + _Out_ DispatchTypes::EraseType* const pEraseType) const { bool fSuccess = false; // If we have too many parameters or don't know what to do with the given value, return false. *pEraseType = s_defaultEraseType; // if we fail, just put the default type in. @@ -866,7 +865,7 @@ bool OutputStateMachineEngine::_GetEraseOperation(_In_reads_(cParams) const unsi case DispatchTypes::EraseType::FromBeginning: case DispatchTypes::EraseType::All: case DispatchTypes::EraseType::Scrollback: - *pEraseType = (DispatchTypes::EraseType) usParam; + *pEraseType = (DispatchTypes::EraseType)usParam; fSuccess = true; break; } @@ -881,8 +880,9 @@ bool OutputStateMachineEngine::_GetEraseOperation(_In_reads_(cParams) const unsi // - puiDistance - Memory location to receive the distance // Return Value: // - True if we successfully pulled the cursor distance from the parameters we've stored. False otherwise. -_Success_(return) -bool OutputStateMachineEngine::_GetCursorDistance(_In_reads_(cParams) const unsigned short* const rgusParams, const unsigned short cParams, _Out_ unsigned int* const puiDistance) const +_Success_(return ) bool OutputStateMachineEngine::_GetCursorDistance(_In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams, + _Out_ unsigned int* const puiDistance) const { bool fSuccess = false; *puiDistance = s_uiDefaultCursorDistance; @@ -914,8 +914,9 @@ bool OutputStateMachineEngine::_GetCursorDistance(_In_reads_(cParams) const unsi // - puiDistance - Memory location to receive the distance // Return Value: // - True if we successfully pulled the scroll distance from the parameters we've stored. False otherwise. -_Success_(return) -bool OutputStateMachineEngine::_GetScrollDistance(_In_reads_(cParams) const unsigned short* const rgusParams, const unsigned short cParams, _Out_ unsigned int* const puiDistance) const +_Success_(return ) bool OutputStateMachineEngine::_GetScrollDistance(_In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams, + _Out_ unsigned int* const puiDistance) const { bool fSuccess = false; *puiDistance = s_uiDefaultScrollDistance; @@ -947,8 +948,9 @@ bool OutputStateMachineEngine::_GetScrollDistance(_In_reads_(cParams) const unsi // - puiConsoleWidth - Memory location to receive the width // Return Value: // - True if we successfully pulled the width from the parameters we've stored. False otherwise. -_Success_(return) -bool OutputStateMachineEngine::_GetConsoleWidth(_In_reads_(cParams) const unsigned short* const rgusParams, const unsigned short cParams, _Out_ unsigned int* const puiConsoleWidth) const +_Success_(return ) bool OutputStateMachineEngine::_GetConsoleWidth(_In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams, + _Out_ unsigned int* const puiConsoleWidth) const { bool fSuccess = false; *puiConsoleWidth = s_uiDefaultConsoleWidth; @@ -981,8 +983,10 @@ bool OutputStateMachineEngine::_GetConsoleWidth(_In_reads_(cParams) const unsign // - puiColumn - Memory location to receive the X/Column position // Return Value: // - True if we successfully pulled the cursor coordinates from the parameters we've stored. False otherwise. -_Success_(return) -bool OutputStateMachineEngine::_GetXYPosition(_In_reads_(cParams) const unsigned short* const rgusParams, const unsigned short cParams, _Out_ unsigned int* const puiLine, _Out_ unsigned int* const puiColumn) const +_Success_(return ) bool OutputStateMachineEngine::_GetXYPosition(_In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams, + _Out_ unsigned int* const puiLine, + _Out_ unsigned int* const puiColumn) const { bool fSuccess = false; *puiLine = s_uiDefaultLine; @@ -1028,8 +1032,10 @@ bool OutputStateMachineEngine::_GetXYPosition(_In_reads_(cParams) const unsigned // - psBottomMargin - Memory location to receive the bottom margin // Return Value: // - True if we successfully pulled the margin settings from the parameters we've stored. False otherwise. -_Success_(return) -bool OutputStateMachineEngine::_GetTopBottomMargins(_In_reads_(cParams) const unsigned short* const rgusParams, const unsigned short cParams, _Out_ SHORT* const psTopMargin, _Out_ SHORT* const psBottomMargin) const +_Success_(return ) bool OutputStateMachineEngine::_GetTopBottomMargins(_In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams, + _Out_ SHORT* const psTopMargin, + _Out_ SHORT* const psBottomMargin) const { // Notes: (input -> state machine out) // having only a top param is legal ([3;r -> 3,0) @@ -1071,8 +1077,9 @@ bool OutputStateMachineEngine::_GetTopBottomMargins(_In_reads_(cParams) const un // - pStatusType - Memory location to receive the Status Type parameter // Return Value: // - True if we successfully found a device operation in the parameters stored. False otherwise. -_Success_(return) -bool OutputStateMachineEngine::_GetDeviceStatusOperation(_In_reads_(cParams) const unsigned short* const rgusParams, const unsigned short cParams, _Out_ DispatchTypes::AnsiStatusType* const pStatusType) const +_Success_(return ) bool OutputStateMachineEngine::_GetDeviceStatusOperation(_In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams, + _Out_ DispatchTypes::AnsiStatusType* const pStatusType) const { bool fSuccess = false; *pStatusType = (DispatchTypes::AnsiStatusType)0; @@ -1102,11 +1109,10 @@ bool OutputStateMachineEngine::_GetDeviceStatusOperation(_In_reads_(cParams) con // - pcParams - Pointer to the length of rPrivateModeParams on the way in, and the count of the array used on the way out. // Return Value: // - True if we successfully retrieved an array of private mode params from the parameters we've stored. False otherwise. -_Success_(return) -bool OutputStateMachineEngine::_GetPrivateModeParams(_In_reads_(cParams) const unsigned short* const rgusParams, - const unsigned short cParams, - _Out_writes_(*pcParams) DispatchTypes::PrivateModeParams* const rgPrivateModeParams, - _Inout_ size_t* const pcParams) const +_Success_(return ) bool OutputStateMachineEngine::_GetPrivateModeParams(_In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams, + _Out_writes_(*pcParams) DispatchTypes::PrivateModeParams* const rgPrivateModeParams, + _Inout_ size_t* const pcParams) const { bool fSuccess = false; // Can't just set nothing at all @@ -1135,8 +1141,7 @@ bool OutputStateMachineEngine::_GetPrivateModeParams(_In_reads_(cParams) const u // - // Return Value: // - True if there were no parameters. False otherwise. -_Success_(return) -bool OutputStateMachineEngine::_VerifyHasNoParameters(const unsigned short cParams) const +_Success_(return ) bool OutputStateMachineEngine::_VerifyHasNoParameters(const unsigned short cParams) const { return cParams == 0; } @@ -1148,8 +1153,8 @@ bool OutputStateMachineEngine::_VerifyHasNoParameters(const unsigned short cPara // - // Return Value: // - True if the DA params were valid. False otherwise. -_Success_(return) -bool OutputStateMachineEngine::_VerifyDeviceAttributesParams(_In_reads_(cParams) const unsigned short* const rgusParams, const unsigned short cParams) const +_Success_(return ) bool OutputStateMachineEngine::_VerifyDeviceAttributesParams(_In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams) const { bool fSuccess = false; @@ -1175,11 +1180,10 @@ bool OutputStateMachineEngine::_VerifyDeviceAttributesParams(_In_reads_(cParams) // - pcchTitle - a pointer place the length of ppwchTitle into. // Return Value: // - True if there was a title to output. (a title with length=0 is still valid) -_Success_(return) -bool OutputStateMachineEngine::_GetOscTitle(_Inout_updates_(cchOscString) wchar_t* const pwchOscStringBuffer, - const unsigned short cchOscString, - _Outptr_result_buffer_(*pcchTitle) wchar_t** const ppwchTitle, - _Out_ unsigned short * pcchTitle) const +_Success_(return ) bool OutputStateMachineEngine::_GetOscTitle(_Inout_updates_(cchOscString) wchar_t* const pwchOscStringBuffer, + const unsigned short cchOscString, + _Outptr_result_buffer_(*pcchTitle) wchar_t** const ppwchTitle, + _Out_ unsigned short* pcchTitle) const { *ppwchTitle = pwchOscStringBuffer; *pcchTitle = cchOscString; @@ -1193,8 +1197,9 @@ bool OutputStateMachineEngine::_GetOscTitle(_Inout_updates_(cchOscString) wchar_ // - psDistance - Memory location to receive the distance // Return Value: // - True if we successfully pulled the tab distance from the parameters we've stored. False otherwise. -_Success_(return) -bool OutputStateMachineEngine::_GetTabDistance(_In_reads_(cParams) const unsigned short* const rgusParams, const unsigned short cParams, _Out_ SHORT* const psDistance) const +_Success_(return ) bool OutputStateMachineEngine::_GetTabDistance(_In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams, + _Out_ SHORT* const psDistance) const { bool fSuccess = false; *psDistance = s_sDefaultTabDistance; @@ -1226,8 +1231,9 @@ bool OutputStateMachineEngine::_GetTabDistance(_In_reads_(cParams) const unsigne // - psClearType - Memory location to receive the clear type // Return Value: // - True if we successfully pulled the tab clear type from the parameters we've stored. False otherwise. -_Success_(return) -bool OutputStateMachineEngine::_GetTabClearType(_In_reads_(cParams) const unsigned short* const rgusParams, const unsigned short cParams, _Out_ SHORT* const psClearType) const +_Success_(return ) bool OutputStateMachineEngine::_GetTabClearType(_In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams, + _Out_ SHORT* const psClearType) const { bool fSuccess = false; *psClearType = s_sDefaultTabClearType; @@ -1252,13 +1258,13 @@ bool OutputStateMachineEngine::_GetTabClearType(_In_reads_(cParams) const unsign // - pDesignateType - Memory location to receive the designate type. // Return Value: // - True if we successfully pulled the designate type from the intermediate we've stored. False otherwise. -_Success_(return) -bool OutputStateMachineEngine::_GetDesignateType(const wchar_t wchIntermediate, _Out_ DesignateCharsetTypes* const pDesignateType) const +_Success_(return ) bool OutputStateMachineEngine::_GetDesignateType(const wchar_t wchIntermediate, + _Out_ DesignateCharsetTypes* const pDesignateType) const { bool fSuccess = false; *pDesignateType = s_DefaultDesignateCharsetType; - switch(wchIntermediate) + switch (wchIntermediate) { case '(': *pDesignateType = DesignateCharsetTypes::G0; @@ -1319,7 +1325,7 @@ bool OutputStateMachineEngine::DispatchControlCharsFromEscape() const // Return Value: // - true iff the character is a hex character. bool OutputStateMachineEngine::s_HexToUint(const wchar_t wch, - _Out_ unsigned int * const puiValue) + _Out_ unsigned int* const puiValue) { *puiValue = 0; bool fSuccess = false; @@ -1385,7 +1391,7 @@ bool OutputStateMachineEngine::s_ParseColorSpec(_In_reads_(cchBuffer) const wcha const wchar_t* const pwchEnd = pwchBuffer + cchBuffer; bool foundRGB = false; bool foundValidColorSpec = false; - unsigned int rguiColorValues[3] = {0}; + unsigned int rguiColorValues[3] = { 0 }; bool fSuccess = false; // We can have anywhere between [11,15] characters // 9 "rgb:h/h/h" @@ -1404,7 +1410,7 @@ bool OutputStateMachineEngine::s_ParseColorSpec(_In_reads_(cchBuffer) const wcha if ((pwchCurr[0] == L'r') && (pwchCurr[1] == L'g') && (pwchCurr[2] == L'b') && - (pwchCurr[3] == L':') ) + (pwchCurr[3] == L':')) { foundRGB = true; } @@ -1419,7 +1425,6 @@ bool OutputStateMachineEngine::s_ParseColorSpec(_In_reads_(cchBuffer) const wcha unsigned int* const pValue = &(rguiColorValues[component]); for (size_t i = 0; i < 3; i++) { - const wchar_t wch = *pwchCurr; pwchCurr++; @@ -1555,7 +1560,6 @@ bool OutputStateMachineEngine::_GetOscSetColorTable(_In_reads_(cchOscString) con } } - return fSuccess; } @@ -1571,8 +1575,8 @@ bool OutputStateMachineEngine::_GetOscSetColorTable(_In_reads_(cchOscString) con // Return Value: // - True if a table index and color was parsed successfully. False otherwise. bool OutputStateMachineEngine::_GetOscSetColor(_In_reads_(cchOscString) const wchar_t* const pwchOscStringBuffer, - const size_t cchOscString, - _Out_ DWORD* const pRgb) const + const size_t cchOscString, + _Out_ DWORD* const pRgb) const { *pRgb = 0; const wchar_t* pwchCurr = pwchOscStringBuffer; @@ -1611,36 +1615,34 @@ bool OutputStateMachineEngine::_GetWindowManipulationType(_In_reads_(cParams) co if (cParams > 0) { - switch(rgusParams[0]) + switch (rgusParams[0]) { - case DispatchTypes::WindowManipulationType::RefreshWindow: - *puiFunction = DispatchTypes::WindowManipulationType::RefreshWindow; - fSuccess = true; - break; - case DispatchTypes::WindowManipulationType::ResizeWindowInCharacters: - *puiFunction = DispatchTypes::WindowManipulationType::ResizeWindowInCharacters; - fSuccess = true; - break; - default: - fSuccess = false; - break; + case DispatchTypes::WindowManipulationType::RefreshWindow: + *puiFunction = DispatchTypes::WindowManipulationType::RefreshWindow; + fSuccess = true; + break; + case DispatchTypes::WindowManipulationType::ResizeWindowInCharacters: + *puiFunction = DispatchTypes::WindowManipulationType::ResizeWindowInCharacters; + fSuccess = true; + break; + default: + fSuccess = false; + break; } } return fSuccess; } - // Routine Description: // - Retrieves a distance for a scroll operation from the parameter pool stored during Param actions. // Arguments: // - puiDistance - Memory location to receive the distance // Return Value: // - True if we successfully pulled the scroll distance from the parameters we've stored. False otherwise. -_Success_(return) -bool OutputStateMachineEngine::_GetCursorStyle(_In_reads_(cParams) const unsigned short* const rgusParams, - const unsigned short cParams, - _Out_ DispatchTypes::CursorStyle* const pCursorStyle) const +_Success_(return ) bool OutputStateMachineEngine::_GetCursorStyle(_In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams, + _Out_ DispatchTypes::CursorStyle* const pCursorStyle) const { bool fSuccess = false; *pCursorStyle = s_defaultCursorStyle; @@ -1680,7 +1682,6 @@ void OutputStateMachineEngine::SetTerminalConnection(ITerminalOutputConnection* this->_pfnFlushToTerminal = pfnFlushToTerminal; } - // Routine Description: // - Retrieves a number of times to repeat the last graphical character // Arguments: @@ -1688,10 +1689,9 @@ void OutputStateMachineEngine::SetTerminalConnection(ITerminalOutputConnection* // Return Value: // - True if we successfully pulled the repeat count from the parameters. // False otherwise. -_Success_(return) -bool OutputStateMachineEngine::_GetRepeatCount(_In_reads_(cParams) const unsigned short* const rgusParams, - const unsigned short cParams, - _Out_ unsigned int* const puiRepeatCount) const noexcept +_Success_(return ) bool OutputStateMachineEngine::_GetRepeatCount(_In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams, + _Out_ unsigned int* const puiRepeatCount) const noexcept { bool fSuccess = false; *puiRepeatCount = s_uiDefaultRepeatCount; diff --git a/src/terminal/parser/OutputStateMachineEngine.hpp b/src/terminal/parser/OutputStateMachineEngine.hpp index 11ad0d8bf..5ef8de6be 100644 --- a/src/terminal/parser/OutputStateMachineEngine.hpp +++ b/src/terminal/parser/OutputStateMachineEngine.hpp @@ -150,101 +150,85 @@ namespace Microsoft::Console::VirtualTerminal }; static const DispatchTypes::GraphicsOptions s_defaultGraphicsOption = DispatchTypes::GraphicsOptions::Off; - _Success_(return) - bool _GetGraphicsOptions(_In_reads_(cParams) const unsigned short* const rgusParams, - const unsigned short cParams, - _Out_writes_(*pcOptions) DispatchTypes::GraphicsOptions* const rgGraphicsOptions, - _Inout_ size_t* const pcOptions) const; + _Success_(return ) bool _GetGraphicsOptions(_In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams, + _Out_writes_(*pcOptions) DispatchTypes::GraphicsOptions* const rgGraphicsOptions, + _Inout_ size_t* const pcOptions) const; static const DispatchTypes::EraseType s_defaultEraseType = DispatchTypes::EraseType::ToEnd; - _Success_(return) - bool _GetEraseOperation(_In_reads_(cParams) const unsigned short* const rgusParams, - const unsigned short cParams, - _Out_ DispatchTypes::EraseType* const pEraseType) const; + _Success_(return ) bool _GetEraseOperation(_In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams, + _Out_ DispatchTypes::EraseType* const pEraseType) const; static const unsigned int s_uiDefaultCursorDistance = 1; - _Success_(return) - bool _GetCursorDistance(_In_reads_(cParams) const unsigned short* const rgusParams, - const unsigned short cParams, - _Out_ unsigned int* const puiDistance) const; + _Success_(return ) bool _GetCursorDistance(_In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams, + _Out_ unsigned int* const puiDistance) const; static const unsigned int s_uiDefaultScrollDistance = 1; - _Success_(return) - bool _GetScrollDistance(_In_reads_(cParams) const unsigned short* const rgusParams, - const unsigned short cParams, - _Out_ unsigned int* const puiDistance) const; + _Success_(return ) bool _GetScrollDistance(_In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams, + _Out_ unsigned int* const puiDistance) const; static const unsigned int s_uiDefaultConsoleWidth = 80; - _Success_(return) - bool _GetConsoleWidth(_In_reads_(cParams) const unsigned short* const rgusParams, - const unsigned short cParams, - _Out_ unsigned int* const puiConsoleWidth) const; + _Success_(return ) bool _GetConsoleWidth(_In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams, + _Out_ unsigned int* const puiConsoleWidth) const; static const unsigned int s_uiDefaultLine = 1; static const unsigned int s_uiDefaultColumn = 1; - _Success_(return) - bool _GetXYPosition(_In_reads_(cParams) const unsigned short* const rgusParams, - const unsigned short cParams, - _Out_ unsigned int* const puiLine, - _Out_ unsigned int* const puiColumn) const; + _Success_(return ) bool _GetXYPosition(_In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams, + _Out_ unsigned int* const puiLine, + _Out_ unsigned int* const puiColumn) const; - _Success_(return) - bool _GetDeviceStatusOperation(_In_reads_(cParams) const unsigned short* const rgusParams, - const unsigned short cParams, - _Out_ DispatchTypes::AnsiStatusType* const pStatusType) const; + _Success_(return ) bool _GetDeviceStatusOperation(_In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams, + _Out_ DispatchTypes::AnsiStatusType* const pStatusType) const; - _Success_(return) - bool _VerifyHasNoParameters(const unsigned short cParams) const; + _Success_(return ) bool _VerifyHasNoParameters(const unsigned short cParams) const; - _Success_(return) - bool _VerifyDeviceAttributesParams(_In_reads_(cParams) const unsigned short* const rgusParams, - const unsigned short cParams) const; + _Success_(return ) bool _VerifyDeviceAttributesParams(_In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams) const; - _Success_(return) - bool _GetPrivateModeParams(_In_reads_(cParams) const unsigned short* const rgusParams, - const unsigned short cParams, - _Out_writes_(*pcParams) DispatchTypes::PrivateModeParams* const rgPrivateModeParams, - _Inout_ size_t* const pcParams) const; + _Success_(return ) bool _GetPrivateModeParams(_In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams, + _Out_writes_(*pcParams) DispatchTypes::PrivateModeParams* const rgPrivateModeParams, + _Inout_ size_t* const pcParams) const; static const SHORT s_sDefaultTopMargin = 0; static const SHORT s_sDefaultBottomMargin = 0; - _Success_(return) - bool _GetTopBottomMargins(_In_reads_(cParams) const unsigned short* const rgusParams, - const unsigned short cParams, - _Out_ SHORT* const psTopMargin, - _Out_ SHORT* const psBottomMargin) const; + _Success_(return ) bool _GetTopBottomMargins(_In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams, + _Out_ SHORT* const psTopMargin, + _Out_ SHORT* const psBottomMargin) const; - _Success_(return) - bool _GetOscTitle(_Inout_updates_(cchOscString) wchar_t* const pwchOscStringBuffer, - const unsigned short cchOscString, - _Outptr_result_buffer_(*pcchTitle) wchar_t** const ppwchTitle, - _Out_ unsigned short * pcchTitle) const; + _Success_(return ) bool _GetOscTitle(_Inout_updates_(cchOscString) wchar_t* const pwchOscStringBuffer, + const unsigned short cchOscString, + _Outptr_result_buffer_(*pcchTitle) wchar_t** const ppwchTitle, + _Out_ unsigned short* pcchTitle) const; static const SHORT s_sDefaultTabDistance = 1; - _Success_(return) - bool _GetTabDistance(_In_reads_(cParams) const unsigned short* const rgusParams, - const unsigned short cParams, - _Out_ SHORT* const psDistance) const; + _Success_(return ) bool _GetTabDistance(_In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams, + _Out_ SHORT* const psDistance) const; static const SHORT s_sDefaultTabClearType = 0; - _Success_(return) - bool _GetTabClearType(_In_reads_(cParams) const unsigned short* const rgusParams, - const unsigned short cParams, - _Out_ SHORT* const psClearType) const; + _Success_(return ) bool _GetTabClearType(_In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams, + _Out_ SHORT* const psClearType) const; static const DesignateCharsetTypes s_DefaultDesignateCharsetType = DesignateCharsetTypes::G0; - _Success_(return) - bool _GetDesignateType(const wchar_t wchIntermediate, - _Out_ DesignateCharsetTypes* const pDesignateType) const; + _Success_(return ) bool _GetDesignateType(const wchar_t wchIntermediate, + _Out_ DesignateCharsetTypes* const pDesignateType) const; static const DispatchTypes::WindowManipulationType s_DefaultWindowManipulationType = DispatchTypes::WindowManipulationType::Invalid; - _Success_(return) - bool _GetWindowManipulationType(_In_reads_(cParams) const unsigned short* const rgusParams, - const unsigned short cParams, - _Out_ unsigned int* const puiFunction) const; + _Success_(return ) bool _GetWindowManipulationType(_In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams, + _Out_ unsigned int* const puiFunction) const; static bool s_HexToUint(const wchar_t wch, - _Out_ unsigned int * const puiValue); + _Out_ unsigned int* const puiValue); static bool s_IsNumber(const wchar_t wch); static bool s_IsHexNumber(const wchar_t wch); bool _GetOscSetColorTable(_In_reads_(cchOscString) const wchar_t* const pwchOscStringBuffer, @@ -261,18 +245,15 @@ namespace Microsoft::Console::VirtualTerminal _Out_ DWORD* const pRgb) const; static const DispatchTypes::CursorStyle s_defaultCursorStyle = DispatchTypes::CursorStyle::BlinkingBlockDefault; - _Success_(return) - bool _GetCursorStyle(_In_reads_(cParams) const unsigned short* const rgusParams, - const unsigned short cParams, - _Out_ DispatchTypes::CursorStyle* const pCursorStyle) const; + _Success_(return ) bool _GetCursorStyle(_In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams, + _Out_ DispatchTypes::CursorStyle* const pCursorStyle) const; static const unsigned int s_uiDefaultRepeatCount = 1; - _Success_(return) - bool _GetRepeatCount(_In_reads_(cParams) const unsigned short* const rgusParams, - const unsigned short cParams, - _Out_ unsigned int* const puiRepeatCount) const noexcept; + _Success_(return ) bool _GetRepeatCount(_In_reads_(cParams) const unsigned short* const rgusParams, + const unsigned short cParams, + _Out_ unsigned int* const puiRepeatCount) const noexcept; void _ClearLastChar() noexcept; - }; } diff --git a/src/terminal/parser/ft_fuzzer/VTCommandFuzzer.cpp b/src/terminal/parser/ft_fuzzer/VTCommandFuzzer.cpp index 589a6c75b..9d5fc1527 100644 --- a/src/terminal/parser/ft_fuzzer/VTCommandFuzzer.cpp +++ b/src/terminal/parser/ft_fuzzer/VTCommandFuzzer.cpp @@ -11,16 +11,16 @@ using namespace fuzz; // VT100 spec defines the ESC sequence as the char 0x1b -const CHAR ESC[2] { 0x1b, 0x0 }; +const CHAR ESC[2]{ 0x1b, 0x0 }; // VT100 spec defines the CSI sequence as ESC followed by [ -const CHAR CSI[3] { 0x1b, 0x5b, 0x0 }; +const CHAR CSI[3]{ 0x1b, 0x5b, 0x0 }; // There is an alternative, single-character CSI in the C1 control set: -const CHAR C1CSI[2] { static_cast(static_cast(0x9b)), 0x0 }; +const CHAR C1CSI[2]{ static_cast(static_cast(0x9b)), 0x0 }; // VT100 spec defines the OSC sequence as ESC followed by ] -const CHAR OSC[3] { 0x1b, 0x5d, 0x0 }; +const CHAR OSC[3]{ 0x1b, 0x5d, 0x0 }; static std::string GenerateSGRToken(); static std::string GenerateCUXToken(); @@ -39,15 +39,13 @@ static std::string GenerateHardResetToken(); static std::string GenerateSoftResetToken(); static std::string GenerateOscColorTableToken(); -const fuzz::_fuzz_type_entry g_repeatMap[] = -{ +const fuzz::_fuzz_type_entry g_repeatMap[] = { { 4, [](BYTE) { return CFuzzChance::GetRandom(2, 0xF); } }, { 1, [](BYTE) { return CFuzzChance::GetRandom(2, 0xFF); } }, { 20, [](BYTE) { return (BYTE)0; } } }; -const std::function g_tokenGenerators[] = -{ +const std::function g_tokenGenerators[] = { GenerateSGRToken, GenerateCUXToken, GenerateCUXToken2, @@ -65,8 +63,7 @@ const std::function g_tokenGenerators[] = std::string GenerateTokenLowProbability() { - const _fuzz_type_entry tokenGeneratorMap[] = - { + const _fuzz_type_entry tokenGeneratorMap[] = { { 3, [&](std::string) { return CFuzzChance::SelectOne(g_tokenGenerators, ARRAYSIZE(g_tokenGenerators))(); } }, { 1, [](std::string) { return GenerateInvalidToken(); } }, { 1, [](std::string) { return GenerateTextToken(); } }, @@ -79,8 +76,7 @@ std::string GenerateTokenLowProbability() std::string GenerateToken() { - const _fuzz_type_entry tokenGeneratorMap[] = - { + const _fuzz_type_entry tokenGeneratorMap[] = { { 50, [](std::string) { return GenerateTextToken(); } }, { 40, [&](std::string) { return CFuzzChance::SelectOne(g_tokenGenerators, ARRAYSIZE(g_tokenGenerators))(); } }, { 1, [](std::string) { return GenerateInvalidToken(); } }, @@ -93,8 +89,7 @@ std::string GenerateToken() std::string GenerateWhiteSpaceToken() { - const _fuzz_type_entry ftMap[] = - { + const _fuzz_type_entry ftMap[] = { { 5, [](DWORD) { return CFuzzChance::GetRandom(0, 0xF); } }, { 5, [](DWORD) { return CFuzzChance::GetRandom(0, 0xFF); } } }; @@ -111,8 +106,7 @@ std::string GenerateWhiteSpaceToken() std::string GenerateTextToken() { - const LPSTR tokens[] = - { + const LPSTR tokens[] = { "The cow jumped over the moon.", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?", @@ -134,14 +128,14 @@ std::string GenerateTextToken() std::string GenerateInvalidToken() { - const LPSTR tokens[] { ":", "'", "\"", "\\" }; + const LPSTR tokens[]{ ":", "'", "\"", "\\" }; return std::string(CFuzzChance::SelectOne(tokens, ARRAYSIZE(tokens))); } std::string GenerateFuzzedToken( - __in_ecount(cmap) const _fuzz_type_entry *map, + __in_ecount(cmap) const _fuzz_type_entry* map, __in DWORD cmap, - __in_ecount(ctokens) const LPSTR *tokens, + __in_ecount(ctokens) const LPSTR* tokens, __in DWORD ctokens) { std::string csis[] = { CSI, C1CSI }; @@ -163,9 +157,9 @@ std::string GenerateFuzzedToken( } std::string GenerateFuzzedOscToken( - __in_ecount(cmap) const _fuzz_type_entry *map, + __in_ecount(cmap) const _fuzz_type_entry* map, __in DWORD cmap, - __in_ecount(ctokens) const LPSTR *tokens, + __in_ecount(ctokens) const LPSTR* tokens, __in DWORD ctokens) { std::string s(OSC); @@ -188,17 +182,47 @@ std::string GenerateFuzzedOscToken( // For instance, 37;1;44m will do foreground white (low intensity, so effectively a gray) then set high intensity blue background. std::string GenerateSGRToken() { - const BYTE psValid[] = - { - 0, 1, 2, 3, 4, 5, 6, 7, - 8, 9, 10, 11, 12, 13, 14, 15, 24, 27, - 30, 31, 32, 33, 34, 35, 36, 37, 39, - 40, 41, 42, 43, 44, 45, 46, 47, 49, + const BYTE psValid[] = { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 24, + 27, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 49, }; const LPSTR tokens[] = { "m" }; - const _fuzz_type_entry map[] = - { + const _fuzz_type_entry map[] = { { 40, [&](std::string) { std::string s; AppendFormat(s, "%02d", CFuzzChance::SelectOne(psValid, ARRAYSIZE(psValid))); return s; } }, { 10, [](std::string) { std::string s; AppendFormat(s, "%d", CFuzzChance::GetRandom()); return s; } }, { 25, [](std::string) { return std::string("35;5"); } }, @@ -213,8 +237,7 @@ std::string GenerateSGRToken() std::string GenerateCUXToken() { const LPSTR tokens[] = { "A", "B", "C", "D", "E", "F", "G" }; - const _fuzz_type_entry map[] = - { + const _fuzz_type_entry map[] = { { 25, [](std::string) { std::string s; AppendFormat(s, "%d", CFuzzChance::GetRandom()); return s; } }, { 25, [](std::string) { std::string s; AppendFormat(s, "%d", CFuzzChance::GetRandom()); return s; } } }; @@ -238,12 +261,11 @@ std::string GenerateCUXToken2() std::string GenerateCUXToken3() { const LPSTR tokens[]{ "H" }; - const _fuzz_type_entry map[] = - { - {60, [](std::string) { std::string s; AppendFormat(s, "%d;%d", CFuzzChance::GetRandom(), CFuzzChance::GetRandom()); return s; } }, // 60% give us two numbers in the valid range - {10, [](std::string) { return std::string(";"); } }, // 10% give us just a ; - {10, [](std::string) { std::string s; AppendFormat(s, "%d;", CFuzzChance::GetRandom()); return s; } }, // 10% give us a column and no line - {10, [](std::string) { std::string s; AppendFormat(s, ";%d", CFuzzChance::GetRandom()); return s; } }, // 10% give us a line and no column + const _fuzz_type_entry map[] = { + { 60, [](std::string) { std::string s; AppendFormat(s, "%d;%d", CFuzzChance::GetRandom(), CFuzzChance::GetRandom()); return s; } }, // 60% give us two numbers in the valid range + { 10, [](std::string) { return std::string(";"); } }, // 10% give us just a ; + { 10, [](std::string) { std::string s; AppendFormat(s, "%d;", CFuzzChance::GetRandom()); return s; } }, // 10% give us a column and no line + { 10, [](std::string) { std::string s; AppendFormat(s, ";%d", CFuzzChance::GetRandom()); return s; } }, // 10% give us a line and no column // 10% give us nothing }; @@ -277,8 +299,7 @@ std::string GenerateSoftResetToken() std::string GeneratePrivateModeParamToken() { const LPSTR tokens[] = { "h", "l" }; - const _fuzz_type_entry map[] = - { + const _fuzz_type_entry map[] = { { 12, [](std::string) { std::string s; AppendFormat(s, "?%02d", CFuzzChance::GetRandom()); return s; } }, { 8, [](std::string) { return std::string("?1"); } }, { 8, [](std::string) { return std::string("?3"); } }, @@ -300,8 +321,7 @@ std::string GeneratePrivateModeParamToken() std::string GenerateEraseToken() { const LPSTR tokens[] = { "J", "K" }; - const _fuzz_type_entry map[] = - { + const _fuzz_type_entry map[] = { { 9, [](std::string) { return std::string(""); } }, { 25, [](std::string) { return std::string("0"); } }, { 25, [](std::string) { return std::string("1"); } }, @@ -317,8 +337,7 @@ std::string GenerateEraseToken() std::string GenerateDeviceAttributesToken() { const LPSTR tokens[] = { "c" }; - const _fuzz_type_entry map[] = - { + const _fuzz_type_entry map[] = { { 70, [](std::string) { return std::string(""); } }, // 70% leave it blank (valid) { 29, [](std::string) { return std::string("0"); } }, // 29% put in a 0 (valid) { 1, [](std::string) { std::string s; AppendFormat(s, "%02d", CFuzzChance::GetRandom()); return s; } } // 1% make a mess (anything else) @@ -331,8 +350,7 @@ std::string GenerateDeviceAttributesToken() std::string GenerateDeviceStatusReportToken() { const LPSTR tokens[] = { "n" }; - const _fuzz_type_entry map[] = - { + const _fuzz_type_entry map[] = { { 50, [](std::string) { return std::string("6"); } }, // 50% of the time, give us the one we were looking for (6, cursor report) { 49, [](std::string) { std::string s; AppendFormat(s, "%02d", CFuzzChance::GetRandom()); return s; } } // 49% of the time, put in a random value // 1% leave it blank @@ -345,8 +363,7 @@ std::string GenerateDeviceStatusReportToken() std::string GenerateScrollToken() { const LPSTR tokens[] = { "S", "T" }; - const _fuzz_type_entry map[] = - { + const _fuzz_type_entry map[] = { { 5, [](std::string) { std::string s; AppendFormat(s, "%08d", CFuzzChance::GetRandom()); return s; } }, { 5, [](std::string) { std::string s; AppendFormat(s, "%08d", CFuzzChance::GetRandom()); return s; } }, { 50, [](std::string) { std::string s; AppendFormat(s, "%d", CFuzzChance::GetRandom(0, 0x4000)); return s; } }, @@ -366,8 +383,7 @@ std::string GenerateResizeToken() // 45% - generate a resize with two params // 10% - generate a resize with only the first param // 10% - generate a resize with only the second param - const _fuzz_type_entry map[] = - { + const _fuzz_type_entry map[] = { { 5, [](std::string) { std::string s; AppendFormat(s, "%d;%d;%d", CFuzzChance::GetRandom(0, 0x4000), CFuzzChance::GetRandom(0, 0x4000), CFuzzChance::GetRandom(0, 0x4000)); return s; } }, { 5, [](std::string) { std::string s; AppendFormat(s, "%d;%d", CFuzzChance::GetRandom(0, 0x4000), CFuzzChance::GetRandom(0, 0x4000)); return s; } }, { 5, [](std::string) { std::string s; AppendFormat(s, "%d", CFuzzChance::GetRandom(0, 0x4000)); return s; } }, @@ -384,28 +400,25 @@ std::string GenerateResizeToken() std::string GenerateOscTitleToken() { const LPSTR tokens[] = { "\x7" }; - const _fuzz_type_entry map[] = - { - { - 100, - [](std::string) { - std::string s; - SHORT limit = CFuzzChance::GetRandom(0, 10); - // append up to 10 numbers for the param - for(SHORT i = 0; i < limit; i++) - { - AppendFormat(s, "%d", CFuzzChance::GetRandom(0, 9)); - } - s.append(";"); - // append some characters for the string - limit = CFuzzChance::GetRandom(); - for(SHORT i = 0; i < limit; i++) - { - AppendFormat(s, "%c", CFuzzChance::GetRandom()); - } - return s; - } - } + const _fuzz_type_entry map[] = { + { 100, + [](std::string) { + std::string s; + SHORT limit = CFuzzChance::GetRandom(0, 10); + // append up to 10 numbers for the param + for (SHORT i = 0; i < limit; i++) + { + AppendFormat(s, "%d", CFuzzChance::GetRandom(0, 9)); + } + s.append(";"); + // append some characters for the string + limit = CFuzzChance::GetRandom(); + for (SHORT i = 0; i < limit; i++) + { + AppendFormat(s, "%c", CFuzzChance::GetRandom()); + } + return s; + } } }; return GenerateFuzzedOscToken(FUZZ_MAP(map), tokens, ARRAYSIZE(tokens)); @@ -416,82 +429,77 @@ std::string GenerateOscTitleToken() std::string GenerateOscColorTableToken() { const LPSTR tokens[] = { "\x7", "\x1b\\" }; - const _fuzz_type_entry map[] = - { - { - 100, - [](std::string) { - std::string s; - SHORT limit = CFuzzChance::GetRandom(0, 10); - // append up to 10 numbers for the param - for(SHORT i = 0; i < limit; i++) - { - AppendFormat(s, "%d", CFuzzChance::GetRandom(0, 9)); - } - s.append(";"); + const _fuzz_type_entry map[] = { + { 100, + [](std::string) { + std::string s; + SHORT limit = CFuzzChance::GetRandom(0, 10); + // append up to 10 numbers for the param + for (SHORT i = 0; i < limit; i++) + { + AppendFormat(s, "%d", CFuzzChance::GetRandom(0, 9)); + } + s.append(";"); - // Append some random numbers for the index - limit = CFuzzChance::GetRandom(0, 10); - // append up to 10 numbers for the param - for(SHORT i = 0; i < limit; i++) - { - AppendFormat(s, "%d", CFuzzChance::GetRandom(0, 9)); - } - // Maybe add more text - if (CFuzzChance::GetRandom()) - { - // usually add a RGB - limit = CFuzzChance::GetRandom(0, 10); - switch(limit) - { - case 0: - case 1: - case 2: - case 3: - case 4: - case 5: - case 6: - s.append("rgb:"); - break; - case 7: - s.append("rgbi:"); - break; - case 8: - s.append("cmyk:"); - break; - default: - // append some characters for the string - limit = CFuzzChance::GetRandom(); - for(SHORT i = 0; i < limit; i++) - { - AppendFormat(s, "%c", CFuzzChance::GetRandom()); - } - } + // Append some random numbers for the index + limit = CFuzzChance::GetRandom(0, 10); + // append up to 10 numbers for the param + for (SHORT i = 0; i < limit; i++) + { + AppendFormat(s, "%d", CFuzzChance::GetRandom(0, 9)); + } + // Maybe add more text + if (CFuzzChance::GetRandom()) + { + // usually add a RGB + limit = CFuzzChance::GetRandom(0, 10); + switch (limit) + { + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + s.append("rgb:"); + break; + case 7: + s.append("rgbi:"); + break; + case 8: + s.append("cmyk:"); + break; + default: + // append some characters for the string + limit = CFuzzChance::GetRandom(); + for (SHORT i = 0; i < limit; i++) + { + AppendFormat(s, "%c", CFuzzChance::GetRandom()); + } + } + SHORT numColors = CFuzzChance::GetRandom(0, 5); - SHORT numColors = CFuzzChance::GetRandom(0, 5); - - // append up to 10 numbers for the param - for(SHORT i = 0; i < numColors; i++) - { - // Append some random numbers for the value - limit = CFuzzChance::GetRandom(0, 10); - // append up to 10 numbers for the param - for(SHORT j = 0; j < limit; j++) - { - AppendFormat(s, "%d", CFuzzChance::GetRandom(0, 9)); - } - // Sometimes don't add a '/' - if (CFuzzChance::GetRandom(0, 10) != 0) - { - s.append("/"); - } - } - - } - return s; - } - } + // append up to 10 numbers for the param + for (SHORT i = 0; i < numColors; i++) + { + // Append some random numbers for the value + limit = CFuzzChance::GetRandom(0, 10); + // append up to 10 numbers for the param + for (SHORT j = 0; j < limit; j++) + { + AppendFormat(s, "%d", CFuzzChance::GetRandom(0, 9)); + } + // Sometimes don't add a '/' + if (CFuzzChance::GetRandom(0, 10) != 0) + { + s.append("/"); + } + } + } + return s; + } } }; return GenerateFuzzedOscToken(FUZZ_MAP(map), tokens, ARRAYSIZE(tokens)); diff --git a/src/terminal/parser/ft_fuzzer/fuzzing_directed.h b/src/terminal/parser/ft_fuzzer/fuzzing_directed.h index 135219fab..5e816fbbd 100644 --- a/src/terminal/parser/ft_fuzzer/fuzzing_directed.h +++ b/src/terminal/parser/ft_fuzzer/fuzzing_directed.h @@ -15,7 +15,7 @@ #include #pragma warning(push) -#pragma warning(disable:4242) // Standard random library contains C4242 warning about conversion from unsigned int to unsigned short. +#pragma warning(disable : 4242) // Standard random library contains C4242 warning about conversion from unsigned int to unsigned short. #include #pragma warning(pop) @@ -24,7 +24,7 @@ #include #include -#pragma warning(disable:4505) +#pragma warning(disable : 4505) #include "memallocator.h" #ifndef __FUZZING_ALLOCATOR @@ -33,19 +33,25 @@ namespace variadic { - template - struct index {}; + template + struct index + { + }; - template - struct gen_seq : gen_seq {}; + template + struct gen_seq : gen_seq + { + }; - template - struct gen_seq<0, Is...> : index{}; + template + struct gen_seq<0, Is...> : index + { + }; } namespace fuzz { - // Fuzz traits change inherent behavior of the CFuzzType class + // Fuzz traits change inherent behavior of the CFuzzType class // (and associated derived classes). This is a bit-flag such that // multiple traits can be applied as needed. enum _FuzzTraits : unsigned int @@ -66,9 +72,9 @@ namespace fuzz // buffer and our fuzz classes frees the other buffer. // Example: // DWORD cbSize = 0; - // __untrusted_array_size(BYTE, DWORD) cbSizeUntrusted = + // __untrusted_array_size(BYTE, DWORD) cbSizeUntrusted = // __untrusted_array_size_init(BYTE, DWORD)(cbSize); - // __untrusted_array(BYTE, DWORD) arr = + // __untrusted_array(BYTE, DWORD) arr = // __untrusted_array_init(FUZZ_MAP(...), nullptr, cbSizeUntrusted); // AllocateArray(&arr, &cbSizeUntrusted); // arr overloads & operator to // // allow allocation and then wraps @@ -81,7 +87,7 @@ namespace fuzz // Given the design of the CFuzzArray class, it could be unclear // if the corresponding size of the array is the number of elements // or the overall byte count. The class defaults to assuming - // the number of elements, but the trait below can be used to + // the number of elements, but the trait below can be used to // inform the class that the size is actually the number of total // bytes. Note that when using byte arrays, there is no difference // in behavior. @@ -106,15 +112,15 @@ namespace fuzz }; // Fuzz type entries provide a fuzzing function, specified as pfnFuzz, - // together with a percentage that this fuzzing function should be + // together with a percentage that this fuzzing function should be // invoked. The percentage, uiPercentage, should be between 1-100. - // There are some fuzzing classes (i.e. CFuzzString) that allow - // for fuzzed values to be reallocated, in these cases a function - // must be specified via pfnDealloc that can free the resulting - // memory appropriately. If no memory is being reallocated, pfnDealloc + // There are some fuzzing classes (i.e. CFuzzString) that allow + // for fuzzed values to be reallocated, in these cases a function + // must be specified via pfnDealloc that can free the resulting + // memory appropriately. If no memory is being reallocated, pfnDealloc // can be nullptr. // - // An array of fuzz type entries (or fuzz array entries) is referred + // An array of fuzz type entries (or fuzz array entries) is referred // to as a fuzz map in subsequent documentation. // // The design of pfnFuzz is to allow for mutational based fuzzing @@ -122,15 +128,15 @@ namespace fuzz // via the function parameter. This data will be whatever the // fuzzing class' value is, either from initialization of the class // or by setting the value directly. - // For example: - // __untrusted_lpwstr pwsz = + // For example: + // __untrusted_lpwstr pwsz = // __untrusted_lpwstr_init(FUZZ_MAP(...), L"foo"); // LPWSTR pwszFuzzed = pwsz; // Asking for the LPWSTR member will - // // cause the fuzzing map to be + // // cause the fuzzing map to be // // evaluated, if a fuzz type entry is // // selected, L"foo" will be passed // // as the parameter to pfnFuzz - template + template struct _fuzz_type_entry { unsigned int uiPercentage; @@ -142,7 +148,7 @@ namespace fuzz // specified within the fuzz type entry struct into its associated // probability range. It is not expected that users of this codebase // will need to use this struct type directly. - template + template struct _range_fuzz_type_entry { _fuzz_type_entry<_Type, _Args...> fte; @@ -155,12 +161,12 @@ namespace fuzz // in sync. To support this, fuzz array entries have two template // parameters, the first one is the type of objects in the array, // and the second parameter is the size, either in bytes or in element - // count. When designing a fuzz map for an array, you will need to + // count. When designing a fuzz map for an array, you will need to // determine whether _Type2 is the byte count or the element count. // - // With respect to pfnFuzz, once again this follows a mutational + // With respect to pfnFuzz, once again this follows a mutational // based approach, where the parameters will be whatever CFuzzArray - // is initialized to. Notice that the second parameter is an + // is initialized to. Notice that the second parameter is an // automatic reference to the size, which allows this value to be // updated in the event that a new fuzzed buffer is allocation and // returned from pfnFuzz. If reallocation occurs, pfnDealloc must @@ -169,9 +175,9 @@ namespace fuzz // DWORD cbSize = 0; // __untrusted_array_size(BYTE, DWORD) cbSizeUntrusted = // __untrusted_array_size_init(cbSize); - // __untrusted_array(BYTE, DWORD) arr = + // __untrusted_array(BYTE, DWORD) arr = // __untrusted_array_init(FUZZ_MAP(...), nullptr, cbSizeUntrusted); - // AllocateArray(&arr, &cbSizeUntrusted); // Operator overloading on & will + // AllocateArray(&arr, &cbSizeUntrusted); // Operator overloading on & will // // allow the array to be allocated // // and then wrapped by CFuzzArray // BYTE *rgFuzzed = arr; // Asking for the BYTE* value will cause @@ -179,18 +185,18 @@ namespace fuzz // // buffer is reallocated, pfnFuzz will // // have a reference to cbSize which can be // // updated appropriately. - template + template struct _fuzz_array_entry { unsigned int uiPercentage; - std::function<_Type1* (_Type1*, _Type2&, _Args...)> pfnFuzz; + std::function<_Type1*(_Type1*, _Type2&, _Args...)> pfnFuzz; std::function pfnDealloc; }; // Internal struct for mapping percentages to value ranges. Not // expected to be used by users of this codebase but for internal // use instead. - template + template struct _range_fuzz_array_entry { _fuzz_array_entry<_Type1, _Type2, _Args...> fae; @@ -198,7 +204,7 @@ namespace fuzz }; // During initialization of the fuzz classes, if the fuzz map - // percentages add up to more than 100% and the fuzz trait + // percentages add up to more than 100% and the fuzz trait // TRAIT_THROW_ON_INIT_FAILURE is applied, the CFuzzRangeException // will be thrown. Since constructors cannot return errors, this allows // for verifying that numeric errors have not been made when designing @@ -209,14 +215,14 @@ namespace fuzz class CFuzzRangeException { public: - CFuzzRangeException() { }; - virtual ~CFuzzRangeException() { }; + CFuzzRangeException(){}; + virtual ~CFuzzRangeException(){}; }; // In an effort to avoid fuzzing code from scattering rand() throughout // the codebase, the CFuzzChance class is designed as the go to place // for generating random values (or random selection of values). This - // class is also used by the various fuzz classes internally for + // class is also used by the various fuzz classes internally for // determining which fuzzing routine should be applied from the fuzz map. class CFuzzChance { @@ -233,7 +239,7 @@ namespace fuzz #undef max #endif template - static _Type GetRandom() throw () + static _Type GetRandom() throw() { return GetRandom<_Type>(std::numeric_limits<_Type>::min(), std::numeric_limits<_Type>::max()); } @@ -268,32 +274,33 @@ namespace fuzz } #ifdef __min_collision__ #undef __min_collision__ -#define min(a,b) (((a) < (b)) ? (a) : (b)) +#define min(a, b) (((a) < (b)) ? (a) : (b)) #endif #ifdef __max_collision__ #undef __max_collision__ -#define max(a,b) (((a) > (b)) ? (a) : (b)) +#define max(a, b) (((a) > (b)) ? (a) : (b)) #endif - // Given an array of elements, select a random element from the + // Given an array of elements, select a random element from the // collection. Note that cElems is the number of items in the array. - template - static _Type SelectOne(__in_ecount(cElems) const _Type *rg, __in size_t cElems) throw() + template + static _Type SelectOne(__in_ecount(cElems) const _Type* rg, __in size_t cElems) throw() { return rg[GetRandom(cElems)]; } // Given an array of elements, select a random element from the // collection. Note that _cElems is the number of items in the array. - template + template static _Type SelectOne(const _Type (&rg)[_cElems]) throw() { return rg[GetRandom(_cElems)]; } + private: - CFuzzChance() { } - virtual ~CFuzzChance() { } + CFuzzChance() {} + virtual ~CFuzzChance() {} static std::random_device m_rd; }; @@ -307,21 +314,21 @@ namespace fuzz protected: CFuzzBase() : m_fFuzzed(FALSE), - m_iPercentageTotal(100) - { }; - virtual ~CFuzzBase() { }; + m_iPercentageTotal(100){}; + virtual ~CFuzzBase(){}; // Converts a percentage into a valid range. Note that riTotal // is a reference value, which allows for a running total to be // decremented as fuzz map percentages are mapped to valid ranges. void ConvertPercentageToRange(__in unsigned int iPercentage, - __inout int &riTotal, - __deref_out _range *pr) const + __inout int& riTotal, + __deref_out _range* pr) const { pr->iHigh = riTotal; pr->iLow = riTotal - iPercentage; riTotal -= iPercentage; } + protected: BOOL m_fFuzzed; int m_iPercentageTotal; @@ -340,18 +347,19 @@ namespace fuzz // appropriate and should be changed to CCRTAllocator. Adding new // allocator classes is as easy as writing a new class that supports // Allocate/Free/Reallocate, see documentation for CComAllocator. - template + template class CFuzzArray : public CFuzzBase { public: - template friend class CFuzzArraySize; + template + friend class CFuzzArraySize; // Creates a CFuzzArray instance that wraps a buffer specfied by // rg, together with its size (note that this is the number of elements // not necessarily the byte count). cElems is a reference so it must // point to a valid variable. In this constructor, it is valid for // the fuzz map to be a null pointer, but it is expected that a fuzz - // map will be provided at a later time via SetFuzzArrayMap or + // map will be provided at a later time via SetFuzzArrayMap or // AddFuzzArrayEntry. // // If CFuzzArray is initialized with rg == nullptr, this usage case @@ -363,15 +371,15 @@ namespace fuzz // not desirable, the situation is avoided by either not reallocating // or by not initializing via &. CFuzzArray( - __in_ecount(cfae) const _fuzz_array_entry<_Type1, _Type2, _Args...> *rgfae, + __in_ecount(cfae) const _fuzz_array_entry<_Type1, _Type2, _Args...>* rgfae, __in ULONG cfae, - __in_ecount_opt(cElems) _Type1 *rg, + __in_ecount_opt(cElems) _Type1* rg, __inout _Type2& cElems, __in _Args&&... args) : - m_rgCaller(rg), - m_pcElems(&cElems), - m_pfas(nullptr), - m_tArgs(std::forward<_Args>(args)...) + m_rgCaller(rg), + m_pcElems(&cElems), + m_pfas(nullptr), + m_tArgs(std::forward<_Args>(args)...) { Init(rgfae, cfae); } @@ -379,15 +387,15 @@ namespace fuzz // Constructor that allows association with a companion CFuzzArraySize object. // See CFuzzArraySize comments for more details. CFuzzArray( - __in_ecount(cfae) const _fuzz_array_entry<_Type1, _Type2, _Args...> *rgfae, + __in_ecount(cfae) const _fuzz_array_entry<_Type1, _Type2, _Args...>* rgfae, __in ULONG cfae, - __in_opt _Type1 *rg, - __in CFuzzArraySize<_Type1, _Type2, _Args...> &size, + __in_opt _Type1* rg, + __in CFuzzArraySize<_Type1, _Type2, _Args...>& size, __in _Args&&... args) : - m_rgCaller(rg), - m_pcElems(size.m_pcElems), - m_pfas(nullptr), - m_tArgs(std::forward<_Args>(args)...) + m_rgCaller(rg), + m_pcElems(size.m_pcElems), + m_pfas(nullptr), + m_tArgs(std::forward<_Args>(args)...) { if (SUCCEEDED(Init(rgfae, cfae))) { @@ -405,7 +413,7 @@ namespace fuzz // evaluated, potentially returning a fuzzed value. Note that fuzzing // is only evaluated once, so repeated access will return the same // fuzzed choice. - __inline operator _Type1* () throw() + __inline operator _Type1*() throw() { return GetValueFromMap(); } @@ -413,7 +421,7 @@ namespace fuzz // Allow calls to get the size of the fuzzed array ensuring evaluation // of the fuzzmap. Designed primarily to be called from the CFuzzArraySize // friend class. - __inline operator _Type2 () throw() + __inline operator _Type2() throw() { GetValueFromMap(); return *m_pcElems; @@ -424,10 +432,10 @@ namespace fuzz // via the constructor. If this operator is used and the fuzzing map // applies reallocation, ownership of the respective buffers is transferred // such that the fuzzed buffer becomes the caller's responsibility and the - // initial buffer is freed when this class is destroyed. Users of this + // initial buffer is freed when this class is destroyed. Users of this // codebase are responsible for ensuring the correct allocator is specified // for _Alloc and that the calling code is still functionally correct. - __inline _Type1** operator &() throw() + __inline _Type1** operator&() throw() { assert(m_rgCaller == nullptr); m_ftEffectiveTraits |= TRAIT_TRANSFER_ALLOCATION; @@ -435,20 +443,19 @@ namespace fuzz } // Const version of this operator overload does not assume ownership transfer - // like the above case. - __inline const _Type1** operator &() const throw() + // like the above case. + __inline const _Type1** operator&() const throw() { assert(m_rgCaller == nullptr); return (m_rgRealloc) ? &m_rgRealloc : &m_rgCaller; } - // Setting the fuzz map will clear any previous applied fuzz map. The - // AddFuzzArrayEntry function can be used to add additional fuzz map - // entries without removing the existing map. Returns E_INVALIDARG in the + // Setting the fuzz map will clear any previous applied fuzz map. The + // AddFuzzArrayEntry function can be used to add additional fuzz map + // entries without removing the existing map. Returns E_INVALIDARG in the // event that the total percentages add up to more than 100%. - [[nodiscard]] - __inline HRESULT SetFuzzArrayMap( - __in_ecount(cfae) const _fuzz_array_entry<_Type1, _Type2, _Args...> *rgfae, + [[nodiscard]] __inline HRESULT SetFuzzArrayMap( + __in_ecount(cfae) const _fuzz_array_entry<_Type1, _Type2, _Args...>* rgfae, __in ULONG cfae) throw() { ClearFuzzArrayEntries(); @@ -463,10 +470,9 @@ namespace fuzz // Adds an additional fuzz map entry, without clearing the existing // fuzz map. Returns E_INVALIDARG in the event that the total percentages // add up to more than 100%. - [[nodiscard]] - HRESULT AddFuzzArrayEntry( + [[nodiscard]] HRESULT AddFuzzArrayEntry( __in unsigned int uiPercentage, - __in std::function<_Type1* (_Type1*, _Type2&, _Args...)> pfnFuzz, + __in std::function<_Type1*(_Type1*, _Type2&, _Args...)> pfnFuzz, __in std::function pfnDealloc = nullptr) throw() { _range_fuzz_array_entry<_Type1, _Type2, _Args...> r = { 0 }; @@ -486,9 +492,9 @@ namespace fuzz // Invokes the fuzz map in the event that fuzzing as not been applied. // Since the fuzz map entries have their own potential allocation and - // deallocation routines, we actually make another copy of the fuzzed + // deallocation routines, we actually make another copy of the fuzzed // buffer in the event that reallocation has occurred (determined by - // comparing against the original initialized pointer value). This + // comparing against the original initialized pointer value). This // is important because we use the _Alloc value to ensure the correct // memory allocator is used that is appropriate for the calling code. __inline _Type1* GetValueFromMap() @@ -497,16 +503,16 @@ namespace fuzz { m_fFuzzed = TRUE; WORD wRandom = CFuzzChance::GetRandom(100); - for (auto &r : m_map) + for (auto& r : m_map) { if (r.range.iLow <= wRandom && wRandom < r.range.iHigh) { - _Type1 *rgTemp = CallFuzzMapFunction(r.fae.pfnFuzz, m_rgCaller, *m_pcElems, m_tArgs); + _Type1* rgTemp = CallFuzzMapFunction(r.fae.pfnFuzz, m_rgCaller, *m_pcElems, m_tArgs); if (rgTemp && rgTemp != m_rgCaller) { size_t cbRealloc = (m_ftEffectiveTraits & TRAIT_SIZE_IS_BCOUNT) ? - *m_pcElems : - *m_pcElems * sizeof(_Type1); + *m_pcElems : + *m_pcElems * sizeof(_Type1); m_rgRealloc = reinterpret_cast<_Type1*>(_Alloc::Allocate(cbRealloc)); if (m_rgRealloc) { @@ -526,13 +532,14 @@ namespace fuzz return (m_rgRealloc) ? m_rgRealloc : m_rgCaller; } + private: _Type1* m_rgCaller; _Type1* m_rgRealloc; - _Type2 *m_pcElems; + _Type2* m_pcElems; FuzzTraits m_ftEffectiveTraits; CFuzzArraySize<_Type1, _Type2, _Args...>* m_pfas; - std::vector<_range_fuzz_array_entry<_Type1, _Type2, _Args...> > m_map; + std::vector<_range_fuzz_array_entry<_Type1, _Type2, _Args...>> m_map; std::tuple<_Args...> m_tArgs; CFuzzArray<__FUZZING_ALLOCATOR, _Type1, _Type2, _Args...>* Reference() @@ -540,11 +547,11 @@ namespace fuzz return this; } - template + template _Type1* CallFuzzMapFunction( - std::function<_Type1* (_Type1*, _Type2&, _Args...)> pfnFuzz, - _Type1 *t1, - _Type2 &t2, + std::function<_Type1*(_Type1*, _Type2&, _Args...)> pfnFuzz, + _Type1* t1, + _Type2& t2, std::tuple<_Args...>& tup, variadic::index) { @@ -552,23 +559,22 @@ namespace fuzz } _Type1* CallFuzzMapFunction( - std::function<_Type1* (_Type1*, _Type2&, _Args...)> pfnFuzz, - _Type1 *t1, - _Type2 &t2, + std::function<_Type1*(_Type1*, _Type2&, _Args...)> pfnFuzz, + _Type1* t1, + _Type2& t2, std::tuple<_Args...>& tup) { - return CallFuzzMapFunction(pfnFuzz, t1, t2, tup, variadic::gen_seq < sizeof...(_Args) > {}); + return CallFuzzMapFunction(pfnFuzz, t1, t2, tup, variadic::gen_seq{}); } - [[nodiscard]] - HRESULT Init( - __in_ecount(cfae) const _fuzz_array_entry<_Type1, _Type2, _Args...> *rgfae, + [[nodiscard]] HRESULT Init( + __in_ecount(cfae) const _fuzz_array_entry<_Type1, _Type2, _Args...>* rgfae, __in ULONG cfae) { m_rgRealloc = nullptr; m_ftEffectiveTraits = m_traits; - // Since constructors cannot return error values, the + // Since constructors cannot return error values, the // TRAIT_THROW_ON_INIT_FAILURE trait allows for an exception // to be thrown in the event that this class was not initialized // correctly. The intended purpose is to catch users of this @@ -608,7 +614,7 @@ namespace fuzz } }; - // When working with arrays, care must be taken when passing a pointer to a + // When working with arrays, care must be taken when passing a pointer to a // fuzzed array together with the size to ensure the size lines up with the // the evaluated fuzz map. Consider the following: // @@ -631,11 +637,12 @@ namespace fuzz // __untrusted_array_size(BYTE, size_t) cbUntrusted = __untrusted_array_size_init(cb); // __untrusted_array(BYTE, size_t) rgUntrusted = __untrusted_array_init(FUZZ_MAP(...), rg, cbUntrusted); // hr = foo(rgUntrusted, cbUntrusted); - template + template class CFuzzArraySize { public: - template friend class CFuzzArray; + template + friend class CFuzzArray; CFuzzArraySize(__inout _Type2& cElems) : m_pcElems(&cElems), @@ -643,9 +650,9 @@ namespace fuzz { } - virtual ~CFuzzArraySize() { } + virtual ~CFuzzArraySize() {} - __inline operator _Type2 () throw() + __inline operator _Type2() throw() { if (m_pfa) { @@ -655,23 +662,24 @@ namespace fuzz return *m_pcElems; } - __inline _Type2* operator &() throw() + __inline _Type2* operator&() throw() { return m_pcElems; } - __inline const _Type2* operator &() const throw() + __inline const _Type2* operator&() const throw() { return m_pcElems; } - __inline void Pair(__in CFuzzArray<__FUZZING_ALLOCATOR, _Type1, _Type2, _Args...> &rfa) + __inline void Pair(__in CFuzzArray<__FUZZING_ALLOCATOR, _Type1, _Type2, _Args...>& rfa) { m_pfa = rfa.Reference(); } + private: - CFuzzArray<__FUZZING_ALLOCATOR, _Type1, _Type2, _Args...> *m_pfa; - _Type2 *m_pcElems; + CFuzzArray<__FUZZING_ALLOCATOR, _Type1, _Type2, _Args...>* m_pfa; + _Type2* m_pcElems; CFuzzArraySize<_Type1, _Type2, _Args...>* Reference() { @@ -682,9 +690,9 @@ namespace fuzz // The CFuzzType class is primarily designed for primitive types but // is also used as the base class for CFuzzTypePtr and CFuzzLpwstr. // The various operator overloads allow this class to wrap a type and - // usage of that type works transparently. Asking for the value + // usage of that type works transparently. Asking for the value // of the type wrapped by this class will invoke the fuzzing map. - template + template class CFuzzType : public CFuzzBase { public: @@ -693,18 +701,18 @@ namespace fuzz // is optional, but then expected to be provided via SetFuzzTypeMap // or AddFuzzTypeEntry if fuzzing is to be applied. CFuzzType( - __in_ecount(cfte) const _fuzz_type_entry<_Type, _Args...> *rgfte, + __in_ecount(cfte) const _fuzz_type_entry<_Type, _Args...>* rgfte, __in ULONG cfte, __in _Type t, __in _Args&&... args) : - m_t(t), - m_tInit(t), - m_tArgs(std::forward<_Args>(args)...) + m_t(t), + m_tInit(t), + m_tArgs(std::forward<_Args>(args)...) { m_pfnOnFuzzedValueFromMap = [](_Type t, std::function) { return t; }; HRESULT hr = SetFuzzTypeMap(rgfte, cfte); - // Since constructors cannot return error values, the + // Since constructors cannot return error values, the // TRAIT_THROW_ON_INIT_FAILURE trait allows for an exception // to be thrown in the event that this class was not initialized // correctly. The intended purpose is to catch users of this @@ -720,7 +728,7 @@ namespace fuzz { } - // Initializes with the value specified by t and then applies + // Initializes with the value specified by t and then applies // the fuzz map to produce a fuzzed return value. Usage of this // operator will make the CFuzzType instance look like a function // call, which might be desirable in some instances. @@ -729,7 +737,7 @@ namespace fuzz // int iFuzzedVal = iVal(15); // re-initializes the default value to 15, // // then applies the fuzz map to return // // a potentially fuzzed value - __inline _Type operator () (__in _Type t) throw() + __inline _Type operator()(__in _Type t) throw() { m_t = m_tInit = t; return GetValueFromMap(); @@ -739,7 +747,7 @@ namespace fuzz // If the fuzzing map has already been evaluated, initializing // via the = operator will not cause the fuzzing map to be // evaluated when the value is subsequently retrieved. - __inline void operator = (__in _Type t) throw() + __inline void operator=(__in _Type t) throw() { m_t = m_tInit = t; } @@ -747,33 +755,32 @@ namespace fuzz // Getting the value of this instance will cause the fuzz map // to be evaluated. The fuzz map will only be evaluated once, // subsequent access will always return the selected value. - __inline operator _Type () throw() + __inline operator _Type() throw() { return GetValueFromMap(); } - // Allows initialization of the internal type by providing a + // Allows initialization of the internal type by providing a // reference. If the fuzz map has been evaluated, the reference // is provided to the fuzzed value. - __inline virtual _Type* operator &() throw() + __inline virtual _Type* operator&() throw() { return (m_fFuzzed) ? &m_t : &m_tInit; } // Similar to above, if the fuzz map has been evaluated, the // reference is provided to the fuzzed value. - __inline const _Type* operator &() const throw() + __inline const _Type* operator&() const throw() { return (m_fFuzzed) ? &m_t : &m_tInit; } - // Setting the fuzz map will clear any previous applied fuzz map. The - // AddFuzzArrayEntry function can be used to add additional fuzz map - // entries without removing the existing map. Returns E_INVALIDARG in the + // Setting the fuzz map will clear any previous applied fuzz map. The + // AddFuzzArrayEntry function can be used to add additional fuzz map + // entries without removing the existing map. Returns E_INVALIDARG in the // event that the total percentages add up to more than 100%. - [[nodiscard]] - __inline HRESULT SetFuzzTypeMap( - __in_ecount(cfte) const _fuzz_type_entry<_Type, _Args...> *rgfte, + [[nodiscard]] __inline HRESULT SetFuzzTypeMap( + __in_ecount(cfte) const _fuzz_type_entry<_Type, _Args...>* rgfte, __in ULONG cfte) throw() { ClearFuzzTypeEntries(); @@ -791,8 +798,7 @@ namespace fuzz // Adds an additional fuzz map entry, without clearing the existing // fuzz map. Returns E_INVALIDARG in the event that the total percentages // add up to more than 100%. - [[nodiscard]] - HRESULT AddFuzzTypeEntry( + [[nodiscard]] HRESULT AddFuzzTypeEntry( __in unsigned int uiPercentage, __in std::function<_Type(_Type, _Args...)> pfnFuzz, __in std::function pfnDealloc = nullptr) throw() @@ -811,10 +817,11 @@ namespace fuzz m_map.clear(); m_iPercentageTotal = 100; } + protected: _Type m_t; _Type m_tInit; - std::vector<_range_fuzz_type_entry<_Type, _Args...> > m_map; + std::vector<_range_fuzz_type_entry<_Type, _Args...>> m_map; std::function<_Type(_Type, std::function)> m_pfnOnFuzzedValueFromMap; std::tuple<_Args...> m_tArgs; @@ -823,13 +830,13 @@ namespace fuzz _Type t, std::tuple<_Args...>& tup) { - return CallFuzzMapFunction(pfnFuzz, t, tup, variadic::gen_seq < sizeof...(_Args) > {}); + return CallFuzzMapFunction(pfnFuzz, t, tup, variadic::gen_seq{}); } // To support sub classes ability to realloc fuzzed values, // the m_pfnOnFuzzedValueFromMap will be invoked whenever a fuzz map // entry is selected. When not overridden, the default behavior is to - // set this classes value to the fuzzed value returned from the + // set this classes value to the fuzzed value returned from the // associated fuzzing routine. For an example that alters this behavior // take a look at the CFuzzLpwstr class. __inline virtual _Type GetValueFromMap() @@ -839,7 +846,7 @@ namespace fuzz m_fFuzzed = TRUE; m_t = m_tInit; WORD wRandom = CFuzzChance::GetRandom(100); - for (auto &r : m_map) + for (auto& r : m_map) { if (r.range.iLow <= wRandom && wRandom < r.range.iHigh) { @@ -851,8 +858,9 @@ namespace fuzz return m_t; } + private: - template + template _Type CallFuzzMapFunction( std::function<_Type(_Type, _Args...)> pfnFuzz, _Type t, @@ -865,28 +873,28 @@ namespace fuzz }; // The CFuzzTypePtr class provides all the same functionality as the - // base CFuzzType class, but also provides an additional operator + // base CFuzzType class, but also provides an additional operator // override for ->. This allows pointers to be wrapped by this class // to be seamlessly used in the calling codebase. Note that correct // fuzzing behavior is entirely dependent on the design of the fuzzing // map, this class is not intended to fuzz actual pointer values. - template - class CFuzzTypePtr : public CFuzzType < _Type, _Args... > + template + class CFuzzTypePtr : public CFuzzType<_Type, _Args...> { public: // Note that _Type is expected to be a pointer type (thus making // the operator override of -> make sense). It is the callers // responsibility to set the type appropriately. CFuzzTypePtr( - __in_ecount(cfte) const _fuzz_type_entry<_Type> *rgfte, + __in_ecount(cfte) const _fuzz_type_entry<_Type>* rgfte, __in ULONG cfte, __in _Type pt, __in _Args&&... args) : - CFuzzType(rgfte, cfte, pt, std::forward<_Args>(args)...) + CFuzzType(rgfte, cfte, pt, std::forward<_Args>(args)...) { } - virtual ~CFuzzTypePtr() { } + virtual ~CFuzzTypePtr() {} _Type operator->() const throw() { @@ -894,12 +902,12 @@ namespace fuzz } // This operator makes it possible to invoke the fuzzing map - // by calling this class like a parameterless function. This is + // by calling this class like a parameterless function. This is // used to support the __make_untrusted call below. Note that once // the fuzzing map is invoked, all future access of the pointer // members will be pointed to potentially fuzzed data (as per // the logic of the fuzz map). - __inline void operator() () throw() + __inline void operator()() throw() { GetValueFromMap(); } @@ -914,16 +922,16 @@ namespace fuzz // is allowed, _Alloc needs to match the appropriate allocation // method used by the calling code. Please see CFuzzArray documentation // for more details. - template - class CFuzzString : public CFuzzType <_Type*, _Args...> + template + class CFuzzString : public CFuzzType<_Type*, _Args...> { public: CFuzzString( - __in_ecount(cfte) const _fuzz_type_entry<_Type*, _Args...> *rgfte, + __in_ecount(cfte) const _fuzz_type_entry<_Type*, _Args...>* rgfte, __in ULONG cfte, - __in _Type *psz, + __in _Type* psz, __in _Args... args) : - CFuzzType(rgfte, cfte, psz, std::forward<_Args>(args)...) + CFuzzType(rgfte, cfte, psz, std::forward<_Args>(args)...) { OnFuzzedValueFromMap(); } @@ -949,36 +957,36 @@ namespace fuzz // // fuzzed string. This means // // pwsz is responsible for freeing // // the original allocation. - __inline virtual _Type** operator &() throw() + __inline virtual _Type** operator&() throw() { m_ftEffectiveTraits |= TRAIT_TRANSFER_ALLOCATION; return (m_fFuzzed) ? &m_t : &m_tInit; } + private: - _Type *m_pszFuzzed; + _Type* m_pszFuzzed; FuzzTraits m_ftEffectiveTraits; // Since reallocation could occur that is dependent on matching the - // allocation routines of the calling code, we want to ensure we + // allocation routines of the calling code, we want to ensure we // allocate using the correct allocator specified by _Alloc. However, // the allocation routines in the fuzzing map could differ, therefore // we copy the fuzzed string as appropriate and use the specified // dealloc function in the fuzz map entry to delete the fuzzed string // created by the fuzz map entry. Slightly inefficient, but safer - // and supports a wider variety of scenarios. + // and supports a wider variety of scenarios. void OnFuzzedValueFromMap() { m_pszFuzzed = nullptr; m_ftEffectiveTraits = m_traits; - m_pfnOnFuzzedValueFromMap = [&](_Type *psz, std::function dealloc) - { + m_pfnOnFuzzedValueFromMap = [&](_Type* psz, std::function dealloc) { FreeFuzzedString(); - _Type *pszFuzzed = psz; + _Type* pszFuzzed = psz; if (psz && psz != m_tInit) { size_t cb = (sizeof(_Type) == sizeof(char)) ? - (strlen(reinterpret_cast(psz)) + 1) * sizeof(char) : - (wcslen(reinterpret_cast(psz)) + 1) * sizeof(WCHAR); + (strlen(reinterpret_cast(psz)) + 1) * sizeof(char) : + (wcslen(reinterpret_cast(psz)) + 1) * sizeof(WCHAR); m_pszFuzzed = reinterpret_cast<_Type*>(_Alloc::Allocate(cb)); if (m_pszFuzzed) { @@ -1018,7 +1026,7 @@ namespace fuzz } }; - // The CFuzzFlags class extends the CFuzzType base class, but + // The CFuzzFlags class extends the CFuzzType base class, but // operates slightly differently than other fuzz class implementations. // The intended usage of this class is when dealing with bit flags, // where covering the range of possible bit flag combinations would be @@ -1040,24 +1048,25 @@ namespace fuzz // }; // // Also note that this class should specifically not have the - // TRAIT_THROW_ON_INIT_FAILURE trait, as it is expected that the + // TRAIT_THROW_ON_INIT_FAILURE trait, as it is expected that the // percentages will total more than 100% when added together. - template - class CFuzzFlags : public CFuzzType < _Type, _Args... > + template + class CFuzzFlags : public CFuzzType<_Type, _Args...> { public: CFuzzFlags( - __in_ecount(cfte) const _fuzz_type_entry<_Type> *rgfte, + __in_ecount(cfte) const _fuzz_type_entry<_Type>* rgfte, __in ULONG cfte, __in _Type flags, __in _Args&&... args) : - CFuzzType(rgfte, cfte, flags, std::forward<_Args>(args)...) + CFuzzType(rgfte, cfte, flags, std::forward<_Args>(args)...) { } virtual ~CFuzzFlags() { } + protected: __inline virtual _Type GetValueFromMap() { @@ -1065,10 +1074,10 @@ namespace fuzz { m_t = 0; m_fFuzzed = TRUE; - for (auto &r : m_map) + for (auto& r : m_map) { // Generate a new random value during each map entry - // and use it to evaluate if each individual fuzz map + // and use it to evaluate if each individual fuzz map // entry should be applied. WORD wRandom = CFuzzChance::GetRandom(100); @@ -1091,9 +1100,9 @@ namespace fuzz // To make using these classes a no-opt if fuzzing is not intended to // be applied, the following set of functions and defines operate // differently if __GENERATE_DIRECTED_FUZZING is defined. If defined, -// these wrappers use the correct fuzz classes and initialize these +// these wrappers use the correct fuzz classes and initialize these // classes with the appropriate map specified by the caller. If not -// defined, essentially the use of these classes disappear and the +// defined, essentially the use of these classes disappear and the // remaining functions are optimized away by the compiler. When // applied appropriately, not turning on fuzzing leaves no performance // impact, no size footprint, and no leakage of information into the @@ -1101,11 +1110,15 @@ namespace fuzz #ifdef __GENERATE_DIRECTED_FUZZING #define FUZZ_ARRAY_START_STATIC(name, type, size, ...) static const fuzz::_fuzz_array_entry name[] = { #define FUZZ_ARRAY_START(name, type, size, ...) const fuzz::_fuzz_array_entry name[] = { -#define FUZZ_ARRAY_END() }; +#define FUZZ_ARRAY_END() \ + } \ + ; #define FUZZ_TYPE_START_STATIC(name, type, ...) static const fuzz::_fuzz_type_entry name[] = { #define FUZZ_TYPE_START(name, type, ...) const fuzz::_fuzz_type_entry name[] = { -#define FUZZ_TYPE_END() }; +#define FUZZ_TYPE_END() \ + } \ + ; #define FUZZ_MAP_ENTRY_ALLOC(i, pfnAlloc, pfnDelete) { i, pfnAlloc, pfnDelete }, #define FUZZ_MAP_ENTRY(i, pfnAlloc) { i, pfnAlloc }, @@ -1123,7 +1136,7 @@ namespace fuzz template static fuzz::CFuzzType<_Type, _Args...> __untrusted_init( - __in_ecount(cfte) const fuzz::_fuzz_type_entry<_Type, _Args...> *rgfte, + __in_ecount(cfte) const fuzz::_fuzz_type_entry<_Type, _Args...>* rgfte, __in ULONG cfte, __in _Type t, __in _Args&&... args) @@ -1133,7 +1146,7 @@ static fuzz::CFuzzType<_Type, _Args...> __untrusted_init( template static fuzz::CFuzzString<__FUZZING_ALLOCATOR, WCHAR, _Args...> __untrusted_lpwstr_init( - __in_ecount(cfte) const fuzz::_fuzz_type_entry *rgfte, + __in_ecount(cfte) const fuzz::_fuzz_type_entry* rgfte, __in ULONG cfte, __in LPWSTR pwsz, __in _Args&&... args) @@ -1143,7 +1156,7 @@ static fuzz::CFuzzString<__FUZZING_ALLOCATOR, WCHAR, _Args...> __untrusted_lpwst template static fuzz::CFuzzString<__FUZZING_ALLOCATOR, CHAR, _Args...> __untrusted_lpstr_init( - __in_ecount(cfte) const fuzz::_fuzz_type_entry *rgfte, + __in_ecount(cfte) const fuzz::_fuzz_type_entry* rgfte, __in ULONG cfte, __in LPSTR psz, __in _Args&&... args) @@ -1153,23 +1166,23 @@ static fuzz::CFuzzString<__FUZZING_ALLOCATOR, CHAR, _Args...> __untrusted_lpstr_ template static fuzz::CFuzzArray<__FUZZING_ALLOCATOR, _Type1, _Type2, _Args...> __untrusted_array_init( - __in_ecount(cfae) const fuzz::_fuzz_array_entry<_Type1, _Type2, _Args...> *rgfae, + __in_ecount(cfae) const fuzz::_fuzz_array_entry<_Type1, _Type2, _Args...>* rgfae, __in ULONG cfae, - __in _Type1 *pt, - __in fuzz::CFuzzArraySize<_Type1, _Type2, _Args...> &rfas, + __in _Type1* pt, + __in fuzz::CFuzzArraySize<_Type1, _Type2, _Args...>& rfas, __in _Args&&... args) { return fuzz::CFuzzArray<__FUZZING_ALLOCATOR, _Type1, _Type2, _Args...>(rgfae, cfae, pt, rfas, std::forward<_Args>(args)...); } template -static fuzz::CFuzzArraySize<_Type1, _Type2, _Args...> __untrusted_array_size_init(__inout _Type2 &t2) +static fuzz::CFuzzArraySize<_Type1, _Type2, _Args...> __untrusted_array_size_init(__inout _Type2& t2) { return fuzz::CFuzzArraySize<_Type1, _Type2, _Args...>(t2); } template -static void __make_untrusted_ptr(__in fuzz::CFuzzTypePtr<_Type, _Args...> &rftp) +static void __make_untrusted_ptr(__in fuzz::CFuzzTypePtr<_Type, _Args...>& rftp) { rftp(); } @@ -1198,7 +1211,7 @@ static void __make_untrusted_ptr(__in fuzz::CFuzzTypePtr<_Type, _Args...> &rftp) template static __forceinline _Type __untrusted_init( - __in_opt void*, + __in_opt void*, __in ULONG, __in _Type t, __in _Args&&...) @@ -1206,9 +1219,9 @@ static __forceinline _Type __untrusted_init( return t; } -template +template static __forceinline LPWSTR __untrusted_lpwstr_init( - __in_opt void*, + __in_opt void*, __in ULONG, __in LPWSTR pwsz, __in _Args&&...) @@ -1216,9 +1229,9 @@ static __forceinline LPWSTR __untrusted_lpwstr_init( return pwsz; } -template +template static __forceinline LPSTR __untrusted_lpstr_init( - __in_opt void*, + __in_opt void*, __in ULONG, __in LPSTR psz, __in _Args&&...) @@ -1228,9 +1241,9 @@ static __forceinline LPSTR __untrusted_lpstr_init( template static __forceinline _Type1* __untrusted_array_init( - __in_opt void*, + __in_opt void*, __in ULONG, - __in _Type1 *pt, + __in _Type1* pt, __in _Type2, __in _Args&&...) { diff --git a/src/terminal/parser/ft_fuzzer/fuzzing_logic.h b/src/terminal/parser/ft_fuzzer/fuzzing_logic.h index a2978c85e..888a8b2bb 100644 --- a/src/terminal/parser/ft_fuzzer/fuzzing_logic.h +++ b/src/terminal/parser/ft_fuzzer/fuzzing_logic.h @@ -34,7 +34,7 @@ namespace fuzz // Inserts a format character to a random location within the string. // Note that rcch is the count of characters (minus the NULL terminator), not the count of bytes. - static LPWSTR _fz_wsz_addFormatChar(__inout_ecount(rcch) WCHAR *pwsz, __inout size_t &rcch) + static LPWSTR _fz_wsz_addFormatChar(__inout_ecount(rcch) WCHAR* pwsz, __inout size_t& rcch) { if (rcch > 1) { @@ -52,7 +52,7 @@ namespace fuzz // Inserts a format character to a random location within the string. // Note that rcch does not include the NULL terminator - static LPSTR _fz_sz_addFormatChar(__inout_ecount(rcch) CHAR *psz, __inout size_t &rcch) + static LPSTR _fz_sz_addFormatChar(__inout_ecount(rcch) CHAR* psz, __inout size_t& rcch) { if (rcch > 1) { @@ -70,7 +70,7 @@ namespace fuzz // Adds a character related to paths to a random location within the string. // Note that rcch is the count of characters (minus the NULL terminator), not the count of bytes. - static LPWSTR _fz_wsz_addPathChar(__inout_ecount(rcch) WCHAR *pwsz, __inout size_t &rcch) + static LPWSTR _fz_wsz_addPathChar(__inout_ecount(rcch) WCHAR* pwsz, __inout size_t& rcch) { if (rcch > 0) { @@ -84,7 +84,7 @@ namespace fuzz // Adds a character related to paths to a random location within the string. // Note that rcch does not include the NULL terminator - static LPSTR _fz_sz_addPathChar(__inout_ecount(rcch) CHAR *psz, __inout size_t &rcch) + static LPSTR _fz_sz_addPathChar(__inout_ecount(rcch) CHAR* psz, __inout size_t& rcch) { if (rcch > 0) { @@ -98,7 +98,7 @@ namespace fuzz // Adds an invalid path character to a random location within the string. // Note that rcch is the count of characters (minus the NULL terminator), not the count of bytes. - static LPWSTR _fz_wsz_addInvalidPathChar(__inout_ecount(rcch) WCHAR *pwsz, __inout size_t &rcch) + static LPWSTR _fz_wsz_addInvalidPathChar(__inout_ecount(rcch) WCHAR* pwsz, __inout size_t& rcch) { if (rcch > 0) { @@ -112,7 +112,7 @@ namespace fuzz // Adds an invalid path character to a random location within the string. // Note that rcch does not include the NULL terminator - static LPSTR _fz_sz_addInvalidPathChar(__inout_ecount(rcch) CHAR *psz, __inout size_t &rcch) + static LPSTR _fz_sz_addInvalidPathChar(__inout_ecount(rcch) CHAR* psz, __inout size_t& rcch) { if (rcch > 0) { @@ -126,13 +126,15 @@ namespace fuzz // Implementation depends on CFuzzLogic class and is therefore // declared after CFuzzLogic is defined below. - template static _Type* _fz_flipBYTE(__inout_ecount(rcelms) _Type *p, __inout size_t &rcelms); - template static _Type* _fz_flipWCHAR(__inout_ecount(rcelms) _Type *p, __inout size_t &rcelms); - static char* _fz_sz_tokenizeSpaces(__in char *psz); + template + static _Type* _fz_flipBYTE(__inout_ecount(rcelms) _Type* p, __inout size_t& rcelms); + template + static _Type* _fz_flipWCHAR(__inout_ecount(rcelms) _Type* p, __inout size_t& rcelms); + static char* _fz_sz_tokenizeSpaces(__in char* psz); // Mirrors the first half of the string across the second half of the string. // Note that rcch is the count of characters (minus the NULL terminator), not the count of bytes. - static LPWSTR _const_wsz_mirror(__inout_ecount(rcch) WCHAR *pwsz, __inout size_t &rcch) + static LPWSTR _const_wsz_mirror(__inout_ecount(rcch) WCHAR* pwsz, __inout size_t& rcch) { if (rcch > 0) { @@ -149,7 +151,7 @@ namespace fuzz // Mirrors the first half of the string across the second half of the string. // Note that rcch does not include the NULL terminator - static LPSTR _const_sz_mirror(__inout_ecount(rcch) CHAR *psz, __inout size_t &rcch) + static LPSTR _const_sz_mirror(__inout_ecount(rcch) CHAR* psz, __inout size_t& rcch) { if (rcch > 0) { @@ -166,7 +168,7 @@ namespace fuzz // Replicates the string repeatedly until the end of the buffer is reached. // Note that rcch is the count of characters (minus the NULL terminator), not the count of bytes. - static LPWSTR _const_wsz_replicate(__inout_ecount(rcch) WCHAR *pwsz, __inout size_t &rcch) + static LPWSTR _const_wsz_replicate(__inout_ecount(rcch) WCHAR* pwsz, __inout size_t& rcch) { if (rcch > 0) { @@ -183,7 +185,7 @@ namespace fuzz // Replicates the string repeatedly until the end of the buffer is reached. // Note that rcch does not include the NULL terminator - static LPSTR _const_sz_replicate(__inout_ecount(rcch) CHAR *psz, __inout size_t &rcch) + static LPSTR _const_sz_replicate(__inout_ecount(rcch) CHAR* psz, __inout size_t& rcch) { if (rcch > 0) { @@ -200,7 +202,7 @@ namespace fuzz // Replaces the string with a valid system path to shell32.dll in the system32 dir. // Note that rcch is the count of characters (minus the NULL terminator), not the count of bytes. - static LPWSTR _const_wsz_validPath(__inout_ecount(rcch) WCHAR *pwsz, __inout size_t &rcch) + static LPWSTR _const_wsz_validPath(__inout_ecount(rcch) WCHAR* pwsz, __inout size_t& rcch) { WCHAR wszSystemDirectory[MAX_PATH] = { 0 }; if (GetSystemDirectoryW(wszSystemDirectory, ARRAYSIZE(wszSystemDirectory))) @@ -213,7 +215,7 @@ namespace fuzz // Replaces the string with a valid system path to shell32.dll in the system32 dir. // Note that rcch does not include the NULL terminator - static LPSTR _const_sz_validPath(__inout_ecount(rcch) CHAR *psz, __inout size_t &rcch) + static LPSTR _const_sz_validPath(__inout_ecount(rcch) CHAR* psz, __inout size_t& rcch) { CHAR szSystemDirectory[MAX_PATH] = { 0 }; if (GetSystemDirectoryA(szSystemDirectory, ARRAYSIZE(szSystemDirectory))) @@ -225,13 +227,13 @@ namespace fuzz } // Reverses the string in place. - static LPWSTR _const_wsz_reverse(__inout WCHAR *pwsz, __inout size_t &) + static LPWSTR _const_wsz_reverse(__inout WCHAR* pwsz, __inout size_t&) { return _wcsrev(pwsz); } // Reverses the string in place. - static LPSTR _const_sz_reverse(__inout CHAR *psz, __inout size_t &) + static LPSTR _const_sz_reverse(__inout CHAR* psz, __inout size_t&) { return _strrev(psz); } @@ -241,7 +243,7 @@ namespace fuzz // that does not require external modules or complex setup. This should // make fuzzing easier to implement and test, as well as more explicit // with regard to what fuzzing manipulations are possible. - template + template class CFuzzLogic { public: @@ -249,8 +251,8 @@ namespace fuzz // contained within the size of a single element. See _fz_wsz_flipBYTE // and _fz_wsz_flipWCHAR for an example of how the element size determines // the amount of data manipulated. - template - static _Type* FuzzArrayElement(__in_ecount(cElems) _Type *rg, __in size_t cElems) throw() + template + static _Type* FuzzArrayElement(__in_ecount(cElems) _Type* rg, __in size_t cElems) throw() { if (rg && cElems) { @@ -264,12 +266,11 @@ namespace fuzz // Fuzzes a string by allocating a new fuzzed string. Note that the string // length can shrink or grow in relation to the template data passed in - // via pwsz. The maximum size the string can grow is 2 times the current + // via pwsz. The maximum size the string can grow is 2 times the current // length. static LPWSTR FuzzStringW(__in LPCWSTR pwsz) throw() { - const _fuzz_type_entry rgfte[] = - { + const _fuzz_type_entry rgfte[] = { { 10, [](size_t cch) { return CFuzzChance::GetRandom(cch + 1); } }, { 50, [](size_t cch) { return cch + CFuzzChance::GetRandom(cch + 1); } } }; @@ -289,14 +290,13 @@ namespace fuzz // Fuzzes a string by allocating a new fuzzed string. Note that the string // length can shrink or grow in relation to the template data passed in - // via pwsz. The maximum size the string can grow is 2 times the current + // via pwsz. The maximum size the string can grow is 2 times the current // length. static LPSTR FuzzStringA(__in LPCSTR psz) throw() { LPSTR pszRealloc = nullptr; - const _fuzz_type_entry rgfte[] = - { + const _fuzz_type_entry rgfte[] = { { 10, [](size_t cch) { return CFuzzChance::GetRandom(cch + 1); } }, { 50, [](size_t cch) { return cch + CFuzzChance::GetRandom(cch + 1); } } }; @@ -309,15 +309,12 @@ namespace fuzz pszReallocTemp[--cchTemp] = '\0'; StringCchCopyA(pszReallocTemp, cchTemp, psz); - const _fuzz_type_entry fuzzMap[] = - { + const _fuzz_type_entry fuzzMap[] = { { 5, _fz_sz_tokenizeSpaces, FreeFuzzedBuffer }, - { 95, [=](LPSTR p) - { - size_t cchInner = cchTemp; - return FuzzStringA_NoRealloc(p, cchInner); - } - } + { 95, [=](LPSTR p) { + size_t cchInner = cchTemp; + return FuzzStringA_NoRealloc(p, cchInner); + } } }; CFuzzString<__FUZZING_ALLOCATOR, CHAR> eval(FUZZ_MAP(fuzzMap), pszReallocTemp); @@ -338,7 +335,7 @@ namespace fuzz return pszRealloc; } - // Fuzzes a string in place, no new memory is allocated to perform this + // Fuzzes a string in place, no new memory is allocated to perform this // fuzzing. This means that the return value is the same as the pwsz // parameter. static LPWSTR FuzzStringW_NoRealloc(__inout LPWSTR pwsz) throw() @@ -347,7 +344,7 @@ namespace fuzz return FuzzStringW_NoRealloc(pwsz, cch); } - // Fuzzes a string in place, no new memory is allocated to perform this + // Fuzzes a string in place, no new memory is allocated to perform this // fuzzing. This means that the return value is the same as the psz // parameter. static LPSTR FuzzStringA_NoRealloc(__inout LPSTR psz) throw() @@ -373,26 +370,26 @@ namespace fuzz // always be freed with FreeFuzzedBuffer. The prototype of this function // should always support being used within a fuzz array entry or a fuzz // type entry as the pfnDealloc function. - static void FreeFuzzedBuffer(void *pv) throw() + static void FreeFuzzedBuffer(void* pv) throw() { _Alloc::Free(pv); } - private: - CFuzzLogic() { }; - virtual ~CFuzzLogic() { }; - static LPWSTR FuzzStringW_NoRealloc(__inout LPWSTR pwsz, __inout size_t &rcch) + private: + CFuzzLogic(){}; + virtual ~CFuzzLogic(){}; + + static LPWSTR FuzzStringW_NoRealloc(__inout LPWSTR pwsz, __inout size_t& rcch) { if (rcch > 0) { - const _fuzz_array_entry rgfae[] = - { + const _fuzz_array_entry rgfae[] = { // small randomized manipulations { 21, _fz_wsz_addFormatChar }, { 21, _fz_wsz_addPathChar }, { 21, _fz_wsz_addInvalidPathChar }, - { 11, [](WCHAR *pwsz, size_t &rcch) { return _fz_flipByte(pwsz, rcch); } }, - { 10, [](WCHAR *pwsz, size_t &rcch) { return _fz_flipEntry(pwsz, rcch); } }, + { 11, [](WCHAR* pwsz, size_t& rcch) { return _fz_flipByte(pwsz, rcch); } }, + { 10, [](WCHAR* pwsz, size_t& rcch) { return _fz_flipEntry(pwsz, rcch); } }, // non-random manipulations { 4, _const_wsz_replicate }, @@ -407,17 +404,16 @@ namespace fuzz return pwsz; } - static LPSTR FuzzStringA_NoRealloc(__inout LPSTR psz, __inout size_t &rcch) + static LPSTR FuzzStringA_NoRealloc(__inout LPSTR psz, __inout size_t& rcch) { if (rcch > 0) { - const _fuzz_array_entry rgfae[] = - { + const _fuzz_array_entry rgfae[] = { // small randomized manipulations { 21, _fz_sz_addFormatChar }, { 21, _fz_sz_addPathChar }, { 21, _fz_sz_addInvalidPathChar }, - { 21, [](CHAR *psz, size_t &rcch) { return _fz_flipByte(psz, rcch); } }, + { 21, [](CHAR* psz, size_t& rcch) { return _fz_flipByte(psz, rcch); } }, // non-random manipulations { 4, _const_sz_replicate }, @@ -434,21 +430,21 @@ namespace fuzz }; // Flips a random byte value within the buffer. - template - static _Type* _fz_flipByte(__inout_ecount(rcelms) _Type *p, __inout size_t &rcelms) + template + static _Type* _fz_flipByte(__inout_ecount(rcelms) _Type* p, __inout size_t& rcelms) { if (rcelms > 0) { return reinterpret_cast<_Type*>(CFuzzLogic<>::FuzzArrayElement( - reinterpret_cast(p), (rcelms)* sizeof(_Type))); + reinterpret_cast(p), (rcelms) * sizeof(_Type))); } return p; } // Flips a random entry value within the buffer - template - static _Type* _fz_flipEntry(__inout_ecount(rcelms) _Type *p, __inout size_t &rcelms) + template + static _Type* _fz_flipEntry(__inout_ecount(rcelms) _Type* p, __inout size_t& rcelms) { if (rcelms > 0) { @@ -458,18 +454,17 @@ namespace fuzz return p; } - static char* _fz_sz_tokenizeSpaces(__in char *psz) + static char* _fz_sz_tokenizeSpaces(__in char* psz) { - const _fuzz_type_entry repeatMap[] = - { + const _fuzz_type_entry repeatMap[] = { { 10, [](DWORD) { return 0; } }, { 10, [](DWORD) { return 2; } }, { 1, [](DWORD) { return CFuzzChance::GetRandom(0xF); } } }; std::string sFuzzed; - char *next_token = nullptr; - char *token = strtok_s(psz, " ", &next_token); + char* next_token = nullptr; + char* token = strtok_s(psz, " ", &next_token); while (token) { CFuzzType repeat(FUZZ_MAP(repeatMap), 1); diff --git a/src/terminal/parser/stateMachine.cpp b/src/terminal/parser/stateMachine.cpp index 79ed50a03..ebab72d59 100644 --- a/src/terminal/parser/stateMachine.cpp +++ b/src/terminal/parser/stateMachine.cpp @@ -263,7 +263,7 @@ bool StateMachine::s_IsOscInvalid(const wchar_t wch) { return wch <= L'\x17' || wch == L'\x19' || - (wch >= L'\x1c' && wch <= L'\x1f') ; + (wch >= L'\x1c' && wch <= L'\x1f'); } // Routine Description: @@ -299,7 +299,6 @@ void StateMachine::_ActionExecute(const wchar_t wch) { _trace.TraceOnExecute(wch); _pEngine->ActionExecute(wch); - } // Routine Description: @@ -314,7 +313,6 @@ void StateMachine::_ActionExecuteFromEscape(const wchar_t wch) { _trace.TraceOnExecuteFromEscape(wch); _pEngine->ActionExecuteFromEscape(wch); - } // Routine Description: @@ -329,7 +327,6 @@ void StateMachine::_ActionPrint(const wchar_t wch) _pEngine->ActionPrint(wch); } - // Routine Description: // - Triggers the EscDispatch action to indicate that the listener should handle a simple escape sequence. // These sequences traditionally start with ESC and a simple letter. No complicated parameters. @@ -500,7 +497,6 @@ void StateMachine::_ActionClear() _sOscNextChar = 0; _pEngine->ActionClear(); - } // Routine Description: @@ -1323,7 +1319,7 @@ bool StateMachine::FlushToTerminal() // However, if we're here, then the processing of pwchChar triggered the // engine to request the entire sequence get passed through, including pwchCurr. return _pEngine->ActionPassThroughString(_pwchSequenceStart, - _pwchCurr-_pwchSequenceStart+1); + _pwchCurr - _pwchSequenceStart + 1); } // Routine Description: @@ -1346,15 +1342,15 @@ void StateMachine::ProcessString(const wchar_t* const rgwch, const size_t cch) // we want the partial sequence state to persist. static bool s_fProcessIndividually = false; - for(size_t cchCharsRemaining = cch; cchCharsRemaining > 0; cchCharsRemaining--) + for (size_t cchCharsRemaining = cch; cchCharsRemaining > 0; cchCharsRemaining--) { if (s_fProcessIndividually) { // If we're processing characters individually, send it to the state machine. ProcessCharacter(*_pwchCurr); _pwchCurr++; - if (_state == VTStates::Ground) // Then check if we're back at ground. If we are, the next character (pwchCurr) - { // is the start of the next run of characters that might be printable. + if (_state == VTStates::Ground) // Then check if we're back at ground. If we are, the next character (pwchCurr) + { // is the start of the next run of characters that might be printable. s_fProcessIndividually = false; _pwchSequenceStart = _pwchCurr; _currRunLength = 0; @@ -1362,7 +1358,7 @@ void StateMachine::ProcessString(const wchar_t* const rgwch, const size_t cch) } else { - if (s_IsActionableFromGround(*_pwchCurr)) // If the current char is the start of an escape sequence, or should be executed in ground state... + if (s_IsActionableFromGround(*_pwchCurr)) // If the current char is the start of an escape sequence, or should be executed in ground state... { FAIL_FAST_IF(!(_pwchSequenceStart + _currRunLength <= rgwch + cch)); _pEngine->ActionPrintString(_pwchSequenceStart, _currRunLength); // ... print all the chars leading up to it as part of the run... @@ -1371,7 +1367,7 @@ void StateMachine::ProcessString(const wchar_t* const rgwch, const size_t cch) _currRunLength = 0; _pwchSequenceStart = _pwchCurr; ProcessCharacter(*_pwchCurr); // ... Then process the character individually. - if (_state == VTStates::Ground) // If the character took us right back to ground, start another run after it. + if (_state == VTStates::Ground) // If the character took us right back to ground, start another run after it. { s_fProcessIndividually = false; _pwchSequenceStart = _pwchCurr + 1; @@ -1392,7 +1388,6 @@ void StateMachine::ProcessString(const wchar_t* const rgwch, const size_t cch) // print the rest of the characters in the string _pEngine->ActionPrintString(_pwchSequenceStart, _currRunLength); _trace.DispatchPrintRunTrace(_pwchSequenceStart, _currRunLength); - } else if (s_fProcessIndividually) { @@ -1402,7 +1397,7 @@ void StateMachine::ProcessString(const wchar_t* const rgwch, const size_t cch) ResetState(); // Chars to flush are [pwchSequenceStart, pwchCurr) const wchar_t* pwch = _pwchSequenceStart; - for (; pwch < _pwchCurr-1; pwch++) + for (; pwch < _pwchCurr - 1; pwch++) { ProcessCharacter(*pwch); } @@ -1429,7 +1424,6 @@ void StateMachine::ProcessString(const wchar_t* const rgwch, const size_t cch) default: return; } - } } } diff --git a/src/terminal/parser/stateMachine.hpp b/src/terminal/parser/stateMachine.hpp index 5133a30b1..ce6980191 100644 --- a/src/terminal/parser/stateMachine.hpp +++ b/src/terminal/parser/stateMachine.hpp @@ -150,6 +150,5 @@ namespace Microsoft::Console::VirtualTerminal const wchar_t* _pwchCurr; const wchar_t* _pwchSequenceStart; size_t _currRunLength; - }; } diff --git a/src/terminal/parser/telemetry.cpp b/src/terminal/parser/telemetry.cpp index 90d81f08f..5517de15f 100644 --- a/src/terminal/parser/telemetry.cpp +++ b/src/terminal/parser/telemetry.cpp @@ -6,17 +6,17 @@ #include "telemetry.hpp" TRACELOGGING_DEFINE_PROVIDER(g_hConsoleVirtTermParserEventTraceProvider, - "Microsoft.Windows.Console.VirtualTerminal.Parser", - // {c9ba2a84-d3ca-5e19-2bd6-776a0910cb9d} - (0xc9ba2a84, 0xd3ca, 0x5e19, 0x2b, 0xd6, 0x77, 0x6a, 0x09, 0x10, 0xcb, 0x9d)); + "Microsoft.Windows.Console.VirtualTerminal.Parser", + // {c9ba2a84-d3ca-5e19-2bd6-776a0910cb9d} + (0xc9ba2a84, 0xd3ca, 0x5e19, 0x2b, 0xd6, 0x77, 0x6a, 0x09, 0x10, 0xcb, 0x9d)); using namespace Microsoft::Console::VirtualTerminal; #pragma warning(push) // Disable 4351 so we can initialize the arrays to 0 without a warning. -#pragma warning(disable:4351) -TermTelemetry::TermTelemetry() - : _uiTimesUsedCurrent(0), +#pragma warning(disable : 4351) +TermTelemetry::TermTelemetry() : + _uiTimesUsedCurrent(0), _uiTimesFailedCurrent(0), _uiTimesFailedOutsideRangeCurrent(0), _uiTimesUsed(), @@ -140,7 +140,7 @@ void TermTelemetry::SetShouldWriteFinalLog(const bool writeLog) // - activityId - Pointer to Guid to set our activity Id to. // Return Value: // - -void TermTelemetry::SetActivityId(const GUID *activityId) +void TermTelemetry::SetActivityId(const GUID* activityId) { _activityId = *activityId; } @@ -192,62 +192,62 @@ void TermTelemetry::WriteFinalTraceLog() const // So just log each enum count separately with its string representation which makes it more human readable. // Set the related activity to NULL since we aren't using it. TraceLoggingWriteActivity(g_hConsoleVirtTermParserEventTraceProvider, - "ControlCodesUsed", - &_activityId, - NULL, - TraceLoggingUInt32(_uiTimesUsed[CUU], "CUU"), - TraceLoggingUInt32(_uiTimesUsed[CUD], "CUD"), - TraceLoggingUInt32(_uiTimesUsed[CUF], "CUF"), - TraceLoggingUInt32(_uiTimesUsed[CUB], "CUB"), - TraceLoggingUInt32(_uiTimesUsed[CNL], "CNL"), - TraceLoggingUInt32(_uiTimesUsed[CPL], "CPL"), - TraceLoggingUInt32(_uiTimesUsed[CHA], "CHA"), - TraceLoggingUInt32(_uiTimesUsed[CUP], "CUP"), - TraceLoggingUInt32(_uiTimesUsed[ED], "ED"), - TraceLoggingUInt32(_uiTimesUsed[EL], "EL"), - TraceLoggingUInt32(_uiTimesUsed[SGR], "SGR"), - TraceLoggingUInt32(_uiTimesUsed[DECSC], "DECSC"), - TraceLoggingUInt32(_uiTimesUsed[DECRC], "DECRC"), - TraceLoggingUInt32(_uiTimesUsed[DECSET], "DECSET"), - TraceLoggingUInt32(_uiTimesUsed[DECRST], "DECRST"), - TraceLoggingUInt32(_uiTimesUsed[DECKPAM], "DECKPAM"), - TraceLoggingUInt32(_uiTimesUsed[DECKPNM], "DECKPNM"), - TraceLoggingUInt32(_uiTimesUsed[DSR], "DSR"), - TraceLoggingUInt32(_uiTimesUsed[DA], "DA"), - TraceLoggingUInt32(_uiTimesUsed[VPA], "VPA"), - TraceLoggingUInt32(_uiTimesUsed[ICH], "ICH"), - TraceLoggingUInt32(_uiTimesUsed[DCH], "DCH"), - TraceLoggingUInt32(_uiTimesUsed[IL], "IL"), - TraceLoggingUInt32(_uiTimesUsed[DL], "DL"), - TraceLoggingUInt32(_uiTimesUsed[SU], "SU"), - TraceLoggingUInt32(_uiTimesUsed[SD], "SD"), - TraceLoggingUInt32(_uiTimesUsed[ANSISYSSC], "ANSISYSSC"), - TraceLoggingUInt32(_uiTimesUsed[ANSISYSRC], "ANSISYSRC"), - TraceLoggingUInt32(_uiTimesUsed[DECSTBM], "DECSTBM"), - TraceLoggingUInt32(_uiTimesUsed[RI], "RI"), - TraceLoggingUInt32(_uiTimesUsed[OSCWT], "OscWindowTitle"), - TraceLoggingUInt32(_uiTimesUsed[HTS], "HTS"), - TraceLoggingUInt32(_uiTimesUsed[CHT], "CHT"), - TraceLoggingUInt32(_uiTimesUsed[CBT], "CBT"), - TraceLoggingUInt32(_uiTimesUsed[TBC], "TBC"), - TraceLoggingUInt32(_uiTimesUsed[ECH], "ECH"), - TraceLoggingUInt32(_uiTimesUsed[DesignateG0], "DesignateG0"), - TraceLoggingUInt32(_uiTimesUsed[DesignateG1], "DesignateG1"), - TraceLoggingUInt32(_uiTimesUsed[DesignateG2], "DesignateG2"), - TraceLoggingUInt32(_uiTimesUsed[DesignateG3], "DesignateG3"), - TraceLoggingUInt32(_uiTimesUsed[HVP], "HVP"), - TraceLoggingUInt32(_uiTimesUsed[DECSTR], "DECSTR"), - TraceLoggingUInt32(_uiTimesUsed[RIS], "RIS"), - TraceLoggingUInt32(_uiTimesUsed[DECSCUSR], "DECSCUSR"), - TraceLoggingUInt32(_uiTimesUsed[DTTERM_WM], "DTTERM_WM"), - TraceLoggingUInt32(_uiTimesUsed[OSCCT], "OscColorTable"), - TraceLoggingUInt32(_uiTimesUsed[OSCSCC], "OscSetCursorColor"), - TraceLoggingUInt32(_uiTimesUsed[OSCRCC], "OscResetCursorColor"), - TraceLoggingUInt32(_uiTimesUsed[OSCFG], "OscForegroundColor"), - TraceLoggingUInt32(_uiTimesUsed[OSCBG], "OscBackgroundColor"), - TraceLoggingUInt32(_uiTimesUsed[REP], "REP"), - TraceLoggingUInt32Array(_uiTimesFailed, ARRAYSIZE(_uiTimesFailed), "Failed"), - TraceLoggingUInt32(_uiTimesFailedOutsideRange, "FailedOutsideRange")); + "ControlCodesUsed", + &_activityId, + NULL, + TraceLoggingUInt32(_uiTimesUsed[CUU], "CUU"), + TraceLoggingUInt32(_uiTimesUsed[CUD], "CUD"), + TraceLoggingUInt32(_uiTimesUsed[CUF], "CUF"), + TraceLoggingUInt32(_uiTimesUsed[CUB], "CUB"), + TraceLoggingUInt32(_uiTimesUsed[CNL], "CNL"), + TraceLoggingUInt32(_uiTimesUsed[CPL], "CPL"), + TraceLoggingUInt32(_uiTimesUsed[CHA], "CHA"), + TraceLoggingUInt32(_uiTimesUsed[CUP], "CUP"), + TraceLoggingUInt32(_uiTimesUsed[ED], "ED"), + TraceLoggingUInt32(_uiTimesUsed[EL], "EL"), + TraceLoggingUInt32(_uiTimesUsed[SGR], "SGR"), + TraceLoggingUInt32(_uiTimesUsed[DECSC], "DECSC"), + TraceLoggingUInt32(_uiTimesUsed[DECRC], "DECRC"), + TraceLoggingUInt32(_uiTimesUsed[DECSET], "DECSET"), + TraceLoggingUInt32(_uiTimesUsed[DECRST], "DECRST"), + TraceLoggingUInt32(_uiTimesUsed[DECKPAM], "DECKPAM"), + TraceLoggingUInt32(_uiTimesUsed[DECKPNM], "DECKPNM"), + TraceLoggingUInt32(_uiTimesUsed[DSR], "DSR"), + TraceLoggingUInt32(_uiTimesUsed[DA], "DA"), + TraceLoggingUInt32(_uiTimesUsed[VPA], "VPA"), + TraceLoggingUInt32(_uiTimesUsed[ICH], "ICH"), + TraceLoggingUInt32(_uiTimesUsed[DCH], "DCH"), + TraceLoggingUInt32(_uiTimesUsed[IL], "IL"), + TraceLoggingUInt32(_uiTimesUsed[DL], "DL"), + TraceLoggingUInt32(_uiTimesUsed[SU], "SU"), + TraceLoggingUInt32(_uiTimesUsed[SD], "SD"), + TraceLoggingUInt32(_uiTimesUsed[ANSISYSSC], "ANSISYSSC"), + TraceLoggingUInt32(_uiTimesUsed[ANSISYSRC], "ANSISYSRC"), + TraceLoggingUInt32(_uiTimesUsed[DECSTBM], "DECSTBM"), + TraceLoggingUInt32(_uiTimesUsed[RI], "RI"), + TraceLoggingUInt32(_uiTimesUsed[OSCWT], "OscWindowTitle"), + TraceLoggingUInt32(_uiTimesUsed[HTS], "HTS"), + TraceLoggingUInt32(_uiTimesUsed[CHT], "CHT"), + TraceLoggingUInt32(_uiTimesUsed[CBT], "CBT"), + TraceLoggingUInt32(_uiTimesUsed[TBC], "TBC"), + TraceLoggingUInt32(_uiTimesUsed[ECH], "ECH"), + TraceLoggingUInt32(_uiTimesUsed[DesignateG0], "DesignateG0"), + TraceLoggingUInt32(_uiTimesUsed[DesignateG1], "DesignateG1"), + TraceLoggingUInt32(_uiTimesUsed[DesignateG2], "DesignateG2"), + TraceLoggingUInt32(_uiTimesUsed[DesignateG3], "DesignateG3"), + TraceLoggingUInt32(_uiTimesUsed[HVP], "HVP"), + TraceLoggingUInt32(_uiTimesUsed[DECSTR], "DECSTR"), + TraceLoggingUInt32(_uiTimesUsed[RIS], "RIS"), + TraceLoggingUInt32(_uiTimesUsed[DECSCUSR], "DECSCUSR"), + TraceLoggingUInt32(_uiTimesUsed[DTTERM_WM], "DTTERM_WM"), + TraceLoggingUInt32(_uiTimesUsed[OSCCT], "OscColorTable"), + TraceLoggingUInt32(_uiTimesUsed[OSCSCC], "OscSetCursorColor"), + TraceLoggingUInt32(_uiTimesUsed[OSCRCC], "OscResetCursorColor"), + TraceLoggingUInt32(_uiTimesUsed[OSCFG], "OscForegroundColor"), + TraceLoggingUInt32(_uiTimesUsed[OSCBG], "OscBackgroundColor"), + TraceLoggingUInt32(_uiTimesUsed[REP], "REP"), + TraceLoggingUInt32Array(_uiTimesFailed, ARRAYSIZE(_uiTimesFailed), "Failed"), + TraceLoggingUInt32(_uiTimesFailedOutsideRange, "FailedOutsideRange")); } } } diff --git a/src/terminal/parser/telemetry.hpp b/src/terminal/parser/telemetry.hpp index 59c8752d3..3627ce822 100644 --- a/src/terminal/parser/telemetry.hpp +++ b/src/terminal/parser/telemetry.hpp @@ -22,7 +22,6 @@ namespace Microsoft::Console::VirtualTerminal { class TermTelemetry sealed { - public: // Implement this as a singleton class. static TermTelemetry& Instance() @@ -91,7 +90,7 @@ namespace Microsoft::Console::VirtualTerminal void Log(const Codes code); void LogFailed(const wchar_t wch); void SetShouldWriteFinalLog(const bool writeLog); - void SetActivityId(const GUID *activityId); + void SetActivityId(const GUID* activityId); unsigned int GetAndResetTimesUsedCurrent(); unsigned int GetAndResetTimesFailedCurrent(); unsigned int GetAndResetTimesFailedOutsideRangeCurrent(); diff --git a/src/terminal/parser/tracing.cpp b/src/terminal/parser/tracing.cpp index 878ad7bad..78feed1e6 100644 --- a/src/terminal/parser/tracing.cpp +++ b/src/terminal/parser/tracing.cpp @@ -13,51 +13,50 @@ ParserTracing::ParserTracing() ParserTracing::~ParserTracing() { - } void ParserTracing::TraceStateChange(_In_ PCWSTR const pwszName) const { - TraceLoggingWrite(g_hConsoleVirtTermParserEventTraceProvider, "StateMachine_EnterState", - TraceLoggingWideString(pwszName), - TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE) - ); + TraceLoggingWrite(g_hConsoleVirtTermParserEventTraceProvider, + "StateMachine_EnterState", + TraceLoggingWideString(pwszName), + TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE)); } void ParserTracing::TraceOnAction(_In_ PCWSTR const pwszName) const { - TraceLoggingWrite(g_hConsoleVirtTermParserEventTraceProvider, "StateMachine_Action", - TraceLoggingWideString(pwszName), - TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE) - ); + TraceLoggingWrite(g_hConsoleVirtTermParserEventTraceProvider, + "StateMachine_Action", + TraceLoggingWideString(pwszName), + TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE)); } void ParserTracing::TraceOnExecute(const wchar_t wch) const { INT16 sch = (INT16)wch; - TraceLoggingWrite(g_hConsoleVirtTermParserEventTraceProvider, "StateMachine_Execute", - TraceLoggingWChar(wch), - TraceLoggingHexInt16(sch), - TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE) - ); + TraceLoggingWrite(g_hConsoleVirtTermParserEventTraceProvider, + "StateMachine_Execute", + TraceLoggingWChar(wch), + TraceLoggingHexInt16(sch), + TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE)); } void ParserTracing::TraceOnExecuteFromEscape(const wchar_t wch) const { INT16 sch = (INT16)wch; - TraceLoggingWrite(g_hConsoleVirtTermParserEventTraceProvider, "StateMachine_ExecuteFromEscape", - TraceLoggingWChar(wch), - TraceLoggingHexInt16(sch), - TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE) - ); + TraceLoggingWrite(g_hConsoleVirtTermParserEventTraceProvider, + "StateMachine_ExecuteFromEscape", + TraceLoggingWChar(wch), + TraceLoggingHexInt16(sch), + TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE)); } void ParserTracing::TraceOnEvent(_In_ PCWSTR const pwszName) const { - TraceLoggingWrite(g_hConsoleVirtTermParserEventTraceProvider, "StateMachine_Event", - TraceLoggingWideString(pwszName), - TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE) - ); + TraceLoggingWrite(g_hConsoleVirtTermParserEventTraceProvider, + "StateMachine_Event", + TraceLoggingWideString(pwszName), + TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE)); } void ParserTracing::TraceCharInput(const wchar_t wch) @@ -65,11 +64,11 @@ void ParserTracing::TraceCharInput(const wchar_t wch) AddSequenceTrace(wch); INT16 sch = (INT16)wch; - TraceLoggingWrite(g_hConsoleVirtTermParserEventTraceProvider, "StateMachine_NewChar", - TraceLoggingWChar(wch), - TraceLoggingHexInt16(sch), - TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE) - ); + TraceLoggingWrite(g_hConsoleVirtTermParserEventTraceProvider, + "StateMachine_NewChar", + TraceLoggingWChar(wch), + TraceLoggingHexInt16(sch), + TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE)); } void ParserTracing::AddSequenceTrace(const wchar_t wch) @@ -86,17 +85,17 @@ void ParserTracing::DispatchSequenceTrace(const bool fSuccess) { if (fSuccess) { - TraceLoggingWrite(g_hConsoleVirtTermParserEventTraceProvider, "StateMachine_Sequence_OK", + TraceLoggingWrite(g_hConsoleVirtTermParserEventTraceProvider, + "StateMachine_Sequence_OK", TraceLoggingWideString(_rgwchSequenceTrace), - TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE) - ); + TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE)); } else { - TraceLoggingWrite(g_hConsoleVirtTermParserEventTraceProvider, "StateMachine_Sequence_FAIL", + TraceLoggingWrite(g_hConsoleVirtTermParserEventTraceProvider, + "StateMachine_Sequence_FAIL", TraceLoggingWideString(_rgwchSequenceTrace), - TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE) - ); + TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE)); } ClearSequenceTrace(); @@ -118,11 +117,11 @@ void ParserTracing::DispatchPrintRunTrace(const wchar_t* const pwsString, const { wchar_t wch = *pwsString; INT16 sch = (INT16)wch; - TraceLoggingWrite(g_hConsoleVirtTermParserEventTraceProvider, "StateMachine_PrintRun", - TraceLoggingWChar(wch), - TraceLoggingHexInt16(sch), - TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE) - ); + TraceLoggingWrite(g_hConsoleVirtTermParserEventTraceProvider, + "StateMachine_PrintRun", + TraceLoggingWChar(wch), + TraceLoggingHexInt16(sch), + TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE)); } else { @@ -142,12 +141,11 @@ void ParserTracing::DispatchPrintRunTrace(const wchar_t* const pwsString, const memcpy(str, pwsString, sizeof(wchar_t) * strLen); str[strLen] = '\0'; - TraceLoggingWrite(g_hConsoleVirtTermParserEventTraceProvider, "StateMachine_PrintRun", + TraceLoggingWrite(g_hConsoleVirtTermParserEventTraceProvider, + "StateMachine_PrintRun", TraceLoggingWideString(str), TraceLoggingValue(strLen), - TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE) - ); - + TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE)); } } } diff --git a/src/terminal/parser/tracing.hpp b/src/terminal/parser/tracing.hpp index b871d41dc..772b2abed 100644 --- a/src/terminal/parser/tracing.hpp +++ b/src/terminal/parser/tracing.hpp @@ -21,7 +21,6 @@ namespace Microsoft::Console::VirtualTerminal class ParserTracing sealed { public: - ParserTracing(); ~ParserTracing(); @@ -42,7 +41,5 @@ namespace Microsoft::Console::VirtualTerminal wchar_t _rgwchSequenceTrace[s_cMaxSequenceTrace]; size_t _cchSequenceTrace; - - }; } diff --git a/src/terminal/parser/ut_parser/InputEngineTest.cpp b/src/terminal/parser/ut_parser/InputEngineTest.cpp index 9e7de77a0..bee06f35f 100644 --- a/src/terminal/parser/ut_parser/InputEngineTest.cpp +++ b/src/terminal/parser/ut_parser/InputEngineTest.cpp @@ -92,8 +92,7 @@ public: } } Log::Comment( - NoThrowString().Format(L"\tvtseq: \"%s\"(%zu)", vtseq.c_str(), vtseq.length()) - ); + NoThrowString().Format(L"\tvtseq: \"%s\"(%zu)", vtseq.c_str(), vtseq.length())); _stateMachine->ProcessString(&vtseq[0], vtseq.length()); Log::Comment(L"String processed"); @@ -109,8 +108,7 @@ public: Log::Comment( NoThrowString().Format(L"\texpected:\t") + - VerifyOutputTraits::ToString(irExpected) - ); + VerifyOutputTraits::ToString(irExpected)); // Look for an equivalent input record. // Differences between left and right modifiers are ignored, as long as one is pressed. @@ -119,8 +117,7 @@ public: { Log::Comment( NoThrowString().Format(L"\tActual :\t") + - VerifyOutputTraits::ToString(inRec) - ); + VerifyOutputTraits::ToString(inRec)); bool areEqual = (irExpected.EventType == inRec.EventType) && @@ -148,17 +145,13 @@ public: { Log::Comment( NoThrowString().Format(L"\texpected:\t") + - VerifyOutputTraits::ToString(expected) - ); - + VerifyOutputTraits::ToString(expected)); } INPUT_RECORD irExpected = vExpectedInput.front(); Log::Comment( NoThrowString().Format(L"\tLooking for:\t") + - VerifyOutputTraits::ToString(irExpected) - ); - + VerifyOutputTraits::ToString(irExpected)); // Look for an equivalent input record. // Differences between left and right modifiers are ignored, as long as one is pressed. @@ -167,8 +160,7 @@ public: { Log::Comment( NoThrowString().Format(L"\tActual :\t") + - VerifyOutputTraits::ToString(inRec) - ); + VerifyOutputTraits::ToString(inRec)); bool areEqual = (irExpected.EventType == inRec.EventType) && @@ -186,8 +178,7 @@ public: irExpected = vExpectedInput.front(); Log::Comment( NoThrowString().Format(L"\tLooking for:\t") + - VerifyOutputTraits::ToString(irExpected) - ); + VerifyOutputTraits::ToString(irExpected)); } } } @@ -214,7 +205,6 @@ class Microsoft::Console::VirtualTerminal::InputEngineTest void TestInputCallback(std::deque>& inEvents); void TestInputStringCallback(std::deque>& inEvents); - TEST_CLASS_SETUP(ClassSetup) { return true; @@ -243,7 +233,6 @@ class Microsoft::Console::VirtualTerminal::InputEngineTest friend class TestInteractDispatch; }; - class Microsoft::Console::VirtualTerminal::TestInteractDispatch final : public IInteractDispatch { public: @@ -270,7 +259,6 @@ TestInteractDispatch::TestInteractDispatch(_In_ std::function>& inputEvents) @@ -292,10 +280,9 @@ bool TestInteractDispatch::WindowManipulation(const DispatchTypes::WindowManipul _In_reads_(cParams) const unsigned short* const rgusParams, const size_t cParams) { - VERIFY_ARE_EQUAL(true, _testState->_expectedToCallWindowManipulation); VERIFY_ARE_EQUAL(_testState->_expectedWindowManipulation, uiFunction); - for(size_t i = 0; i < cParams; i++) + for (size_t i = 0; i < cParams; i++) { VERIFY_ARE_EQUAL(_testState->_expectedParams[i], rgusParams[i]); } @@ -350,23 +337,23 @@ void InputEngineTest::C0Test() wchar_t expectedWch = wch + 0x40; bool writeCtrl = true; // These two are weird exceptional cases. - switch(wch) + switch (wch) { - case L'\r': // Enter - expectedWch = wch; - writeCtrl = false; - break; - case L'\x1b': // Escape - expectedWch = wch; - writeCtrl = false; - break; - case L'\t': // Tab - writeCtrl = false; - break; + case L'\r': // Enter + expectedWch = wch; + writeCtrl = false; + break; + case L'\x1b': // Escape + expectedWch = wch; + writeCtrl = false; + break; + case L'\t': // Tab + writeCtrl = false; + break; } short keyscan = VkKeyScanW(expectedWch); - short vkey = keyscan & 0xff; + short vkey = keyscan & 0xff; short keyscanModifiers = (keyscan >> 8) & 0xff; WORD scanCode = (WORD)MapVirtualKeyW(vkey, MAPVK_VK_TO_VSC); @@ -377,7 +364,7 @@ void InputEngineTest::C0Test() } // If we need to press shift for this key, but not on alphabetical chars // Eg simulating C-z, not C-S-z. - if (WI_IsFlagSet(keyscanModifiers, 1) && (expectedWch < L'A' || expectedWch > L'Z' )) + if (WI_IsFlagSet(keyscanModifiers, 1) && (expectedWch < L'A' || expectedWch > L'Z')) { dwModifierState = WI_SetFlag(dwModifierState, SHIFT_PRESSED); } @@ -387,16 +374,20 @@ void InputEngineTest::C0Test() { Log::Comment(NoThrowString().Format( L"We used to expect 0x%x, 0x%x, 0x%x, 0x%x here", - vkey, scanCode, wch, dwModifierState - )); + vkey, + scanCode, + wch, + dwModifierState)); vkey = 'C'; scanCode = 0; wch = UNICODE_ETX; dwModifierState = LEFT_CTRL_PRESSED; Log::Comment(NoThrowString().Format( L"Now we expect 0x%x, 0x%x, 0x%x, 0x%x here", - vkey, scanCode, wch, dwModifierState - )); + vkey, + scanCode, + wch, + dwModifierState)); testState._expectSendCtrlC = true; } else @@ -420,7 +411,6 @@ void InputEngineTest::C0Test() testState.vExpectedInput.push_back(inputRec); _stateMachine->ProcessString(&inputSeq[0], inputSeq.length()); - } } @@ -441,15 +431,15 @@ void InputEngineTest::AlphanumericTest() std::wstring inputSeq = std::wstring(&wch, 1); short keyscan = VkKeyScanW(wch); - short vkey = keyscan & 0xff; + short vkey = keyscan & 0xff; WORD scanCode = (wchar_t)MapVirtualKeyW(vkey, MAPVK_VK_TO_VSC); short keyscanModifiers = (keyscan >> 8) & 0xff; // Because of course, these are not the same flags. DWORD dwModifierState = 0 | - (WI_IsFlagSet(keyscanModifiers, 1) ? SHIFT_PRESSED : 0) | - (WI_IsFlagSet(keyscanModifiers, 2) ? LEFT_CTRL_PRESSED : 0) | - (WI_IsFlagSet(keyscanModifiers, 4) ? LEFT_ALT_PRESSED : 0) ; + (WI_IsFlagSet(keyscanModifiers, 1) ? SHIFT_PRESSED : 0) | + (WI_IsFlagSet(keyscanModifiers, 2) ? LEFT_CTRL_PRESSED : 0) | + (WI_IsFlagSet(keyscanModifiers, 4) ? LEFT_ALT_PRESSED : 0); Log::Comment(NoThrowString().Format(L"Testing char 0x%x", wch)); Log::Comment(NoThrowString().Format(L"Input Sequence=\"%s\"", inputSeq.c_str())); @@ -467,7 +457,6 @@ void InputEngineTest::AlphanumericTest() _stateMachine->ProcessString(&inputSeq[0], inputSeq.length()); } - } void InputEngineTest::RoundTripTest() @@ -499,7 +488,7 @@ void InputEngineTest::RoundTripTest() // A-Z need shift pressed in addition to the 'a'-'z' chars. uiActualKeystate = WI_SetFlag(uiActualKeystate, SHIFT_PRESSED); } - else if (vkey == VK_CANCEL || vkey == VK_PAUSE) + else if (vkey == VK_CANCEL || vkey == VK_PAUSE) { uiActualKeystate = WI_SetFlag(uiActualKeystate, LEFT_CTRL_PRESSED); } @@ -520,8 +509,7 @@ void InputEngineTest::RoundTripTest() Log::Comment( NoThrowString().Format(L"Expecting:: ") + - VerifyOutputTraits::ToString(irTest) - ); + VerifyOutputTraits::ToString(irTest)); testState.vExpectedInput.clear(); testState.vExpectedInput.push_back(irTest); @@ -529,7 +517,6 @@ void InputEngineTest::RoundTripTest() auto inputKey = IInputEvent::Create(irTest); terminalInput.HandleKey(inputKey.get()); } - } void InputEngineTest::WindowManipulationTest() @@ -545,8 +532,7 @@ void InputEngineTest::WindowManipulationTest() Log::Comment(NoThrowString().Format( L"Try sending a bunch of Window Manipulation sequences. " L"Only the valid ones should call the " - L"TestInteractDispatch::WindowManipulation callback." - )); + L"TestInteractDispatch::WindowManipulation callback.")); bool fValidType = false; @@ -555,7 +541,7 @@ void InputEngineTest::WindowManipulationTest() const wchar_t* const wszParam1 = L"123"; const wchar_t* const wszParam2 = L"456"; - for(unsigned int i = 0; i < static_cast(BYTE_MAX); i++) + for (unsigned int i = 0; i < static_cast(BYTE_MAX); i++) { if (i == DispatchTypes::WindowManipulationType::ResizeWindowInCharacters) { @@ -565,7 +551,6 @@ void InputEngineTest::WindowManipulationTest() std::wstringstream seqBuilder; seqBuilder << L"\x1b[" << i; - if (i == DispatchTypes::WindowManipulationType::ResizeWindowInCharacters) { // We need to build the string with the params as strings for some reason - @@ -596,8 +581,7 @@ void InputEngineTest::WindowManipulationTest() seqBuilder << L"t"; std::wstring seq = seqBuilder.str(); Log::Comment(NoThrowString().Format( - L"Processing \"%s\"", seq.c_str() - )); + L"Processing \"%s\"", seq.c_str())); _stateMachine->ProcessString(&seq[0], seq.length()); } } @@ -613,7 +597,7 @@ void InputEngineTest::NonAsciiTest() testState._stateMachine = _stateMachine.get(); Log::Comment(L"Sending various non-ascii strings, and seeing what we get out"); - INPUT_RECORD proto = {0}; + INPUT_RECORD proto = { 0 }; proto.EventType = KEY_EVENT; proto.Event.KeyEvent.dwControlKeyState = 0; proto.Event.KeyEvent.wRepeatCount = 1; @@ -625,8 +609,7 @@ void InputEngineTest::NonAsciiTest() Log::Comment(NoThrowString().Format( L"We're sending utf-16 characters here, because the VtInputThread has " - L"already converted the ut8 input to utf16 by the time it calls the state machine." - )); + L"already converted the ut8 input to utf16 by the time it calls the state machine.")); // "Л", UTF-16: 0x041B, utf8: "\xd09b" std::wstring utf8Input = L"\x041B"; @@ -634,8 +617,7 @@ void InputEngineTest::NonAsciiTest() test.Event.KeyEvent.uChar.UnicodeChar = utf8Input[0]; Log::Comment(NoThrowString().Format( - L"Processing \"%s\"", utf8Input.c_str() - )); + L"Processing \"%s\"", utf8Input.c_str())); testState.vExpectedInput.clear(); testState.vExpectedInput.push_back(test); @@ -649,8 +631,7 @@ void InputEngineTest::NonAsciiTest() test.Event.KeyEvent.uChar.UnicodeChar = utf8Input[0]; Log::Comment(NoThrowString().Format( - L"Processing \"%s\"", utf8Input.c_str() - )); + L"Processing \"%s\"", utf8Input.c_str())); testState.vExpectedInput.clear(); testState.vExpectedInput.push_back(test); @@ -676,16 +657,14 @@ void InputEngineTest::CursorPositioningTest() L"Try sending a cursor position response, then send it again. " L"The first time, it should be interpreted as a cursor position. " L"The state machine engine should reset itself to normal operation " - L"after that, and treat the second as an F3." - )); + L"after that, and treat the second as an F3.")); std::wstring seq = L"\x1b[1;4R"; testState._expectCursorPosition = true; testState._expectedCursor = { 4, 1 }; Log::Comment(NoThrowString().Format( - L"Processing \"%s\"", seq.c_str() - )); + L"Processing \"%s\"", seq.c_str())); _stateMachine->ProcessString(&seq[0], seq.length()); testState._expectCursorPosition = false; @@ -701,8 +680,7 @@ void InputEngineTest::CursorPositioningTest() testState.vExpectedInput.push_back(inputRec); Log::Comment(NoThrowString().Format( - L"Processing \"%s\"", seq.c_str() - )); + L"Processing \"%s\"", seq.c_str())); _stateMachine->ProcessString(&seq[0], seq.length()); } @@ -730,8 +708,7 @@ void InputEngineTest::CSICursorBackTabTest() const std::wstring seq = L"\x1b[Z"; Log::Comment(NoThrowString().Format( - L"Processing \"%s\"", seq.c_str() - )); + L"Processing \"%s\"", seq.c_str())); _stateMachine->ProcessString(&seq[0], seq.length()); } diff --git a/src/terminal/parser/ut_parser/OutputEngineTest.cpp b/src/terminal/parser/ut_parser/OutputEngineTest.cpp index 84fed5c35..6139db843 100644 --- a/src/terminal/parser/ut_parser/OutputEngineTest.cpp +++ b/src/terminal/parser/ut_parser/OutputEngineTest.cpp @@ -145,11 +145,10 @@ class Microsoft::Console::VirtualTerminal::OutputEngineTest final } mach.ProcessCharacter(AsciiChars::ESC); - if(shouldEscapeOut) + if (shouldEscapeOut) { VERIFY_ARE_EQUAL(mach._state, StateMachine::VTStates::Escape); } - } TEST_METHOD(TestEscapeImmediatePath) @@ -193,7 +192,6 @@ class Microsoft::Console::VirtualTerminal::OutputEngineTest final VERIFY_ARE_EQUAL(mach._state, StateMachine::VTStates::Ground); } - TEST_METHOD(TestGroundPrint) { StateMachine mach(new OutputStateMachineEngine(new DummyDispatch)); @@ -602,7 +600,6 @@ class Microsoft::Console::VirtualTerminal::OutputEngineTest final class StatefulDispatch final : public TermDispatch { public: - virtual void Execute(const wchar_t /*wchControl*/) override { } @@ -765,7 +762,8 @@ public: return true; } - bool SetGraphicsRendition(_In_reads_(cOptions) const DispatchTypes::GraphicsOptions* const rgOptions, const size_t cOptions) override + bool SetGraphicsRendition(_In_reads_(cOptions) const DispatchTypes::GraphicsOptions* const rgOptions, + const size_t cOptions) override { size_t cCopyLength = std::min(cOptions, s_cMaxOptions); // whichever is smaller, our buffer size or the number given _cOptions = cCopyLength; @@ -794,7 +792,7 @@ public: bool _PrivateModeParamsHelper(_In_ DispatchTypes::PrivateModeParams const param, const bool fEnable) { bool fSuccess = false; - switch(param) + switch (param) { case DispatchTypes::PrivateModeParams::DECCKM_CursorKeysMode: // set - Enable Application Mode, reset - Numeric/normal mode @@ -810,7 +808,7 @@ public: fSuccess = CursorVisibility(fEnable); break; case DispatchTypes::PrivateModeParams::ASB_AlternateScreenBuffer: - fSuccess = fEnable? UseAlternateScreenBuffer() : UseMainScreenBuffer(); + fSuccess = fEnable ? UseAlternateScreenBuffer() : UseMainScreenBuffer(); break; default: // If no functions to call, overall dispatch was a failure. @@ -827,17 +825,19 @@ public: size_t cFailures = 0; for (size_t i = 0; i < cParams; i++) { - cFailures += _PrivateModeParamsHelper(rParams[i], fEnable)? 0 : 1; // increment the number of failures if we fail. + cFailures += _PrivateModeParamsHelper(rParams[i], fEnable) ? 0 : 1; // increment the number of failures if we fail. } return cFailures == 0; } - bool SetPrivateModes(_In_reads_(cParams) const DispatchTypes::PrivateModeParams* const rParams, const size_t cParams) override + bool SetPrivateModes(_In_reads_(cParams) const DispatchTypes::PrivateModeParams* const rParams, + const size_t cParams) override { return _SetResetPrivateModesHelper(rParams, cParams, true); } - bool ResetPrivateModes(_In_reads_(cParams) const DispatchTypes::PrivateModeParams* const rParams, const size_t cParams) override + bool ResetPrivateModes(_In_reads_(cParams) const DispatchTypes::PrivateModeParams* const rParams, + const size_t cParams) override { return _SetResetPrivateModesHelper(rParams, cParams, false); } @@ -975,7 +975,8 @@ class StateMachineExternalTest final } } - void TestCsiCursorMovement(wchar_t const wchCommand, unsigned int const uiDistance, + void TestCsiCursorMovement(wchar_t const wchCommand, + unsigned int const uiDistance, const bool fUseDistance, const bool* const pfFlag, StateMachine& mach, @@ -1327,14 +1328,13 @@ class StateMachineExternalTest final mach.ProcessCharacter(wchOp); - VERIFY_IS_TRUE(*pfOperationCallback); VERIFY_ARE_EQUAL(expectedDispatchTypes, pDispatch->_eraseType); } void VerifyDispatchTypes(_In_reads_(cExpectedOptions) const DispatchTypes::GraphicsOptions* const rgExpectedOptions, - const size_t cExpectedOptions, - const StatefulDispatch& dispatch) + const size_t cExpectedOptions, + const StatefulDispatch& dispatch) { VERIFY_ARE_EQUAL(cExpectedOptions, dispatch._cOptions); bool fOptionsValid = true; @@ -1684,7 +1684,6 @@ class StateMachineExternalTest final mach.ProcessCharacter(L'm'); - VERIFY_IS_TRUE(pDispatch->_fSetGraphics); VERIFY_IS_FALSE(pDispatch->_fEraseDisplay); VerifyDispatchTypes(rgExpected, 2, *pDispatch); @@ -1698,6 +1697,5 @@ class StateMachineExternalTest final VERIFY_ARE_EQUAL(expectedDispatchTypes, pDispatch->_eraseType); pDispatch->ClearState(); - } }; diff --git a/src/tools/buffersize/main.cpp b/src/tools/buffersize/main.cpp index 6f7dfa8be..b833e890b 100644 --- a/src/tools/buffersize/main.cpp +++ b/src/tools/buffersize/main.cpp @@ -7,8 +7,8 @@ #include #include #include -#include /* srand, rand */ -#include /* time */ +#include /* srand, rand */ +#include /* time */ #include #include @@ -37,7 +37,7 @@ void printCSI(std::string seq) void printCUP(int x, int y) { - printf("\x1b[%d;%dH", y+1, x+1); // save cursor + printf("\x1b[%d;%dH", y + 1, x + 1); // save cursor } void print256color(int bg) @@ -69,32 +69,35 @@ int __cdecl wmain(int /*argc*/, WCHAR* /*argv[]*/) std::string topBorder = std::string(width, '-'); std::string bottomBorder = std::string(width, '='); - + int color = 17; int const colorStep = 1; printf("Buffer size is wxh=%dx%d\n", width, height); printCSI("s"); // save cursor printCSI("H"); // Go Home - print256color(color); color += colorStep; + print256color(color); + color += colorStep; printf("%s", topBorder.c_str()); - printCUP(0, height-1); - print256color(color); color += colorStep; + printCUP(0, height - 1); + print256color(color); + color += colorStep; printf("%s", bottomBorder.c_str()); - for (int y = 1; y < height-1; y++) + for (int y = 1; y < height - 1; y++) { printCUP(0, y); - print256color(color); color += colorStep; + print256color(color); + color += colorStep; printf("L"); - - printCUP(width-1, y); - print256color(color); color += colorStep; + + printCUP(width - 1, y); + print256color(color); + color += colorStep; printf("R\n"); } printCSI("u"); // restore cursor printCSI("m"); // restore color - } return 0; diff --git a/src/tools/closetest/closetest.cpp b/src/tools/closetest/closetest.cpp index 476ed3a71..8ad7b22b2 100644 --- a/src/tools/closetest/closetest.cpp +++ b/src/tools/closetest/closetest.cpp @@ -213,44 +213,48 @@ static std::wstring g_pipestr; static HANDLE g_hLogging = INVALID_HANDLE_VALUE; static int g_childNum; -static const wchar_t *const kChildDivider = L"--"; -static const wchar_t *const kChildCommand_Job = L"j"; -static const wchar_t *const kChildCommand_Read = L"r"; -static const wchar_t *const kChildCommand_Hold = L"h"; +static const wchar_t* const kChildDivider = L"--"; +static const wchar_t* const kChildCommand_Job = L"j"; +static const wchar_t* const kChildCommand_Read = L"r"; +static const wchar_t* const kChildCommand_Hold = L"h"; -struct PipeHandles { +struct PipeHandles +{ HANDLE rh; HANDLE wh; }; -static PipeHandles createPipe() { - PipeHandles ret {}; +static PipeHandles createPipe() +{ + PipeHandles ret{}; const BOOL success = CreatePipe(&ret.rh, &ret.wh, nullptr, 0); UNREFERENCED_PARAMETER(success); // to make release builds happy. assert(success && "CreatePipe failed"); return ret; } -static HANDLE makeJob() { +static HANDLE makeJob() +{ HANDLE job = CreateJobObjectW(nullptr, nullptr); assert(job); - JOBOBJECT_EXTENDED_LIMIT_INFORMATION info {}; + JOBOBJECT_EXTENDED_LIMIT_INFORMATION info{}; info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_BREAKAWAY_OK | JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK | JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION | JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; BOOL success = SetInformationJobObject(job, - JobObjectExtendedLimitInformation, - &info, - sizeof(info)); + JobObjectExtendedLimitInformation, + &info, + sizeof(info)); UNREFERENCED_PARAMETER(success); // to make release builds happy. assert(success && "SetInformationJobObject failed"); return job; } -static std::wstring exeName() { - std::array self {}; +static std::wstring exeName() +{ + std::array self{}; DWORD len = GetModuleFileNameW(nullptr, self.data(), (DWORD)self.size()); UNREFERENCED_PARAMETER(len); // to make release builds happy. assert(len >= 1 && len < self.size() && "GetModuleFileNameW failed"); @@ -264,8 +268,9 @@ static std::wstring exeName() { #endif #define TRACE(fmt, ...) trace("closetest: " fmt, ##__VA_ARGS__) -static void trace(const char *fmt, ...) PL_PRINTF_FORMAT(1, 2); -static void trace(const char *fmt, ...) { +static void trace(const char* fmt, ...) PL_PRINTF_FORMAT(1, 2); +static void trace(const char* fmt, ...) +{ std::array buf; int written = 0; va_list ap; @@ -286,7 +291,8 @@ static void trace(const char *fmt, ...) { OutputDebugStringA(buf.data()); } -static std::vector getConsoleProcessList() { +static std::vector getConsoleProcessList() +{ std::vector ret; ret.resize(1); const DWORD count1 = GetConsoleProcessList(&ret[0], (DWORD)ret.size()); @@ -297,10 +303,13 @@ static std::vector getConsoleProcessList() { return ret; } -static void dumpConsoleProcessList() { +static void dumpConsoleProcessList() +{ std::string msg; - for (DWORD pid : getConsoleProcessList()) { - if (!msg.empty()) { + for (DWORD pid : getConsoleProcessList()) + { + if (!msg.empty()) + { msg += ", "; } msg += std::to_string(pid); @@ -308,23 +317,34 @@ static void dumpConsoleProcessList() { TRACE("attached process list: %s", msg.c_str()); } -static std::wstring argvToCommandLine(const std::vector &argv) { +static std::wstring argvToCommandLine(const std::vector& argv) +{ std::wstring ret; - for (const auto &arg : argv) { + for (const auto& arg : argv) + { // Strictly incorrect, but good enough. - if (!ret.empty()) { + if (!ret.empty()) + { ret.push_back(L' '); } const bool quote = arg.empty() || arg.find(L' ') != std::wstring::npos; - if (quote) { ret.push_back(L'\"'); } + if (quote) + { + ret.push_back(L'\"'); + } ret.append(arg); - if (quote) { ret.push_back(L'\"'); } + if (quote) + { + ret.push_back(L'\"'); + } } return ret; } -static void spawnChildTree(DWORD masterPid, const std::vector &extraArgs) { - if (extraArgs.empty()) { +static void spawnChildTree(DWORD masterPid, const std::vector& extraArgs) +{ + if (extraArgs.empty()) + { return; } @@ -348,11 +368,10 @@ static void spawnChildTree(DWORD masterPid, const std::vector &ext //TRACE("spawning: %ls", cmdline.c_str()); - BOOL success {}; - STARTUPINFOW sui { sizeof(sui) }; - PROCESS_INFORMATION pi {}; - success = CreateProcessW(exeName().c_str(), &cmdline[0], nullptr, nullptr, FALSE, - 0, nullptr, nullptr, &sui, &pi); + BOOL success{}; + STARTUPINFOW sui{ sizeof(sui) }; + PROCESS_INFORMATION pi{}; + success = CreateProcessW(exeName().c_str(), &cmdline[0], nullptr, nullptr, FALSE, 0, nullptr, nullptr, &sui, &pi); assert(success && "CreateProcessW failed"); const DWORD waitRet = WaitForSingleObject(readyEvent, INFINITE); @@ -363,9 +382,11 @@ static void spawnChildTree(DWORD masterPid, const std::vector &ext } // Split args up into children and spawn each child as a sibling. -static void spawnSiblings(DWORD masterPid, const std::vector &args) { +static void spawnSiblings(DWORD masterPid, const std::vector& args) +{ auto it = args.begin(); - while (it != args.end()) { + while (it != args.end()) + { assert(*it == kChildDivider); const auto itEnd = std::find(it + 1, args.end(), kChildDivider); const std::vector child(it, itEnd); @@ -374,7 +395,8 @@ static void spawnSiblings(DWORD masterPid, const std::vector &args } } -static void genChild(int n, const std::wstring &desc, int allocChunk, std::vector &out) { +static void genChild(int n, const std::wstring& desc, int allocChunk, std::vector& out) +{ assert(desc != kChildDivider); // A divider as the desc would break spawnSiblings's parsing. out.push_back(kChildDivider); out.push_back(std::to_wstring(n)); @@ -382,8 +404,13 @@ static void genChild(int n, const std::wstring &desc, int allocChunk, std::vecto out.push_back(std::to_wstring(allocChunk / 1024)); } -static void genBatch(bool forward, bool useJob, bool useGapProcess, int allocChunk, - std::vector &out, std::vector &handles) { +static void genBatch(bool forward, + bool useJob, + bool useGapProcess, + int allocChunk, + std::vector& out, + std::vector& handles) +{ static int cnt = 1; const PipeHandles pipe = createPipe(); @@ -394,10 +421,13 @@ static void genBatch(bool forward, bool useJob, bool useGapProcess, int allocChu auto genVictim = [&](int n, int /*n2*/) { genChild(n, L"", allocChunk, out); - if (useJob) { + if (useJob) + { out.push_back(kChildCommand_Job); out.push_back(std::to_wstring((uintptr_t)job)); - } else { + } + else + { out.push_back(kChildCommand_Read); out.push_back(std::to_wstring((uintptr_t)pipe.rh)); } @@ -415,15 +445,20 @@ static void genBatch(bool forward, bool useJob, bool useGapProcess, int allocChu const int gap = cnt + 1; const int second = cnt + 1 + useGapProcess; - if (forward) { + if (forward) + { genKiller(first, second); - if (useGapProcess) { + if (useGapProcess) + { genChild(gap, L"", allocChunk, out); } genVictim(second, first); - } else { + } + else + { genVictim(first, second); - if (useGapProcess) { + if (useGapProcess) + { genChild(gap, L"", allocChunk, out); } genKiller(second, first); @@ -431,8 +466,10 @@ static void genBatch(bool forward, bool useJob, bool useGapProcess, int allocChu cnt += 2 + useGapProcess; } -static BOOL WINAPI ctrlHandler(DWORD type) { - if (type == CTRL_CLOSE_EVENT) { +static BOOL WINAPI ctrlHandler(DWORD type) +{ + if (type == CTRL_CLOSE_EVENT) + { TRACE("child %d: CTRL_CLOSE_EVENT received, pausing...", g_childNum); Sleep(250); TRACE("child %d: CTRL_CLOSE_EVENT received, exiting...", g_childNum); @@ -443,52 +480,58 @@ static BOOL WINAPI ctrlHandler(DWORD type) { // Duplicate a handle from `srcProc` into a non-inheritable handle in the // current process. -static HANDLE duplicateHandle(HANDLE srcProc, HANDLE srcHandle) { - HANDLE ret {}; +static HANDLE duplicateHandle(HANDLE srcProc, HANDLE srcHandle) +{ + HANDLE ret{}; const auto success = - DuplicateHandle(srcProc, srcHandle, - GetCurrentProcess(), &ret, - 0, FALSE, DUPLICATE_SAME_ACCESS); + DuplicateHandle(srcProc, srcHandle, GetCurrentProcess(), &ret, 0, FALSE, DUPLICATE_SAME_ACCESS); assert(success && "DuplicateHandle failed"); return ret; } -static HANDLE openProcess(DWORD pid) { +static HANDLE openProcess(DWORD pid) +{ const HANDLE ret = OpenProcess(PROCESS_DUP_HANDLE, FALSE, pid); assert(ret != nullptr && "OpenProcess failed"); return ret; } -static std::deque getCommandLine() { +static std::deque getCommandLine() +{ // Link with Shell32.lib for CommandLineToArgvW. std::deque ret; const auto cmdline = GetCommandLineW(); - int argc {}; + int argc{}; const auto argv = CommandLineToArgvW(cmdline, &argc); - for (int i = 0; i < argc; ++i) { + for (int i = 0; i < argc; ++i) + { ret.push_back(argv[i]); } LocalFree((HLOCAL)argv); return ret; } -template -static T shift(std::deque &container) { +template +static T shift(std::deque& container) +{ assert(!container.empty()); T ret = container.front(); container.pop_front(); return ret; } -static int shiftInt(std::deque &container) { +static int shiftInt(std::deque& container) +{ return _wtoi(shift(container).c_str()); } -static HANDLE shiftHandle(std::deque &container) { +static HANDLE shiftHandle(std::deque& container) +{ return (HANDLE)(uintptr_t)shiftInt(container); } -static int doChild(std::deque argv) { +static int doChild(std::deque argv) +{ // closetest.exe --child -- [cmd arg] [...] shift(argv); assert(shift(argv) == L"--child"); @@ -518,30 +561,38 @@ static int doChild(std::deque argv) { SetConsoleCtrlHandler(ctrlHandler, TRUE); - TRACE("child %d: attached to console%ls", g_childNum, - desc.empty() ? L"" : (std::wstring(L" (") + desc + L")").c_str()); + TRACE("child %d: attached to console%ls", g_childNum, desc.empty() ? L"" : (std::wstring(L" (") + desc + L")").c_str()); - if (allocChunk > 0) { + if (allocChunk > 0) + { // Slow process termination down by allocating a chunk of memory. - char *buf = new char[allocChunk]; + char* buf = new char[allocChunk]; memset(buf, 0xcc, allocChunk); } HANDLE readHandle = nullptr; HANDLE jobHandle = nullptr; - while (!argv.empty() && argv.front() != kChildDivider) { + while (!argv.empty() && argv.front() != kChildDivider) + { const auto cmd = shift(argv); - if (cmd == kChildCommand_Hold) { + if (cmd == kChildCommand_Hold) + { // Duplicate the handle into this process, then forget it. duplicateHandle(masterProc, shiftHandle(argv)); - } else if (cmd == kChildCommand_Read) { + } + else if (cmd == kChildCommand_Read) + { assert(readHandle == nullptr); readHandle = duplicateHandle(masterProc, shiftHandle(argv)); - } else if (cmd == kChildCommand_Job) { + } + else if (cmd == kChildCommand_Job) + { assert(jobHandle == nullptr); jobHandle = duplicateHandle(masterProc, shiftHandle(argv)); - } else { + } + else + { TRACE("Invalid child command: %ls", cmd.c_str()); exit(1); } @@ -550,7 +601,8 @@ static int doChild(std::deque argv) { spawnChildTree(masterPid, std::vector(argv.begin(), argv.end())); // Assign self to a job object. - if (jobHandle != nullptr) { + if (jobHandle != nullptr) + { const BOOL success = AssignProcessToJobObject(jobHandle, GetCurrentProcess()); assert(success && "AssignProcessToJobObject failed"); @@ -570,19 +622,23 @@ static int doChild(std::deque argv) { CloseHandle(readyEvent); readyEvent = nullptr; - if (readHandle != nullptr) { - char buf {}; - DWORD actual {}; + if (readHandle != nullptr) + { + char buf{}; + DWORD actual{}; ReadFile(readHandle, &buf, sizeof(buf), &actual, nullptr); TRACE("child %d: ReadFile() returned, exiting...", g_childNum); - } else { + } + else + { Sleep(300 * 1000); } return 0; } -static void usage() { +static void usage() +{ printf("usage: %ls [options]\n", exeName().c_str()); printf("Options:\n"); printf(" -n NUM_BATCHES Start NUM_BATCHES batches of processes [default: 4]\n"); @@ -605,8 +661,8 @@ static void usage() { printf(" --no-realloc Skip free/alloc console to break out of the initial session\n"); } -static int doParent(std::deque argv) { - +static int doParent(std::deque argv) +{ int numBatches = 4; int dir = 0; bool useJob = false; @@ -617,46 +673,88 @@ static int doParent(std::deque argv) { // Parse arguments shift(argv); // discard the program name. - while (!argv.empty()) { + while (!argv.empty()) + { const auto arg = shift(argv); const auto hasNext = !argv.empty(); - if (arg == L"--help" || arg == L"-h") { + if (arg == L"--help" || arg == L"-h") + { usage(); exit(0); - } else if (arg == L"-n" && hasNext) { + } + else if (arg == L"-n" && hasNext) + { numBatches = shiftInt(argv); - } else if (arg == L"-d" && hasNext) { + } + else if (arg == L"-d" && hasNext) + { const auto next = shift(argv); - if (next == L"forward") { dir = 1; } - else if (next == L"backward") { dir = 2; } - else if (next == L"alternate") { dir = 3; } - else if (next == L"none") { dir = 0; } - else { + if (next == L"forward") + { + dir = 1; + } + else if (next == L"backward") + { + dir = 2; + } + else if (next == L"alternate") + { + dir = 3; + } + else if (next == L"none") + { + dir = 0; + } + else + { fprintf(stderr, "error: unrecognized -d argument: %ls\n", next.c_str()); exit(1); } - } else if (arg == L"--gap") { + } + else if (arg == L"--gap") + { useGapProcess = true; - } else if (arg == L"--no-gap") { + } + else if (arg == L"--no-gap") + { useGapProcess = false; - } else if (arg == L"--alloc" && hasNext) { + } + else if (arg == L"--alloc" && hasNext) + { const auto next = shift(argv); allocChunk = (int)(_wtof(next.c_str()) * 1024.0 * 1024.0); - } else if (arg == L"-m" && hasNext) { + } + else if (arg == L"-m" && hasNext) + { const auto next = shift(argv); - if (next == L"pipe") { useJob = false; } - else if (next == L"job") { useJob = true; } - else { + if (next == L"pipe") + { + useJob = false; + } + else if (next == L"job") + { + useJob = true; + } + else + { fprintf(stderr, "error: unrecognized -m argument: %ls\n", next.c_str()); exit(1); } } - else if (arg == L"--graph" && hasNext) { + else if (arg == L"--graph" && hasNext) + { const auto next = shift(argv); - if (next == L"tree") { useSiblings = false; } - else if (next == L"list") { useSiblings = true; } - else { + if (next == L"tree") + { + useSiblings = false; + } + else if (next == L"list") + { + useSiblings = true; + } + else + { fprintf(stderr, "error: unrecognized --graph argument: %ls\n", next.c_str()); exit(1); } @@ -688,7 +786,8 @@ static int doParent(std::deque argv) { { noRealloc = true; } - else { + else + { usage(); fprintf(stderr, "\nerror: unrecognized argument: %ls\n", arg.c_str()); exit(1); @@ -698,14 +797,18 @@ static int doParent(std::deque argv) { // Decide which children to start. std::vector spawnList; std::vector handles; - for (int i = 0; i < numBatches; ++i) { - if (dir == 0) { + for (int i = 0; i < numBatches; ++i) + { + if (dir == 0) + { genChild(i + 1, L"", allocChunk, spawnList); } - if (dir & 1) { + if (dir & 1) + { genBatch(true, useJob, useGapProcess, allocChunk, spawnList, handles); } - if (dir & 2) { + if (dir & 2) + { genBatch(false, useJob, useGapProcess, allocChunk, spawnList, handles); } } @@ -717,12 +820,16 @@ static int doParent(std::deque argv) { AllocConsole(); } - if (useSiblings) { + if (useSiblings) + { spawnSiblings(GetCurrentProcessId(), spawnList); - } else { + } + else + { spawnChildTree(GetCurrentProcessId(), spawnList); } - for (auto h : handles) { + for (auto h : handles) + { CloseHandle(h); } @@ -733,12 +840,16 @@ static int doParent(std::deque argv) { return 0; } -int main() { +int main() +{ setlocale(LC_ALL, ""); auto argv = getCommandLine(); - if (argv.size() >= 2 && argv[1] == L"--child") { + if (argv.size() >= 2 && argv[1] == L"--child") + { return doChild(std::move(argv)); - } else { + } + else + { return doParent(std::move(argv)); } } diff --git a/src/tools/echokey/main.cpp b/src/tools/echokey/main.cpp index 0fa1cf03f..55e005846 100644 --- a/src/tools/echokey/main.cpp +++ b/src/tools/echokey/main.cpp @@ -33,7 +33,10 @@ static const char CTRL_D = 0x4; void csi(string seq) { - if (!gVtOutput) return; + if (!gVtOutput) + { + return; + } string fullSeq = "\x1b["; fullSeq += seq; printf(fullSeq.c_str()); @@ -58,7 +61,8 @@ void toPrintableBuffer(char c, char* printBuffer, int* printCch) printBuffer[2] = '\0'; *printCch = 2; } - else if (c == '\x03') { + else if (c == '\x03') + { printBuffer[0] = '^'; printBuffer[1] = 'C'; printBuffer[2] = '\0'; @@ -106,7 +110,6 @@ void toPrintableBuffer(char c, char* printBuffer, int* printCch) printBuffer[2] = '\0'; *printCch = 2; } - } void handleKeyEvent(KEY_EVENT_RECORD keyEvent) @@ -158,14 +161,18 @@ void handleWindowEvent(WINDOW_BUFFER_SIZE_RECORD windowEvent) unsigned short viewWidth = srViewport.Right - srViewport.Left + 1; unsigned short viewHeight = srViewport.Bottom - srViewport.Top + 1; wprintf(L"BufferSize: (%d,%d) Viewport:(x, y, w, h)=(%d,%d,%d,%d)\r\n", - bufferWidth, bufferHeight, viewX, viewY, viewWidth, viewHeight); + bufferWidth, + bufferHeight, + viewX, + viewY, + viewWidth, + viewHeight); } - } -BOOL WINAPI CtrlHandler( DWORD fdwCtrlType ) +BOOL WINAPI CtrlHandler(DWORD fdwCtrlType) { - switch( fdwCtrlType ) + switch (fdwCtrlType) { // Handle the CTRL-C signal. case CTRL_C_EVENT: @@ -195,7 +202,7 @@ int __cdecl wmain(int argc, wchar_t* argv[]) gUseAltBuffer = false; gExitRequested = false; - for(int i = 1; i < argc; i++) + for (int i = 1; i < argc; i++) { wstring arg = wstring(argv[i]); wprintf(L"arg=%s\n", arg.c_str()); @@ -239,7 +246,7 @@ int __cdecl wmain(int argc, wchar_t* argv[]) DWORD dwInMode = 0; GetConsoleMode(g_hOut, &dwOutMode); GetConsoleMode(g_hIn, &dwInMode); - SetConsoleCtrlHandler(CtrlHandler, TRUE ); + SetConsoleCtrlHandler(CtrlHandler, TRUE); const DWORD initialInMode = dwInMode; const DWORD initialOutMode = dwOutMode; @@ -277,7 +284,7 @@ int __cdecl wmain(int argc, wchar_t* argv[]) wprintf(L"New Mode (i/o):(0x%4x, 0x%4x)\n", dwInMode, dwOutMode); wprintf(L"Press ^D to exit\n"); - while(!gExitRequested) + while (!gExitRequested) { INPUT_RECORD rc; DWORD dwRead = 0; @@ -295,7 +302,6 @@ int __cdecl wmain(int argc, wchar_t* argv[]) handleWindowEvent(rc.Event.WindowBufferSizeEvent); break; } - } } @@ -306,6 +312,5 @@ int __cdecl wmain(int argc, wchar_t* argv[]) SetConsoleMode(g_hOut, initialOutMode); SetConsoleMode(g_hIn, initialInMode); - exit (EXIT_FAILURE); - + exit(EXIT_FAILURE); } diff --git a/src/tools/fontlist/main.cpp b/src/tools/fontlist/main.cpp index 2affcf6b0..27442e0c0 100644 --- a/src/tools/fontlist/main.cpp +++ b/src/tools/fontlist/main.cpp @@ -5,10 +5,9 @@ #include #include -int CALLBACK FontEnumForV2Console(ENUMLOGFONT *pelf, NEWTEXTMETRIC *pntm, int nFontType, LPARAM lParam); -int -AddFont( - ENUMLOGFONT *pelf, +int CALLBACK FontEnumForV2Console(ENUMLOGFONT* pelf, NEWTEXTMETRIC* pntm, int nFontType, LPARAM lParam); +int AddFont( + ENUMLOGFONT* pelf, NEWTEXTMETRIC* pntm, int nFontType, HDC hDC); @@ -32,31 +31,45 @@ int __cdecl wmain(int /*argc*/, WCHAR* /*argv[]*/) #define CONTINUE_ENUM 1 #define END_ENUM 0 +// clang-format off #define IS_ANY_DBCS_CHARSET( CharSet ) \ ( ((CharSet) == SHIFTJIS_CHARSET) ? TRUE : \ ((CharSet) == HANGEUL_CHARSET) ? TRUE : \ ((CharSet) == CHINESEBIG5_CHARSET) ? TRUE : \ ((CharSet) == GB2312_CHARSET) ? TRUE : FALSE ) +// clang-format on -#define CP_US ((UINT)437) -#define CP_JPN ((UINT)932) -#define CP_WANSUNG ((UINT)949) -#define CP_TC ((UINT)950) -#define CP_SC ((UINT)936) -#define IsEastAsianCP(cp) ((cp)==CP_JPN || (cp)==CP_WANSUNG || (cp)==CP_TC || (cp)==CP_SC) +#define CP_US ((UINT)437) +#define CP_JPN ((UINT)932) +#define CP_WANSUNG ((UINT)949) +#define CP_TC ((UINT)950) +#define CP_SC ((UINT)936) +#define IsEastAsianCP(cp) ((cp) == CP_JPN || (cp) == CP_WANSUNG || (cp) == CP_TC || (cp) == CP_SC) /* * TTPoints -- Initial font pixel heights for TT fonts * NOTE: -* Font pixel heights for TT fonts of DBCS are the same list except +* Font pixel heights for TT fonts of DBCS are the same list except * odd point size because font width is (SBCS:DBCS != 1:2). */ SHORT TTPoints[] = { - 5, 6, 7, 8, 10, 12, 14, 16, 18, 20, 24, 28, 36, 72 + 5, + 6, + 7, + 8, + 10, + 12, + 14, + 16, + 18, + 20, + 24, + 28, + 36, + 72 }; - -int CALLBACK FontEnumForV2Console(ENUMLOGFONT *pelf, NEWTEXTMETRIC *pntm, int nFontType, LPARAM lParam) +int CALLBACK FontEnumForV2Console(ENUMLOGFONT* pelf, NEWTEXTMETRIC* pntm, int nFontType, LPARAM lParam) { UINT i; LPCWSTR pwszFace = pelf->elfLogFont.lfFaceName; @@ -112,7 +125,6 @@ int CALLBACK FontEnumForV2Console(ENUMLOGFONT *pelf, NEWTEXTMETRIC *pntm, int nF default: pwszCharSet = L"Unknown"; break; - } wprintf(L"Enum'd font: '%ls' (X: %d, Y: %d) weight 0x%lx (%d) charset %s \r\n", @@ -142,7 +154,8 @@ int CALLBACK FontEnumForV2Console(ENUMLOGFONT *pelf, NEWTEXTMETRIC *pntm, int nF // reject non-TT fonts that aren't OEM if ((nFontType != TRUETYPE_FONTTYPE) && (!fIsEastAsianCP || !IS_ANY_DBCS_CHARSET(pelf->elfLogFont.lfCharSet)) && - (pelf->elfLogFont.lfCharSet != OEM_CHARSET)) { + (pelf->elfLogFont.lfCharSet != OEM_CHARSET)) + { wprintf(L"Rejecting raster font that isn't OEM_CHARSET.\r\n"); return CONTINUE_ENUM; } @@ -162,7 +175,8 @@ int CALLBACK FontEnumForV2Console(ENUMLOGFONT *pelf, NEWTEXTMETRIC *pntm, int nF } // reject East Asian TT fonts that aren't East Asian charset. - if (fIsEastAsianCP && !IS_ANY_DBCS_CHARSET(pelf->elfLogFont.lfCharSet)) { + if (fIsEastAsianCP && !IS_ANY_DBCS_CHARSET(pelf->elfLogFont.lfCharSet)) + { wprintf(L"Rejecting East Asian TrueType font that isn't marked with East Asian charsets.\r\n"); return CONTINUE_ENUM; } @@ -174,8 +188,10 @@ int CALLBACK FontEnumForV2Console(ENUMLOGFONT *pelf, NEWTEXTMETRIC *pntm, int nF return CONTINUE_ENUM; } - if (nFontType & TRUETYPE_FONTTYPE) { - for (i = 0; i < ARRAYSIZE(TTPoints); i++) { + if (nFontType & TRUETYPE_FONTTYPE) + { + for (i = 0; i < ARRAYSIZE(TTPoints); i++) + { pelf->elfLogFont.lfHeight = TTPoints[i]; // If it's an East Asian enum, skip all odd height fonts. @@ -189,19 +205,19 @@ int CALLBACK FontEnumForV2Console(ENUMLOGFONT *pelf, NEWTEXTMETRIC *pntm, int nF AddFont(pelf, pntm, nFontType, (HDC)lParam); } } - else { + else + { AddFont(pelf, pntm, nFontType, (HDC)lParam); } - return CONTINUE_ENUM; // and continue enumeration + return CONTINUE_ENUM; // and continue enumeration } // Routine Description: // - Add the font described by the LOGFONT structure to the font table if // it's not already there. -int -AddFont( - ENUMLOGFONT *pelf, +int AddFont( + ENUMLOGFONT* pelf, NEWTEXTMETRIC* /*pntm*/, int /*nFontType*/, HDC hDC) diff --git a/src/tools/integrity/exeuwp/consoleuwp.cpp b/src/tools/integrity/exeuwp/consoleuwp.cpp index d2c3c36b9..694e71404 100644 --- a/src/tools/integrity/exeuwp/consoleuwp.cpp +++ b/src/tools/integrity/exeuwp/consoleuwp.cpp @@ -10,7 +10,7 @@ #include "util.h" #pragma optimize("", off) -#pragma warning(disable: 4748) +#pragma warning(disable : 4748) int __cdecl wmain(int /*argc*/, __in_ecount(argc) PCWSTR* /*argv*/) { diff --git a/src/tools/integrity/lib/util.cpp b/src/tools/integrity/lib/util.cpp index 3273b63ea..3ea8e4c6e 100644 --- a/src/tools/integrity/lib/util.cpp +++ b/src/tools/integrity/lib/util.cpp @@ -18,7 +18,7 @@ PCWSTR GetIntegrityLevel() THROW_IF_FAILED(wil::GetTokenInformationNoThrow(tokenLabel, GetCurrentProcessToken())); dwIntegrityLevel = *GetSidSubAuthority(tokenLabel->Label.Sid, - (DWORD)(UCHAR)(*GetSidSubAuthorityCount(tokenLabel->Label.Sid) - 1)); + (DWORD)(UCHAR)(*GetSidSubAuthorityCount(tokenLabel->Label.Sid) - 1)); switch (dwIntegrityLevel) { diff --git a/src/tools/lnkd/main.cpp b/src/tools/lnkd/main.cpp index be38372b7..4e47fd8b4 100644 --- a/src/tools/lnkd/main.cpp +++ b/src/tools/lnkd/main.cpp @@ -9,7 +9,7 @@ void PrintUsage() wprintf(L"\tlnkd \n"); } -HRESULT GetPropertyBoolValue(_In_ IPropertyStore *pPropStore, _In_ REFPROPERTYKEY refPropKey, _Out_ BOOL *pfValue) +HRESULT GetPropertyBoolValue(_In_ IPropertyStore* pPropStore, _In_ REFPROPERTYKEY refPropKey, _Out_ BOOL* pfValue) { PROPVARIANT propvar; HRESULT hr = pPropStore->GetValue(refPropKey, &propvar); @@ -21,7 +21,7 @@ HRESULT GetPropertyBoolValue(_In_ IPropertyStore *pPropStore, _In_ REFPROPERTYKE return hr; } -HRESULT GetPropertyByteValue(_In_ IPropertyStore *pPropStore, _In_ REFPROPERTYKEY refPropKey, _Out_ BYTE *pbValue) +HRESULT GetPropertyByteValue(_In_ IPropertyStore* pPropStore, _In_ REFPROPERTYKEY refPropKey, _Out_ BYTE* pbValue) { PROPVARIANT propvar; HRESULT hr = pPropStore->GetValue(refPropKey, &propvar); @@ -42,9 +42,9 @@ HRESULT GetPropertyByteValue(_In_ IPropertyStore *pPropStore, _In_ REFPROPERTYKE return hr; } -void DumpV2Properties(_In_ IShellLink *pslConsole) +void DumpV2Properties(_In_ IShellLink* pslConsole) { - IPropertyStore *pPropStoreLnk; + IPropertyStore* pPropStoreLnk; HRESULT hr = pslConsole->QueryInterface(IID_PPV_ARGS(&pPropStoreLnk)); if (SUCCEEDED(hr)) { @@ -133,13 +133,13 @@ void DumpBool(_In_ PCWSTR pszAttrName, const BOOL fEnabled) wprintf(L"\t%s: %s\n", pszAttrName, fEnabled ? L"true" : L"false"); } -HRESULT DumpV1Properties(_In_ IShellLink *pslConsole) +HRESULT DumpV1Properties(_In_ IShellLink* pslConsole) { - IShellLinkDataList *pConsoleLnkDataList; + IShellLinkDataList* pConsoleLnkDataList; HRESULT hr = pslConsole->QueryInterface(IID_PPV_ARGS(&pConsoleLnkDataList)); if (SUCCEEDED(hr)) { - NT_CONSOLE_PROPS *pNtConsoleProps = nullptr; + NT_CONSOLE_PROPS* pNtConsoleProps = nullptr; hr = pConsoleLnkDataList->CopyDataBlock(NT_CONSOLE_PROPS_SIG, (void**)&pNtConsoleProps); if (SUCCEEDED(hr)) { @@ -161,7 +161,7 @@ HRESULT DumpV1Properties(_In_ IShellLink *pslConsole) DumpBool(L"bQuickEdit", pNtConsoleProps->bQuickEdit); DumpBool(L"bInsertMode", pNtConsoleProps->bInsertMode); DumpBool(L"bAutoPosition", pNtConsoleProps->bAutoPosition); - wprintf(L"\tuHistoryBufferSize: %d\n", pNtConsoleProps-> uHistoryBufferSize); + wprintf(L"\tuHistoryBufferSize: %d\n", pNtConsoleProps->uHistoryBufferSize); wprintf(L"\tuNumberOfHistoryBuffers: %d\n", pNtConsoleProps->uNumberOfHistoryBuffers); DumpBool(L"bHistoryNoDup", pNtConsoleProps->bHistoryNoDup); wprintf(L"\tColorTable:\n"); @@ -179,7 +179,7 @@ HRESULT DumpV1Properties(_In_ IShellLink *pslConsole) if (SUCCEEDED(hr)) { // now dump East Asian properties if we can - NT_FE_CONSOLE_PROPS *pNtFEConsoleProps; + NT_FE_CONSOLE_PROPS* pNtFEConsoleProps; if (SUCCEEDED(pConsoleLnkDataList->CopyDataBlock(NT_FE_CONSOLE_PROPS_SIG, (void**)&pNtFEConsoleProps))) { @@ -200,11 +200,11 @@ HRESULT DumpV1Properties(_In_ IShellLink *pslConsole) HRESULT DumpProperties(_In_ PCWSTR pszLnkFile) { - IShellLink *pslConsole; + IShellLink* pslConsole; HRESULT hr = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC, IID_PPV_ARGS(&pslConsole)); if (SUCCEEDED(hr)) { - IPersistFile *pPersistFileLnk; + IPersistFile* pPersistFileLnk; hr = pslConsole->QueryInterface(IID_PPV_ARGS(&pPersistFileLnk)); if (SUCCEEDED(hr)) { diff --git a/src/tools/pixels/main.cpp b/src/tools/pixels/main.cpp index 41d9868c3..8a1061430 100644 --- a/src/tools/pixels/main.cpp +++ b/src/tools/pixels/main.cpp @@ -11,8 +11,7 @@ using namespace std; using namespace Windows::Internal; #define CONSOLE_WINDOW_FLAGS (WS_OVERLAPPEDWINDOW | WS_HSCROLL | WS_VSCROLL) -#define CONSOLE_WINDOW_EX_FLAGS (WS_EX_WINDOWEDGE | WS_EX_ACCEPTFILES | WS_EX_APPWINDOW ) - +#define CONSOLE_WINDOW_EX_FLAGS (WS_EX_WINDOWEDGE | WS_EX_ACCEPTFILES | WS_EX_APPWINDOW) void PrintRect(LPCWSTR pwszLabel, RECT& rc) { @@ -73,10 +72,10 @@ HRESULT PrintMonitorInfo(LPCWSTR pwszLabel, HMONITOR hmon) BOOL CALLBACK MonitorEnumProc( _In_ HMONITOR hMonitor, - _In_ HDC /*hdcMonitor*/, - _In_ LPRECT /*lprcMonitor*/, - _In_ LPARAM /*dwData*/ - ) + _In_ HDC /*hdcMonitor*/, + _In_ LPRECT /*lprcMonitor*/, + _In_ LPARAM /*dwData*/ +) { PrintMonitorInfo(L"--- Monitor ---", hMonitor); wcout << endl; @@ -129,12 +128,12 @@ int __cdecl wmain(int /*argc*/, WCHAR* /*argv*/[]) SetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE); HANDLE hOut = CreateFileW(L"CONOUT$", - GENERIC_READ | GENERIC_WRITE, - FILE_SHARE_WRITE, - 0, - OPEN_EXISTING, - 0, - 0); + GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_WRITE, + 0, + OPEN_EXISTING, + 0, + 0); RETURN_IF_HANDLE_INVALID(hOut); @@ -177,7 +176,7 @@ int __cdecl wmain(int /*argc*/, WCHAR* /*argv*/[]) PrintSize(L"Scroll Bar Reservations (unscaled):", sz); HMODULE hUser32 = LoadLibraryW(L"user32.dll"); - typedef int(*PfnGetDpiMetrics)(int nIndex, int dpi); + typedef int (*PfnGetDpiMetrics)(int nIndex, int dpi); bool fGotMetrics = false; if (hUser32 != nullptr) @@ -197,7 +196,6 @@ int __cdecl wmain(int /*argc*/, WCHAR* /*argv*/[]) sz.cy = (SHORT)pfn(SM_CYHSCROLL, dpiy); fGotMetrics = true; } - } if (!fGotMetrics) @@ -256,7 +254,8 @@ int __cdecl wmain(int /*argc*/, WCHAR* /*argv*/[]) bool fHorizScroll = (csbiex.dwSize.X > (szClient.cx / szFontScaled.cx)); bool fVertScroll = (csbiex.dwSize.Y > (szClient.cy / szFontScaled.cy)); - wcout << "Start with adjusted window dimensions (scaled for DPI). We take the outer window rect and ask the system to scale it down to what we could use for a client." << endl << endl; + wcout << "Start with adjusted window dimensions (scaled for DPI). We take the outer window rect and ask the system to scale it down to what we could use for a client." << endl + << endl; wcout << "Width: " << endl; wcout << " Window Adjusted: " << szClient.cx << endl; wcout << " / Font : " << szFontScaled.cx << endl; @@ -296,7 +295,8 @@ int __cdecl wmain(int /*argc*/, WCHAR* /*argv*/[]) szCharLeftoverFinal.cx = szAvailableClient.cx % szFontScaled.cx; szCharLeftoverFinal.cy = szAvailableClient.cy % szFontScaled.cy; - wcout << "Now math out the space we actually have for the viewport with scroll bars if necessary." << endl << endl; + wcout << "Now math out the space we actually have for the viewport with scroll bars if necessary." << endl + << endl; wcout << "Width: " << endl; wcout << " Window Adjusted: " << szClient.cx << endl; wcout << " - Vert Scroll : " << szRemoveBars.cx << endl; diff --git a/src/tools/test/main.cpp b/src/tools/test/main.cpp index 789462cc8..ad600169c 100644 --- a/src/tools/test/main.cpp +++ b/src/tools/test/main.cpp @@ -5,7 +5,6 @@ #include #include - int TestSetViewport(HANDLE hIn, HANDLE hOut); int TestGetchar(HANDLE hIn, HANDLE hOut); @@ -27,13 +26,13 @@ int __cdecl wmain(int /*argc*/, WCHAR* /*argv[]*/) return 0; } - int TestSetViewport(HANDLE /*hIn*/, HANDLE hOut) { CONSOLE_SCREEN_BUFFER_INFOEX csbiex = { 0 }; csbiex.cbSize = sizeof(CONSOLE_SCREEN_BUFFER_INFOEX); bool fSuccess = GetConsoleScreenBufferInfoEx(hOut, &csbiex); - if (fSuccess) { + if (fSuccess) + { const SMALL_RECT Screen = csbiex.srWindow; const short sWidth = Screen.Right - Screen.Left; const short sHeight = Screen.Bottom - Screen.Top; @@ -44,7 +43,6 @@ int TestSetViewport(HANDLE /*hIn*/, HANDLE hOut) csbiex.srWindow.Right = sWidth; SetConsoleScreenBufferInfoEx(hOut, &csbiex); - } return 0; } diff --git a/src/tools/vtpipeterm/VtConsole.cpp b/src/tools/vtpipeterm/VtConsole.cpp index dd4635d76..d42c1efe4 100644 --- a/src/tools/vtpipeterm/VtConsole.cpp +++ b/src/tools/vtpipeterm/VtConsole.cpp @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. - #include "..\..\inc\conpty.h" #include "VtConsole.hpp" -#include /* srand, rand */ -#include /* time */ +#include /* srand, rand */ +#include /* time */ #include #include @@ -71,7 +70,7 @@ HRESULT CreatePseudoConsoleAndHandles(COORD size, _Out_ HANDLE* phOutput, _Out_ HPCON* phPC) { - if(phPC == NULL || phInput == NULL || phOutput == NULL) + if (phPC == NULL || phInput == NULL || phOutput == NULL) { return E_INVALIDARG; } @@ -149,7 +148,6 @@ void VtConsole::_spawn(const std::wstring& command) this, 0, &_dwOutputThreadId); - } PCWSTR GetCmdLine() @@ -176,26 +174,27 @@ void VtConsole::_createPseudoConsole(const std::wstring& command) THROW_IF_FAILED(AttachPseudoConsole(_hPC, siEx.lpAttributeList)); std::wstring realCommand = command; - if (realCommand == L""){ + if (realCommand == L"") + { realCommand = L"cmd.exe"; } std::unique_ptr mutableCommandline = std::make_unique(realCommand.length() + 1); 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); fSuccess = !!CreateProcessW( nullptr, mutableCommandline.get(), - nullptr, // lpProcessAttributes - nullptr, // lpThreadAttributes - true, // bInheritHandles - EXTENDED_STARTUPINFO_PRESENT, // dwCreationFlags - nullptr, // lpEnvironment - nullptr, // lpCurrentDirectory - &siEx.StartupInfo, // lpStartupInfo - &_piClient // lpProcessInformation + nullptr, // lpProcessAttributes + nullptr, // lpThreadAttributes + true, // bInheritHandles + EXTENDED_STARTUPINFO_PRESENT, // dwCreationFlags + nullptr, // lpEnvironment + nullptr, // lpCurrentDirectory + &siEx.StartupInfo, // lpStartupInfo + &_piClient // lpProcessInformation ); THROW_LAST_ERROR_IF(!fSuccess); DeleteProcThreadAttributeList(siEx.lpAttributeList); @@ -212,7 +211,6 @@ void VtConsole::_createConptyManually(const std::wstring& command) &_outPipe, &_signalPipe, &_piPty)); - } else { @@ -272,7 +270,7 @@ void VtConsole::_createConptyViaCommandline(const std::wstring& command) si.hStdError = outPipeConhostSide.get(); si.dwFlags |= STARTF_USESTDHANDLES; - if(!(_lastDimensions.X == 0 && _lastDimensions.Y == 0)) + if (!(_lastDimensions.X == 0 && _lastDimensions.Y == 0)) { // STARTF_USECOUNTCHARS does not work. // minkernel/console/client/dllinit will write that value to conhost @@ -303,14 +301,14 @@ void VtConsole::_createConptyViaCommandline(const std::wstring& command) bool fSuccess = !!CreateProcess( nullptr, &cmdline[0], - nullptr, // lpProcessAttributes - nullptr, // lpThreadAttributes - true, // bInheritHandles - 0, // dwCreationFlags - nullptr, // lpEnvironment - nullptr, // lpCurrentDirectory - &si, // lpStartupInfo - &_piPty // lpProcessInformation + nullptr, // lpProcessAttributes + nullptr, // lpThreadAttributes + true, // bInheritHandles + 0, // dwCreationFlags + nullptr, // lpEnvironment + nullptr, // lpCurrentDirectory + &si, // lpStartupInfo + &_piPty // lpProcessInformation ); if (!fSuccess) @@ -366,7 +364,7 @@ bool VtConsole::Resize(const unsigned short rows, const unsigned short cols) { if (_fUseConPty) { - return SUCCEEDED(ResizePseudoConsole(_hPC, {(SHORT)cols, (SHORT)rows})); + return SUCCEEDED(ResizePseudoConsole(_hPC, { (SHORT)cols, (SHORT)rows })); } else { diff --git a/src/tools/vtpipeterm/VtConsole.hpp b/src/tools/vtpipeterm/VtConsole.hpp index fae5bc822..bd65b6b1f 100644 --- a/src/tools/vtpipeterm/VtConsole.hpp +++ b/src/tools/vtpipeterm/VtConsole.hpp @@ -14,14 +14,13 @@ Author(s): - Mike Griese (MiGrie) 2017 --*/ - #include #include #include #include -typedef void(*PipeReadCallback)(BYTE* buffer, DWORD dwRead); +typedef void (*PipeReadCallback)(BYTE* buffer, DWORD dwRead); class VtConsole { @@ -80,5 +79,4 @@ private: void _spawn(const std::wstring& command); DWORD _OutputThread(); - }; diff --git a/src/tools/vtpipeterm/main.cpp b/src/tools/vtpipeterm/main.cpp index fa0812858..5b77ff9aa 100644 --- a/src/tools/vtpipeterm/main.cpp +++ b/src/tools/vtpipeterm/main.cpp @@ -7,8 +7,8 @@ #include #include #include -#include /* srand, rand */ -#include /* time */ +#include /* srand, rand */ +#include /* time */ #include #include @@ -115,7 +115,7 @@ HANDLE outPipe() void newConsole() { - auto con = new VtConsole(ReadCallback, g_headless, g_useConpty, {lastTerminalWidth, lastTerminalHeight}); + auto con = new VtConsole(ReadCallback, g_headless, g_useConpty, { lastTerminalWidth, lastTerminalHeight }); con->spawn(); consoles.push_back(con); } @@ -160,7 +160,6 @@ void printKeyEvent(KEY_EVENT_RECORD keyEvent) keyEvent.uChar.AsciiChar, keyEvent.dwControlKeyState); } - } void toPrintableBuffer(char c, char* printBuffer, int* printCch) @@ -171,7 +170,8 @@ void toPrintableBuffer(char c, char* printBuffer, int* printCch) printBuffer[1] = '['; *printCch = 2; } - else if (c == '\x03') { + else if (c == '\x03') + { printBuffer[0] = '^'; printBuffer[1] = 'C'; *printCch = 2; @@ -197,7 +197,7 @@ void toPrintableBuffer(char c, char* printBuffer, int* printCch) else if (c < '\x20') { printBuffer[0] = '^'; - printBuffer[1] = c+0x40; + printBuffer[1] = c + 0x40; *printCch = 2; } else if (c == '\x7f') @@ -300,30 +300,30 @@ void handleManyEvents(const INPUT_RECORD* const inputBuffer, int cEvents) } if (doUnicode) { - switch(c) + switch (c) { - case '1': - lang = TEST_LANG_CYRILLIC; - break; - case '2': - lang = TEST_LANG_CHINESE; - break; - case '3': - lang = TEST_LANG_JAPANESE; - break; - case '4': - lang = TEST_LANG_KOREAN; - break; - case '#': - lang = TEST_LANG_GOOD_POUND; - break; - case '$': - lang = TEST_LANG_BAD_POUND; - break; - default: - doUnicode = false; - lang = TEST_LANG_NONE; - break; + case '1': + lang = TEST_LANG_CYRILLIC; + break; + case '2': + lang = TEST_LANG_CHINESE; + break; + case '3': + lang = TEST_LANG_JAPANESE; + break; + case '4': + lang = TEST_LANG_KOREAN; + break; + case '#': + lang = TEST_LANG_GOOD_POUND; + break; + case '$': + lang = TEST_LANG_BAD_POUND; + break; + default: + doUnicode = false; + lang = TEST_LANG_NONE; + break; } } else if (!prefixPressed) @@ -341,26 +341,26 @@ void handleManyEvents(const INPUT_RECORD* const inputBuffer, int cEvents) } else { - switch(c) + switch (c) { - case 'n': - case '\t': - nextConsole(); - break; - case 't': - newConsole(); - nextConsole(); - break; - case 'u': - doUnicode = true; - break; - case 'r': - signalConsole(); - break; - default: - *nextBuffer = c; - nextBuffer++; - bufferCch++; + case 'n': + case '\t': + nextConsole(); + break; + case 't': + newConsole(); + nextConsole(); + break; + case 'u': + doUnicode = true; + break; + case 'r': + signalConsole(); + break; + default: + *nextBuffer = c; + nextBuffer++; + bufferCch++; } prefixPressed = false; } @@ -375,7 +375,6 @@ void handleManyEvents(const INPUT_RECORD* const inputBuffer, int cEvents) WINDOW_BUFFER_SIZE_RECORD resize = event.Event.WindowBufferSizeEvent; handleResize(); } - } if (bufferCch > 0) @@ -389,29 +388,29 @@ void handleManyEvents(const INPUT_RECORD* const inputBuffer, int cEvents) if (doUnicode && lang != TEST_LANG_NONE) { std::string str; - switch(lang) + switch (lang) { - case TEST_LANG_CYRILLIC: - str = "Лорем ипсум долор сит амет, пер цлита поссит ех, ат мунере фабулас петентиум сит."; - break; - case TEST_LANG_CHINESE: - str = "側経意責家方家閉討店暖育田庁載社転線宇。"; - break; - case TEST_LANG_JAPANESE: - str = "旅ロ京青利セムレ弱改フヨス波府かばぼ意送でぼ調掲察たス日西重ケアナ住橋ユムミク順待ふかんぼ人奨貯鏡すびそ。"; - break; - case TEST_LANG_KOREAN: - str = "국민경제의 발전을 위한 중요정책의 수립에 관하여 대통령의 자문에 응하기 위하여 국민경제자문회의를 둘 수 있다."; - break; - case TEST_LANG_GOOD_POUND: - str = "\xc2\xa3"; // UTF-8 £ - break; - case TEST_LANG_BAD_POUND: - str = "\xa3"; // UTF-16 £ - break; - default: - str = ""; - break; + case TEST_LANG_CYRILLIC: + str = "Лорем ипсум долор сит амет, пер цлита поссит ех, ат мунере фабулас петентиум сит."; + break; + case TEST_LANG_CHINESE: + str = "側経意責家方家閉討店暖育田庁載社転線宇。"; + break; + case TEST_LANG_JAPANESE: + str = "旅ロ京青利セムレ弱改フヨス波府かばぼ意送でぼ調掲察たス日西重ケアナ住橋ユムミク順待ふかんぼ人奨貯鏡すびそ。"; + break; + case TEST_LANG_KOREAN: + str = "국민경제의 발전을 위한 중요정책의 수립에 관하여 대통령의 자문에 응하기 위하여 국민경제자문회의를 둘 수 있다."; + break; + case TEST_LANG_GOOD_POUND: + str = "\xc2\xa3"; // UTF-8 £ + break; + case TEST_LANG_BAD_POUND: + str = "\xa3"; // UTF-16 £ + break; + default: + str = ""; + break; } getConsole()->WriteInput(str); PrintInputToDebug(str); @@ -470,13 +469,11 @@ DWORD WINAPI InputThread(LPVOID /*lpParameter*/) unsigned int launchCP = GetConsoleCP(); THROW_LAST_ERROR_IF(!SetConsoleOutputCP(CP_UTF8)); THROW_LAST_ERROR_IF(!SetConsoleCP(CP_UTF8)); - auto restore = wil::scope_exit([&] - { + auto restore = wil::scope_exit([&] { SetConsoleOutputCP(launchOutputCP); SetConsoleCP(launchCP); }); - for (;;) { INPUT_RECORD rc[256]; @@ -494,25 +491,23 @@ DWORD WINAPI InputThread(LPVOID /*lpParameter*/) } } - void CreateIOThreads() { // The VtConsoles themselves handle their output threads. - DWORD dwInputThreadId = (DWORD) -1; + DWORD dwInputThreadId = (DWORD)-1; HANDLE hInputThread = CreateThread(nullptr, - 0, - InputThread, - nullptr, - 0, - &dwInputThreadId); + 0, + InputThread, + nullptr, + 0, + &dwInputThreadId); hInputThread; } - -BOOL WINAPI CtrlHandler( DWORD fdwCtrlType ) +BOOL WINAPI CtrlHandler(DWORD fdwCtrlType) { - switch( fdwCtrlType ) + switch (fdwCtrlType) { // Handle the CTRL-C signal. case CTRL_C_EVENT: @@ -526,12 +521,12 @@ BOOL WINAPI CtrlHandler( DWORD fdwCtrlType ) // this function has unreachable code due to its unusual lifetime. We // disable the warning about it here. #pragma warning(push) -#pragma warning(disable:4702) +#pragma warning(disable : 4702) int __cdecl wmain(int argc, WCHAR* argv[]) { // initialize random seed: srand((unsigned int)time(NULL)); - SetConsoleCtrlHandler(CtrlHandler, TRUE ); + SetConsoleCtrlHandler(CtrlHandler, TRUE); hOut = GetStdHandle(STD_OUTPUT_HANDLE); hIn = GetStdHandle(STD_INPUT_HANDLE); @@ -555,10 +550,10 @@ int __cdecl wmain(int argc, WCHAR* argv[]) { fUseDebug = true; } - else if (arg == std::wstring(L"--out") && i+1 < argc) + else if (arg == std::wstring(L"--out") && i + 1 < argc) { g_useOutfile = true; - outfile = argv[i+1]; + outfile = argv[i + 1]; i++; } } @@ -572,13 +567,12 @@ int __cdecl wmain(int argc, WCHAR* argv[]) if (g_useOutfile) { - hOutFile = CreateFileW(outfile.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL , NULL); + hOutFile = CreateFileW(outfile.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hOutFile == INVALID_HANDLE_VALUE) { printf("Failed to open outfile (%ls) for writing\n", outfile.c_str()); Sleep(1000); exit(0); - } } @@ -595,7 +589,7 @@ int __cdecl wmain(int argc, WCHAR* argv[]) if (fUseDebug) { // Create a debug console for writting debugging output to. - debug = new VtConsole(DebugReadCallback, false, false, {80,32}); + debug = new VtConsole(DebugReadCallback, false, false, { 80, 32 }); // Echo stdin to stdout, but ignore newlines (so cat doesn't echo the input) // debug->spawn(L"ubuntu run tr -d '\n' | cat -sA"); debug->spawn(L"wsl tr -d '\n' | cat -sA"); diff --git a/src/tsf/ConsoleTSF.cpp b/src/tsf/ConsoleTSF.cpp index d8d8b277e..a47c63d6b 100644 --- a/src/tsf/ConsoleTSF.cpp +++ b/src/tsf/ConsoleTSF.cpp @@ -6,7 +6,7 @@ #include "TfEditSes.h" /* 626761ad-78d2-44d2-be8b-752cf122acec */ -const GUID GUID_APPLICATION = { 0x626761ad, 0x78d2, 0x44d2, {0xbe, 0x8b, 0x75, 0x2c, 0xf1, 0x22, 0xac, 0xec} }; +const GUID GUID_APPLICATION = { 0x626761ad, 0x78d2, 0x44d2, { 0xbe, 0x8b, 0x75, 0x2c, 0xf1, 0x22, 0xac, 0xec } }; //+--------------------------------------------------------------------------- // @@ -14,10 +14,14 @@ const GUID GUID_APPLICATION = { 0x626761ad, 0x78d2, 0x44d2, {0xbe, 0x8b, 0x75, 0 // //---------------------------------------------------------------------------- -#define Init_CheckResult() if (FAILED(hr)) { Uninitialize(); return hr; } +#define Init_CheckResult() \ + if (FAILED(hr)) \ + { \ + Uninitialize(); \ + return hr; \ + } -[[nodiscard]] -HRESULT CConsoleTSF::Initialize() +[[nodiscard]] HRESULT CConsoleTSF::Initialize() { HRESULT hr; @@ -72,8 +76,7 @@ HRESULT CConsoleTSF::Initialize() hr = spITfProfilesMgr->GetActiveProfile(GUID_TFCAT_TIP_KEYBOARD, &ipp); if (SUCCEEDED(hr)) { - OnActivated(ipp.dwProfileType, ipp.langid, ipp.clsid, ipp.catid, - ipp.guidProfile, ipp.hkl, ipp.dwFlags); + OnActivated(ipp.dwProfileType, ipp.langid, ipp.clsid, ipp.catid, ipp.guidProfile, ipp.hkl, ipp.dwFlags); } } Init_CheckResult(); @@ -252,12 +255,14 @@ STDMETHODIMP CConsoleTSF::QueryInterface(REFIID riid, void** ppvObj) return (*ppvObj) ? S_OK : E_NOINTERFACE; } -STDAPI_(ULONG) CConsoleTSF::AddRef() +STDAPI_(ULONG) +CConsoleTSF::AddRef() { return InterlockedIncrement(&_cRef); } -STDAPI_(ULONG) CConsoleTSF::Release() +STDAPI_(ULONG) +CConsoleTSF::Release() { ULONG cr = InterlockedDecrement(&_cRef); if (cr == 0) @@ -370,7 +375,7 @@ STDMETHODIMP CConsoleTSF::OnEndComposition(ITfCompositionView* pCompView) // //---------------------------------------------------------------------------- -STDMETHODIMP CConsoleTSF::OnEndEdit(ITfContext *pInputContext, TfEditCookie ecReadOnly, ITfEditRecord *pEditRecord) +STDMETHODIMP CConsoleTSF::OnEndEdit(ITfContext* pInputContext, TfEditCookie ecReadOnly, ITfEditRecord* pEditRecord) { if (_cCompositions && _pConversionArea && _HasCompositionChanged(pInputContext, ecReadOnly, pEditRecord)) { @@ -385,8 +390,13 @@ STDMETHODIMP CConsoleTSF::OnEndEdit(ITfContext *pInputContext, TfEditCookie ecRe // //---------------------------------------------------------------------------- -STDMETHODIMP CConsoleTSF::OnActivated(DWORD /*dwProfileType*/, LANGID /*langid*/, REFCLSID /*clsid*/, - REFGUID catid, REFGUID /*guidProfile*/, HKL /*hkl*/, DWORD dwFlags) +STDMETHODIMP CConsoleTSF::OnActivated(DWORD /*dwProfileType*/, + LANGID /*langid*/, + REFCLSID /*clsid*/, + REFGUID catid, + REFGUID /*guidProfile*/, + HKL /*hkl*/, + DWORD dwFlags) { if (!(dwFlags & TF_IPSINK_FLAG_ACTIVE)) { @@ -413,7 +423,7 @@ STDMETHODIMP CConsoleTSF::OnActivated(DWORD /*dwProfileType*/, LANGID /*langid*/ // //---------------------------------------------------------------------------- -STDMETHODIMP CConsoleTSF::BeginUIElement(DWORD /*dwUIElementId*/, BOOL *pbShow) +STDMETHODIMP CConsoleTSF::BeginUIElement(DWORD /*dwUIElementId*/, BOOL* pbShow) { *pbShow = TRUE; return S_OK; @@ -447,7 +457,7 @@ STDMETHODIMP CConsoleTSF::EndUIElement(DWORD /*dwUIElementId*/) // //---------------------------------------------------------------------------- - CConversionArea* CConsoleTSF::CreateConversionArea() +CConversionArea* CConsoleTSF::CreateConversionArea() { BOOL fHadConvArea = (_pConversionArea != NULL); @@ -472,8 +482,7 @@ STDMETHODIMP CConsoleTSF::EndUIElement(DWORD /*dwUIElementId*/) // //---------------------------------------------------------------------------- -[[nodiscard]] -HRESULT CConsoleTSF::_OnUpdateComposition() +[[nodiscard]] HRESULT CConsoleTSF::_OnUpdateComposition() { if (_fEditSessionRequested) { @@ -481,7 +490,7 @@ HRESULT CConsoleTSF::_OnUpdateComposition() } HRESULT hr = E_OUTOFMEMORY; - CEditSessionUpdateCompositionString* pEditSession = new(std::nothrow) CEditSessionUpdateCompositionString(); + CEditSessionUpdateCompositionString* pEditSession = new (std::nothrow) CEditSessionUpdateCompositionString(); if (pEditSession) { // Can't use TF_ES_SYNC because called from OnEndEdit. @@ -502,13 +511,12 @@ HRESULT CConsoleTSF::_OnUpdateComposition() // //---------------------------------------------------------------------------- -[[nodiscard]] -HRESULT CConsoleTSF::_OnCompleteComposition() +[[nodiscard]] HRESULT CConsoleTSF::_OnCompleteComposition() { // Update the composition area. HRESULT hr = E_OUTOFMEMORY; - CEditSessionCompositionComplete* pEditSession = new(std::nothrow) CEditSessionCompositionComplete(); + CEditSessionCompositionComplete* pEditSession = new (std::nothrow) CEditSessionCompositionComplete(); if (pEditSession) { // The composition could have been finalized because of a caret move, therefore it must be @@ -524,7 +532,7 @@ HRESULT CConsoleTSF::_OnCompleteComposition() if (!_fCleanupSessionRequested) { _fCleanupSessionRequested = TRUE; - CEditSessionCompositionCleanup* pEditSessionCleanup = new(std::nothrow) CEditSessionCompositionCleanup(); + CEditSessionCompositionCleanup* pEditSessionCleanup = new (std::nothrow) CEditSessionCompositionCleanup(); if (pEditSessionCleanup) { // Can't use TF_ES_SYNC because requesting RW while called within another session. diff --git a/src/tsf/ConsoleTSF.h b/src/tsf/ConsoleTSF.h index ee20d21f3..ebfcfddab 100644 --- a/src/tsf/ConsoleTSF.h +++ b/src/tsf/ConsoleTSF.h @@ -23,7 +23,7 @@ Notes: class CConversionArea; -class CConsoleTSF final: +class CConsoleTSF final : public ITfContextOwner, public ITfContextOwnerCompositionSink, public ITfInputProcessorProfileActivationSink, @@ -44,18 +44,19 @@ public: virtual ~CConsoleTSF() { } - [[nodiscard]] - HRESULT Initialize(); - void Uninitialize(); + [[nodiscard]] HRESULT Initialize(); + void Uninitialize(); public: // IUnknown methods - STDMETHODIMP QueryInterface(REFIID riid, void **ppvObj); - STDMETHODIMP_(ULONG) AddRef(void); - STDMETHODIMP_(ULONG) Release(void); + STDMETHODIMP QueryInterface(REFIID riid, void** ppvObj); + STDMETHODIMP_(ULONG) + AddRef(void); + STDMETHODIMP_(ULONG) + Release(void); // ITfContextOwner - STDMETHODIMP GetACPFromPoint(const POINT*, DWORD, LONG *pCP) + STDMETHODIMP GetACPFromPoint(const POINT*, DWORD, LONG* pCP) { if (pCP) { @@ -65,8 +66,7 @@ public: return S_OK; } - - STDMETHODIMP GetScreenExt(RECT *pRect) + STDMETHODIMP GetScreenExt(RECT* pRect) { if (pRect) { @@ -76,7 +76,7 @@ public: return S_OK; } - STDMETHODIMP GetTextExt(LONG, LONG, RECT *pRect, BOOL *pbClipped) + STDMETHODIMP GetTextExt(LONG, LONG, RECT* pRect, BOOL* pbClipped) { if (pRect) { @@ -91,7 +91,7 @@ public: return S_OK; } - STDMETHODIMP GetStatus(TF_STATUS *pTfStatus) + STDMETHODIMP GetStatus(TF_STATUS* pTfStatus) { if (pTfStatus) { @@ -105,28 +105,29 @@ public: *phwnd = _hwndConsole; return S_OK; } - STDMETHODIMP GetAttribute(REFGUID, VARIANT*) - { return E_NOTIMPL; } + STDMETHODIMP GetAttribute(REFGUID, VARIANT*) + { + return E_NOTIMPL; + } // ITfContextOwnerCompositionSink methods - STDMETHODIMP OnStartComposition(ITfCompositionView *pComposition, BOOL *pfOk); - STDMETHODIMP OnUpdateComposition(ITfCompositionView *pComposition, ITfRange *pRangeNew); + STDMETHODIMP OnStartComposition(ITfCompositionView* pComposition, BOOL* pfOk); + STDMETHODIMP OnUpdateComposition(ITfCompositionView* pComposition, ITfRange* pRangeNew); STDMETHODIMP OnEndComposition(ITfCompositionView* pComposition); // ITfInputProcessorProfileActivationSink - STDMETHODIMP OnActivated(DWORD dwProfileType, LANGID langid, REFCLSID clsid, - REFGUID catid, REFGUID guidProfile, HKL hkl, DWORD dwFlags); + STDMETHODIMP OnActivated(DWORD dwProfileType, LANGID langid, REFCLSID clsid, REFGUID catid, REFGUID guidProfile, HKL hkl, DWORD dwFlags); // ITfUIElementSink methods - STDMETHODIMP BeginUIElement(DWORD dwUIELementId, BOOL *pbShow); + STDMETHODIMP BeginUIElement(DWORD dwUIELementId, BOOL* pbShow); STDMETHODIMP UpdateUIElement(DWORD dwUIELementId); STDMETHODIMP EndUIElement(DWORD dwUIELementId); // ITfCleanupContextSink methods - STDMETHODIMP OnCleanupContext(TfEditCookie ecWrite, ITfContext *pic); + STDMETHODIMP OnCleanupContext(TfEditCookie ecWrite, ITfContext* pic); // ITfTextEditSink methods - STDMETHODIMP OnEndEdit(ITfContext *pInputContext, TfEditCookie ecReadOnly, ITfEditRecord *pEditRecord); + STDMETHODIMP OnEndEdit(ITfContext* pInputContext, TfEditCookie ecReadOnly, ITfEditRecord* pEditRecord); public: CConversionArea* CreateConversionArea(); @@ -171,44 +172,42 @@ public: void SetCompletedRangeLength(long cch) { _cchCompleted = cch; } private: - [[nodiscard]] - HRESULT _OnUpdateComposition(); - [[nodiscard]] - HRESULT _OnCompleteComposition(); - BOOL _HasCompositionChanged(ITfContext *pInputContext, TfEditCookie ecReadOnly, ITfEditRecord *pEditRecord); + [[nodiscard]] HRESULT _OnUpdateComposition(); + [[nodiscard]] HRESULT _OnCompleteComposition(); + BOOL _HasCompositionChanged(ITfContext* pInputContext, TfEditCookie ecReadOnly, ITfEditRecord* pEditRecord); private: // ref count. DWORD _cRef; // Cicero stuff. - TfClientId _tid; + TfClientId _tid; wil::com_ptr_nothrow _spITfThreadMgr; wil::com_ptr_nothrow _spITfDocumentMgr; - wil::com_ptr_nothrow _spITfInputContext; + wil::com_ptr_nothrow _spITfInputContext; // Event sink cookies. - DWORD _dwContextOwnerCookie = 0; - DWORD _dwUIElementSinkCookie = 0; - DWORD _dwTextEditSinkCookie = 0; - DWORD _dwActivationSinkCookie = 0; + DWORD _dwContextOwnerCookie = 0; + DWORD _dwUIElementSinkCookie = 0; + DWORD _dwTextEditSinkCookie = 0; + DWORD _dwActivationSinkCookie = 0; // Conversion area object for the languages. - CConversionArea* _pConversionArea = nullptr; + CConversionArea* _pConversionArea = nullptr; // Console info. - HWND _hwndConsole; + HWND _hwndConsole; GetSuggestionWindowPos _pfnPosition; // Miscellaneous flags - BOOL _fModifyingDoc = FALSE; // Set TRUE, when calls ITfRange::SetText + BOOL _fModifyingDoc = FALSE; // Set TRUE, when calls ITfRange::SetText BOOL _fCoInitialized = FALSE; BOOL _fEditSessionRequested = FALSE; BOOL _fCleanupSessionRequested = FALSE; BOOL _fCompositionCleanupSkipped = FALSE; - int _cCompositions = 0; - long _cchCompleted = 0; // length of completed composition waiting for cleanup + int _cCompositions = 0; + long _cchCompleted = 0; // length of completed composition waiting for cleanup }; extern CConsoleTSF* g_pConsoleTSF; diff --git a/src/tsf/TfCatUtil.cpp b/src/tsf/TfCatUtil.cpp index 9678cdf20..0898e3c55 100644 --- a/src/tsf/TfCatUtil.cpp +++ b/src/tsf/TfCatUtil.cpp @@ -19,7 +19,6 @@ Notes: --*/ - #include "precomp.h" #include "TfCatUtil.h" @@ -44,8 +43,7 @@ CicCategoryMgr::~CicCategoryMgr() // //---------------------------------------------------------------------------- -[[nodiscard]] -HRESULT CicCategoryMgr::GetGUIDFromGUIDATOM(TfGuidAtom guidatom, GUID *pguid) +[[nodiscard]] HRESULT CicCategoryMgr::GetGUIDFromGUIDATOM(TfGuidAtom guidatom, GUID* pguid) { return m_pcat->GetGUID(guidatom, pguid); } @@ -56,8 +54,7 @@ HRESULT CicCategoryMgr::GetGUIDFromGUIDATOM(TfGuidAtom guidatom, GUID *pguid) // //---------------------------------------------------------------------------- -[[nodiscard]] -HRESULT CicCategoryMgr::InitCategoryInstance( ) +[[nodiscard]] HRESULT CicCategoryMgr::InitCategoryInstance() { // // Create ITfCategoryMgr instance. diff --git a/src/tsf/TfCatUtil.h b/src/tsf/TfCatUtil.h index d1573688d..c749098dd 100644 --- a/src/tsf/TfCatUtil.h +++ b/src/tsf/TfCatUtil.h @@ -28,13 +28,11 @@ public: virtual ~CicCategoryMgr(); public: - [[nodiscard]] - HRESULT GetGUIDFromGUIDATOM(TfGuidAtom guidatom, GUID *pguid); - [[nodiscard]] - HRESULT InitCategoryInstance(); + [[nodiscard]] HRESULT GetGUIDFromGUIDATOM(TfGuidAtom guidatom, GUID* pguid); + [[nodiscard]] HRESULT InitCategoryInstance(); inline ITfCategoryMgr* GetCategoryMgr() { return m_pcat.get(); } private: - wil::com_ptr_nothrow m_pcat; + wil::com_ptr_nothrow m_pcat; }; diff --git a/src/tsf/TfConvArea.cpp b/src/tsf/TfConvArea.cpp index 6b2e4953e..ea647f340 100644 --- a/src/tsf/TfConvArea.cpp +++ b/src/tsf/TfConvArea.cpp @@ -28,10 +28,9 @@ Notes: // CConversionArea //---------------------------------------------------------------------------- -[[nodiscard]] -HRESULT CConversionArea::DrawComposition(const std::wstring_view CompStr, - const std::vector& DisplayAttributes, - const DWORD CompCursorPos) +[[nodiscard]] HRESULT CConversionArea::DrawComposition(const std::wstring_view CompStr, + const std::vector& DisplayAttributes, + const DWORD CompCursorPos) { // Set up colors. static const std::array colors{ DEFAULT_COMP_ENTERED, @@ -41,8 +40,7 @@ HRESULT CConversionArea::DrawComposition(const std::wstring_view CompStr, DEFAULT_COMP_INPUT_ERROR, DEFAULT_COMP_INPUT_ERROR, DEFAULT_COMP_INPUT_ERROR, - DEFAULT_COMP_INPUT_ERROR - }; + DEFAULT_COMP_INPUT_ERROR }; const auto encodedAttributes = _DisplayAttributesToEncodedAttributes(DisplayAttributes, CompCursorPos); @@ -53,21 +51,18 @@ HRESULT CConversionArea::DrawComposition(const std::wstring_view CompStr, return ImeComposeData(CompStr, attributes, colorArray); } -[[nodiscard]] -HRESULT CConversionArea::ClearComposition() +[[nodiscard]] HRESULT CConversionArea::ClearComposition() { return ImeClearComposeData(); } -[[nodiscard]] -HRESULT CConversionArea::DrawResult(const std::wstring_view ResultStr) +[[nodiscard]] HRESULT CConversionArea::DrawResult(const std::wstring_view ResultStr) { return ImeComposeResult(ResultStr); } -[[nodiscard]] -std::vector CConversionArea::_DisplayAttributesToEncodedAttributes(const std::vector& DisplayAttributes, - const DWORD CompCursorPos) +[[nodiscard]] std::vector CConversionArea::_DisplayAttributesToEncodedAttributes(const std::vector& DisplayAttributes, + const DWORD CompCursorPos) { std::vector encodedAttrs; for (const auto& da : DisplayAttributes) @@ -96,11 +91,11 @@ std::vector CConversionArea::_DisplayAttributesToEncodedAttributes(const s { if (CompCursorPos == 0) { - encodedAttrs[CompCursorPos] |= (BYTE)CONIME_CURSOR_LEFT; // special handling for ConSrv... 0x20 = COMMON_LVB_GRID_SINGLEFLAG + COMMON_LVB_GRID_LVERTICAL + encodedAttrs[CompCursorPos] |= (BYTE)CONIME_CURSOR_LEFT; // special handling for ConSrv... 0x20 = COMMON_LVB_GRID_SINGLEFLAG + COMMON_LVB_GRID_LVERTICAL } else if (CompCursorPos - 1 < DisplayAttributes.size()) { - encodedAttrs[CompCursorPos - 1] |= (BYTE)CONIME_CURSOR_RIGHT; // special handling for ConSrv... 0x10 = COMMON_LVB_GRID_SINGLEFLAG + COMMON_LVB_GRID_RVERTICAL + encodedAttrs[CompCursorPos - 1] |= (BYTE)CONIME_CURSOR_RIGHT; // special handling for ConSrv... 0x10 = COMMON_LVB_GRID_SINGLEFLAG + COMMON_LVB_GRID_RVERTICAL } } diff --git a/src/tsf/TfConvArea.h b/src/tsf/TfConvArea.h index d34265536..e6ae9466e 100644 --- a/src/tsf/TfConvArea.h +++ b/src/tsf/TfConvArea.h @@ -30,20 +30,15 @@ Notes: class CConversionArea { public: - [[nodiscard]] - HRESULT DrawComposition(const std::wstring_view CompStr, - const std::vector& DisplayAttributes, - const DWORD CompCursorPos = -1); + [[nodiscard]] HRESULT DrawComposition(const std::wstring_view CompStr, + const std::vector& DisplayAttributes, + const DWORD CompCursorPos = -1); - [[nodiscard]] - HRESULT ClearComposition(); + [[nodiscard]] HRESULT ClearComposition(); - [[nodiscard]] - HRESULT DrawResult(const std::wstring_view ResultStr); + [[nodiscard]] HRESULT DrawResult(const std::wstring_view ResultStr); private: - [[nodiscard]] - std::vector _DisplayAttributesToEncodedAttributes(const std::vector& DisplayAttributes, - const DWORD CompCursorPos); - + [[nodiscard]] std::vector _DisplayAttributesToEncodedAttributes(const std::vector& DisplayAttributes, + const DWORD CompCursorPos); }; diff --git a/src/tsf/TfDispAttr.cpp b/src/tsf/TfDispAttr.cpp index a8b642cbb..ceccf9b66 100644 --- a/src/tsf/TfDispAttr.cpp +++ b/src/tsf/TfDispAttr.cpp @@ -19,7 +19,6 @@ Notes: --*/ - #include "precomp.h" #include "TfDispAttr.h" @@ -44,29 +43,38 @@ CicDisplayAttributeMgr::~CicDisplayAttributeMgr() // //---------------------------------------------------------------------------- -[[nodiscard]] -HRESULT CicDisplayAttributeMgr::GetDisplayAttributeTrackPropertyRange(TfEditCookie ec, ITfContext *pic, ITfRange *pRange, - ITfReadOnlyProperty **ppProp, IEnumTfRanges **ppEnum, ULONG *pulNumProp) +[[nodiscard]] HRESULT CicDisplayAttributeMgr::GetDisplayAttributeTrackPropertyRange(TfEditCookie ec, + ITfContext* pic, + ITfRange* pRange, + ITfReadOnlyProperty** ppProp, + IEnumTfRanges** ppEnum, + ULONG* pulNumProp) { HRESULT hr = E_FAIL; - try { + try + { ULONG ulNumProp = static_cast(m_DispAttrProp.size()); - if (ulNumProp) { + if (ulNumProp) + { // TrackProperties wants an array of GUID *'s auto ppguidProp = std::make_unique(ulNumProp); - for (ULONG i = 0; i < ulNumProp; i++) { + for (ULONG i = 0; i < ulNumProp; i++) + { ppguidProp[i] = &m_DispAttrProp.at(i); } wil::com_ptr pProp; - if (SUCCEEDED(hr = pic->TrackProperties(ppguidProp.get(), ulNumProp, 0, NULL, &pProp))) { + if (SUCCEEDED(hr = pic->TrackProperties(ppguidProp.get(), ulNumProp, 0, NULL, &pProp))) + { hr = pProp->EnumRanges(ec, ppEnum, pRange); - if (SUCCEEDED(hr)) { + if (SUCCEEDED(hr)) + { *ppProp = pProp.detach(); } } - if (SUCCEEDED(hr)) { + if (SUCCEEDED(hr)) + { *pulNumProp = ulNumProp; } } @@ -81,21 +89,30 @@ HRESULT CicDisplayAttributeMgr::GetDisplayAttributeTrackPropertyRange(TfEditCook // //---------------------------------------------------------------------------- -[[nodiscard]] -HRESULT CicDisplayAttributeMgr::GetDisplayAttributeData(ITfCategoryMgr *pcat, TfEditCookie ec, ITfReadOnlyProperty *pProp, ITfRange *pRange, TF_DISPLAYATTRIBUTE *pda, TfGuidAtom *pguid, ULONG /*ulNumProp*/) +[[nodiscard]] HRESULT CicDisplayAttributeMgr::GetDisplayAttributeData(ITfCategoryMgr* pcat, + TfEditCookie ec, + ITfReadOnlyProperty* pProp, + ITfRange* pRange, + TF_DISPLAYATTRIBUTE* pda, + TfGuidAtom* pguid, + ULONG /*ulNumProp*/) { VARIANT var; HRESULT hr = E_FAIL; - if (SUCCEEDED(pProp->GetValue(ec, pRange, &var))) { + if (SUCCEEDED(pProp->GetValue(ec, pRange, &var))) + { FAIL_FAST_IF(!(var.vt == VT_UNKNOWN)); wil::com_ptr_nothrow pEnumPropertyVal; - if (wil::try_com_query_to(var.punkVal, &pEnumPropertyVal)) { + if (wil::try_com_query_to(var.punkVal, &pEnumPropertyVal)) + { TF_PROPERTYVAL tfPropVal; - while (pEnumPropertyVal->Next(1, &tfPropVal, NULL) == S_OK) { - if (tfPropVal.varValue.vt == VT_EMPTY) { + while (pEnumPropertyVal->Next(1, &tfPropVal, NULL) == S_OK) + { + if (tfPropVal.varValue.vt == VT_EMPTY) + { continue; // prop has no value over this span } @@ -107,7 +124,8 @@ HRESULT CicDisplayAttributeMgr::GetDisplayAttributeData(ITfCategoryMgr *pcat, Tf pcat->GetGUID(gaVal, &guid); wil::com_ptr_nothrow pDAI; - if (SUCCEEDED(m_pDAM->GetDisplayAttributeInfo(guid, &pDAI, NULL))) { + if (SUCCEEDED(m_pDAM->GetDisplayAttributeInfo(guid, &pDAI, NULL))) + { // // Issue: for simple apps. // @@ -115,11 +133,13 @@ HRESULT CicDisplayAttributeMgr::GetDisplayAttributeData(ITfCategoryMgr *pcat, Tf // this helper function returns only one // DISPLAYATTRIBUTE structure. // - if (pda) { + if (pda) + { pDAI->GetAttributeInfo(pda); } - if (pguid) { + if (pguid) + { *pguid = gaVal; } @@ -139,15 +159,15 @@ HRESULT CicDisplayAttributeMgr::GetDisplayAttributeData(ITfCategoryMgr *pcat, Tf // //---------------------------------------------------------------------------- -[[nodiscard]] -HRESULT CicDisplayAttributeMgr::InitDisplayAttributeInstance(ITfCategoryMgr* pcat) +[[nodiscard]] HRESULT CicDisplayAttributeMgr::InitDisplayAttributeInstance(ITfCategoryMgr* pcat) { HRESULT hr; // // Create ITfDisplayAttributeMgr instance. // - if (FAILED(hr = ::CoCreateInstance(CLSID_TF_DisplayAttributeMgr, nullptr, CLSCTX_ALL, IID_PPV_ARGS(&m_pDAM)))) { + if (FAILED(hr = ::CoCreateInstance(CLSID_TF_DisplayAttributeMgr, nullptr, CLSCTX_ALL, IID_PPV_ARGS(&m_pDAM)))) + { return hr; } @@ -157,23 +177,27 @@ HRESULT CicDisplayAttributeMgr::InitDisplayAttributeInstance(ITfCategoryMgr* pca // // make a database for Display Attribute Properties. // - if (pEnumProp) { - GUID guidProp; + if (pEnumProp) + { + GUID guidProp; - try { - // - // add System Display Attribute first. - // so no other Display Attribute property overwrite it. - // - m_DispAttrProp.emplace_back(GUID_PROP_ATTRIBUTE); + try + { + // + // add System Display Attribute first. + // so no other Display Attribute property overwrite it. + // + m_DispAttrProp.emplace_back(GUID_PROP_ATTRIBUTE); - while (pEnumProp->Next(1, &guidProp, NULL) == S_OK) { - if (!IsEqualGUID(guidProp, GUID_PROP_ATTRIBUTE)) { - m_DispAttrProp.emplace_back(guidProp); - } - } - } - CATCH_RETURN(); + while (pEnumProp->Next(1, &guidProp, NULL) == S_OK) + { + if (!IsEqualGUID(guidProp, GUID_PROP_ATTRIBUTE)) + { + m_DispAttrProp.emplace_back(guidProp); + } + } + } + CATCH_RETURN(); } return hr; } diff --git a/src/tsf/TfDispAttr.h b/src/tsf/TfDispAttr.h index bf60c52db..74fc4dd7f 100644 --- a/src/tsf/TfDispAttr.h +++ b/src/tsf/TfDispAttr.h @@ -28,27 +28,24 @@ public: virtual ~CicDisplayAttributeMgr(); public: - [[nodiscard]] - HRESULT GetDisplayAttributeTrackPropertyRange(TfEditCookie ec, - ITfContext *pic, - ITfRange *pRange, - ITfReadOnlyProperty **ppProp, - IEnumTfRanges **ppEnum, - ULONG *pulNumProp); - [[nodiscard]] - HRESULT GetDisplayAttributeData(ITfCategoryMgr *pcat, - TfEditCookie ec, - ITfReadOnlyProperty *pProp, - ITfRange *pRange, - TF_DISPLAYATTRIBUTE *pda, - TfGuidAtom *pguid, - ULONG ulNumProp); - [[nodiscard]] - HRESULT InitDisplayAttributeInstance(ITfCategoryMgr* pcat); + [[nodiscard]] HRESULT GetDisplayAttributeTrackPropertyRange(TfEditCookie ec, + ITfContext* pic, + ITfRange* pRange, + ITfReadOnlyProperty** ppProp, + IEnumTfRanges** ppEnum, + ULONG* pulNumProp); + [[nodiscard]] HRESULT GetDisplayAttributeData(ITfCategoryMgr* pcat, + TfEditCookie ec, + ITfReadOnlyProperty* pProp, + ITfRange* pRange, + TF_DISPLAYATTRIBUTE* pda, + TfGuidAtom* pguid, + ULONG ulNumProp); + [[nodiscard]] HRESULT InitDisplayAttributeInstance(ITfCategoryMgr* pcat); inline ITfDisplayAttributeMgr* GetDisplayAttributeMgr() { return m_pDAM.get(); } private: - wil::com_ptr_nothrow m_pDAM; - std::vector m_DispAttrProp; + wil::com_ptr_nothrow m_pDAM; + std::vector m_DispAttrProp; }; diff --git a/src/tsf/TfEditses.cpp b/src/tsf/TfEditses.cpp index 13cb38493..a3c1179c3 100644 --- a/src/tsf/TfEditses.cpp +++ b/src/tsf/TfEditses.cpp @@ -19,7 +19,6 @@ Notes: --*/ - #include "precomp.h" #include "TfConvArea.h" #include "TfCatUtil.h" @@ -38,14 +37,17 @@ STDAPI CEditSessionObject::QueryInterface(REFIID riid, void** ppvObj) { *ppvObj = NULL; - if (IsEqualIID(riid, IID_ITfEditSession)) { + if (IsEqualIID(riid, IID_ITfEditSession)) + { *ppvObj = static_cast(this); } - else if (IsEqualIID(riid, IID_IUnknown)) { + else if (IsEqualIID(riid, IID_IUnknown)) + { *ppvObj = static_cast(this); } - if (*ppvObj) { + if (*ppvObj) + { AddRef(); return S_OK; } @@ -53,26 +55,28 @@ STDAPI CEditSessionObject::QueryInterface(REFIID riid, void** ppvObj) return E_NOINTERFACE; } -STDAPI_(ULONG) CEditSessionObject::AddRef() +STDAPI_(ULONG) +CEditSessionObject::AddRef() { return ++m_cRef; } -STDAPI_(ULONG) CEditSessionObject::Release() +STDAPI_(ULONG) +CEditSessionObject::Release() { long cr; cr = --m_cRef; FAIL_FAST_IF(!(cr >= 0)); - if (cr == 0) { + if (cr == 0) + { delete this; } return cr; } - //+--------------------------------------------------------------------------- // // CEditSessionObject::GetAllTextRange @@ -80,8 +84,11 @@ STDAPI_(ULONG) CEditSessionObject::Release() //---------------------------------------------------------------------------- // static -[[nodiscard]] -HRESULT CEditSessionObject::GetAllTextRange(TfEditCookie ec, ITfContext* ic, ITfRange** range, LONG* lpTextLength, TF_HALTCOND* lpHaltCond) +[[nodiscard]] HRESULT CEditSessionObject::GetAllTextRange(TfEditCookie ec, + ITfContext* ic, + ITfRange** range, + LONG* lpTextLength, + TF_HALTCOND* lpHaltCond) { HRESULT hr; @@ -94,16 +101,19 @@ HRESULT CEditSessionObject::GetAllTextRange(TfEditCookie ec, ITfContext* ic, ITf // Create the range that covers all the text. // wil::com_ptr_nothrow rangeFull; - if (FAILED(hr = ic->GetStart(ec, &rangeFull))) { + if (FAILED(hr = ic->GetStart(ec, &rangeFull))) + { return hr; } LONG cch = 0; - if (FAILED(hr = rangeFull->ShiftEnd(ec, LONG_MAX, &cch, lpHaltCond))) { + if (FAILED(hr = rangeFull->ShiftEnd(ec, LONG_MAX, &cch, lpHaltCond))) + { return hr; } - if (FAILED(hr = rangeFull->Clone(range))) { + if (FAILED(hr = rangeFull->Clone(range))) + { return hr; } @@ -112,15 +122,16 @@ HRESULT CEditSessionObject::GetAllTextRange(TfEditCookie ec, ITfContext* ic, ITf return S_OK; } - //+--------------------------------------------------------------------------- // // CEditSessionObject::SetTextInRange // //---------------------------------------------------------------------------- -[[nodiscard]] -HRESULT CEditSessionObject::SetTextInRange(TfEditCookie ec, ITfRange* range, __in_ecount_opt(len) LPWSTR psz, DWORD len) +[[nodiscard]] HRESULT CEditSessionObject::SetTextInRange(TfEditCookie ec, + ITfRange* range, + __in_ecount_opt(len) LPWSTR psz, + DWORD len) { HRESULT hr = E_FAIL; if (g_pConsoleTSF) @@ -132,15 +143,13 @@ HRESULT CEditSessionObject::SetTextInRange(TfEditCookie ec, ITfRange* range, __i return hr; } - //+--------------------------------------------------------------------------- // // CEditSessionObject::ClearTextInRange // //---------------------------------------------------------------------------- -[[nodiscard]] -HRESULT CEditSessionObject::ClearTextInRange(TfEditCookie ec, ITfRange* range) +[[nodiscard]] HRESULT CEditSessionObject::ClearTextInRange(TfEditCookie ec, ITfRange* range) { // // Clear the text in Cicero TOM @@ -154,11 +163,11 @@ HRESULT CEditSessionObject::ClearTextInRange(TfEditCookie ec, ITfRange* range) // //---------------------------------------------------------------------------- -[[nodiscard]] -HRESULT CEditSessionObject::_GetCursorPosition(TfEditCookie ec, CCompCursorPos& CompCursorPos) +[[nodiscard]] HRESULT CEditSessionObject::_GetCursorPosition(TfEditCookie ec, CCompCursorPos& CompCursorPos) { ITfContext* pic = g_pConsoleTSF ? g_pConsoleTSF->GetInputContext() : NULL; - if (pic == NULL) { + if (pic == NULL) + { return E_FAIL; } @@ -168,7 +177,8 @@ HRESULT CEditSessionObject::_GetCursorPosition(TfEditCookie ec, CCompCursorPos& TF_SELECTION sel; sel.range = NULL; - if (SUCCEEDED(hr = pic->GetSelection(ec, TF_DEFAULT_SELECTION, 1, &sel, &cFetched))) { + if (SUCCEEDED(hr = pic->GetSelection(ec, TF_DEFAULT_SELECTION, 1, &sel, &cFetched))) + { wil::com_ptr_nothrow start; LONG ich; TF_HALTCOND hc; @@ -177,7 +187,8 @@ HRESULT CEditSessionObject::_GetCursorPosition(TfEditCookie ec, CCompCursorPos& hc.aHaltPos = (sel.style.ase == TF_AE_START) ? TF_ANCHOR_START : TF_ANCHOR_END; hc.dwFlags = 0; - if (SUCCEEDED(hr = GetAllTextRange(ec, pic, &start, &ich, &hc))) { + if (SUCCEEDED(hr = GetAllTextRange(ec, pic, &start, &ich, &hc))) + { CompCursorPos.SetCursorPosition(ich); } @@ -213,16 +224,20 @@ HRESULT CEditSessionObject::_GetCursorPosition(TfEditCookie ec, CCompCursorPos& // +1 <- 0 -> -1 // -[[nodiscard]] -HRESULT CEditSessionObject::_GetTextAndAttribute(TfEditCookie ec, ITfRange* rangeIn, - std::wstring& CompStr, std::vector& CompGuid, std::wstring& ResultStr, - BOOL bInWriteSession, - CicCategoryMgr* pCicCatMgr, CicDisplayAttributeMgr* pCicDispAttr) +[[nodiscard]] HRESULT CEditSessionObject::_GetTextAndAttribute(TfEditCookie ec, + ITfRange* rangeIn, + std::wstring& CompStr, + std::vector& CompGuid, + std::wstring& ResultStr, + BOOL bInWriteSession, + CicCategoryMgr* pCicCatMgr, + CicDisplayAttributeMgr* pCicDispAttr) { HRESULT hr; ITfContext* pic = g_pConsoleTSF ? g_pConsoleTSF->GetInputContext() : NULL; - if (pic == NULL) { + if (pic == NULL) + { return E_FAIL; } @@ -232,50 +247,56 @@ HRESULT CEditSessionObject::_GetTextAndAttribute(TfEditCookie ec, ITfRange* rang // LONG result_comp; wil::com_ptr_nothrow no_display_attribute_range; - if (FAILED(hr = rangeIn->Clone(&no_display_attribute_range))) { + if (FAILED(hr = rangeIn->Clone(&no_display_attribute_range))) + { return hr; } const GUID* guids[] = { &GUID_PROP_COMPOSING }; - const int guid_size = sizeof(guids) / sizeof(GUID*); + const int guid_size = sizeof(guids) / sizeof(GUID*); - if (FAILED(hr = _GetNoDisplayAttributeRange(ec, rangeIn, - guids, guid_size, - no_display_attribute_range.get()))) { + if (FAILED(hr = _GetNoDisplayAttributeRange(ec, rangeIn, guids, guid_size, no_display_attribute_range.get()))) + { return hr; } - - wil::com_ptr_nothrow propComp; - if (FAILED(hr = pic->TrackProperties(guids, guid_size, // system property - NULL, 0, // application property - &propComp))) { + if (FAILED(hr = pic->TrackProperties(guids, guid_size, // system property + NULL, + 0, // application property + &propComp))) + { return hr; } - wil::com_ptr_nothrow enumComp; - if (FAILED(hr = propComp->EnumRanges(ec, &enumComp, rangeIn))) { + if (FAILED(hr = propComp->EnumRanges(ec, &enumComp, rangeIn))) + { return hr; } wil::com_ptr_nothrow range; - while (enumComp->Next(1, &range, NULL) == S_OK) { + while (enumComp->Next(1, &range, NULL) == S_OK) + { VARIANT var; BOOL fCompExist = FALSE; hr = propComp->GetValue(ec, range.get(), &var); - if (S_OK == hr) { - + if (S_OK == hr) + { wil::com_ptr_nothrow EnumPropVal; - if (wil::try_com_query_to(var.punkVal, &EnumPropVal)) { + if (wil::try_com_query_to(var.punkVal, &EnumPropVal)) + { TF_PROPERTYVAL tfPropertyVal; - while (EnumPropVal->Next(1, &tfPropertyVal, NULL) == S_OK) { - for (int i = 0; i < guid_size; i++) { - if (IsEqualGUID(tfPropertyVal.guidId, *guids[i])) { - if ((V_VT(&tfPropertyVal.varValue) == VT_I4 && V_I4(&tfPropertyVal.varValue) != 0)) { + while (EnumPropVal->Next(1, &tfPropertyVal, NULL) == S_OK) + { + for (int i = 0; i < guid_size; i++) + { + if (IsEqualGUID(tfPropertyVal.guidId, *guids[i])) + { + if ((V_VT(&tfPropertyVal.varValue) == VT_I4 && V_I4(&tfPropertyVal.varValue) != 0)) + { fCompExist = TRUE; break; } @@ -284,7 +305,8 @@ HRESULT CEditSessionObject::_GetTextAndAttribute(TfEditCookie ec, ITfRange* rang VariantClear(&tfPropertyVal.varValue); - if (fCompExist) { + if (fCompExist) + { break; } } @@ -297,25 +319,28 @@ HRESULT CEditSessionObject::_GetTextAndAttribute(TfEditCookie ec, ITfRange* rang wil::com_ptr_nothrow enumProp; wil::com_ptr_nothrow prop; - if (FAILED(hr = pCicDispAttr->GetDisplayAttributeTrackPropertyRange(ec, pic, range.get(), &prop, &enumProp, &ulNumProp))) { + if (FAILED(hr = pCicDispAttr->GetDisplayAttributeTrackPropertyRange(ec, pic, range.get(), &prop, &enumProp, &ulNumProp))) + { return hr; } // use text range for get text wil::com_ptr_nothrow textRange; - if (FAILED(hr = range->Clone(&textRange))) { + if (FAILED(hr = range->Clone(&textRange))) + { return hr; } // use text range for gap text (no property range). wil::com_ptr_nothrow gap_range; - if (FAILED(hr = range->Clone(&gap_range))) { + if (FAILED(hr = range->Clone(&gap_range))) + { return hr; } wil::com_ptr_nothrow pPropRange; - while (enumProp->Next(1, &pPropRange, NULL) == S_OK) { - + while (enumProp->Next(1, &pPropRange, NULL) == S_OK) + { // pick up the gap up to the next property gap_range->ShiftEndToRange(ec, pPropRange.get(), TF_ANCHOR_START); @@ -326,7 +351,8 @@ HRESULT CEditSessionObject::_GetTextAndAttribute(TfEditCookie ec, ITfRange* rang LOG_IF_FAILED(_GetTextAndAttributeGapRange(ec, gap_range.get(), result_comp, - CompStr, CompGuid, + CompStr, + CompGuid, ResultStr)); // @@ -372,7 +398,8 @@ HRESULT CEditSessionObject::_GetTextAndAttribute(TfEditCookie ec, ITfRange* rang textRange->ShiftEndToRange(ec, range.get(), TF_ANCHOR_END); BOOL fEmpty; - while (textRange->IsEmpty(ec, &fEmpty) == S_OK && !fEmpty) { + while (textRange->IsEmpty(ec, &fEmpty) == S_OK && !fEmpty) + { WCHAR wstr0[256 + 1]; ULONG ulcch0 = ARRAYSIZE(wstr0) - 1; textRange->GetText(ec, TF_TF_MOVESTART, wstr0, ulcch0, &ulcch0); @@ -383,7 +410,8 @@ HRESULT CEditSessionObject::_GetTextAndAttribute(TfEditCookie ec, ITfRange* rang TF_DISPLAYATTRIBUTE da; da.bAttr = TF_ATTR_INPUT; - try { + try + { CompGuid.insert(CompGuid.end(), ulcch0, guidatom); CompStr.append(wstr0, ulcch0); } @@ -394,12 +422,12 @@ HRESULT CEditSessionObject::_GetTextAndAttribute(TfEditCookie ec, ITfRange* rang } // out-most while for GUID_PROP_COMPOSING - // // set GUID_PROP_CONIME_TRACKCOMPOSITION // wil::com_ptr_nothrow PropertyTrackComposition; - if (SUCCEEDED(hr = pic->GetProperty(GUID_PROP_CONIME_TRACKCOMPOSITION, &PropertyTrackComposition))) { + if (SUCCEEDED(hr = pic->GetProperty(GUID_PROP_CONIME_TRACKCOMPOSITION, &PropertyTrackComposition))) + { VARIANT var; var.vt = VT_I4; var.lVal = 1; @@ -415,9 +443,12 @@ HRESULT CEditSessionObject::_GetTextAndAttribute(TfEditCookie ec, ITfRange* rang // //---------------------------------------------------------------------------- -[[nodiscard]] -HRESULT CEditSessionObject::_GetTextAndAttributeGapRange(TfEditCookie ec, ITfRange* gap_range, LONG result_comp, - std::wstring& CompStr, std::vector& CompGuid, std::wstring& ResultStr) +[[nodiscard]] HRESULT CEditSessionObject::_GetTextAndAttributeGapRange(TfEditCookie ec, + ITfRange* gap_range, + LONG result_comp, + std::wstring& CompStr, + std::vector& CompGuid, + std::wstring& ResultStr) { TfGuidAtom guidatom; guidatom = TF_INVALID_GUIDATOM; @@ -429,9 +460,11 @@ HRESULT CEditSessionObject::_GetTextAndAttributeGapRange(TfEditCookie ec, ITfRan WCHAR wstr0[256 + 1]; ULONG ulcch0; - while (gap_range->IsEmpty(ec, &fEmpty) == S_OK && !fEmpty) { + while (gap_range->IsEmpty(ec, &fEmpty) == S_OK && !fEmpty) + { wil::com_ptr_nothrow backup_range; - if (FAILED(gap_range->Clone(&backup_range))) { + if (FAILED(gap_range->Clone(&backup_range))) + { return E_FAIL; } @@ -440,18 +473,23 @@ HRESULT CEditSessionObject::_GetTextAndAttributeGapRange(TfEditCookie ec, ITfRan // ulcch0 = ARRAYSIZE(wstr0) - 1; if (FAILED(gap_range->GetText(ec, - TF_TF_MOVESTART, // Move range to next after get text. + TF_TF_MOVESTART, // Move range to next after get text. wstr0, - ulcch0, &ulcch0))) { + ulcch0, + &ulcch0))) + { return E_FAIL; } - try { - if (result_comp <= 0) { + try + { + if (result_comp <= 0) + { CompGuid.insert(CompGuid.end(), ulcch0, guidatom); CompStr.append(wstr0, ulcch0); } - else { + else + { ResultStr.append(wstr0, ulcch0); LOG_IF_FAILED(ClearTextInRange(ec, backup_range.get())); } @@ -459,7 +497,6 @@ HRESULT CEditSessionObject::_GetTextAndAttributeGapRange(TfEditCookie ec, ITfRan CATCH_RETURN(); } - return S_OK; } @@ -469,25 +506,26 @@ HRESULT CEditSessionObject::_GetTextAndAttributeGapRange(TfEditCookie ec, ITfRan // //---------------------------------------------------------------------------- -[[nodiscard]] -HRESULT CEditSessionObject::_GetTextAndAttributePropertyRange(TfEditCookie ec, - ITfRange* pPropRange, - BOOL fCompExist, - LONG result_comp, - BOOL bInWriteSession, - TF_DISPLAYATTRIBUTE da, - TfGuidAtom guidatom, - std::wstring& CompStr, - std::vector& CompGuid, - std::wstring& ResultStr) +[[nodiscard]] HRESULT CEditSessionObject::_GetTextAndAttributePropertyRange(TfEditCookie ec, + ITfRange* pPropRange, + BOOL fCompExist, + LONG result_comp, + BOOL bInWriteSession, + TF_DISPLAYATTRIBUTE da, + TfGuidAtom guidatom, + std::wstring& CompStr, + std::vector& CompGuid, + std::wstring& ResultStr) { BOOL fEmpty; WCHAR wstr0[256 + 1]; ULONG ulcch0; - while (pPropRange->IsEmpty(ec, &fEmpty) == S_OK && !fEmpty) { + while (pPropRange->IsEmpty(ec, &fEmpty) == S_OK && !fEmpty) + { wil::com_ptr_nothrow backup_range; - if (FAILED(pPropRange->Clone(&backup_range))) { + if (FAILED(pPropRange->Clone(&backup_range))) + { return E_FAIL; } @@ -496,22 +534,28 @@ HRESULT CEditSessionObject::_GetTextAndAttributePropertyRange(TfEditCookie ec, // ulcch0 = ARRAYSIZE(wstr0) - 1; if (FAILED(pPropRange->GetText(ec, - TF_TF_MOVESTART, // Move range to next after get text. + TF_TF_MOVESTART, // Move range to next after get text. wstr0, - ulcch0, &ulcch0))) { + ulcch0, + &ulcch0))) + { return E_FAIL; } - try { + try + { // see if there is a valid disp attribute - if (fCompExist == TRUE && result_comp <= 0) { - if (guidatom == TF_INVALID_GUIDATOM) { + if (fCompExist == TRUE && result_comp <= 0) + { + if (guidatom == TF_INVALID_GUIDATOM) + { da.bAttr = TF_ATTR_INPUT; } CompGuid.insert(CompGuid.end(), ulcch0, guidatom); CompStr.append(wstr0, ulcch0); } - else if (bInWriteSession) { + else if (bInWriteSession) + { // if there's no disp attribute attached, it probably means // the part of string is finalized. // @@ -522,7 +566,8 @@ HRESULT CEditSessionObject::_GetTextAndAttributePropertyRange(TfEditCookie ec, // LOG_IF_FAILED(ClearTextInRange(ec, backup_range.get())); } - else { + else + { // // Prevent infinite loop // @@ -541,45 +586,58 @@ HRESULT CEditSessionObject::_GetTextAndAttributePropertyRange(TfEditCookie ec, // //---------------------------------------------------------------------------- -[[nodiscard]] -HRESULT CEditSessionObject::_GetNoDisplayAttributeRange(TfEditCookie ec, ITfRange* rangeIn, const GUID** guids, const int guid_size, ITfRange* no_display_attribute_range) +[[nodiscard]] HRESULT CEditSessionObject::_GetNoDisplayAttributeRange(TfEditCookie ec, + ITfRange* rangeIn, + const GUID** guids, + const int guid_size, + ITfRange* no_display_attribute_range) { ITfContext* pic = g_pConsoleTSF ? g_pConsoleTSF->GetInputContext() : NULL; - if (pic == NULL) { + if (pic == NULL) + { return E_FAIL; } wil::com_ptr_nothrow propComp; - HRESULT hr = pic->TrackProperties(guids, guid_size, // system property - NULL, 0, // application property + HRESULT hr = pic->TrackProperties(guids, guid_size, // system property + NULL, + 0, // application property &propComp); - if (FAILED(hr)) { + if (FAILED(hr)) + { return hr; } wil::com_ptr_nothrow enumComp; hr = propComp->EnumRanges(ec, &enumComp, rangeIn); - if (FAILED(hr)) { + if (FAILED(hr)) + { return hr; } wil::com_ptr_nothrow pRange; - while (enumComp->Next(1, &pRange, NULL) == S_OK) { + while (enumComp->Next(1, &pRange, NULL) == S_OK) + { VARIANT var; BOOL fCompExist = FALSE; hr = propComp->GetValue(ec, pRange.get(), &var); - if (S_OK == hr) { - + if (S_OK == hr) + { wil::com_ptr_nothrow EnumPropVal; - if (wil::try_com_query_to(var.punkVal, &EnumPropVal)) { + if (wil::try_com_query_to(var.punkVal, &EnumPropVal)) + { TF_PROPERTYVAL tfPropertyVal; - while (EnumPropVal->Next(1, &tfPropertyVal, NULL) == S_OK) { - for (int i = 0; i < guid_size; i++) { - if (IsEqualGUID(tfPropertyVal.guidId, *guids[i])) { - if ((V_VT(&tfPropertyVal.varValue) == VT_I4 && V_I4(&tfPropertyVal.varValue) != 0)) { + while (EnumPropVal->Next(1, &tfPropertyVal, NULL) == S_OK) + { + for (int i = 0; i < guid_size; i++) + { + if (IsEqualGUID(tfPropertyVal.guidId, *guids[i])) + { + if ((V_VT(&tfPropertyVal.varValue) == VT_I4 && V_I4(&tfPropertyVal.varValue) != 0)) + { fCompExist = TRUE; break; } @@ -588,15 +646,16 @@ HRESULT CEditSessionObject::_GetNoDisplayAttributeRange(TfEditCookie ec, ITfRang VariantClear(&tfPropertyVal.varValue); - if (fCompExist) { + if (fCompExist) + { break; } } } } - if (!fCompExist) { - + if (!fCompExist) + { // Adjust GAP range's start anchor to the end of proprty range. no_display_attribute_range->ShiftStartToRange(ec, pRange.get(), TF_ANCHOR_START); } @@ -613,8 +672,7 @@ HRESULT CEditSessionObject::_GetNoDisplayAttributeRange(TfEditCookie ec, ITfRang // //---------------------------------------------------------------------------- -[[nodiscard]] -HRESULT CEditSessionCompositionComplete::CompComplete(TfEditCookie ec) +[[nodiscard]] HRESULT CEditSessionCompositionComplete::CompComplete(TfEditCookie ec) { ITfContext* pic = g_pConsoleTSF ? g_pConsoleTSF->GetInputContext() : NULL; RETURN_HR_IF_NULL(E_FAIL, pic); @@ -645,7 +703,8 @@ HRESULT CEditSessionCompositionComplete::CompComplete(TfEditCookie ec) RETURN_HR_IF_NULL(E_FAIL, conv_area); // If there is no string in TextStore we don't have to do anything. - if (!cch) { + if (!cch) + { // Clear composition LOG_IF_FAILED(conv_area->ClearComposition()); return S_OK; @@ -671,15 +730,13 @@ HRESULT CEditSessionCompositionComplete::CompComplete(TfEditCookie ec) return hr; } - //+--------------------------------------------------------------------------- // // CEditSessionCompositionCleanup::EmptyCompositionRange() // //---------------------------------------------------------------------------- -[[nodiscard]] -HRESULT CEditSessionCompositionCleanup::EmptyCompositionRange(TfEditCookie ec) +[[nodiscard]] HRESULT CEditSessionCompositionCleanup::EmptyCompositionRange(TfEditCookie ec) { if (!g_pConsoleTSF) { @@ -711,7 +768,7 @@ HRESULT CEditSessionCompositionCleanup::EmptyCompositionRange(TfEditCookie ec) spRange->ShiftEnd(ec, (cchCompleted - cch), &cch, NULL); } hr = ClearTextInRange(ec, spRange.get()); - g_pConsoleTSF->SetCompletedRangeLength(0); // cleaned up all completed text + g_pConsoleTSF->SetCompletedRangeLength(0); // cleaned up all completed text } } } @@ -719,20 +776,19 @@ HRESULT CEditSessionCompositionCleanup::EmptyCompositionRange(TfEditCookie ec) return hr; } - //+--------------------------------------------------------------------------- // // CEditSessionUpdateCompositionString::UpdateCompositionString // //---------------------------------------------------------------------------- -[[nodiscard]] -HRESULT CEditSessionUpdateCompositionString::UpdateCompositionString(TfEditCookie ec) +[[nodiscard]] HRESULT CEditSessionUpdateCompositionString::UpdateCompositionString(TfEditCookie ec) { HRESULT hr; ITfContext* pic = g_pConsoleTSF ? g_pConsoleTSF->GetInputContext() : NULL; - if (pic == NULL) { + if (pic == NULL) + { return E_FAIL; } @@ -746,19 +802,22 @@ HRESULT CEditSessionUpdateCompositionString::UpdateCompositionString(TfEditCooki } BOOL bInWriteSession; - if (FAILED(hr = pic->InWriteSession(g_pConsoleTSF->GetTfClientId(), &bInWriteSession))) { + if (FAILED(hr = pic->InWriteSession(g_pConsoleTSF->GetTfClientId(), &bInWriteSession))) + { return hr; } wil::com_ptr_nothrow FullTextRange; LONG lTextLength; - if (FAILED(hr = GetAllTextRange(ec, pic, &FullTextRange, &lTextLength))) { + if (FAILED(hr = GetAllTextRange(ec, pic, &FullTextRange, &lTextLength))) + { return hr; } wil::com_ptr_nothrow InterimRange; BOOL fInterim = FALSE; - if (FAILED(hr = _IsInterimSelection(ec, &InterimRange, &fInterim))) { + if (FAILED(hr = _IsInterimSelection(ec, &InterimRange, &fInterim))) + { return hr; } @@ -769,19 +828,30 @@ HRESULT CEditSessionUpdateCompositionString::UpdateCompositionString(TfEditCooki // Create Cicero Category Manager and Display Attribute Manager // hr = _CreateCategoryAndDisplayAttributeManager(&pCicCat, &pDispAttr); - if (SUCCEEDED(hr)) { - if (fInterim) { - hr = _MakeInterimString(ec, FullTextRange.get(), InterimRange.get(), lTextLength, bInWriteSession, pCicCat, pDispAttr); + if (SUCCEEDED(hr)) + { + if (fInterim) + { + hr = _MakeInterimString(ec, + FullTextRange.get(), + InterimRange.get(), + lTextLength, + bInWriteSession, + pCicCat, + pDispAttr); } - else { + else + { hr = _MakeCompositionString(ec, FullTextRange.get(), bInWriteSession, pCicCat, pDispAttr); } } - if (pCicCat) { + if (pCicCat) + { delete pCicCat; } - if (pDispAttr) { + if (pDispAttr) + { delete pDispAttr; } @@ -794,11 +864,13 @@ HRESULT CEditSessionUpdateCompositionString::UpdateCompositionString(TfEditCooki // //---------------------------------------------------------------------------- -[[nodiscard]] -HRESULT CEditSessionUpdateCompositionString::_IsInterimSelection(TfEditCookie ec, ITfRange** pInterimRange, BOOL *pfInterim) +[[nodiscard]] HRESULT CEditSessionUpdateCompositionString::_IsInterimSelection(TfEditCookie ec, + ITfRange** pInterimRange, + BOOL* pfInterim) { ITfContext* pic = g_pConsoleTSF ? g_pConsoleTSF->GetInputContext() : NULL; - if (pic == NULL) { + if (pic == NULL) + { return E_FAIL; } @@ -808,14 +880,17 @@ HRESULT CEditSessionUpdateCompositionString::_IsInterimSelection(TfEditCookie ec sel.range = NULL; *pfInterim = FALSE; - if (pic->GetSelection(ec, TF_DEFAULT_SELECTION, 1, &sel, &cFetched) != S_OK) { + if (pic->GetSelection(ec, TF_DEFAULT_SELECTION, 1, &sel, &cFetched) != S_OK) + { // no selection. we can return S_OK. return S_OK; } - if (sel.style.fInterimChar && sel.range) { + if (sel.style.fInterimChar && sel.range) + { HRESULT hr; - if (FAILED(hr = sel.range->Clone(pInterimRange))) { + if (FAILED(hr = sel.range->Clone(pInterimRange))) + { SafeReleaseClear(sel.range); return hr; } @@ -834,9 +909,11 @@ HRESULT CEditSessionUpdateCompositionString::_IsInterimSelection(TfEditCookie ec // //---------------------------------------------------------------------------- -[[nodiscard]] -HRESULT CEditSessionUpdateCompositionString::_MakeCompositionString(TfEditCookie ec, ITfRange* FullTextRange, BOOL bInWriteSession, - CicCategoryMgr* pCicCatMgr, CicDisplayAttributeMgr* pCicDispAttr) +[[nodiscard]] HRESULT CEditSessionUpdateCompositionString::_MakeCompositionString(TfEditCookie ec, + ITfRange* FullTextRange, + BOOL bInWriteSession, + CicCategoryMgr* pCicCatMgr, + CicDisplayAttributeMgr* pCicDispAttr) { std::wstring CompStr; std::vector CompGuid; @@ -844,10 +921,14 @@ HRESULT CEditSessionUpdateCompositionString::_MakeCompositionString(TfEditCookie std::wstring ResultStr; BOOL fIgnorePreviousCompositionResult = FALSE; - RETURN_IF_FAILED(_GetTextAndAttribute(ec, FullTextRange, - CompStr, CompGuid, ResultStr, + RETURN_IF_FAILED(_GetTextAndAttribute(ec, + FullTextRange, + CompStr, + CompGuid, + ResultStr, bInWriteSession, - pCicCatMgr, pCicDispAttr)); + pCicCatMgr, + pCicDispAttr)); if (g_pConsoleTSF && g_pConsoleTSF->IsPendingCompositionCleanup()) { @@ -874,24 +955,29 @@ HRESULT CEditSessionUpdateCompositionString::_MakeCompositionString(TfEditCookie CConversionArea* conv_area = g_pConsoleTSF ? g_pConsoleTSF->GetConversionArea() : NULL; RETURN_HR_IF_NULL(E_FAIL, conv_area); - if (!ResultStr.empty() && !fIgnorePreviousCompositionResult) { + if (!ResultStr.empty() && !fIgnorePreviousCompositionResult) + { return conv_area->DrawResult(ResultStr); } - if (!CompStr.empty()) { + if (!CompStr.empty()) + { const size_t cchDisplayAttribute = CompGuid.size(); std::vector DisplayAttributes; DisplayAttributes.reserve(cchDisplayAttribute); - for (size_t i = 0; i < cchDisplayAttribute; i++) { + for (size_t i = 0; i < cchDisplayAttribute; i++) + { TF_DISPLAYATTRIBUTE da; ZeroMemory(&da, sizeof(da)); da.bAttr = TF_ATTR_OTHER; GUID guid; - if (SUCCEEDED(cat->GetGUID(CompGuid.at(i), &guid))) { + if (SUCCEEDED(cat->GetGUID(CompGuid.at(i), &guid))) + { CLSID clsid; wil::com_ptr_nothrow dai; - if (SUCCEEDED(dam->GetDisplayAttributeInfo(guid, &dai, &clsid))) { + if (SUCCEEDED(dam->GetDisplayAttributeInfo(guid, &dai, &clsid))) + { dai->GetAttributeInfo(&da); } } @@ -915,14 +1001,13 @@ HRESULT CEditSessionUpdateCompositionString::_MakeCompositionString(TfEditCookie // //---------------------------------------------------------------------------- -[[nodiscard]] -HRESULT CEditSessionUpdateCompositionString::_MakeInterimString(TfEditCookie ec, - ITfRange* FullTextRange, - ITfRange* InterimRange, - LONG lTextLength, - BOOL bInWriteSession, - CicCategoryMgr* pCicCatMgr, - CicDisplayAttributeMgr* pCicDispAttr) +[[nodiscard]] HRESULT CEditSessionUpdateCompositionString::_MakeInterimString(TfEditCookie ec, + ITfRange* FullTextRange, + ITfRange* InterimRange, + LONG lTextLength, + BOOL bInWriteSession, + CicCategoryMgr* pCicCatMgr, + CicDisplayAttributeMgr* pCicDispAttr) { LONG lStartResult; LONG lEndResult; @@ -933,7 +1018,8 @@ HRESULT CEditSessionUpdateCompositionString::_MakeInterimString(TfEditCookie ec, FullTextRange->CompareEnd(ec, InterimRange, TF_ANCHOR_END, &lEndResult); RETURN_HR_IF(E_FAIL, lEndResult != 1); - if (lStartResult < 0) { + if (lStartResult < 0) + { // Make result string. RETURN_IF_FAILED(FullTextRange->ShiftEndToRange(ec, InterimRange, TF_ANCHOR_START)); @@ -943,13 +1029,15 @@ HRESULT CEditSessionUpdateCompositionString::_MakeInterimString(TfEditCookie ec, FAIL_FAST_IF(!(lTextLength > 0)); - if (lTextLength > 0) { + if (lTextLength > 0) + { try { auto wstr = std::make_unique(lTextLength + 1); // Get the result text, finalize it, and erase the result text. - if (SUCCEEDED(FullTextRange->GetText(ec, TF_TF_IGNOREEND, wstr.get(), (ULONG)lTextLength, (ULONG*)&lTextLength))) { + if (SUCCEEDED(FullTextRange->GetText(ec, TF_TF_IGNOREEND, wstr.get(), (ULONG)lTextLength, (ULONG*)&lTextLength))) + { // Clear the TOM LOG_IF_FAILED(ClearTextInRange(ec, FullTextRange)); } @@ -963,11 +1051,14 @@ HRESULT CEditSessionUpdateCompositionString::_MakeInterimString(TfEditCookie ec, std::vector CompGuid; std::wstring _tempResultStr; - RETURN_IF_FAILED(_GetTextAndAttribute(ec, InterimRange, - CompStr, CompGuid, _tempResultStr, + RETURN_IF_FAILED(_GetTextAndAttribute(ec, + InterimRange, + CompStr, + CompGuid, + _tempResultStr, bInWriteSession, - pCicCatMgr, pCicDispAttr)); - + pCicCatMgr, + pCicDispAttr)); // Get display attribute manager ITfDisplayAttributeMgr* dam = pCicDispAttr->GetDisplayAttributeMgr(); @@ -984,20 +1075,24 @@ HRESULT CEditSessionUpdateCompositionString::_MakeInterimString(TfEditCookie ec, CConversionArea* conv_area = g_pConsoleTSF ? g_pConsoleTSF->GetConversionArea() : NULL; RETURN_HR_IF_NULL(E_FAIL, conv_area); - if (!CompStr.empty()) { + if (!CompStr.empty()) + { const size_t cchDisplayAttribute = CompGuid.size(); std::vector DisplayAttributes; DisplayAttributes.reserve(cchDisplayAttribute); - for (size_t i = 0; i < cchDisplayAttribute; i++) { + for (size_t i = 0; i < cchDisplayAttribute; i++) + { TF_DISPLAYATTRIBUTE da; ZeroMemory(&da, sizeof(da)); da.bAttr = TF_ATTR_OTHER; - GUID guid; - if (SUCCEEDED(cat->GetGUID(CompGuid.at(i), &guid))) { + GUID guid; + if (SUCCEEDED(cat->GetGUID(CompGuid.at(i), &guid))) + { CLSID clsid; wil::com_ptr_nothrow dai; - if (SUCCEEDED(dam->GetDisplayAttributeInfo(guid, &dai, &clsid))) { + if (SUCCEEDED(dam->GetDisplayAttributeInfo(guid, &dai, &clsid))) + { dai->GetAttributeInfo(&da); } } @@ -1011,7 +1106,6 @@ HRESULT CEditSessionUpdateCompositionString::_MakeInterimString(TfEditCookie ec, } CATCH_RETURN(); - return S_OK; } @@ -1021,8 +1115,9 @@ HRESULT CEditSessionUpdateCompositionString::_MakeInterimString(TfEditCookie ec, // //---------------------------------------------------------------------------- -[[nodiscard]] -HRESULT CEditSessionUpdateCompositionString::_CreateCategoryAndDisplayAttributeManager(CicCategoryMgr** pCicCatMgr, CicDisplayAttributeMgr** pCicDispAttr) +[[nodiscard]] HRESULT CEditSessionUpdateCompositionString::_CreateCategoryAndDisplayAttributeManager( + CicCategoryMgr** pCicCatMgr, + CicDisplayAttributeMgr** pCicDispAttr) { HRESULT hr = E_OUTOFMEMORY; @@ -1032,18 +1127,22 @@ HRESULT CEditSessionUpdateCompositionString::_CreateCategoryAndDisplayAttributeM // // Create Cicero Category Manager // - pTmpCat = new(std::nothrow) CicCategoryMgr; - if (pTmpCat) { - if (SUCCEEDED(hr = pTmpCat->InitCategoryInstance())) { - + pTmpCat = new (std::nothrow) CicCategoryMgr; + if (pTmpCat) + { + if (SUCCEEDED(hr = pTmpCat->InitCategoryInstance())) + { ITfCategoryMgr* pcat = pTmpCat->GetCategoryMgr(); - if (pcat) { + if (pcat) + { // // Create Cicero Display Attribute Manager // - pTmpDispAttr = new(std::nothrow) CicDisplayAttributeMgr; - if (pTmpDispAttr) { - if (SUCCEEDED(hr = pTmpDispAttr->InitDisplayAttributeInstance(pcat))) { + pTmpDispAttr = new (std::nothrow) CicDisplayAttributeMgr; + if (pTmpDispAttr) + { + if (SUCCEEDED(hr = pTmpDispAttr->InitDisplayAttributeInstance(pcat))) + { *pCicCatMgr = pTmpCat; *pCicDispAttr = pTmpDispAttr; } @@ -1052,11 +1151,14 @@ HRESULT CEditSessionUpdateCompositionString::_CreateCategoryAndDisplayAttributeM } } - if (FAILED(hr)) { - if (pTmpCat) { + if (FAILED(hr)) + { + if (pTmpCat) + { delete pTmpCat; } - if (pTmpDispAttr) { + if (pTmpDispAttr) + { delete pTmpDispAttr; } } diff --git a/src/tsf/TfEditses.h b/src/tsf/TfEditses.h index 6a6d71a07..002bbcafa 100644 --- a/src/tsf/TfEditses.h +++ b/src/tsf/TfEditses.h @@ -29,7 +29,7 @@ const GUID GUID_PROP_CONIME_TRACKCOMPOSITION = { 0x183c627a, 0xb46c, 0x44ad, - {0xb7, 0x97, 0x82, 0xf6, 0xbe, 0xc8, 0x21, 0x31} + { 0xb7, 0x97, 0x82, 0xf6, 0xbe, 0xc8, 0x21, 0x31 } }; //+--------------------------------------------------------------------------- @@ -41,16 +41,19 @@ const GUID GUID_PROP_CONIME_TRACKCOMPOSITION = { class CEditSessionObject : public ITfEditSession { public: - CEditSessionObject() : m_cRef(1) {} - virtual ~CEditSessionObject() { }; + CEditSessionObject() : + m_cRef(1) {} + virtual ~CEditSessionObject(){}; public: // // IUnknown methods // - STDMETHODIMP QueryInterface(REFIID riid, void **ppvObj); - STDMETHODIMP_(ULONG) AddRef(void); - STDMETHODIMP_(ULONG) Release(void); + STDMETHODIMP QueryInterface(REFIID riid, void** ppvObj); + STDMETHODIMP_(ULONG) + AddRef(void); + STDMETHODIMP_(ULONG) + Release(void); // // ITfEditSession method @@ -58,7 +61,7 @@ public: STDMETHODIMP DoEditSession(TfEditCookie ec) { HRESULT hr = _DoEditSession(ec); - Release(); // Release reference count for asynchronous edit session. + Release(); // Release reference count for asynchronous edit session. return hr; } @@ -66,67 +69,76 @@ public: // ImmIfSessionObject methods // protected: - [[nodiscard]] - virtual HRESULT _DoEditSession(TfEditCookie ec) = 0; + [[nodiscard]] virtual HRESULT _DoEditSession(TfEditCookie ec) = 0; // // EditSession methods. // public: - [[nodiscard]] - static HRESULT GetAllTextRange(TfEditCookie ec, ITfContext* ic, ITfRange** range, LONG* lpTextLength, TF_HALTCOND* lpHaltCond=NULL); + [[nodiscard]] static HRESULT GetAllTextRange(TfEditCookie ec, + ITfContext* ic, + ITfRange** range, + LONG* lpTextLength, + TF_HALTCOND* lpHaltCond = NULL); protected: - [[nodiscard]] - HRESULT SetTextInRange(TfEditCookie ec, ITfRange* range, __in_ecount_opt(len) LPWSTR psz, DWORD len); - [[nodiscard]] - HRESULT ClearTextInRange(TfEditCookie ec, ITfRange* range); + [[nodiscard]] HRESULT SetTextInRange(TfEditCookie ec, + ITfRange* range, + __in_ecount_opt(len) LPWSTR psz, + DWORD len); + [[nodiscard]] HRESULT ClearTextInRange(TfEditCookie ec, + ITfRange* range); - [[nodiscard]] - HRESULT _GetTextAndAttribute(TfEditCookie ec, ITfRange* range, - std::wstring& CompStr, std::vector CompGuid, - BOOL bInWriteSession, - CicCategoryMgr* pCicCatMgr, CicDisplayAttributeMgr* pCicDispAttr) + [[nodiscard]] HRESULT _GetTextAndAttribute(TfEditCookie ec, + ITfRange* range, + std::wstring& CompStr, + std::vector CompGuid, + BOOL bInWriteSession, + CicCategoryMgr* pCicCatMgr, + CicDisplayAttributeMgr* pCicDispAttr) { std::wstring ResultStr; - return _GetTextAndAttribute(ec, range, - CompStr, CompGuid, ResultStr, - bInWriteSession, - pCicCatMgr, pCicDispAttr); + return _GetTextAndAttribute(ec, range, CompStr, CompGuid, ResultStr, bInWriteSession, pCicCatMgr, pCicDispAttr); } - [[nodiscard]] - HRESULT _GetTextAndAttribute(TfEditCookie ec, ITfRange* range, - std::wstring& CompStr, std::vector& CompGuid, std::wstring& ResultStr, - BOOL bInWriteSession, - CicCategoryMgr* pCicCatMgr, CicDisplayAttributeMgr* pCicDispAttr); + [[nodiscard]] HRESULT _GetTextAndAttribute(TfEditCookie ec, + ITfRange* range, + std::wstring& CompStr, + std::vector& CompGuid, + std::wstring& ResultStr, + BOOL bInWriteSession, + CicCategoryMgr* pCicCatMgr, + CicDisplayAttributeMgr* pCicDispAttr); + [[nodiscard]] HRESULT _GetTextAndAttributeGapRange(TfEditCookie ec, + ITfRange* gap_range, + LONG result_comp, + std::wstring& CompStr, + std::vector& CompGuid, + std::wstring& ResultStr); - [[nodiscard]] - HRESULT _GetTextAndAttributeGapRange(TfEditCookie ec, ITfRange* gap_range, LONG result_comp, - std::wstring& CompStr, std::vector& CompGuid, std::wstring& ResultStr); + [[nodiscard]] HRESULT _GetTextAndAttributePropertyRange(TfEditCookie ec, + ITfRange* pPropRange, + BOOL fDispAttribute, + LONG result_comp, + BOOL bInWriteSession, + TF_DISPLAYATTRIBUTE da, + TfGuidAtom guidatom, + std::wstring& CompStr, + std::vector& CompGuid, + std::wstring& ResultStr); - [[nodiscard]] - HRESULT _GetTextAndAttributePropertyRange(TfEditCookie ec, ITfRange* pPropRange, - BOOL fDispAttribute, - LONG result_comp, - BOOL bInWriteSession, - TF_DISPLAYATTRIBUTE da, - TfGuidAtom guidatom, - std::wstring& CompStr, std::vector& CompGuid, std::wstring& ResultStr); + [[nodiscard]] HRESULT _GetNoDisplayAttributeRange(TfEditCookie ec, + ITfRange* range, + const GUID** guids, + const int guid_size, + ITfRange* no_display_attribute_range); - [[nodiscard]] - HRESULT _GetNoDisplayAttributeRange(TfEditCookie ec, ITfRange* range, - const GUID** guids, - const int guid_size, - ITfRange* no_display_attribute_range); - - [[nodiscard]] - HRESULT _GetCursorPosition(TfEditCookie ec, - CCompCursorPos& CompCursorPos); + [[nodiscard]] HRESULT _GetCursorPosition(TfEditCookie ec, + CCompCursorPos& CompCursorPos); private: - int m_cRef; + int m_cRef; }; //+--------------------------------------------------------------------------- @@ -138,19 +150,16 @@ private: class CEditSessionCompositionComplete : public CEditSessionObject { public: - CEditSessionCompositionComplete() { } + CEditSessionCompositionComplete() {} - [[nodiscard]] - HRESULT _DoEditSession(TfEditCookie ec) + [[nodiscard]] HRESULT _DoEditSession(TfEditCookie ec) { return CompComplete(ec); } - [[nodiscard]] - HRESULT CompComplete(TfEditCookie ec); + [[nodiscard]] HRESULT CompComplete(TfEditCookie ec); }; - //+--------------------------------------------------------------------------- // // CEditSessionCompositionCleanup @@ -160,19 +169,16 @@ public: class CEditSessionCompositionCleanup : public CEditSessionObject { public: - CEditSessionCompositionCleanup() { } + CEditSessionCompositionCleanup() {} - [[nodiscard]] - HRESULT _DoEditSession(TfEditCookie ec) + [[nodiscard]] HRESULT _DoEditSession(TfEditCookie ec) { return EmptyCompositionRange(ec); } - [[nodiscard]] - HRESULT EmptyCompositionRange(TfEditCookie ec); + [[nodiscard]] HRESULT EmptyCompositionRange(TfEditCookie ec); }; - //+--------------------------------------------------------------------------- // // CEditSessionUpdateCompositionString @@ -184,27 +190,30 @@ class CEditSessionUpdateCompositionString : public CEditSessionObject public: CEditSessionUpdateCompositionString() {} - [[nodiscard]] - HRESULT _DoEditSession(TfEditCookie ec) + [[nodiscard]] HRESULT _DoEditSession(TfEditCookie ec) { return UpdateCompositionString(ec); } - [[nodiscard]] - HRESULT UpdateCompositionString(TfEditCookie ec); + [[nodiscard]] HRESULT UpdateCompositionString(TfEditCookie ec); private: - [[nodiscard]] - HRESULT _IsInterimSelection(TfEditCookie ec, ITfRange** pInterimRange, BOOL *pfInterim); + [[nodiscard]] HRESULT _IsInterimSelection(TfEditCookie ec, ITfRange** pInterimRange, BOOL* pfInterim); - [[nodiscard]] - HRESULT _MakeCompositionString(TfEditCookie ec, ITfRange* FullTextRange, BOOL bInWriteSession, - CicCategoryMgr* pCicCatMgr, CicDisplayAttributeMgr* pCicDispAttr); + [[nodiscard]] HRESULT _MakeCompositionString(TfEditCookie ec, + ITfRange* FullTextRange, + BOOL bInWriteSession, + CicCategoryMgr* pCicCatMgr, + CicDisplayAttributeMgr* pCicDispAttr); - [[nodiscard]] - HRESULT _MakeInterimString(TfEditCookie ec, ITfRange* FullTextRange, ITfRange* InterimRange, LONG lTextLength, BOOL bInWriteSession, - CicCategoryMgr* pCicCatMgr, CicDisplayAttributeMgr* pCicDispAttr); + [[nodiscard]] HRESULT _MakeInterimString(TfEditCookie ec, + ITfRange* FullTextRange, + ITfRange* InterimRange, + LONG lTextLength, + BOOL bInWriteSession, + CicCategoryMgr* pCicCatMgr, + CicDisplayAttributeMgr* pCicDispAttr); - [[nodiscard]] - HRESULT _CreateCategoryAndDisplayAttributeManager(CicCategoryMgr** pCicCatMgr, CicDisplayAttributeMgr** pCicDispAttr); + [[nodiscard]] HRESULT _CreateCategoryAndDisplayAttributeManager(CicCategoryMgr** pCicCatMgr, + CicDisplayAttributeMgr** pCicDispAttr); }; diff --git a/src/tsf/TfTxtevCb.cpp b/src/tsf/TfTxtevCb.cpp index 5a337f4ea..dd4d57083 100644 --- a/src/tsf/TfTxtevCb.cpp +++ b/src/tsf/TfTxtevCb.cpp @@ -19,7 +19,6 @@ Notes: --*/ - #include "precomp.h" #include "ConsoleTSF.h" #include "TfEditses.h" @@ -30,12 +29,13 @@ Notes: // //---------------------------------------------------------------------------- -BOOL CConsoleTSF::_HasCompositionChanged(ITfContext *pInputContext, TfEditCookie ecReadOnly, ITfEditRecord *pEditRecord) +BOOL CConsoleTSF::_HasCompositionChanged(ITfContext* pInputContext, TfEditCookie ecReadOnly, ITfEditRecord* pEditRecord) { BOOL fChanged; if (SUCCEEDED(pEditRecord->GetSelectionStatus(&fChanged))) { - if (fChanged) { + if (fChanged) + { return TRUE; } } @@ -45,28 +45,30 @@ BOOL CConsoleTSF::_HasCompositionChanged(ITfContext *pInputContext, TfEditCookie // wil::com_ptr_nothrow Property; - wil::com_ptr_nothrow FoundRange; + wil::com_ptr_nothrow FoundRange; wil::com_ptr_nothrow PropertyTrackComposition; BOOL bFound = FALSE; - if (SUCCEEDED(pInputContext->GetProperty(GUID_PROP_CONIME_TRACKCOMPOSITION, &Property))) { - + if (SUCCEEDED(pInputContext->GetProperty(GUID_PROP_CONIME_TRACKCOMPOSITION, &Property))) + { wil::com_ptr_nothrow EnumFindFirstTrackCompRange; - if (SUCCEEDED(Property->EnumRanges(ecReadOnly, &EnumFindFirstTrackCompRange, NULL))) { - + if (SUCCEEDED(Property->EnumRanges(ecReadOnly, &EnumFindFirstTrackCompRange, NULL))) + { HRESULT hr; wil::com_ptr_nothrow range; - while ((hr = EnumFindFirstTrackCompRange->Next(1, &range, NULL)) == S_OK) { - + while ((hr = EnumFindFirstTrackCompRange->Next(1, &range, NULL)) == S_OK) + { VARIANT var; VariantInit(&var); hr = Property->GetValue(ecReadOnly, range.get(), &var); - if (SUCCEEDED(hr)) { - if ((V_VT(&var) == VT_I4 && V_I4(&var) != 0)) { + if (SUCCEEDED(hr)) + { + if ((V_VT(&var) == VT_I4 && V_I4(&var) != 0)) + { range->Clone(&FoundRange); bFound = TRUE; // FOUND!! break; @@ -75,7 +77,8 @@ BOOL CConsoleTSF::_HasCompositionChanged(ITfContext *pInputContext, TfEditCookie VariantClear(&var); - if (bFound) { + if (bFound) + { break; // FOUND!! } } @@ -86,41 +89,43 @@ BOOL CConsoleTSF::_HasCompositionChanged(ITfContext *pInputContext, TfEditCookie // if there is no track composition property, // the composition has been changed since we put it. // - if (! bFound) { + if (!bFound) + { return TRUE; } - if (FoundRange == NULL) { + if (FoundRange == NULL) + { return FALSE; } - - bFound = FALSE; // RESET bFound flag... + bFound = FALSE; // RESET bFound flag... wil::com_ptr_nothrow rangeTrackComposition; - if (SUCCEEDED(FoundRange->Clone(&rangeTrackComposition))) { - + if (SUCCEEDED(FoundRange->Clone(&rangeTrackComposition))) + { // // get the text range that does not include read only area for // reconversion. // wil::com_ptr_nothrow rangeAllText; LONG cch; - if (SUCCEEDED(CEditSessionObject::GetAllTextRange(ecReadOnly, pInputContext, &rangeAllText, &cch))) { - + if (SUCCEEDED(CEditSessionObject::GetAllTextRange(ecReadOnly, pInputContext, &rangeAllText, &cch))) + { LONG lResult; - if (SUCCEEDED(rangeTrackComposition->CompareStart(ecReadOnly, rangeAllText.get(), TF_ANCHOR_START, &lResult))) { - + if (SUCCEEDED(rangeTrackComposition->CompareStart(ecReadOnly, rangeAllText.get(), TF_ANCHOR_START, &lResult))) + { // // if the start position of the track composition range is not // the beggining of IC, // the composition has been changed since we put it. // - if (lResult != 0) { - bFound = TRUE; // FOUND!! + if (lResult != 0) + { + bFound = TRUE; // FOUND!! } - else if (SUCCEEDED(rangeTrackComposition->CompareEnd(ecReadOnly, rangeAllText.get(), TF_ANCHOR_END, &lResult))) { - + else if (SUCCEEDED(rangeTrackComposition->CompareEnd(ecReadOnly, rangeAllText.get(), TF_ANCHOR_END, &lResult))) + { // // if the start position of the track composition range is not // the beggining of IC, @@ -129,27 +134,30 @@ BOOL CConsoleTSF::_HasCompositionChanged(ITfContext *pInputContext, TfEditCookie // // If we find the changes in these property, we need to update hIMC. // - const GUID *guids[] = {&GUID_PROP_COMPOSING, - &GUID_PROP_ATTRIBUTE}; + const GUID* guids[] = { &GUID_PROP_COMPOSING, + &GUID_PROP_ATTRIBUTE }; const int guid_size = sizeof(guids) / sizeof(GUID*); wil::com_ptr_nothrow EnumPropertyChanged; - if (lResult != 0) { - bFound = TRUE; // FOUND!! + if (lResult != 0) + { + bFound = TRUE; // FOUND!! } - else if (SUCCEEDED(pEditRecord->GetTextAndPropertyUpdates(TF_GTP_INCL_TEXT, guids, guid_size, &EnumPropertyChanged))) { - + else if (SUCCEEDED(pEditRecord->GetTextAndPropertyUpdates(TF_GTP_INCL_TEXT, guids, guid_size, &EnumPropertyChanged))) + { HRESULT hr; wil::com_ptr_nothrow range; - while ((hr = EnumPropertyChanged->Next(1, &range, NULL)) == S_OK) { + while ((hr = EnumPropertyChanged->Next(1, &range, NULL)) == S_OK) + { BOOL empty; - if (range->IsEmpty(ecReadOnly, &empty) == S_OK && empty) { + if (range->IsEmpty(ecReadOnly, &empty) == S_OK && empty) + { continue; } - bFound = TRUE; // FOUND!! + bFound = TRUE; // FOUND!! break; } } diff --git a/src/tsf/contsf.cpp b/src/tsf/contsf.cpp index b738e0b24..689313dec 100644 --- a/src/tsf/contsf.cpp +++ b/src/tsf/contsf.cpp @@ -9,7 +9,7 @@ extern "C" BOOL ActivateTextServices(HWND hwndConsole, GetSuggestionWindowPos pf { if (!g_pConsoleTSF && hwndConsole) { - g_pConsoleTSF = new(std::nothrow) CConsoleTSF(hwndConsole, pfnPosition); + g_pConsoleTSF = new (std::nothrow) CConsoleTSF(hwndConsole, pfnPosition); if (g_pConsoleTSF && SUCCEEDED(g_pConsoleTSF->Initialize())) { // Conhost calls this function only when the console window has focus. diff --git a/src/tsf/globals.h b/src/tsf/globals.h index 55494e4b9..0fc503f07 100644 --- a/src/tsf/globals.h +++ b/src/tsf/globals.h @@ -20,7 +20,6 @@ Notes: --*/ - #pragma once // @@ -37,22 +36,22 @@ Notes: // #define MYMAX(x, y) (SAFECAST(x, int), SAFECAST(y, int), ((x) > (y) ? (x) : (y))) // // -#define SAFECAST(_obj, _type) (((_type)(_obj)==(_obj)?0:0), (_type)(_obj)) +#define SAFECAST(_obj, _type) (((_type)(_obj) == (_obj) ? 0 : 0), (_type)(_obj)) // // Bitfields don't get along too well with bools, // so here's an easy way to convert them: // -#define BOOLIFY(expr) (!!(expr)) +#define BOOLIFY(expr) (!!(expr)) // // generic COM stuff // -#define SafeReleaseClear(punk) \ -{ \ - if ((punk) != NULL) \ - { \ - (punk)->Release(); \ - (punk) = NULL; \ - } \ -} +#define SafeReleaseClear(punk) \ + { \ + if ((punk) != NULL) \ + { \ + (punk)->Release(); \ + (punk) = NULL; \ + } \ + } diff --git a/src/tsf/precomp.h b/src/tsf/precomp.h index 2f9498367..79b98f316 100644 --- a/src/tsf/precomp.h +++ b/src/tsf/precomp.h @@ -23,22 +23,21 @@ Notes: #include #include -extern "C" -{ - #include +extern "C" { +#include - #include - #include - #include - #include +#include +#include +#include +#include - #include - #include - #include +#include +#include +#include } -#include // Cicero header -#include // ITextStore standard attributes +#include // Cicero header +#include // ITextStore standard attributes // This includes support libraries from the CRT, STL, WIL, and GSL #include "LibraryIncludes.h" @@ -49,5 +48,3 @@ extern "C" #include "TfCtxtComp.h" #include "ConsoleTSF.h" - - diff --git a/src/types/IInputEvent.cpp b/src/types/IInputEvent.cpp index 93c6795f4..f7a3a925a 100644 --- a/src/types/IInputEvent.cpp +++ b/src/types/IInputEvent.cpp @@ -37,7 +37,6 @@ std::deque> IInputEvent::Create(gsl::span to std::deque> // Arguments: diff --git a/src/types/IInputEventStreams.cpp b/src/types/IInputEventStreams.cpp index 87020fd9f..55c2d8ec2 100644 --- a/src/types/IInputEventStreams.cpp +++ b/src/types/IInputEventStreams.cpp @@ -16,18 +16,18 @@ std::wostream& operator<<(std::wostream& stream, const IInputEvent* const pEvent { switch (pEvent->EventType()) { - case InputEventType::KeyEvent: - return stream << static_cast(pEvent); - case InputEventType::MouseEvent: - return stream << static_cast(pEvent); - case InputEventType::WindowBufferSizeEvent: - return stream << static_cast(pEvent); - case InputEventType::MenuEvent: - return stream << static_cast(pEvent); - case InputEventType::FocusEvent: - return stream << static_cast(pEvent); - default: - return stream << L"IInputEvent()"; + case InputEventType::KeyEvent: + return stream << static_cast(pEvent); + case InputEventType::MouseEvent: + return stream << static_cast(pEvent); + case InputEventType::WindowBufferSizeEvent: + return stream << static_cast(pEvent); + case InputEventType::MenuEvent: + return stream << static_cast(pEvent); + case InputEventType::FocusEvent: + return stream << static_cast(pEvent); + default: + return stream << L"IInputEvent()"; } } catch (...) @@ -50,6 +50,7 @@ std::wostream& operator<<(std::wostream& stream, const KeyEvent* const pKeyEvent charData = L"null"; } + // clang-format off return stream << L"KeyEvent(" << keyMotion << L", " << L"repeat: " << pKeyEvent->_repeatCount << L", " << @@ -57,6 +58,7 @@ std::wostream& operator<<(std::wostream& stream, const KeyEvent* const pKeyEvent L"scanCode: " << pKeyEvent->_virtualScanCode << L", " << L"char: " << charData << L", " << L"mods: " << pKeyEvent->_activeModifierKeys << L")"; + // clang-format on } std::wostream& operator<<(std::wostream& stream, const MouseEvent* const pMouseEvent) @@ -66,12 +68,14 @@ std::wostream& operator<<(std::wostream& stream, const MouseEvent* const pMouseE return stream << L"nullptr"; } + // clang-format off return stream << L"MouseEvent(" << L"X: " << pMouseEvent->_position.X << L", " << L"Y: " << pMouseEvent->_position.Y << L", " << L"buttons: " << pMouseEvent->_buttonState << L", " << L"mods: " << pMouseEvent->_activeModifierKeys << L", " << L"events: " << pMouseEvent->_eventFlags << L")"; + // clang-format on } std::wostream& operator<<(std::wostream& stream, const WindowBufferSizeEvent* const pEvent) @@ -81,9 +85,11 @@ std::wostream& operator<<(std::wostream& stream, const WindowBufferSizeEvent* co return stream << L"nullptr"; } + // clang-format off return stream << L"WindowbufferSizeEvent(" << L"X: " << pEvent->_size.X << L", " << L"Y: " << pEvent->_size.Y << L")"; + // clang-format on } std::wostream& operator<<(std::wostream& stream, const MenuEvent* const pMenuEvent) @@ -93,8 +99,7 @@ std::wostream& operator<<(std::wostream& stream, const MenuEvent* const pMenuEve return stream << L"nullptr"; } - return stream << L"MenuEvent(" << - L"CommandId" << pMenuEvent->_commandId << L")"; + return stream << L"MenuEvent(" << L"CommandId" << pMenuEvent->_commandId << L")"; } std::wostream& operator<<(std::wostream& stream, const FocusEvent* const pFocusEvent) @@ -104,6 +109,5 @@ std::wostream& operator<<(std::wostream& stream, const FocusEvent* const pFocusE return stream << L"nullptr"; } - return stream << L"FocusEvent(" << - L"focus" << pFocusEvent->_focus << L")"; + return stream << L"FocusEvent(" << L"focus" << pFocusEvent->_focus << L")"; } diff --git a/src/types/KeyEvent.cpp b/src/types/KeyEvent.cpp index 18e48e6d6..c62a35c90 100644 --- a/src/types/KeyEvent.cpp +++ b/src/types/KeyEvent.cpp @@ -31,7 +31,6 @@ void KeyEvent::SetKeyDown(const bool keyDown) noexcept _keyDown = keyDown; } - void KeyEvent::SetRepeatCount(const WORD repeatCount) noexcept { _repeatCount = repeatCount; diff --git a/src/types/ModifierKeyState.cpp b/src/types/ModifierKeyState.cpp index 8f0f5bfbd..9d1fd7017 100644 --- a/src/types/ModifierKeyState.cpp +++ b/src/types/ModifierKeyState.cpp @@ -28,45 +28,45 @@ std::unordered_set FromVkKeyScan(const short vkKeyScanFlags) switch (vkKeyScanFlags) { - case VkKeyScanModState::None: - break; - case VkKeyScanModState::ShiftPressed: - keyState.insert(ModifierKeyState::Shift); - break; - case VkKeyScanModState::CtrlPressed: - keyState.insert(ModifierKeyState::LeftCtrl); - keyState.insert(ModifierKeyState::RightCtrl); - break; - case VkKeyScanModState::ShiftAndCtrlPressed: - keyState.insert(ModifierKeyState::Shift); - keyState.insert(ModifierKeyState::LeftCtrl); - keyState.insert(ModifierKeyState::RightCtrl); - break; - case VkKeyScanModState::AltPressed: - keyState.insert(ModifierKeyState::LeftAlt); - keyState.insert(ModifierKeyState::RightAlt); - break; - case VkKeyScanModState::ShiftAndAltPressed: - keyState.insert(ModifierKeyState::Shift); - keyState.insert(ModifierKeyState::LeftAlt); - keyState.insert(ModifierKeyState::RightAlt); - break; - case VkKeyScanModState::CtrlAndAltPressed: - keyState.insert(ModifierKeyState::LeftCtrl); - keyState.insert(ModifierKeyState::RightCtrl); - keyState.insert(ModifierKeyState::LeftAlt); - keyState.insert(ModifierKeyState::RightAlt); - break; - case VkKeyScanModState::ModPressed: - keyState.insert(ModifierKeyState::Shift); - keyState.insert(ModifierKeyState::LeftCtrl); - keyState.insert(ModifierKeyState::RightCtrl); - keyState.insert(ModifierKeyState::LeftAlt); - keyState.insert(ModifierKeyState::RightAlt); - break; - default: - THROW_HR(E_INVALIDARG); - break; + case VkKeyScanModState::None: + break; + case VkKeyScanModState::ShiftPressed: + keyState.insert(ModifierKeyState::Shift); + break; + case VkKeyScanModState::CtrlPressed: + keyState.insert(ModifierKeyState::LeftCtrl); + keyState.insert(ModifierKeyState::RightCtrl); + break; + case VkKeyScanModState::ShiftAndCtrlPressed: + keyState.insert(ModifierKeyState::Shift); + keyState.insert(ModifierKeyState::LeftCtrl); + keyState.insert(ModifierKeyState::RightCtrl); + break; + case VkKeyScanModState::AltPressed: + keyState.insert(ModifierKeyState::LeftAlt); + keyState.insert(ModifierKeyState::RightAlt); + break; + case VkKeyScanModState::ShiftAndAltPressed: + keyState.insert(ModifierKeyState::Shift); + keyState.insert(ModifierKeyState::LeftAlt); + keyState.insert(ModifierKeyState::RightAlt); + break; + case VkKeyScanModState::CtrlAndAltPressed: + keyState.insert(ModifierKeyState::LeftCtrl); + keyState.insert(ModifierKeyState::RightCtrl); + keyState.insert(ModifierKeyState::LeftAlt); + keyState.insert(ModifierKeyState::RightAlt); + break; + case VkKeyScanModState::ModPressed: + keyState.insert(ModifierKeyState::Shift); + keyState.insert(ModifierKeyState::LeftCtrl); + keyState.insert(ModifierKeyState::RightCtrl); + keyState.insert(ModifierKeyState::LeftAlt); + keyState.insert(ModifierKeyState::RightAlt); + break; + default: + THROW_HR(E_INVALIDARG); + break; } return keyState; @@ -74,8 +74,7 @@ std::unordered_set FromVkKeyScan(const short vkKeyScanFlags) using ModifierKeyStateMapping = std::pair; -constexpr static ModifierKeyStateMapping ModifierKeyStateTranslationTable[] = -{ +constexpr static ModifierKeyStateMapping ModifierKeyStateTranslationTable[] = { { ModifierKeyState::RightAlt, RIGHT_ALT_PRESSED }, { ModifierKeyState::LeftAlt, LEFT_ALT_PRESSED }, { ModifierKeyState::RightCtrl, RIGHT_CTRL_PRESSED }, diff --git a/src/types/convert.cpp b/src/types/convert.cpp index a87912ff5..7ca12962c 100644 --- a/src/types/convert.cpp +++ b/src/types/convert.cpp @@ -26,8 +26,7 @@ static const WORD leftShiftScanCode = 0x2A; // Return Value: // - The UTF-16 wide string. // - NOTE: Throws suitable HRESULT errors from memory allocation, safe math, or MultiByteToWideChar failures. -[[nodiscard]] -std::wstring ConvertToW(const UINT codePage, const std::string_view source) +[[nodiscard]] std::wstring ConvertToW(const UINT codePage, const std::string_view source) { // If there's nothing to convert, bail early. if (source.empty()) @@ -65,20 +64,21 @@ std::wstring ConvertToW(const UINT codePage, const std::string_view source) // Return Value: // - The multibyte string encoded in the given codepage // - NOTE: Throws suitable HRESULT errors from memory allocation, safe math, or MultiByteToWideChar failures. -[[nodiscard]] -std::string ConvertToA(const UINT codepage, const std::wstring_view source) +[[nodiscard]] std::string ConvertToA(const UINT codepage, const std::wstring_view source) { // If there's nothing to convert, bail early. if (source.empty()) { return {}; } - + int iSource; // convert to int because Wc2Mb requires it. THROW_IF_FAILED(SizeTToInt(source.size(), &iSource)); // Ask how much space we will need. -#pragma prefast(suppress:__WARNING_W2A_BEST_FIT, "WC_NO_BEST_FIT_CHARS doesn't work in many codepages. Retain old behavior.") + // clang-format off +#pragma prefast(suppress: __WARNING_W2A_BEST_FIT, "WC_NO_BEST_FIT_CHARS doesn't work in many codepages. Retain old behavior.") + // clang-format on int const iTarget = WideCharToMultiByte(codepage, 0, source.data(), iSource, nullptr, 0, nullptr, nullptr); THROW_LAST_ERROR_IF(0 == iTarget); @@ -90,7 +90,9 @@ std::string ConvertToA(const UINT codepage, const std::wstring_view source) THROW_IF_NULL_ALLOC(psOut.get()); // Attempt conversion for real. -#pragma prefast(suppress:__WARNING_W2A_BEST_FIT, "WC_NO_BEST_FIT_CHARS doesn't work in many codepages. Retain old behavior.") + // clang-format off +#pragma prefast(suppress: __WARNING_W2A_BEST_FIT, "WC_NO_BEST_FIT_CHARS doesn't work in many codepages. Retain old behavior.") + // clang-format on THROW_LAST_ERROR_IF(0 == WideCharToMultiByte(codepage, 0, source.data(), iSource, psOut.get(), iTarget, nullptr, nullptr)); // Return as a string @@ -105,8 +107,7 @@ std::string ConvertToA(const UINT codepage, const std::wstring_view source) // Return Value: // - Length in characters of multibyte buffer that would be required to hold this text after conversion // - NOTE: Throws suitable HRESULT errors from memory allocation, safe math, or WideCharToMultiByte failures. -[[nodiscard]] -size_t GetALengthFromW(const UINT codepage, const std::wstring_view source) +[[nodiscard]] size_t GetALengthFromW(const UINT codepage, const std::wstring_view source) { // If there's no bytes, bail early. if (source.empty()) @@ -118,7 +119,9 @@ size_t GetALengthFromW(const UINT codepage, const std::wstring_view source) THROW_IF_FAILED(SizeTToInt(source.size(), &iSource)); // Ask how many bytes this string consumes in the other codepage -#pragma prefast(suppress:__WARNING_W2A_BEST_FIT, "WC_NO_BEST_FIT_CHARS doesn't work in many codepages. Retain old behavior.") + // clang-format off +#pragma prefast(suppress: __WARNING_W2A_BEST_FIT, "WC_NO_BEST_FIT_CHARS doesn't work in many codepages. Retain old behavior.") + // clang-format on int const iTarget = WideCharToMultiByte(codepage, 0, source.data(), iSource, nullptr, 0, nullptr, nullptr); THROW_LAST_ERROR_IF(0 == iTarget); @@ -164,7 +167,6 @@ std::deque> CharToKeyEvents(const wchar_t wch, return convertedEvents; } - // Routine Description: // - converts a wchar_t into a series of KeyEvents as if it was typed // using the keyboard @@ -384,7 +386,7 @@ CodepointWidth GetQuickCharWidth(const wchar_t wch) noexcept // 0x2010 - 0x2B59 varies between narrow, ambiguous, and wide by character and font (Unicode 9.0) // However, there are a bunch of retroactive-emoji in this range. Things that weren't emoji and then they became // "emoji" later. As a result, they jumped from a fixed narrow definition to a now ambiguous definition. - // There are others in this range already defined as wide or ambiguous, but we're just going to + // There are others in this range already defined as wide or ambiguous, but we're just going to // implicitly say they're all ambiguous here to force a font lookup. // I picked the ones that looked like color double-wide emoji in my browser that weren't already // covered easily by the half-width/full-width table (see CodepointWidthDetector.cpp) @@ -467,8 +469,7 @@ CodepointWidth GetQuickCharWidth(const wchar_t wch) noexcept (0x2B05 <= wch && wch <= 0x2B07) || (0x2B1B <= wch && wch <= 0x2B1C) || 0x2B50 == wch || - 0x2B55 == wch - ) + 0x2B55 == wch) { return CodepointWidth::Ambiguous; } diff --git a/src/types/inc/CodepointWidthDetector.hpp b/src/types/inc/CodepointWidthDetector.hpp index ecac9b808..f4324f4c8 100644 --- a/src/types/inc/CodepointWidthDetector.hpp +++ b/src/types/inc/CodepointWidthDetector.hpp @@ -18,28 +18,26 @@ Author: static_assert(sizeof(unsigned int) == sizeof(wchar_t) * 2, "UnicodeRange expects to be able to store a unicode codepoint in an unsigned int"); - // use to measure the width of a codepoint class CodepointWidthDetector final { protected: - // used to store range data in CodepointWidthDetector's internal map class UnicodeRange final { public: UnicodeRange(const unsigned int lowerBound, const unsigned int upperBound) : - _lowerBound{ lowerBound }, - _upperBound{ upperBound }, - _isBounds{ true } + _lowerBound{ lowerBound }, + _upperBound{ upperBound }, + _isBounds{ true } { } UnicodeRange(const unsigned int searchTerm) : - _lowerBound{ searchTerm }, - _upperBound{ searchTerm }, - _isBounds{ false } + _lowerBound{ searchTerm }, + _upperBound{ searchTerm }, + _isBounds{ false } { } diff --git a/src/types/inc/IInputEvent.hpp b/src/types/inc/IInputEvent.hpp index 25bba2792..ded7c903b 100644 --- a/src/types/inc/IInputEvent.hpp +++ b/src/types/inc/IInputEvent.hpp @@ -18,7 +18,7 @@ Author: #ifndef ALTNUMPAD_BIT // from winconp.h -#define ALTNUMPAD_BIT 0x04000000 // AltNumpad OEM char (copied from ntuser\inc\kbd.h) +#define ALTNUMPAD_BIT 0x04000000 // AltNumpad OEM char (copied from ntuser\inc\kbd.h) #endif #include @@ -50,8 +50,8 @@ public: IInputEvent() = default; IInputEvent(const IInputEvent&) = default; IInputEvent(IInputEvent&&) = default; - IInputEvent& operator=(const IInputEvent&)& = default; - IInputEvent& operator=(IInputEvent&&)& = default; + IInputEvent& operator=(const IInputEvent&) & = default; + IInputEvent& operator=(IInputEvent&&) & = default; virtual INPUT_RECORD ToInputRecord() const noexcept = 0; @@ -64,16 +64,15 @@ public: inline IInputEvent::~IInputEvent() { - } #ifdef UNIT_TESTING std::wostream& operator<<(std::wostream& stream, const IInputEvent* pEvent); #endif -#define ALT_PRESSED (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED) -#define CTRL_PRESSED (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED) -#define MOD_PRESSED (SHIFT_PRESSED | ALT_PRESSED | CTRL_PRESSED) +#define ALT_PRESSED (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED) +#define CTRL_PRESSED (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED) +#define MOD_PRESSED (SHIFT_PRESSED | ALT_PRESSED | CTRL_PRESSED) // Note taken from VkKeyScan docs (https://msdn.microsoft.com/en-us/library/windows/desktop/ms646329(v=vs.85).aspx): // For keyboard layouts that use the right-hand ALT key as a shift key @@ -151,7 +150,7 @@ public: _repeatCount{ 0 }, _virtualKeyCode{ 0 }, _virtualScanCode{ 0 }, - _charData { 0 }, + _charData{ 0 }, _activeModifierKeys{ 0 } { } @@ -159,8 +158,8 @@ public: ~KeyEvent(); KeyEvent(const KeyEvent&) = default; KeyEvent(KeyEvent&&) = default; - KeyEvent& operator=(const KeyEvent&)& = default; - KeyEvent& operator=(KeyEvent&&)& = default; + KeyEvent& operator=(const KeyEvent&) & = default; + KeyEvent& operator=(KeyEvent&&) & = default; INPUT_RECORD ToInputRecord() const noexcept override; InputEventType EventType() const noexcept override; @@ -303,8 +302,8 @@ public: ~MouseEvent(); MouseEvent(const MouseEvent&) = default; MouseEvent(MouseEvent&&) = default; - MouseEvent& operator=(const MouseEvent&)& = default; - MouseEvent& operator=(MouseEvent&&)& = default; + MouseEvent& operator=(const MouseEvent&) & = default; + MouseEvent& operator=(MouseEvent&&) & = default; INPUT_RECORD ToInputRecord() const noexcept override; InputEventType EventType() const noexcept override; @@ -370,8 +369,8 @@ public: ~WindowBufferSizeEvent(); WindowBufferSizeEvent(const WindowBufferSizeEvent&) = default; WindowBufferSizeEvent(WindowBufferSizeEvent&&) = default; - WindowBufferSizeEvent& operator=(const WindowBufferSizeEvent&)& = default; - WindowBufferSizeEvent& operator=(WindowBufferSizeEvent&&)& = default; + WindowBufferSizeEvent& operator=(const WindowBufferSizeEvent&) & = default; + WindowBufferSizeEvent& operator=(WindowBufferSizeEvent&&) & = default; INPUT_RECORD ToInputRecord() const noexcept override; InputEventType EventType() const noexcept override; @@ -411,8 +410,8 @@ public: ~MenuEvent(); MenuEvent(const MenuEvent&) = default; MenuEvent(MenuEvent&&) = default; - MenuEvent& operator=(const MenuEvent&)& = default; - MenuEvent& operator=(MenuEvent&&)& = default; + MenuEvent& operator=(const MenuEvent&) & = default; + MenuEvent& operator=(MenuEvent&&) & = default; INPUT_RECORD ToInputRecord() const noexcept override; InputEventType EventType() const noexcept override; @@ -452,8 +451,8 @@ public: ~FocusEvent(); FocusEvent(const FocusEvent&) = default; FocusEvent(FocusEvent&&) = default; - FocusEvent& operator=(const FocusEvent&)& = default; - FocusEvent& operator=(FocusEvent&&)& = default; + FocusEvent& operator=(const FocusEvent&) & = default; + FocusEvent& operator=(FocusEvent&&) & = default; INPUT_RECORD ToInputRecord() const noexcept override; InputEventType EventType() const noexcept override; diff --git a/src/types/inc/Utf16Parser.hpp b/src/types/inc/Utf16Parser.hpp index 4d541eb8f..d093b3396 100644 --- a/src/types/inc/Utf16Parser.hpp +++ b/src/types/inc/Utf16Parser.hpp @@ -18,13 +18,12 @@ Author(s): #include #include - class Utf16Parser final { private: static constexpr unsigned short IndicatorBitCount = 6; static constexpr unsigned short WcharShiftAmount = sizeof(wchar_t) * 8 - IndicatorBitCount; - static constexpr std::bitset LeadingSurrogateMask = { 54 }; // 110 110 indicates a leading surrogate + static constexpr std::bitset LeadingSurrogateMask = { 54 }; // 110 110 indicates a leading surrogate static constexpr std::bitset TrailingSurrogateMask = { 55 }; // 110 111 indicates a trailing surrogate public: diff --git a/src/types/inc/convert.hpp b/src/types/inc/convert.hpp index 10b574e6c..44c6783c0 100644 --- a/src/types/inc/convert.hpp +++ b/src/types/inc/convert.hpp @@ -26,17 +26,14 @@ enum class CodepointWidth : BYTE Invalid // not a valid unicode codepoint }; -[[nodiscard]] -std::wstring ConvertToW(const UINT codepage, - const std::string_view source); +[[nodiscard]] std::wstring ConvertToW(const UINT codepage, + const std::string_view source); -[[nodiscard]] -std::string ConvertToA(const UINT codepage, - const std::wstring_view source); +[[nodiscard]] std::string ConvertToA(const UINT codepage, + const std::wstring_view source); -[[nodiscard]] -size_t GetALengthFromW(const UINT codepage, - const std::wstring_view source); +[[nodiscard]] size_t GetALengthFromW(const UINT codepage, + const std::wstring_view source); std::deque> CharToKeyEvents(const wchar_t wch, const unsigned int codepage); diff --git a/src/types/inc/utils.hpp b/src/types/inc/utils.hpp index 66f8ee978..84204a236 100644 --- a/src/types/inc/utils.hpp +++ b/src/types/inc/utils.hpp @@ -37,9 +37,9 @@ namespace Microsoft::Console::Utils constexpr uint32_t EndianSwap(uint32_t value) { return (value & 0xFF000000) >> 24 | - (value & 0x00FF0000) >> 8 | - (value & 0x0000FF00) << 8 | - (value & 0x000000FF) << 24; + (value & 0x00FF0000) >> 8 | + (value & 0x0000FF00) << 8 | + (value & 0x000000FF) << 24; } constexpr unsigned long EndianSwap(unsigned long value) diff --git a/src/types/inc/viewport.hpp b/src/types/inc/viewport.hpp index 09b7d67c0..d9d8d5c24 100644 --- a/src/types/inc/viewport.hpp +++ b/src/types/inc/viewport.hpp @@ -24,8 +24,8 @@ namespace Microsoft::Console::Types ~Viewport() {} Viewport(const Viewport& other) noexcept; Viewport(Viewport&&) = default; - Viewport& operator=(const Viewport&)& = default; - Viewport& operator=(Viewport&&)& = default; + Viewport& operator=(const Viewport&) & = default; + Viewport& operator=(Viewport&&) & = default; static Viewport Empty() noexcept; @@ -94,12 +94,10 @@ namespace Microsoft::Console::Types bool TrimToViewport(_Inout_ SMALL_RECT* const psr) const noexcept; void ConvertToOrigin(_Inout_ SMALL_RECT* const psr) const noexcept; void ConvertToOrigin(_Inout_ COORD* const pcoord) const noexcept; - [[nodiscard]] - Viewport ConvertToOrigin(const Viewport& other) const noexcept; + [[nodiscard]] Viewport ConvertToOrigin(const Viewport& other) const noexcept; void ConvertFromOrigin(_Inout_ SMALL_RECT* const psr) const noexcept; void ConvertFromOrigin(_Inout_ COORD* const pcoord) const noexcept; - [[nodiscard]] - Viewport ConvertFromOrigin(const Viewport& other) const noexcept; + [[nodiscard]] Viewport ConvertFromOrigin(const Viewport& other) const noexcept; SMALL_RECT ToExclusive() const noexcept; SMALL_RECT ToInclusive() const noexcept; @@ -109,17 +107,13 @@ namespace Microsoft::Console::Types bool IsValid() const noexcept; - [[nodiscard]] - static Viewport Offset(const Viewport& original, const COORD delta); + [[nodiscard]] static Viewport Offset(const Viewport& original, const COORD delta); - [[nodiscard]] - static Viewport Union(const Viewport& lhs, const Viewport& rhs) noexcept; + [[nodiscard]] static Viewport Union(const Viewport& lhs, const Viewport& rhs) noexcept; - [[nodiscard]] - static Viewport Intersect(const Viewport& lhs, const Viewport& rhs) noexcept; + [[nodiscard]] static Viewport Intersect(const Viewport& lhs, const Viewport& rhs) noexcept; - [[nodiscard]] - static SomeViewports Subtract(const Viewport& original, const Viewport& removeMe) noexcept; + [[nodiscard]] static SomeViewports Subtract(const Viewport& original, const Viewport& removeMe) noexcept; private: Viewport(const SMALL_RECT sr) noexcept; @@ -135,7 +129,7 @@ namespace Microsoft::Console::Types struct SomeViewports final { unsigned char used{ 0 }; - std::array viewports { Viewport::Empty(), Viewport::Empty(), Viewport::Empty(), Viewport::Empty() }; + std::array viewports{ Viewport::Empty(), Viewport::Empty(), Viewport::Empty(), Viewport::Empty() }; // These two methods are to make this vaguely look like a std::vector. diff --git a/src/types/precomp.h b/src/types/precomp.h index 5e4fa03d4..972fde4ea 100644 --- a/src/types/precomp.h +++ b/src/types/precomp.h @@ -17,6 +17,8 @@ Abstract: #pragma once +// clang-format off + #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers #endif @@ -85,3 +87,5 @@ constexpr NTSTATUS NTSTATUS_FROM_HRESULT(HRESULT hr) noexcept { return NTSTATUS_FROM_WIN32(HRESULT_CODE(hr)); } + +// clang-format on diff --git a/src/types/ut_types/UuidTests.cpp b/src/types/ut_types/UuidTests.cpp index 4788542af..b1e3ef1c0 100644 --- a/src/types/ut_types/UuidTests.cpp +++ b/src/types/ut_types/UuidTests.cpp @@ -16,15 +16,13 @@ using namespace Microsoft::Console::Utils; class UuidTests { // {AD56DE9E-5167-41B6-80EB-FB19F7927D1A} - static constexpr GUID TEST_NAMESPACE_GUID{ 0xad56de9e, 0x5167, 0x41b6, - { 0x80, 0xeb, 0xfb, 0x19, 0xf7, 0x92, 0x7d, 0x1a } }; + static constexpr GUID TEST_NAMESPACE_GUID{ 0xad56de9e, 0x5167, 0x41b6, { 0x80, 0xeb, 0xfb, 0x19, 0xf7, 0x92, 0x7d, 0x1a } }; TEST_CLASS(UuidTests); TEST_METHOD(TestV5UuidU8String) { - const GUID uuidExpected{ 0x8b9d4336, 0x0c82, 0x54c4, - { 0xb3, 0x15, 0xf1, 0xd2, 0xd2, 0x7e, 0xc6, 0xda} }; + const GUID uuidExpected{ 0x8b9d4336, 0x0c82, 0x54c4, { 0xb3, 0x15, 0xf1, 0xd2, 0xd2, 0x7e, 0xc6, 0xda } }; std::string name{ "testing" }; auto uuidActual = CreateV5Uuid(TEST_NAMESPACE_GUID, gsl::as_bytes(gsl::make_span(name))); @@ -34,8 +32,7 @@ class UuidTests TEST_METHOD(TestV5UuidU16String) { - const GUID uuidExpected{ 0xe04fb1f7, 0x739d, 0x5d63, - { 0xbb, 0x18, 0xe0, 0xea, 0x00, 0xb1, 0x9e, 0xe8 } }; + const GUID uuidExpected{ 0xe04fb1f7, 0x739d, 0x5d63, { 0xbb, 0x18, 0xe0, 0xea, 0x00, 0xb1, 0x9e, 0xe8 } }; // This'll come out in little endian; the reference GUID was generated as such. std::wstring name{ L"testing" }; diff --git a/src/types/utils.cpp b/src/types/utils.cpp index 51f4567ef..73dbd6efc 100644 --- a/src/types/utils.cpp +++ b/src/types/utils.cpp @@ -7,7 +7,7 @@ using namespace Microsoft::Console; // Function Description: -// - Clamps a long in between `min` and `SHRT_MAX` +// - Clamps a long in between `min` and `SHRT_MAX` // Arguments: // - value: the value to clamp // - min: the minimum value to clamp to @@ -16,8 +16,8 @@ using namespace Microsoft::Console; short Utils::ClampToShortMax(const long value, const short min) { return static_cast(std::clamp(value, - static_cast(min), - static_cast(SHRT_MAX))); + static_cast(min), + static_cast(SHRT_MAX))); } // Function Description: @@ -30,11 +30,7 @@ short Utils::ClampToShortMax(const long value, const short min) std::wstring Utils::GuidToString(const GUID guid) { wchar_t guid_cstr[39]; - const int written = swprintf(guid_cstr, sizeof(guid_cstr), - L"{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}", - guid.Data1, guid.Data2, guid.Data3, - guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3], - guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]); + const int written = swprintf(guid_cstr, sizeof(guid_cstr), L"{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}", guid.Data1, guid.Data2, guid.Data3, guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]); THROW_HR_IF(E_INVALIDARG, written == -1); @@ -130,6 +126,7 @@ void Utils::InitializeCampbellColorTable(gsl::span& table) { THROW_HR_IF(E_INVALIDARG, table.size() < 16); + // clang-format off table[0] = RGB( 12, 12, 12); table[1] = RGB( 197, 15, 31); table[2] = RGB( 19, 161, 14); @@ -146,6 +143,7 @@ void Utils::InitializeCampbellColorTable(gsl::span& table) table[13] = RGB( 180, 0, 158); table[14] = RGB( 97, 214, 214); table[15] = RGB( 242, 242, 242); + // clang-format on } // Function Description: @@ -159,6 +157,7 @@ void Utils::Initialize256ColorTable(gsl::span& table) { THROW_HR_IF(E_INVALIDARG, table.size() < 256); + // clang-format off table[0] = RGB( 0x00, 0x00, 0x00); table[1] = RGB( 0x80, 0x00, 0x00); table[2] = RGB( 0x00, 0x80, 0x00); @@ -415,7 +414,7 @@ void Utils::Initialize256ColorTable(gsl::span& table) table[253] = RGB(0xda, 0xda, 0xda); table[254] = RGB(0xe4, 0xe4, 0xe4); table[255] = RGB(0xee, 0xee, 0xee); - + // clang-format on } // Function Description: @@ -428,7 +427,7 @@ void Utils::Initialize256ColorTable(gsl::span& table) void Utils::SetColorTableAlpha(gsl::span& table, const BYTE newAlpha) { const auto shiftedAlpha = newAlpha << 24; - for( auto& color : table) + for (auto& color : table) { WI_UpdateFlagsInMask(color, 0xff000000, shiftedAlpha); } @@ -461,8 +460,8 @@ GUID Utils::CreateV5Uuid(const GUID& namespaceGuid, const gsl::span buffer; THROW_IF_NTSTATUS_FAILED(BCryptFinishHash(hash.get(), buffer.data(), gsl::narrow(buffer.size()), 0)); - buffer[6] = (buffer[6] & 0x0F) | 0x50; // set the uuid version to 5 - buffer[8] = (buffer[8] & 0x3F) | 0x80; // set the variant to 2 (RFC4122) + buffer[6] = (buffer[6] & 0x0F) | 0x50; // set the uuid version to 5 + buffer[8] = (buffer[8] & 0x3F) | 0x80; // set the variant to 2 (RFC4122) // We're using memcpy here pursuant to N4713 6.7.2/3 [basic.types], // "...the underlying bytes making up the object can be copied into an array diff --git a/src/types/viewport.cpp b/src/types/viewport.cpp index 8f076afc9..8484b6536 100644 --- a/src/types/viewport.cpp +++ b/src/types/viewport.cpp @@ -9,13 +9,11 @@ using namespace Microsoft::Console::Types; Viewport::Viewport(const SMALL_RECT sr) noexcept : _sr(sr) { - } Viewport::Viewport(const Viewport& other) noexcept : _sr(other._sr) { - } Viewport Viewport::Empty() noexcept @@ -48,8 +46,7 @@ Viewport Viewport::FromDimensions(const COORD origin, const short width, const short height) noexcept { - return Viewport::FromExclusive({ origin.X, origin.Y, - origin.X + width, origin.Y + height }); + return Viewport::FromExclusive({ origin.X, origin.Y, origin.X + width, origin.Y + height }); } // Function Description: @@ -63,8 +60,7 @@ Viewport Viewport::FromDimensions(const COORD origin, Viewport Viewport::FromDimensions(const COORD origin, const COORD dimensions) noexcept { - return Viewport::FromExclusive({ origin.X, origin.Y, - origin.X + dimensions.X, origin.Y + dimensions.Y }); + return Viewport::FromExclusive({ origin.X, origin.Y, origin.X + dimensions.X, origin.Y + dimensions.Y }); } // Function Description: @@ -87,8 +83,7 @@ Viewport Viewport::FromDimensions(const COORD dimensions) noexcept // - a 1x1 Viewport at the given coordinate Viewport Viewport::FromCoord(const COORD origin) noexcept { - return Viewport::FromInclusive({ origin.X, origin.Y, - origin.X, origin.Y }); + return Viewport::FromInclusive({ origin.X, origin.Y, origin.X, origin.Y }); } SHORT Viewport::Left() const noexcept @@ -162,9 +157,9 @@ COORD Viewport::Dimensions() const noexcept bool Viewport::IsInBounds(const Viewport& other) const noexcept { return other.Left() >= Left() && other.Left() <= RightInclusive() && - other.RightInclusive() >= Left() && other.RightInclusive() <= RightInclusive() && - other.Top() >= Top() && other.Top() <= other.BottomInclusive() && - other.BottomInclusive() >= Top() && other.BottomInclusive() <= BottomInclusive(); + other.RightInclusive() >= Left() && other.RightInclusive() <= RightInclusive() && + other.Top() >= Top() && other.Top() <= other.BottomInclusive() && + other.BottomInclusive() >= Top() && other.BottomInclusive() <= BottomInclusive(); } // Method Description: @@ -176,7 +171,7 @@ bool Viewport::IsInBounds(const Viewport& other) const noexcept bool Viewport::IsInBounds(const COORD& pos) const noexcept { return pos.X >= Left() && pos.X < RightExclusive() && - pos.Y >= Top() && pos.Y < BottomExclusive(); + pos.Y >= Top() && pos.Y < BottomExclusive(); } // Method Description: @@ -717,7 +712,7 @@ SMALL_RECT Viewport::ToExclusive() const noexcept // - an exclusive RECT equivalent to this viewport. RECT Viewport::ToRect() const noexcept { - RECT r{0}; + RECT r{ 0 }; r.left = Left(); r.top = Top(); r.right = RightExclusive(); @@ -762,8 +757,7 @@ Viewport Viewport::ToOrigin() const noexcept // - other: the viewport to convert to this coordinate space // Return Value: // - the input viewport in a the coordinate space with origin at (this.Top, this.Left) -[[nodiscard]] -Viewport Viewport::ConvertToOrigin(const Viewport& other) const noexcept +[[nodiscard]] Viewport Viewport::ConvertToOrigin(const Viewport& other) const noexcept { Viewport returnVal = other; ConvertToOrigin(&returnVal._sr); @@ -780,8 +774,7 @@ Viewport Viewport::ConvertToOrigin(const Viewport& other) const noexcept // - other: the viewport to convert out of this coordinate space // Return Value: // - the input viewport in a the coordinate space with origin at (0, 0) -[[nodiscard]] -Viewport Viewport::ConvertFromOrigin(const Viewport& other) const noexcept +[[nodiscard]] Viewport Viewport::ConvertFromOrigin(const Viewport& other) const noexcept { Viewport returnVal = other; ConvertFromOrigin(&returnVal._sr); @@ -797,8 +790,7 @@ Viewport Viewport::ConvertFromOrigin(const Viewport& other) const noexcept // Return Value: // - The offset viewport by the given delta. // - NOTE: Throws on safe math failure. -[[nodiscard]] -Viewport Viewport::Offset(const Viewport& original, const COORD delta) +[[nodiscard]] Viewport Viewport::Offset(const Viewport& original, const COORD delta) { // If there's no delta, do nothing. if (delta.X == 0 && delta.Y == 0) @@ -829,8 +821,7 @@ Viewport Viewport::Offset(const Viewport& original, const COORD delta) // - rhs: the other viewport to or together // Return Value: // - a Viewport representing the union of the other two viewports. -[[nodiscard]] -Viewport Viewport::Union(const Viewport& lhs, const Viewport& rhs) noexcept +[[nodiscard]] Viewport Viewport::Union(const Viewport& lhs, const Viewport& rhs) noexcept { const auto leftValid = lhs.IsValid(); const auto rightValid = rhs.IsValid(); @@ -870,8 +861,7 @@ Viewport Viewport::Union(const Viewport& lhs, const Viewport& rhs) noexcept // - rhs: the other viepwort to intersect // Return Value: // - a Viewport representing the intersection of the other two, or an empty viewport if there's no intersection. -[[nodiscard]] -Viewport Viewport::Intersect(const Viewport& lhs, const Viewport& rhs) noexcept +[[nodiscard]] Viewport Viewport::Intersect(const Viewport& lhs, const Viewport& rhs) noexcept { const auto left = std::max(lhs.Left(), rhs.Left()); const auto top = std::max(lhs.Top(), rhs.Top()); @@ -904,8 +894,7 @@ Viewport Viewport::Intersect(const Viewport& lhs, const Viewport& rhs) noexcept // - Array of 4 Viewports representing non-overlapping segments of the remaining area // that was covered by `main` before the regional area of `removeMe` was taken out. // - You must check that each viewport .IsValid() before using it. -[[nodiscard]] -SomeViewports Viewport::Subtract(const Viewport& original, const Viewport& removeMe) noexcept +[[nodiscard]] SomeViewports Viewport::Subtract(const Viewport& original, const Viewport& removeMe) noexcept { SomeViewports result; @@ -928,7 +917,7 @@ SomeViewports Viewport::Subtract(const Viewport& original, const Viewport& remov // In the following examples, the found remaining regions are represented by: // T = Top B = Bottom L = Left R = Right // - // 4 Sides but Identical: + // 4 Sides but Identical: // |---------original---------| |---------original---------| // | | | | // | | | | @@ -1037,7 +1026,7 @@ SomeViewports Viewport::Subtract(const Viewport& original, const Viewport& remov result.viewports.at(result.used++) = right; } } - } + } return result; } diff --git a/tools/OpenConsole.psm1 b/tools/OpenConsole.psm1 index 8c7918302..27f0b89ea 100644 --- a/tools/OpenConsole.psm1 +++ b/tools/OpenConsole.psm1 @@ -304,4 +304,36 @@ function Debug-OpenConsole() Debug-Process -Id $process.Id } -Export-ModuleMember -Function Set-MsbuildDevEnvironment,Invoke-OpenConsoleTests,Invoke-OpenConsoleBuild,Start-OpenConsole,Debug-OpenConsole +#.SYNOPSIS +# runs clang-format on list of files +# +#.PARAMETER Path +# The full paths to the files to format +function Invoke-ClangFormat { + [CmdletBinding()] + Param ( + [Parameter(Mandatory=$true,ValueFromPipeline=$true)] + [string[]]$Path + ) + + Process { + ForEach($_ in $Path) { + Try { + $n = Get-Item $_ -ErrorAction Stop | Select -Expand FullName + & "$env:OpenconsoleRoot/dep/llvm/clang-format" -i $n + } Catch { + Write-Error $_ + } + } + } +} + +#.SYNOPSIS +# runs code formatting on all c++ files +function Invoke-CodeFormat() { + Get-ChildItem -Recurse "$env:OpenConsoleRoot/src" -Include *.cpp, *.hpp, *.h | + Where FullName -NotLike "*Generated Files*" | + Invoke-ClangFormat +} + +Export-ModuleMember -Function Set-MsbuildDevEnvironment,Invoke-OpenConsoleTests,Invoke-OpenConsoleBuild,Start-OpenConsole,Debug-OpenConsole,Invoke-CodeFormat diff --git a/tools/README.md b/tools/README.md index 31736db7a..e4441d0a0 100644 --- a/tools/README.md +++ b/tools/README.md @@ -38,6 +38,10 @@ for Linux entrypoint) in your `~` directory. Likewise, `openps` launches powershell. +## runformat + +`runformat` will format the c++ code to match our coding style. + ## testcon, runut, runft `runut` will automatically run all of the unit tests through TAEF. `runft` will run the feature tests, and `testcon` runs all of them. They'll pass any @@ -59,5 +63,6 @@ of the razzle environment, so you can immediately start using the macros: 1. `bcz` 2. `opencon` 3. `testcon` (in the new console window) + 4. `runformat` If they all come out green, then you're ready for a pull request! diff --git a/tools/runformat.cmd b/tools/runformat.cmd new file mode 100644 index 000000000..d9c1d56c7 --- /dev/null +++ b/tools/runformat.cmd @@ -0,0 +1,5 @@ +@echo off + +rem run clang-format on c++ files + +powershell -noprofile "import-module %OPENCON_TOOLS%\openconsole.psm1; Invoke-CodeFormat"